code:
from contextlib import contextmanager

@contextmanager
def _mute():
    with settings(warn_only='true'):
        with hide('running', 'stdout', 'stderr', 'warnings'):
            yield

rawDescription: What's the pythonic way to wrap several functions in the same with statements


code:
import io
import pandas as pd

data = """\
        Name
0  JP2015121
1    US14822
2    US14358
3  JP2015539
4  JP2015156
"""
df = pd.read_csv(io.StringIO(data), delim_whitespace=True, index_col=0)
print(df)

rawDescription: Pandas: read_csv (read multiple tables in a single file)


code:
import subprocess
cmd = "ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'"
co = subprocess.Popen([cmd], shell = True, stdout = subprocess.PIPE)
ips = co.stdout.read().strip().split("\n")

rawDescription: Get all the external IP addresses of a host


rawDescription: remove rows and columns from numpy array

description: Remove rows and columns from numpy array


rawDescription: Assigning (or tieing in) function results back to original data in pandas


code: found = any(item=="the one I'm looking for" for item in items)

rawDescription: For loops and multiple conditions

description: For loops and multiple conditions


code: df[ df.tag == 1 ].groupby(['date', 'name'])['name'].aggregate(len).unstack( ).shift( 1 ).fillna( 0 ).cumsum( )

rawDescription: Calculating previous chance figure for use in chi square test


code:
from functools import total_ordering

@total_ordering
class number_word:
    key = dict(enumerate(
               ("zero one two three four five six seven eight nine ten".split())
              ))
    key.update({v:k for k,v in key.items()})

    def __init__(self,value):
        alt = self.key.get(value,None)
        if isinstance(value,str):
            self.word = value
            self.num = alt

        elif isinstance(value,int):
            self.num = value
            self.word = alt
        else:
            raise TypeError("must be str or int")

    def __repr__(self):
        return "nw(%r)"%self.word

    def __eq__(self,other):
        if not isinstance(other,number_word):
            other = word_number(other)

        if self.num == None == other.num:
            #neither are valid numbers, compare as strings
            return self.word == other.word
        else:
            return self.num == other.num

    def __lt__(self,other):
        if not isinstance(other,number_word):
            other = word_number(other)

        if self.num is None or other.num is None:
            return self.word < other.word
        else:
            return self.num < other.num

rawDescription: Why can't Python understand integers in word form?


code:
inspect.getmembers(Bar,
    lambda m: inspect.ismethod(m) and m.__func__ in m.im_class.__dict__.values())

rawDescription: Python - How can I query the class in which a method is defined?


code:
g = df.groupby(['User','DLang']).count().reset_index()
g = g.rename(columns={'GridCode':'occurrences'})

rawDescription: pandas - unstack with most frequent values in MultiIndex DataFrame

description: Pandas - unstack with most frequent values in MultiIndex DataFrame


code:
from collections import defaultdict
from dateutil.parser import parse
import csv
import re

data = defaultdict(lambda: defaultdict(int))

with open('access_logshort.txt','rU') as f:
    for line in f:
        list1 = re.search(r'(?P<Date>[0-9]{2}/[a-zA-Z]{3}/[0-9]{4})(.+)(GET|POST)\s(http://|https://)([a-zA-Z.]+)(\.)(?P<tld>[a-zA-Z]+)(/).+?"\s200',line)

        if list1 is not None:
            date, domain = list1.group(1,7)
            data[date.lower()][domain.lower()] += 1

with open('my_data.csv', 'wb') as ofile:
    # add delimiter='\t' to the argument list of csv.writer if you want
    # tsv rather than csv
    writer = csv.writer(ofile)

    for key, value in sorted(data.iteritems(), key=lambda x: parse(x[0])):
        domains = sorted(value.iteritems())
        writer.writerow([key] + ['{}:{}'.format(*d) for d in domains])

rawDescription: Sorting and Organizing a Dictionary

description: Sorting and Organizing a Dictionary


code:
#!/usr/bin/env python

import subprocess

# Launch with subprocess in list mode (no shell involved) and
# use a meaningful buffer size to minimize system calls
proc = subprocess.Popen(['gzip', '-cdfq', 'million_lines.txt.gz'], stdout=subprocess.PIPE, bufsize=4096)
# Iterate stdout directly
for line in proc.stdout:
    if line == '1000000\n':  # Avoid stripping
        print("This is the millionth line: Python")
        break
# Prevent deadlocks by terminating, not waiting, child process
proc.terminate()

rawDescription: Python vs Perl: performance reading a gzipped file


code: test.extra_kws['sun'] = 'dock'

rawDescription: Merge decorator function as class

description: Merge decorator function as class


code:
from collections import namedtuple

labels = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
StockDay = namedtuple('StockDay', [s.lower() for s in labels])

day0 = ['Feb 7, 2014', '15,630.64', '15,798.51', '15,625.53', '15,794.08', '105,782,495']
item = StockDay(*day0)

print(item)

rawDescription: python comprehension from two list or zip

description: Python comprehension from two list or zip


code:
for k in myorder:
    x = mydict[k] # do something with x

rawDescription: How to reorder a python ordered dict based on array?

description: Reorder a python ordered dict based on array


code:
class sic:
  def f(cls): ...
  f = classmethod(f)

rawDescription: backport function modifiers to python2.1

description: Backport function modifiers to python2.1


code:
#!python3
import binascii
import struct

# struct module unpacking formats
SHORT_ENTRY = '<11s3B7HL'     # 12 fields described in FAT32 spec
LONG_ENTRY  = '<B10s3B12sH4s' # 8 fields described in FAT32 spec

# attribute bit values (byte offset 11)
ATTR_READ_ONLY = 0x01
ATTR_HIDDEN    = 0x02
ATTR_SYSTEM    = 0x04
ATTR_VOLUME_ID = 0x08
ATTR_DIRECTORY = 0x10
ATTR_ARCHIVE   = 0x20
LAST_LONG_ENTRY = 0x40
ATTR_LONG_NAME = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID
ATTR_LONG_NAME_MASK = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID | ATTR_DIRECTORY | ATTR_ARCHIVE

# A few entries from a FAT32 root directory (32 bytes per row)
data = binascii.unhexlify('''
  42 FC 00 69 00 6E 00 6F 00 2E 00 0F 00 D9 6A 00 70 00 67 00 00 00 FF FF FF FF 00 00 FF FF FF FF
  01 6C 9A 4B 51 6D 00 61 00 F1 00 0F 00 D9 61 00 6E 00 61 00 20 00 70 00 65 00 00 00 6E 00 67 00
  4D 41 A5 41 4E 41 7E 31 4A 50 47 20 00 89 6D 8B FE 40 69 43 00 00 C7 7D 8B 3F 03 00 04 06 7D 00
  41 11 62 2F 66 8E 7F FD 56 BA 4E 0F 00 DC 2E 00 74 00 78 00 74 00 00 00 FF FF 00 00 FF FF FF FF
  46 32 33 33 7E 31 20 20 54 58 54 20 00 4B BA 7B 69 43 69 43 00 00 BB 7B 69 43 00 00 00 00 00 00
'''.strip().replace(' ','').replace('\n',''))

# Long names are built up from multiple entries, so start empty
raw_long = b''

# Iterate through the 32-byte entries in the data
for offset in range(0,len(data),32):
    raw_entry = data[offset:offset+32]

    # Entries that start with 0xE5 are deleted.
    # An entry that starts with zero indicates no more entries
    if raw_entry[0] == 0xE5: continue
    if raw_entry[0] == 0: break

    if raw_entry[11] & ATTR_LONG_NAME_MASK == ATTR_LONG_NAME:
        # Long entries are found last-to-first and are in three parts
        # per entry.  Concatenate the parts and prepend to entries
        # found so far.
        entry = struct.unpack_from(LONG_ENTRY,data,offset)
        raw_long = entry[1] + entry[5] + entry[7] + raw_long
    else:
        entry = struct.unpack_from(SHORT_ENTRY,data,offset)
        # If the short entry is a volume ID, skip it.
        if entry[2] == ATTR_VOLUME_ID: continue
        # Unpack and decode 8.3 filename in OEM
        # character set.
        basename = entry[0][:8].decode('cp437').rstrip(' ')
        ext = entry[0][8:].decode('cp437').rstrip(' ')
        # Decode and strip the current long name value of padding.
        long_name = raw_long.decode('utf-16le').rstrip('\uffff').rstrip('\0')
        print('{:8}.{:3} - {}'.format(basename,ext,long_name))
        raw_long = b'' # Reset the long name to empty

rawDescription: Python 2.7 and unicode

description: Python 2.7 and unicode


code:
# -*- coding: utf-8 -*-
import datetime
def run():
    code_task = get_active_task()
    code_task.new_file(factory_id='canopy.editor.code_editor', editor_type='Python')
    code_editor = code_task.active_editor
    cursor = code_editor.cursor
    cursor.write(u'# Hello world %s' % datetime.datetime.now().strftime("%H-%M-%S"))
    code_editor.autoindent_newline()

rawDescription: Creating template files for Enthought Canopy


code: tuple("{0}{1}".format(x,y) for x,y in zip(t1,t2)) #tuple comverts LC to tuple

rawDescription: Merge two tuples into one

description: Merge two tuples into one


rawDescription: Numpy array and change value regions

description: Numpy array and change value regions


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])
ax.margins(0.05)
plt.show()

rawDescription: Matplotlib - change automatic axis range


code:
source_path = '/path/to/a/directory/or/file'
temp = splitall(source_path)
temp
temp[2] = 'different'
target_path = os.path.join(*temp)
target_path

rawDescription: Python: change part (single directory name) of path


code:
{'authors': u'Kyle Becker',
 'title': u'17 Reactions to the \u2018We Don\u2019t Have a Strategy\u2019 Gaffe That May Haunt the Rest of Obama\u2019s Presidency',
 'url': 'http://www.ijreview.com/2014/08/172569-25-reactions-obamas-dont-strategy-gaffe-may-haunt-rest-presidency/'}

...

rawDescription: Working with post request to load more articles with scrapy python


code:
for b in badwords:
    if b in s:
        score = score+1

rawDescription: A fast and efficient, not-so complex word content filter


code:
def seq(s):
    length = 1
    while True:
        for p in itertools.product(s, repeat=length):
            yield p
        length += 1

rawDescription: Calculating the Nth Sequence of Length M in Python


code:
class general:
    def __init__(self, msgs=()):
        self.msgs = list(msgs)  # Explicitly convert and shallow copy as list

rawDescription: why is this code generating three array values instead of one? python 3.x

description: Why is this code generating three array values instead of one? python 3.x


code:
#!/usr/bin/env python
import socket
from urllib.parse import urlparse

ENCODING = 'ascii'

def geturl(url, timeout=10, receive_buffer=4096):
    parsed = urlparse(url)
    try:
        host, port = parsed.netloc.split(':')
    except ValueError:
        host, port = parsed.netloc, 80

    sock = socket.create_connection((host, port), timeout)

    method  = 'GET %s HTTP/1.0\n\n' % parsed.path
    sock.sendall(bytes(method, ENCODING))

    response = [sock.recv(receive_buffer)]
    while response[-1]:
        response.append(sock.recv(receive_buffer))

    return ''.join(r.decode(ENCODING) for r in response)

print(geturl('http://www.example.com/'))

rawDescription: python: how to fetch an url? (with improper response headers)

description: Python: how to fetch an url? (with improper response headers)


code:
from bs4 import  BeautifulSoup
soup = BeautifulSoup ('''dubstep the music that is created from transformers having s$#''')
soup.find('a').text

rawDescription: python html strip of hyperlinked text only

description: Python html strip of hyperlinked text only


code:
if match:
    print >> take, match.group(1)
elif match2:
    print >> take, match2.group(1)
elif match3:
    print >> take, match3.group(1)

rawDescription: How to include "Elif" in "if match" command - Python

description: Include "Elif" in "if match" command - Python


code:
my_list = [int(k) for k in input().split()]
my_list.sort()

rawDescription: Python - replay values in list

description: Python - replay values in list


code:
if all(e is None for e in myList):
    print('all empty or None')

rawDescription: Most concise way to check whether a list is empty or contains only None?


code: ['{0:06}'.format(i) for i in xrange(1000000) if sum(map(int,str(i))) == 20]

rawDescription: A nice way to find all combinations that give a sum of N?


code: pix[x, y]

rawDescription: What does pix[x, y] mean in Python

description: What does pix[x, y] mean in Python


code:
for method_name, method in inspect.getmembers(my_specific_instance, predicate=inspect.ismethod):
   if hasattr(method, '_action_name'):
       add_to_gui_menu(method._action_name, method)

rawDescription: differentiate between python function and class function

description: Differentiate between python function and class function


code:
for line in fileR:
    line = line.rstrip()

rawDescription: how to use only one loop for iterating over a file in Python?

description: Use only one loop for iterating over a file in Python


rawDescription: How to pickle unicodes and save them in utf-8 databases

description: Pickle unicodes and save them in utf-8 databases


code:
newout.seek(0)
newout.readlines()

rawDescription: Python CGI: Translate from stdout to html (e.g. replace \n with <BR>)


code:
import wx
import subprocess
import sys

def re_run(e):
    new_process = subprocess.Popen([sys.executable]+sys.argv)

app = wx.App(False)  # Create a new app, don't redirect stdout/stderr to a window.
frame = wx.Frame(None, wx.ID_ANY, "Hello World") # A Frame is a top-level window.
s=wx.Button(frame,-1,"New")
s.Bind(wx.EVT_BUTTON, re_run)
frame.Show(True)     # Show the frame.
app.MainLoop()

rawDescription: Running Python Script Again

description: Running Python Script Again


code:
import numpy as np
np.diff(range(10))

rawDescription: matplotlib pylplot: plotting series of cumulative data as differences

description: Matplotlib pylplot: plotting series of cumulative data as differences


rawDescription: Read bipartite graph

description: Read bipartite graph


code: stdout = subprocess.check_output(['/path/to/binary', '-p', 's'])

rawDescription: Python subprocess passes one argument only


code:
from os import popen
cmd = "mplayer alert.ogg"
popen(cmd)

rawDescription: How would I go about playing an alarm sound in python?


rawDescription: Create dynamic Python list with N elements


code:
if fileform.is_valid():
    jfs = fileform.save(commit=True)

rawDescription: Django: Upload Files and Save to Disk

description: Django: Upload Files and Save to Disk


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(500,4), columns=['a','b','c','d'])
df.to_csv('large_data.csv', index=False)

rawDescription: Breaking up large file, but adding header to each subsequent file


rawDescription: Python delete row in numpy array

description: Python delete row in numpy array


code: exec("from project.data_{0}.models import *".format(release)) in locals()

rawDescription: Dynamic Loading of Modules then using "from x import *" on loaded module


rawDescription: Force python calculation in double

description: Force python calculation in double


code:
class CombineResults(models.Model):
    event = models.ForeignKey(CombineEvents, related_name='results')

rawDescription: Filter queryset to return only the best result for each user


code:
with open("filea") as f, open("fileb") as f2:
    # male set of lines stripping newlines
    # so we can compare properly later i.e foo\n != foo
    st  = set(map(str.rstrip, f)) # itertools.imap python2
    for line in f2:
        # split once and extract first element to compare
        if line.strip() and line.split(None, 1)[0] in st:
            print(line.rstrip())

rawDescription: Compared data from 2 files

description: Compared data from 2 files


code:
stemmer = nltk.stem.PorterStemmer()
stems = [stemmer.stem(t) for t in tokens]
nltk.FreqDist(stems).most_common()

rawDescription: nltk frequency combining singular and plural, verb and adverb when tokenizing

description: Nltk frequency combining singular and plural, verb and adverb when tokenizing


rawDescription: C-style escaping in python

description: C-style escaping in python


code:
import re
yourstr = 'asdfasdfasasdaFFD8FFasdfalsjdflajsdfljasdfasdfasdfasdfFFD9asdflasdflasdfFFD9asdfasdfFFD8FFasdfalsjdflajsdfljasdfasdfasdfasdfFFD9'
p = re.compile(r'(FFD8FF((?:(?=([^F]+|F(?!FD8FF)))\3)*)FFD9)(?=.*?FFD8FF)')
re.findall(p, yourstr)

rawDescription: Nongreedy Regex with Repetition

description: Nongreedy Regex with Repetition


rawDescription: Difference between statement and function


code:
def funkyDecorator(cls):
    cls.funky = 1

@funkyDecorator
class MyClass(object):
    pass

rawDescription: How do I add a method with a decorator to a class in python?

description: Add a method with a decorator to a class in python


code: np.array([ [k,i,i+1] for k in range(0,1,1) for i in range(k+1,k+8)]).ravel()

rawDescription: Is there a way to generate a list of indices using numpy


code:
import ctypes
ctypes.c_ubyte * 3

rawDescription: Passing python array to a c function using c_types


code:
import urllib
import urllib2
from bs4 import BeautifulSoup

uni_id = "P22216"
url = "http://www.rcsb.org/pdb/search/smart.do?smartComparator=and&smartSearchSubtype_0=UpAccessionIdQuery&target=Current&accessionIdList_0=%s" % uni_id
text = urllib2.urlopen(url).read()
soup = BeautifulSoup(text)
link = soup.find( "span", {"class":"iconSet-main icon-download"}).parent.get("href")
urllib.urlretrieve("http://www.rcsb.org/" + str(link), str(link.split("=")[-1]) + ".pdb")

rawDescription: download file using python beautifulsoup and selenium

description: Download file using python beautifulsoup and selenium


code:
import json

mydata = {}
mydata['hello'] = { 'value1':1, 'valuuelist':[1,2,3,4] }

print(json.dumps(mydata))

rawDescription: How to retrieve a value from an executed string?

description: Retrieve a value from an executed string


code:
converted_formula = "((FooFunction() + BarFunction()) - (BazFunction()/2))"
answer = 42

rawDescription: Convert custom formula to python function


rawDescription: how to extend column size for some selected rows and also add additional rows of a 2D array python2.7

description: Extend column size for some selected rows and also add additional rows of a 2D array python2.7


code:
filename = "somefile.txt"
with open(filename, mode="wb") as outfile:
    outfile.write("first line")
    outfile.write("\n")
    outfile.write("second line")

rawDescription: Python: How to write a list of strings on separate lines but withot a blank line


code:
memmove(byref(mystruct),
        tar_member_fileobj.read(sizeof(mystruct)),
        sizeof(mystruct)
)

rawDescription: Add .readinto(b) method to tarfile's ExFileObject?


code:
df3.index = pd.MultiIndex.from_arrays(df3[['Item','Code','letters','Year','Month']].values.T,
                                      names=('Item', 'Code','letters','Year','Month'))
df4 = df3[['Price','Quantity']].stack()
df5 = pd.DataFrame(df4)
df5.columns = ['Value']
df5.reset_index()

rawDescription: Excel Table into Organized Pandas Dataframe


code:
class Person(object):
    def addattr(self,x,val):
        self.__dict__[x]=val

rawDescription: Python - Dynamic variables

description: Python - Dynamic variables


rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
import time
c = ExpireCounter()
assert(len(c) == 0)
print(c)
# deque([])

c.add(datetime.datetime.now())
time.sleep(0.75)
c.add(datetime.datetime.now())
assert(len(c) == 2)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 91426), datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])

time.sleep(0.75)
assert(len(c) == 1)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])

rawDescription: container where values expire in python

description: Container where values expire in python


code:
a, b = np.loadtxt("/home/xi_{cos1}<zphot{sig0:.03f}<{cos2}_dat".format(
    cos1=zcos1, sig0=sig0, cos2=zcos2), unpack=True)

rawDescription: Python string formatting, include the 0 at the end


code:
b1=np.broadcast_arrays(b,np.zeros((2,1)))[0]
b1.shape
b1.strides
b1.__array_interface__

rawDescription: Numpy: use reshape or newaxis to add dimensions


rawDescription: Creating a new dict with old keys but with subvalues


code:
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
from random import randint

A = tuple(randint(0, 100) for _ in range(1000))

def one():
    D = defaultdict(list)
    [D[v].append(i) for i, v in enumerate(A)]

def two():
    D = {}
    [D.setdefault(v, []).append(i) for i, v in enumerate(A)]

def three():
    {v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}

from timeit import timeit

for func in (one, two, three):
    print(func.__name__ + ':', timeit(func, number=1000))

rawDescription: Dictionary Comprehension for list values


code:
import os

names = set(['NEWS.txt', 'HISTORY.txt']) # Make this a set of filenames
path = "C:\\"
result = []
for root, dirs, files in os.walk(path):
    found = names.intersection(files) # If any of the files are named any of the names, add it to the result.
    for name in found:
        result.append(os.path.join(root, name) + "\n")

f = open ('testrestult.txt', 'w')
f.writelines(result)

rawDescription: Checking if multiple specific files exist on a given drive


rawDescription: Formatting floats in a numpy array

description: Formatting floats in a numpy array


code:
def using_eight_shifts(data):
    h, w = data.shape
    data2 = np.empty((h+2, w+2))
    data2[(0,-1),:] = np.nan
    data2[:,(0,-1)] = np.nan
    data2[1:1+h,1:1+w] = data

    result = np.where(np.logical_and.reduce([
        (data2[i:i+h,j:j+w] == data)
        for i in range(3)
        for j in range(3)
        if not (i==1 and j==1)]))
    return result

rawDescription: Retrieve position of elements with setting some criteria in numpy


code:
import lxml.html

page="""
 . . .
 """
doc = lxml.html.document_fromstring(page)

# get label1 4810
label = doc.cssselect('.mbg .mbg-l a')[0].text_content()
# get address
addres = doc.cssselect('.u-flL .bsi-c1')[0].text_content()
# get phone
phone = doc.cssselect('.bsi-c2 .bsi-lbl')[0].text_content()
# get mail
mail = doc.cssselect('.bsi-c2 .bsi-lbl')[1].text_content()

rawDescription: Python Scrapy - dynamic HTML, div and span content needed


code:
class A(object):
    def somemethod(self):
        b = B(self)

rawDescription: How to reference creator object in Python?

description: Reference creator object in Python


code:
i = 0
while not exists(image1):
    i = i + 1
    wait(1)
    # After 60 seconds break the loop anyway.
    if (i == 60):
        break

rawDescription: sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working?

description: Sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working


code:
for reg, handler in map.items():
    result = reg.match(line)
    if result:
       handler(result)
       break

rawDescription: Need help in refactoring my python script


code:
empty = (df.TAG == '')
mask = df.IDnumber.str.contains('|'.join(pattern1)) & empty
df.loc[mask, 'TAG'] = group[1]

rawDescription: Python pandas tagging entries in dataframe shortening code


code:
driver.find_element_by_css_selector("tbody > tr:nth-child(4) > td:nth-child(3)")
driver.find_element_by_css_selector("tbody > tr:nth-child(4) > td:nth-child(3)").text

rawDescription: How do I return a web page's table cell value without ID, using column and row names (not index)

description: Return a web page's table cell value without ID, using column and row names (not index)


rawDescription: Compute pairwise distance in a batch without replicating tensor in Tensorflow?


rawDescription: Remove entries of a dictionary that are not in a set


code:
mask = np.zeros(len(df), dtype='bool')
for i in range(length):
    mask[start+i] = True

rawDescription: How can I slice a timeseries dataframe in Pandas based on multiple conditions?

description: Slice a timeseries dataframe in Pandas based on multiple conditions


rawDescription: list comprehension question

description: List comprehension question


code:
person = Person.objects.filter(is_deleted=False, pk=person_id) \
            .prefetch_related(
                Prefetch('task_set', queryset=Task.objects.filter(is_deleted=False))
            ) \
            .get()

rawDescription: How to expose a filtered reverse relationship in Django REST API framework?

description: Expose a filtered reverse relationship in Django REST API framework


rawDescription: Less code on multi key dictionary initialization


code: B

rawDescription: Join 2 dataframes with a startdate and enddate column


code:
class Foo(SQLObject):
    bar = UnicodeCol(length=128)
    baz = BoolCol(default=True)
    lulz = UnicodeCol(length=256)

    def _get_foo(self):
        return "foo"

rawDescription: Easier way to create a JSON object from an SQLObject


code:
class JobCategory(models.Model):
    title = models.CharField(_('title'), max_length=50, help_text=_("Max 50 chars. Required."))
    slug = models.SlugField(_('slug'), help_text=_("Only letters, numbers, or hyphens. Required."))

    class Meta:
        verbose_name = _('job category')
        verbose_name_plural = _('job categories')

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('djobs_category_jobs', args=[self.slug])

    @property
    def active_job_count(self):
        return len(Job.active.filter(category=self))

class ActiveJobManager(models.Manager):
    def get_query_set(self):
        return super(ActiveJobManager, self).get_query_set().filter(created_date__gte=datetime.datetime.now() - datetime.timedelta(days=30))

class Job(models.Model):
    title = models.CharField(_('title'), max_length=50, help_text=_("Max 50 chars. Required."))
    description = models.TextField(_('description'), help_text=_("Required."))
    category = models.ForeignKey(JobCategory, related_name='jobs')
    employment_type = models.CharField(_('employment type'), max_length=5, choices=EMPLOYMENT_TYPE_CHOICES, help_text=_("Required."))
    employment_level = models.CharField(_('employment level'), max_length=5, choices=EMPLOYMENT_LEVEL_CHOICES, help_text=_("Required."))
    employer = models.ForeignKey(Employer)
    location = models.ForeignKey(Location)
    contact = models.ForeignKey(Contact)
    allow_applications = models.BooleanField(_('allow applications'))
    created_date = models.DateTimeField(auto_now_add=True)

    objects = models.Manager()
    active = ActiveJobManager()

    class Meta:
        verbose_name = _('job')
        verbose_name_plural = _('jobs')

    def __unicode__(self):
        return '%s at %s' % (self.title, self.employer.name)

rawDescription: Is it possible to filter on a related item in Django annotations?


code:
print(totals.argsort())
# tz                     2
# Africa/Cairo           4
# Africa/Casablanca      5
# Africa/Ceuta           3
# Africa/Johannesburg    1
# Africa/Lusaka          6
# America/Anchorage      0

rawDescription: Weird Data manipulation in Pandas

description: Weird Data manipulation in Pandas


foo/bar: bar/baz

rawDescription: Python http response decoding

description: Python http response decoding


rawDescription: What is the inverse function of zip in python?


code: contents = open("values.txt", "r").read().split()

rawDescription: Analog of bash "echo $(cat file)" in python (one more time string interpolation)


code:
class MutableString(object):
    def __init__(self, value):
        self.value = value

    def conc(self, value, delim=' '):
        self.value = "{self.value}{delim}{value}".format(**locals())

    def __str__(self):
        return self.value

rawDescription: Modify subclassed string in place

description: Modify subclassed string in place


code:
vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
if any(char in vowels for char in word):
   ...

rawDescription: Check presence of Vowels in word, python


code:
IPython.start_ipython(config=c, user_ns=locals())   # Pass in local variables
IPython.start_ipython(config=c, user_ns=globals())  # Pass in global variables

rawDescription: Can you specify a command to run after you embed into IPython?

description: Specify a command to run after you embed into IPython


code:
df
#>>>       A      B      C     D
#>>> 0  True   True   True  True
#>>> 1  True   True   True  True
#>>> 2  True  False   True  True
#>>> 3  True   True  False  True

df.T
#>>>       0     1      2      3
#>>> A  True  True   True   True
#>>> B  True  True  False   True
#>>> C  True  True   True  False
#>>> D  True  True   True   True

rawDescription: python, rearrange the list to show the item which contains in most list

description: Python, rearrange the list to show the item which contains in most list


code:
class Main(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = uic.loadUi('example.ui',self)

        btn1=QtWidgets.QPushButton('buttonn')
        self.ui.tabwidget.addTab(btn1, 'Tab name')

rawDescription: QtDesigner in combination with PyQt (more specific adding a button to a tab created in QtDesigner


code:
import gtk
import gobject

def main():
    button = gtk.Button("Hello")
    scroll_win = gtk.ScrolledWindow()
    scroll_win.add(button)
    win = gtk.Window(gtk.WINDOW_TOPLEVEL)
    win.add(scroll_win)
    win.show_all()

    # Set timeout to allow time for the screen to be drawn
    # before saving the window image
    gobject.timeout_add(1000, drawWindow, win)

def drawWindow(win):
    width, height = win.get_size()
    pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)

    # Retrieve the pixel data from the gdk.window attribute (win.window)
    # of the gtk.window object
    screenshot = pixbuf.get_from_drawable(win.window, win.get_colormap(),
                                          0, 0, 0, 0, width, height)

    screenshot.save('screenshot.png', 'png')

    # Return False to stop the repeating interval
    return False

if __name__ == '__main__':
    main()
    gtk.main()

rawDescription: Creating a screenshot of a gtk.Window

description: Creating a screenshot of a gtk.Window


rawDescription: How to change the dtype of a numpy recarray?

description: Change the dtype of a numpy recarray


code:
for (k,v) in sampleDict.iteritems():
    key          = k
    phone_number = v[0]
    last_name    = v[1][0]
    first_name   = v[1][0]
    # Do something

rawDescription: How to iterate through a list in a dictionary in python

description: Iterate through a list in a dictionary in python


code:
from django.db import transaction

def viewfunc(request):
    ...
    with transaction.commit_on_success():
        for item in items:
            entry = Entry(a1=item.a1, a2=item.a2)
            entry.save()

rawDescription: What is an efficent way of inserting thousands of records into an SQLite table using Django?


code:
class BottleSerializer(serializers.HyperlinkedModelSerializer):
    wine = WineSerializer(source='wine')

    class Meta:
        model = Bottle
        fields = ('url', 'wine', 'user', 'date_rated', 'rating', 'comment', 'get_more')

rawDescription: Django Rest Framework - Get related model field in serializer


code: print(''.join([r'\x{:x}'.format(ord(c)) for c in x]))

rawDescription: How to print hex to the screen in python

description: Print hex to the screen in python


code:
import numpy as np

def matlab_style_gauss2D(shape=(3,3),sigma=0.5):
    """
    2D gaussian mask - should give the same result as MATLAB's
    fspecial('gaussian',[shape],[sigma])
    """
    m,n = [(ss-1.)/2. for ss in shape]
    y,x = np.ogrid[-m:m+1,-n:n+1]
    h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
    h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
    sumh = h.sum()
    if sumh != 0:
        h /= sumh
    return h

rawDescription: How to obtain a gaussian filter in python

description: Obtain a gaussian filter in python


code:
class MySpider(Spider):
    def __init__(self, *args, **kwargs):
        super(MySpider, self).__init__(*args, **kwargs)

        self.mapping = get_url_id_mapping_from_db()

        self.start_urls = mapping.keys()

    def parse(self, response):
        id = self.mapping[response.url]
        ...

rawDescription: How to load start URLs with parameters?

description: Load start URLs with parameters


code: dropcols = set(dropcols) & set(largefile.columns)

rawDescription: How to remove columns from a file using pandas DataFrame.drop with a list of column headers read in from a second file

description: Remove columns from a file using pandas DataFrame.drop with a list of column headers read in from a second file


code:
# client.py

import os

pipe_name = 'pipe_test'

if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)

print("Waiting for server to start...")
with open(pipe_name, 'w') as pipe:
    action = input("Enter action to send: ")
    pipe.write(action + '\n')

rawDescription: Interprogram communication in python on Linux


code:
def trim(docstring):
    if not docstring:
        return ''
    # Convert tabs to spaces (following the normal Python rules)
    # and split into a list of lines:
    lines = docstring.expandtabs().splitlines()
    # Determine minimum indentation (first line doesn't count):
    indent = sys.maxint
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    # Remove indentation (first line is special):
    trimmed = [lines[0].strip()]
    if indent < sys.maxint:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())
    # Strip off trailing and leading blank lines:
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    # Return a single string:
    return '\n'.join(trimmed)

rawDescription: Proper indentation for Python multiline strings


code:
global mydict #this is line 1
from mydict import mydict
from my_module import my_mod

rawDescription: How to get my global variables to be available during imports of other modules?

description: Get my global variables to be available during imports of other modules


code:
lación
Regula
estado
misión

rawDescription: Encode Python list in order to use re module


code:
a = 256
b = 256
a is b
a = 257
b = 257
a is b
foo = "foo"
bar = "foo"
foo is bar
foo = "$bar"
bar = "$bar"
foo is bar # now False because it does not start with an _ or a letter

rawDescription: Why do the objects __name__ and __main__ have different identities in Python?


code:
# to xyz export a, b, c
import xyz
xyz.a = a
xyz.b = b
xyz.c = c

rawDescription: Is there anything like Python export?

description: Is there anything like Python export


rawDescription: How can I index a line to the next white space available?

description: Index a line to the next white space available


rawDescription: Output an existing defaultdict into appropriate JSON format for flare dendogram Python


rawDescription: How to stop a Python program after some arbitrary timeout

description: Stop a Python program after some arbitrary timeout


code:
def IterateStaples(combo, target):
    # base case
    if all(combo.diff[macro] < 2 for macro in combo.diff): # iterate on combo.diff.values()?
        return combo   # returning combo indicates success!

    for staple in combo.staples:
        staple.increment()                 # update state
        combo.calcTotals()
        combo.findDiff(target)

        if not combo.findConflict(target):  # skip recursing on invalid states
            result = IterateStaples(combo, target)    # recursive case
            if result is not None:      # if the recursion was successful, return the result
                return result

        staple.decrement()  # otherwise, undo the change to the state (backtrack)
        combo.calcTotals()     # these two lines might not be necessary when backtracking
        combo.findDiff(target) # since other branches will call them after staple.increment()

    return None # if we got to the end of the loop, explicitly return None to signal failure

rawDescription: recursive backtracking - python. not returning value

description: Recursive backtracking - python. not returning value


code:
import math
from collections import defaultdict

to_rad = math.pi / 180.0   # convert lat or lng to radians
fname = "site.tsv"        # file format: LAT\tLONG
threshhold_dist=50         # adjust to your needs
threshhold_locations=15    # minimum # of locations needed in a cluster

def dist(lat1,lng1,lat2,lng2):
    global to_rad
    earth_radius_km = 6371

    dLat = (lat2-lat1) * to_rad
    dLon = (lng2-lng1) * to_rad
    lat1_rad = lat1 * to_rad
    lat2_rad = lat2 * to_rad

    a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(lat1_rad) * math.cos(lat2_rad)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a));
    dist = earth_radius_km * c
    return dist

def bounding_box(src, neighbors):
    neighbors.append(src)
    # nw = NorthWest se=SouthEast
    nw_lat = -360
    nw_lng = 360
    se_lat = 360
    se_lng = -360

    for (y,x) in neighbors:
        if y > nw_lat: nw_lat = y
        if x > se_lng: se_lng = x

        if y < se_lat: se_lat = y
        if x < nw_lng: nw_lng = x

    # add some padding
    pad = 0.5
    nw_lat += pad
    nw_lng -= pad
    se_lat -= pad
    se_lng += pad

    # sutiable for r's map() function
    return (se_lat,nw_lat,nw_lng,se_lng)

def sitesDist(site1,site2):
    #just a helper to shorted list comprehension below
    return dist(site1[0],site1[1], site2[0], site2[1])

def load_site_data():
    global fname
    sites = defaultdict(tuple)

    data = open(fname,encoding="latin-1")
    data.readline() # skip header
    for line in data:
        line = line[:-1]
        slots = line.split("\t")
        lat = float(slots[0])
        lng = float(slots[1])
        lat_rad = lat * math.pi / 180.0
        lng_rad = lng * math.pi / 180.0
        sites[(lat,lng)] = (lat,lng) #(lat_rad,lng_rad)
    return sites

def main():
    sites_dict = {}
    sites = load_site_data()
    for site in sites:
        #for each site put it in a dictionary with its value being an array of neighbors
        sites_dict[site] = [x for x in sites if x != site and sitesDist(site,x) < threshhold_dist]

    results = {}
    for site in sites:
        j = len(sites_dict[site])
        if j >= threshhold_locations:
            coord = bounding_box( site, sites_dict[site] )
            results[coord] = coord

    for bbox in results:
        yx="ylim=c(%s,%s), xlim=c(%s,%s)" % (results[bbox]) #(se_lat,nw_lat,nw_lng,se_lng)
        print('map("county", plot=T, fill=T, col=palette(), %s)' % yx)
        rect='rect(%s,%s, %s,%s, col=c("red"))' % (results[bbox][2], results[bbox][0], results[bbox][3], results[bbox][2])
        print(rect)
        print("")

main()

rawDescription: Detecting geographic clusters

description: Detecting geographic clusters


code:
def generate_pins(length, count, alphabet=string.digits):
  alphabet = ''.join(set(alphabet))
  if count > len(alphabet)**length:
    raise ValueError("Can't generate more than %s > %s pins of length %d out of %r" %
                      count, len(alphabet)**length, length, alphabet)
  def onepin(length):
    return ''.join(random.choice(alphabet) for x in xrange(length))
  result = set(onepin(length) for x in xrange(count))
  while len(result) < count:
    result.add(onepin(length))
  return list(result)

rawDescription: unique pin generator

description: Unique pin generator


code: com = 'cat new.txt | tr -d "s/,[]\'\'*//g" >meantenbri.txt2'

rawDescription: writing python code to execute command in main terminal however i need to include ' ' and its not workig

description: Writing python code to execute command in main terminal however i need to include ' ' and its not workig


code:
textchars = bytearray([0,7,8,9,10,12,13,27]) + bytearray(range(0x20, 0x100))
from itertools import zip_longest
textdict = dict(zip_longest(textchars,[''],fillvalue=''))
pprint.pprint(textdict)
'abcdef'.translate(textdict)

rawDescription: migrate str.translate from Python 2 to Python 3

description: Migrate str.translate from Python 2 to Python 3


rawDescription: Solve 2 sides of equation with SymPy

description: Solve 2 sides of equation with SymPy


code:
example = 'Мамлекеттик айыптоочу Биринчи май райондук сотуна берген бул сунушун диний кастыкты ырбатпоо аракети менен негиздеди. Мусулмандарга акаарат келтирип жатат деген кайрылуу каттын негизинде УКМК Тезекбаевге каршы кылмыш ишин козгоп, сотко өткөргөн. Бул ишти бүгүн Биринчи май райондук соту карап бүттү жана өкүм эртең чыгарыларын маалымдады.'

def reattach(sentences):
    punctuation = ('.', '!', '?')
    previous = ''
    for sentence in sentences:
        if sentence not in punctuation:
            previous = sentence
        else:
            yield previous + sentence
            previous = ''
    if previous:
        yield previous

punctuation = re.compile('(?<![\u0410-\u042F])([.!?])(?=(\s)?(\s)?[\u0410-\u042F]|[\u04E8]|["]|[\u201C]|![0-9])')
for sentence in reattach(punctuation.split(example)):
    print(sentence)

rawDescription: Regex splits more than once

description: Regex splits more than once


code:
import random

n = 2  # target row number
random.sample(df.iloc[n, :2], 1)  # Pick one number from this row.

rawDescription: Random selection in pandas dataframe

description: Random selection in pandas dataframe


code:
with spam:                # Attempt to acquire shared ownership.
    if spam:              # Verify ownership was obtained.
        spam.name         # Valid within the context's scope.
        factory.destroy() # spam is still valid.
        spam.name         # Still valid.
                          # spam destroyed once context's scope is exited.

rawDescription: Using weak pointers that evaluate to a None type


code:
with open('file') as f:
    mylist = [int(i.strip()) for i in f]

rawDescription: File of lists, import as individual lists in python 2.7


code:
import sys
sys.path

rawDescription: python how to use imp.find_module or alternative

description: Python how to use imp.find_module or alternative


rawDescription: Update a column in a data frame with the index of another column in another data frame in pandas python


rawDescription: Something about python class

description: Something about python class


code:
import string

result = [fdist.get(l, 0) for l in string.letters]

rawDescription: Sorting letter occurrences in a text alphabetically


code:
def main():
    print("<------Initializing Updating Process------>")
    srcFile ='abc_20160301_(file1).csv'
    srcFile = update2new(srcFile) #get the return here
    print('\nSuccessfully Executed [ {}]......'.format(str(srcFile)),end='\n') #then your printing should be OK
    print ("OK")

rawDescription: Why fuction's not returning value?

description: Why fuction's not returning value


rawDescription: Merge 2 arrays vertical to tuple Numpy

description: Merge 2 arrays vertical to tuple Numpy


rawDescription: Adjusting space around figure with subplots


code:
Example
while True:
    s = input("String? ")
    if not s:
        break
    print("{} is {}abcdearian".format(s, "" if abcdearian(s) else "not "))

rawDescription: Python 3.3: Recursive version of a function


code:
import itertools
stuff, result = ['A', 'B', 'C'], []
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        result.append([i if i in subset else 0 for i in stuff])

rawDescription: Generate list of all combinations and maintain index position


code:
import re

s = 'Спорт not russianA'
d = {
'Спорт':'Досуг',
'russianA':'englishA'
}

pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b')
result = pattern.sub(lambda x: d[x.group()], s)
# Output: 'Досуг not englishA'

rawDescription: Easiest way to replace a string using a dictionary of replacements?


code:
for package in mpl_packages:
    if isinstance(package, str):
        print('')
        print(package.upper())
    else:
        try:
            result = package.check()
            if result is not None:
                message = 'yes [%s]' % result
                print(package.name, message)
        except setupext.CheckFailed as e:
            msg = str(e).strip()
            if len(msg):
                print(package.name, 'no  [%s]' % msg)
            else:
                print(package.name, 'no')

rawDescription: How to know the enabled features of a matplotlib installation?

description: Know the enabled features of a matplotlib installation


code:
[non_rds]
some.unrelated.development.host

[rds]
some.production.host
some.staging.host
some.development.host

[production]
some.production.host

[staging]
some.staging.host

[development]
some.development.host
some.unrelated.development.host

rawDescription: How to get a hostname that contains a certain string from a group in Ansible

description: Get a hostname that contains a certain string from a group in Ansible


code:
try_signaling_nan = struct.unpack(">d", "\x7f\xf0\x00\x00\x00\x00\x00\x01")[0]
struct.pack(">d", try_signaling_nan).encode("hex_codec")

rawDescription: How to distinguish different types of NaN float in Python

description: Distinguish different types of NaN float in Python


code:
def mysort(data, col_name, key=None):
    d = data.copy()
    cols = [i[0] for i in eval(str(d.dtype))]
    if key:
        argsort = np.array([key(i) for i in d[col_name]]).argsort()
    else:
        argsort = d[col_name].argsort()
    for col in cols:
        d[col] = d[col][argsort]
    return d

rawDescription: Sorting numpy matrix for a given column

description: Sorting numpy matrix for a given column


code:
a['breakfast']['time']
'8AM'

a['breakfast']['items']
['banana', 'yogurt']

rawDescription: Dictionaries store pairs. Who stores triples?


rawDescription: How can I apply a math operation on a list of tuples with `map()`?

description: Apply a math operation on a list of tuples with `map()`


code:
@classmethod
def export_to(cls, namespace):
    namespace.update(cls.__members__)

rawDescription: How does one get an Enum's members into the global namespace?

description: Get an Enum's members into the global namespace


code: 'What is the answer to {} x {}?'.format(num1, num2)

rawDescription: Letters inside "int(input(())"

description: Letters inside "int(input(())"


code:
import subprocess
import sys

p = subprocess.Popen([sys.executable, 'sub.py'], stdin=subprocess.PIPE)
p.stdin.write('foo')  # not even a newline seems to be required for this to work, oddly
# p.stdin.flush()  # optional; seems like not required

_, _ = p.communicate()  # this is required--otherwise it just seems to block

rawDescription: program input redirected via python subprocess

description: Program input redirected via python subprocess


code:
def add_unregister(func):
    # build a dictionary mapping names to closure cells
    closure = dict(zip(func.register.__code__.co_freevars,
                       func.register.__closure__))
    registry = closure['registry'].cell_contents
    dispatch_cache = closure['dispatch_cache'].cell_contents
    def unregister(cls):
        del registry[cls]
        dispatch_cache.clear()
    func.unregister = unregister
    return func

rawDescription: Unregister for singledispatch?

description: Unregister for singledispatch


code:
print("{:<26}{}".format("Source HTML","Link"))
print("="*60)
for item in a:
   b = list(item)
   print("{:<26}{}".format(b[0],b[2]))

rawDescription: print formatting with strings

description: Print formatting with strings


code:
class TshirtForm(forms.ModelForm):
    color_code = forms.CharInput()

    class Meta:
        model = Tshirt
        fields = ('name', 'color')
        widget = {'color': forms.HiddenInput(required=False)}

    def clean(self, *args, **kwargs):
        # If users are typing the code, better do some validation
        try:
            color = Color.objects.get(
                code=self.cleaned_data.get('color_code')
            )
        except (ObjectDoesNotExist, MultipleObjectsReturned):
            raise forms.ValidationError('Something went wrong with your code!')
        else:
            # Update the actual field
            self.cleaned_data['color'] = color.id

rawDescription: Django ModelForm make field from other fields


code:
for k,v in scheme.iteritems():
  dataStore[k] = [fetchXMLText(path) for path in v]

rawDescription: The pythonic solution? Traversing a dictionary with an occasional list as a value


code:
new_item= userItem() #model class
new_item.userName= "some data"
new_item.save()
if MusicTag.objects.filter(tag='R&R').exists():
   new_item.tags.add( MusicTag.objects.filter(tag='R&R')[0])
else:
   new_tag= MusicTag(tag='R&R')
   new_tag.save()
   new_item.tags.add(new_tag)

rawDescription: How to design models.py when I want to store the complex data like this?

description: Design models.py when I want to store the complex data like this


code:
class OneAttribute:
    def __init__(self,a=1,**kwargs):
        self.a = a

class TwoAttributes:
    def __init__(self,b=2,c=3,**kwargs):
        self.b = b
        self.c = c

rawDescription: Initializing a class in another class, but passing only set attributes


Text: Telephone

value: contact information

rawDescription: How can I extract a JSON object from a CSV file in Python?

description: Extract a JSON object from a CSV file in Python


code:
def make_sequence(one_positions, zero_count, one_group_sizes):
    zero_group_sizes = [
        end - begin
        for begin, end in zip((0,) + one_positions, one_positions + (zero_count,))
    ]
    return ''.join(
        '0' * z + '1' * o
        for z, o in zip(zero_group_sizes, one_group_sizes + [0])
    )

rawDescription: Generating specific bit sequences in Python


code:
import doctest
doctest.testfile('test-program.txt', optionflags = doctest.NORMALIZE_WHITESPACE)

rawDescription: Good strategy to perform unit tests on program that prints to stdout?


code:
from functools import partial

def bind_method(object, methods):

    for method in methods:
        def my_method(a_method):
            print(a_method.__name__) # this print correct method name
            result = a_method()
            return result

        setattr(object, method.__name__, partial(my_method, method))

rawDescription: Bind method to object runtime late binding


rawDescription: Pandas: Convert array column to numpy Matrix


rawDescription: how to kill a process group using Python subprocess

description: Kill a process group using Python subprocess


code:
f = lambda x: x.sort('C', ascending=False)
sort2 = sort1.groupby('A', sort=False).apply(f)
sort2

rawDescription: Pandas sort by group aggregate and column


oscpu: Windows NT 6.3; WOW64

product: Gecko

appName: Netscape

appCodeName: Mozilla

QuickTime Plug-in 7.7.5

type: application/sdp

description: Playing SDP-files

suffixes: sdp

description: Playing SDP-files

description: The QuickTime Plugin allows you to view a wide variety of multimedia content in Web pages. For more information, visit the QuickTime Web site.

Shockwave Flash

type: application/futuresplash

description: FutureSplash movie

suffixes: spl

type: application/x-shockwave-flash

description: Adobe Flash movie

suffixes: swf

description: FutureSplash movie

description: Adobe Flash movie

description: Shockwave Flash 12.0 r.43

description: FutureSplash movie

description: Shockwave Flash 12.0 r.43

description: Adobe Flash movie

appVersion: 5.0 (Windows)

rawDescription: make a custom json sort order in python

description: Make a custom json sort order in python


code:
random.seed(42)
s = set(A() for i in xrange(1000000))

rawDescription: Python: Retrieve items from a set

description: Python: Retrieve items from a set


code: array[:, ys]

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code:
example_list = ['turtle','cow','goat','pig','swag']
for number_of_ones, item in enumerate(example_list, 1):
    globals()['a'+('1'*i)] = item

print(a11111) # prints 'swag'

rawDescription: Looping Function to Define variables

description: Looping Function to Define variables


code: re.sub(r'[^a-zA-Z]', '', inputtext)

rawDescription: how to Ignore characters other than [a-z][A-Z]

description: Ignore characters other than [a-z][A-Z]


code:
from collections import defaultdict
a = [ 1, 2, 3, 1, 2, 3, 1, 2, 3]
b = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
values = defaultdict(int)
for key, value in zip(a, b):
    values[key] += value
zip(*sorted(values.items()))

rawDescription: Rapid compression of multiple lists with value addition


code:
rperson = RandomPerson()
assert isinstance(rperson,Kyle) or isinstance(rperson,John)

rawDescription: python class factory inherit random parent

description: Python class factory inherit random parent


code:
if event.key == pygame.K_ESCAPE:
    pygame.quit()
elif event.key == pygame.K_q:
    pygame.quit()

rawDescription: Easier way of getting keyboard input in Pygame?


code:
from sys import getrefcount
import example
x = example.func1(None)
assert(2 == getrefcount(x)) # refs: x and getrefcount
d = example.func2(x)
assert(3 == getrefcount(x)) # refs: x, d["key"], and getrefcount
d = None
assert(2 == getrefcount(x)) # refs: x and getrefcount
d = example.func3(None)
x = d["key"]
assert(4 == getrefcount(x)) # refs: x, d["key"], getrefcount, and one leak
d = None
assert(3 == getrefcount(x)) # refs: x, getrefcount, and one leak
d = example.func4(None)
x = d["key"]
assert(3 == getrefcount(x)) # refs: x, d["key"], and getrefcount
d = None
assert(2 == getrefcount(x)) # refs: x and getrefcount

rawDescription: Returning a dictionary of ndarray causes memory leaks using boost python


code:
from twisted.internet import task
from twisted.internet import reactor

def do_something():
    pass # do your work here

task.LoopingCall(do_something).start(1.0)
reactor.run()

rawDescription: How do I ensure that a Python while-loop takes a particular amount of time to run?

description: Ensure that a Python while-loop takes a particular amount of time to run


code:
def get_year(input_sequence):
    return input_sequence[0]

rawDescription: Why do some Python functions have an extra set of parenthesis around the argument list?


code:
f = open('SNPs.csv')
reader = csv.Reader(f, delimiter=',', quotechar='"')
output = [row for row in reader]
output.sort(key=lambda x: x[3])
return dict((row[0], (row[3], row[4])) for row in output[:10])

rawDescription: Parsing through CSV using DictReader in Python


rawDescription: How to change array layout?

description: Change array layout


code:
food = {"Chicken": "Chicken $4.99", "Beef": "Beef $5.95", "Taco": "Taco $3.50"}
toys = {"Blocks": "Blocks $12.35", "Army men": "Army men $5.99"}
                #Ect.

search = input("Search Here ")
print(search)

if search in food:  #  If the key exists in the dict, print all items
    print (food.items())
elif search in toys:
    print (toys.items())

rawDescription: How can group relations be shown?

description: How can group relations be shown


code:
tokens = output['sentences'][0]['tokens']
tokens

rawDescription: Getting NLTK tree leaf values as a string


code: df

rawDescription: Python - Pandas — How to check which column a DataFrame is grouped by?


code: import my_module

rawDescription: importing multiple functions from a Python module

description: Importing multiple functions from a Python module


code: S = R[0::2] + R[1::2] # three column-wise additions at once

rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


rawDescription: Plotting pandas groupby results

description: Plotting pandas groupby results


code:
d = collections.defaultdict(set)
for k, v in s:
    d[k].add(v) # sets don't have duplicates so we don't need a check here

rawDescription: Python How to find duplicate values in Dictionary


code:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'main.middleware.PrintQueryMiddleware',         # chnage path to your app
)

rawDescription: Get Django User ID Without Request Object Available


code:
import subprocess
cmd = "echo /bin/meteo | at 23:00 today "
subprocess.Popen(cmd, shell=True)

rawDescription: how to integrate "at" command in python

description: Integrate "at" command in python


code:
def get_block_from_file(file_path, block_number):
    with open(file_path) as f:
        data = f.read()

    blocks = data.split('\n\n')
    try:
        block = blocks[block_number - 1]
    except IndexError:
        print('Not enough blocks')
        import sys; sys.exit(1)
    v = []
    lines = block.split('\n')
    for line in lines:
        if line == "":
            continue
        v += [map(int, line.split(' '))]

    return map(list, zip(*v))

print(get_block_from_file('data.txt', 2))

rawDescription: Reading columns between empty lines

description: Reading columns between empty lines


code: convert=true,

rawDescription: python + google drive: upload xlsx, convert to google sheet, get sharable link

description: Python + google drive: upload xlsx, convert to google sheet, get sharable link


code: right_align = ">{}".format(width)

rawDescription: What is the pythonic way to print values right aligned?


code:
parser.add_argument(
    "-option1", type=int, default=1,
    choices=xrange(1, 10), help="option 1 message")

rawDescription: Reading default arguments with argparse

description: Reading default arguments with argparse


code:
def rot_center(image, rect, angle):
    """rotate an image while keeping its center"""
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = rot_image.get_rect(center=rect.center)
    return rot_image,rot_rect

rawDescription: How can i rotate an image from the center rather than the corner in pygame?

description: Rotate an image from the center rather than the corner in pygame


code:
from django.views.generic import ListView

class CategoryView(ListView):
    template_name = 'books/categories/show.html'
    paginate_by = 99

    def get_queryset(self):
        self.category = Category.objects.get(pk=self.kwargs['id'])

        books = Book.objects.filter(
           Q(status = 1) & Q(category=self.category)
        ).order_by('-id')

        self.s = Poet.objects.order_by('?')[:3]

        return books

    def get_context_data(self, **kwargs):
        context = super(CategoryView, self).get_context_data(**kwargs)
        context['category'] = self.category
        context['suggestions'] = self.s
        return context

rawDescription: Switching to class-based list_detail

description: Switching to class-based list_detail


code:
def original_app(mu1,mu2,rays):
    intersections = np.empty((r, 2*n, 3))
    for col in range(n):
        intersections[:, col, :] = rays * mu1[:, col][:, np.newaxis]
        intersections[:, col + n, :] = rays * mu2[:, col][:, np.newaxis]

    distances = np.empty((r, 2 * n))
    for col in range(n):
        distances[:, col] = np.linalg.norm(intersections[:, col], axis=1)
        distances[:, col + n] = np.linalg.norm(intersections[:, col + n], axis=1)
    return distances

def vectorized_app1(mu1,mu2,rays):
    intersections = np.hstack((mu1,mu2))[...,None]*rays[:,None,:]
    return np.sqrt((intersections**2).sum(2))

def vectorized_app2(mu1,mu2,rays):
    intersections = np.hstack((mu1,mu2))[...,None]*rays[:,None,:]
    return np.sqrt(np.einsum('ijk,ijk->ij',intersections,intersections))

def vectorized_app3(mu1,mu2,rays):
    mu = np.hstack((mu1,mu2))
    return np.sqrt(np.einsum('ij,ij,ik,ik->ij',mu,mu,rays,rays))

rawDescription: Avoiding numpy loops while calculating intersections


code:
def print_most_common(words_dict, word_len):
    results = []
    max_frequency = 0
    for word, freq in words_dict.items():
        if len(word) != word_len or freq < max_frequency:
            # wrong length or not frequent enough
            continue
        if freq == max_frequency:
            results.append(word)
        else:
            # right word length and *higher* frequency
            max_frequency = freq
            results = [word]
    print (word_len, "letter words:", results, max_frequency)

rawDescription: Dictionary Issue Python

description: Dictionary Issue Python


rawDescription: Missing source page information using urllib2


code:
with open("data") as f:
    d = {}
    header = None
    for line in f:
        if line.startswith('['):
            header = line.strip()
            d[header] = []
        else:
            d[header].append(line.split())

rawDescription: Grab portions of txt after headings

description: Grab portions of txt after headings


code:
class B(object):
    def __init__(self):
            self.__getitem__ = lambda self,i: 42
B()[0]

rawDescription: Replacing special methods of a Python list object


code:
import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib.request.urlopen(req)

rawDescription: Adding authentication header in python 3


rawDescription: Transform bits into byte series

description: Transform bits into byte series


code:
class ArgParseMixin(AttributeHelperMixin):
  __mainParser = None
  __subParser =  None
  __subParsers = {}

  def __init__(self, **kwargs):
    super().__init__()

    # create a commandline argument parser
    import argparse
    self.__mainParser = argparse.ArgumentParser(**kwargs)
    self.__subParser =  self.__mainParser.add_subparsers(help='sub-command help')

    for funcname,func in self.GetMethods():
      defAttributes = DefaultAttribute.GetAttributes(func)
      if (len(defAttributes) != 0):
        defAttribute = defAttributes[0]
        self.__mainParser.set_defaults(func=defAttribute.Handler)
        continue

      cmdAttributes = CommandAttribute.GetAttributes(func)
      if (len(cmdAttributes) != 0):
        cmdAttribute = cmdAttributes[0]
        subParser = self.__subParser.add_parser(cmdAttribute.Command, **(cmdAttribute.KWArgs))
        subParser.set_defaults(func=cmdAttribute.Handler)

        for argAttribute in ArgumentAttribute.GetAttributes(func):
          subParser.add_argument(*(argAttribute.Args), **(argAttribute.KWArgs))

        self.__subParsers[cmdAttribute.Command] = subParser
        continue

  def Run(self):
    # parse command line options and process splitted arguments in callback functions
    args = self.__mainParser.parse_args()
    # because func is a function (unbound to an object), it MUST be called with self as a first parameter
    args.func(self, args)

  @property
  def MainParser(self):
    return self.__mainParser

  @property
  def SubParsers(self):
    return self.__subParsers

rawDescription: Is it possible to implement .NET-like attributes in Python?


rawDescription: Python 3.41 A set

description: Python 3.41 A set


code:
from matplotlib.figure import Figure

self.__fig = Figure(figsize=(16,11))

rawDescription: Declaration of FigureCanvasTkAgg causes memory leak


code:
file_lines = iter(raw_input, '') # Get lines as input until an empty line.
file_content = '\n'.join(file_lines) # Join the file lines to one string, seperated by new-line.

rawDescription: Writing multiple lines to a textfile by taking input in python?


rawDescription: python 2.7.5+ print list without spaces after the commas

description: Python 2.7.5+ print list without spaces after the commas


rawDescription: Storing Class Arguments in a List

description: Storing Class Arguments in a List


code:
form = response.form
form.set('color', True, 0)
form.set('color', True, 2)

rawDescription: How do I use pylons (paste) webtest with multiple checkboxes with the same name?

description: Use pylons (paste) webtest with multiple checkboxes with the same name


code: cursor.execute(statement, numbers)

rawDescription: Change Series of Numbers to List, python


code: vte_terminal_fork_command_full ()

description: GTK+ Vte.Terminal().fork_command_full removed


code:
from collections.abc import MutableMapping

class PolymorphicDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        self._mapping = dict(*args, **kwargs)

    def __getitem__(self, key):
        for cls in key.__mro__:
            if cls in self._mapping:
                return self._mapping[cls]
        raise KeyError(key)

    def __delitem__(self, key):
        del self._mapping[key]

    def __setitem__(self, key, value):
        self._mapping[key] = value

    def __iter__(self):
        return iter(self._mapping)

    def __len__(self):
        return len(self._mapping)

rawDescription: Polymorphic mapping type

description: Polymorphic mapping type


code:
raw_file = open('some_file.csv')
csv_file = csv.reader(raw_file)
for row in csv_file:
    ...

rawDescription: In a CSV file, how can a Python coder remove all but an X number of duplicates across rows?


code:
import subprocess, pkg_resources
subprocess.call(['easy_install', 'pexpect'])
pkg_resources.get_distribution('pexpect').activate()
import pexpect  # Now works

rawDescription: how to import a python module before installing it?

description: Import a python module before installing it


code: data = [','.join([v['name']]+v['sub']) for v in a.values()]

rawDescription: Exclude repeated values from a dictionary and increment the 'qty' field accordingly


code: b'd'

rawDescription: How to get a single byte in a string of bytes, without converting to int

description: Get a single byte in a string of bytes, without converting to int


code:
def triplets(sequence):
    return zip(sequence, sequence[1:], sequence[2:])

rawDescription: How can you manipulate the iterator in a for loop in python?

description: Manipulate the iterator in a for loop in python


code:
import numpy
x = numpy.array([0,1,2,3,4,5,6,7,8,9,10])
indices = list(range(3))+list(range(-4,0))
y = x[indices]
print(y)

rawDescription: Pythonic way of slicing out part of a numpy array


code:
False
True
True

rawDescription: Method to convert object from class to subclass in Python


rawDescription: Determine a,b,c of quadratic equation using data points


code: [ [['O','O'] for _ in range(10)] for x in range(1, 11) ]

rawDescription: 2D Python list will have random results

description: 2D Python list will have random results


rawDescription: why is mimetypes.guess_type('a.json') not working in centos 7

description: Why is mimetypes.guess_type('a.json') not working in centos 7


code:
a = b = []
a.append(1)
a
b

rawDescription: Easiest way to initialize a large number of variables


code: linenos = (self.linenos and 'table') or False

rawDescription: Weird variable setting in python

description: Weird variable setting in python


code: dis.dis(lambda x:x)

rawDescription: Does Python optimize lambda x: x

description: Does Python optimize lambda x: x


code:
import cProfile

def fib(num):
    if num < 3:
        return max(num, 1)
    return fib(num - 1) + fib(num - 2)

fibdict = {0:1, 1:1, 2:2}
def fibber(num):
    if num not in fibdict:
        n = fibber(num - 1) + fibber(num - 2)
        fibdict[num] = n
    return fibdict[num]

a = [fib(i) for i in range(30)]
b = [fibber(i) for i in range(25000)]

rawDescription: Options to profile server side execution times in python code


code:
class App:
    def __init__(self, master):
        self.e1 = Entry(master)
        self.e1.grid(row=1, column=0, sticky=N)
        Button(master, text="Start", command=self.OnButtonClick).grid(row=4, column=0)

rawDescription: How to get Tkinter entry?

description: Get Tkinter entry


code:
l = []
def func(s):
    for i in range(1, 100):
        p = i * 2 + s * 2
        yield p

l.append(list(func(10))) # Need to convert the generator to a list here.
# In this case a simple "l = list(func(10))" would be easier if you don't need to append.

rawDescription: How can I use a 'for' loop for just one variable in a function which depends on two variables?

description: Use a 'for' loop for just one variable in a function which depends on two variables


code:
dm = np.abs(np.diff(f['mz']))
pos = np.flatnonzero(np.r_[True, dm > 2])

totals = np.add.reduceat(f['mz']*f['I'], pos)
counts = np.add.reduceat(f['I'], pos)
result = totals / counts

rawDescription: Numpy: Efficient access to sub-arrays generated by numpy.split


rawDescription: Splitting texts python

description: Splitting texts python


code:
class Item(models.Model):
    parent = models.ForeignKey('self', related_name='children', null=True, blank=True)

rawDescription: Django related key of the same model

description: Django related key of the same model


code:
import posixpath
import urlparse

path = urlparse.urlsplit(URL).path
filename = posixpath.basename(path)

rawDescription: python httplib/urllib get filename

description: Python httplib/urllib get filename


code: print [x.mean() - 3 * x.std(), x.mean() + 3 * x.std()]

rawDescription: Calculate the 3rd standard deviation for an array


code:
setb = set(B)
[x for x in A if not x in setb]

rawDescription: Efficient Compare of two LIST of Lists in Python


code: is_command, word = lookup[1]   # is_command = True, word = "@command"

rawDescription: hmm, lists, tuples, arrays, sets or dicts for this data structure?

description: Hmm, lists, tuples, arrays, sets or dicts for this data structure


code:
    # Problems: (1) style to be used should be existing style of
    # the top-left cell, not an arg.
    # (2) should ensure that any previous data value in
    # non-top-left cells is nobbled.
    # Note: if a cell is set by a data record then later
    # is referenced by a [MUL]BLANK record, Excel will blank
    # out the cell on the screen, but OOo & Gnu will not
    # blank it out. Need to do something better than writing
    # multiple records. In the meantime, avoid this method and use
    # write_merge() instead.

rawDescription: How to write a cell with multiple columns in xlwt?

description: Write a cell with multiple columns in xlwt


code:
def OldClsName(*args, **kwargs):
    from warnings import warn
    warn("get with the program!")
    return NewClsName(*args, **kwargs)

rawDescription: How to warn about class (name) deprecation

description: Warn about class (name) deprecation


rawDescription: Commutative combination of elements of two lists


rawDescription: nltk word pair count using fdist

description: Nltk word pair count using fdist


code:
import csv

with open("database.txt", "r", newline="") as csvfile:
    csvreader = csv.reader(csvfile, delimiter='\t')
    print("Last Name \t Hours \t Wages")
    for row in csvreader:
        print('{}\t{}$\t{}'.format(row[0], row[2], float(row[1])*float(row[2])))

rawDescription: Python: Need to get the product of two columns on each line of a text file


code:
from django.db import connection, transaction
cursor = connection.cursor()

# Data modifying operation - commit required
cursor.execute("vacuum my_table")
transaction.commit_unless_managed()

rawDescription: sqlite vacuum with django

description: Sqlite vacuum with django


code:
from collections import defaultdict

dict1 = defaultdict(int)
# read csv values into dict1
for row in reader:
    dict1[(row[0], row[1])] += int(row[5])

print(dict(dict1))

rawDescription: Python combine overlapping time ranges in csv file


code:
import timeit
timeit.timeit(lambda: [p[:2] for p in (i.partition('.suffix') for i in l)])
timeit.timeit(lambda: [patt.match(i).groups() for i in l])

rawDescription: Python Regex: How to match filenames with optional suffix? Why '(.*?)(\.suffix)?' doesn't work?


rawDescription: Converting columns in a file into separate lists using python


code: 'My name is %(name)s, I am %(age)s years old' % {'name':'John','age':98}

rawDescription: String formatting options: pros and cons


rawDescription: What does pythonapi.PyObject_GC_UnTrack return?


code:
# create a list proxy and append a mutable object (a dictionary)
lproxy = manager.list()
lproxy.append({})
# now mutate the dictionary
d = lproxy[0]
d['a'] = 1
d['b'] = 2
# at this point, the changes to d are not yet synced, but by
# reassigning the dictionary, the proxy is notified of the change
lproxy[0] = d

rawDescription: Python: Using a multidimensional multiprocessing.manager.list()


code:
def merge_dols(dol1, dol2):
  keys = set(dol1).union(dol2)
  no = []
  return dict((k, dol1.get(k, no) + dol2.get(k, no)) for k in keys)

rawDescription: Combining Dictionaries Of Lists In Python


code:
name
clean_compare
for i in name:
    print(i, i in clean_compare)

rawDescription: Searching lists and comparing with another not exact list


code:
def countWords ( textFileName ):
    """

    :param textFileName:
    :return:
    """
    with open(textFileName) as f:
        texts = f.read()
        previous = False
        wordCount = 0
        for text in texts:
            print(text)
            if text == " ":
                previous = False
            elif text == "\n":
                previous = False
            elif text == "\t":
                previous = False
            else:
                if previous == False:
                    wordCount += 1
                previous = True
        print(wordCount)

rawDescription: Counting words in a text file via python


rawDescription: What is the most efficient way to move/rename a node in NetworkX?


rawDescription: Click event is sent immediately after I start application (PySide and Python)


code: [x for x in itertools.combinations([123,345,543,234],3)]

rawDescription: processing row combinations from a array and output in multiple arrays

description: Processing row combinations from a array and output in multiple arrays


code:
onegram_sim = 0.43
twogram_sim = 0.36
threegram_sim = 0.29
fourgram_sim = 0.29
all_sim = sum([onegram_sim, twogram_sim, threegram_sim, fourgram_sim]) / 4
all_sim
all_sim = sum(map(lambda x: x**2, [onegram_sim, twogram_sim, threegram_sim, fourgram_sim])) / 4
all_sim
from operator import mul
onetofour_sim = [onegram_sim, twogram_sim, threegram_sim, fourgram_sim]
reduce(mul, onetofour_sim, 1)

rawDescription: Normalize ranking score with weights

description: Normalize ranking score with weights


code:
# removal of columns in matrix by recreating it

matrixK = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]

matrixK = [[row[i] for i in range(len(row)) if i % 2] for row in matrixK]

print('matrixK after: {}'.format(matrixK))

rawDescription: Delete columns from matrix according to its index


code:
def sgn_pbc(x, y, Lbox):
    d = abs(x-y)
    if d <= Lbox/2.:
        return (y < x) - (x < y)
    else:
        return (x < y) - (y < x)

rawDescription: efficient sign function in python for case of periodic boundary conditions

description: Efficient sign function in python for case of periodic boundary conditions


code:
from myapp.models.meta import Base
Base.metadata.create_all(bind=engine)

rawDescription: How do I split models.py into different files for different models in Pyramid?

description: Split models.py into different files for different models in Pyramid


code:
master_list = [
    'There are many types of intrusion detection devices in production today.',
    'The CTO approved a rewrite of the system',
    'The CTO is about to approve a complete rewrite of the system',
    'The CTO approved a rewriting',
    'Breaching of Firewalls'
]

terms = [
    'Intrusion Detection',
    'Approved rewrite',
    'Firewall'
]

stemmer = PorterStemmer()

# for each term, split it into words (could be just one word) and stem each word
stemmed_terms = ((stemmer.stem(word) for word in s.split()) for s in terms)

# add 'match anything after it' expression to each of the stemmed words
# join result into a pattern string
regex_patterns = [''.join(stem + '.*' for stem in term) for term in stemmed_terms]
print(regex_patterns)
print('')

for sentence in master_list:
    match_obs = (re.search(pattern, sentence, flags=re.IGNORECASE) for pattern in regex_patterns)
    matches = [m.group(0) for m in match_obs if m]
    print(matches)

rawDescription: Best way to match a large list against strings in python

description: Match a large list against strings in python


code:
df.apply(lambda row: (row['bar']*2 if row['foo'] == 'a' else row['xyz']), axis=1)
df['xyz'] = df.apply(lambda row: (row['bar']*2 if row['foo'] == 'a' else row['xyz']), axis=1)
df

rawDescription: Assign to selection in pandas

description: Assign to selection in pandas


rawDescription: Is this the correct way to save a pointer to an upper layer object in Python?


rawDescription: Generate all possible permutations of subsets containing all the element of a set


code: regex.sub('', output)[:-1]

rawDescription: Unicode - Just print the string

description: Unicode - Just print the string


code:
import pandas as pd

df = pd.read_csv("in.csv", delimiter="\s+")

df['e'] = df.applymap(lambda x: str(x).isdigit()).T.all().astype(int)

rawDescription: Regular expression in python 2.7 to identify any non numeric symbol in a column in dataframe


code: SupplyAndDemandModel.S1Vals = []

rawDescription: Python 2.7: Function accessing a list

description: Python 2.7: Function accessing a list


code:
df.iloc[0]
df.iloc[1]

rawDescription: How can we change data type of a dataframe row in pandas?


code:
im.size()    #width and height, (400,600)
im.size[0]   #width, 400
im.size[1]   #height, 600

rawDescription: Getting Width and Height of an Inputted Picture in Python


code:
class FormFactory(object):

    def __init__(self, localizer):
        self.localizer = localizer
        _ = self.localizer
        self.required_msg = _(u'This field is required.')
        self.invalid_email_msg = _(u'Invalid email address.')
        self.password_not_match_msg = _(u'Password must match')

    def make_contact_form(self):
        _ = self.localizer
        class ContactForm(Form):
            email = TextField(_(u'Email address'), [
                validators.Required(self.required_msg),
                validators.Email(self.invalid_email_msg)
            ])
            content = TextAreaField(_(u'Content'), [
                validators.Required(self.required_msg)
            ])
        return ContactForm

rawDescription: How to use Pyramid i18n outside of views and templates?

description: Use Pyramid i18n outside of views and templates


code:
class main1:
    def __init__(self, master):
        # ...
        self.cont = Button(frame,text="Menu option 1", command=self.open_main2).grid(row=1)
    def open_main2(self):
        prac2_link.main2()

rawDescription: Python GUI - Linking one GUI in a class to another class


code: cline = ClustalwCommandline("clustalw", infile=pathToFile)

rawDescription: File management

description: File management


rawDescription: Invoking Jython from Python (or Vice Versa)


rawDescription: Importing UDP Multicast signal into Python


code:
def threaded():
    import time
    while True:
        time.sleep(1)
        loop.call_soon_threadsafe(queue.put_nowait, time.time())
        loop.call_soon_threadsafe(lambda: print(queue.qsize()))

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


code:
import csv
with open("test.txt") as f,open("out.txt","w")as out:
    wr = csv.writer(out)
    for line in f:
        if "Get location" in line:
            data = line.rsplit(None,1)[1]
            wr.writerow(data.strip("()", 2).split(",")[:2])

rawDescription: Python - extracting particular numbers from each line in a file


code:
def f(z,a):
    return z*a

view.map(f, allzeniths, allazimuths)

rawDescription: Parallelise nested for-loop in IPython

description: Parallelise nested for-loop in IPython


code:
now2=dt.datetime(2010,11,12,12,0,0)

def timestamp(date):
    return time.mktime(date.timetuple())

print(timestamp(now2)-timestamp(now))
# 15890.0

rawDescription: Datetime to Second Conversion

description: Datetime to Second Conversion


code:
def rgen (n):
    for elem in list:
        for times in xrange(n):
            yield elem

rawDescription: How to yield element multiple times

description: Yield element multiple times


code: unique_words = set(page.split())

rawDescription: Complex Python List Comprehension

description: Complex Python List Comprehension


code:
for item in reversed(myNumbers):
    print(item)

rawDescription: I am having trouble with a Python list display using "in range"


code:
import os
load(os.path.expanduser('~/path/to/car.jpg')) # relative to user's home directory

rawDescription: importing a JPEG image into an IPython (notebook) program

description: Importing a JPEG image into an IPython (notebook) program


code:
import timeit
timeit.timeit('inplace_add', 'from __main__ import inplace_add', number=10000000)
timeit.timeit('add_and_assign', 'from __main__ import add_and_assign', number=10000000)

rawDescription: Will a+=1 be faster than a = a+1 in Python?


rawDescription: Search Index for user articles

description: Search Index for user articles


code: y = np.sum(x) - x.size * x

rawDescription: Iterate on an array with two implicit loops


rawDescription: Python HDF5 Sparse Out of Core Datasets

description: Python HDF5 Sparse Out of Core Datasets


code:
def input_generator(return_value):
    def input():
        return return_value
    return input

rawDescription: Read values from another cell in IPython Notebook and supply them for "input()"


code:
bluetoothAccept
bluetoothActiveConnections
bluetoothConnect
bluetoothDiscoveryCancel
bluetoothDiscoveryStart
bluetoothGetConnectedDeviceName
bluetoothGetLocalAddress
bluetoothGetLocalName
bluetoothGetRemoteDeviceName
bluetoothGetScanMode
bluetoothIsDiscovering
bluetoothMakeDiscoverable
bluetoothRead
bluetoothReadBinary
bluetoothReadLine
bluetoothReadReady
bluetoothSetLocalName
bluetoothStop
bluetoothWrite
bluetoothWriteBinary
checkBluetoothState
toggleBluetoothState

rawDescription: Using SL4A (Python) and bluetooth

description: Using SL4A (Python) and bluetooth


code: cls = reg.get_class("baz")

rawDescription: Dynamic module import of class list from module given its full path


rawDescription: Why is numpy slower than python? How to make code perform better


code:
data = list(power_set(l))
data.sort()
data

rawDescription: Creating dictionary dynamically in Python


code:
#!/usr/bin/env python
import xml.etree.cElementTree as etree

tree = etree.parse("input.xml")
for field in tree.iterfind('.//Fields/FieldArray/Field'):
    name, alias = [field.find(tag) for tag in ['Name', 'AliasName']]
    if name is None or alias is None:
       continue # skip if either <Name> or <AliasName> are not found
    alias.text = name.text # set <AliasName> text to be the same as <Name>

tree.write('output.xml', encoding='utf-8')

rawDescription: Replace multiple texts with their corresponding texts in XML using Python


code: x, y, z, _, _, _ = odeint(deriv, u0, t).T

rawDescription: plotting orbital trajectories in python

description: Plotting orbital trajectories in python


code:
chunksize = 1024
for c in range(0,len(bytes),chunksize):
   data = [chr(int(x, base=2)) for x in bytes[c:c+chunksize]]
   output.write(''.join(data))

rawDescription: What is the most efficient way to write in binary output in python?


code:
import datetime
from pytz import UTC

dt = datetime.datetime.now()  # just some date
tz_aware_dt = dt.replace(tzinfo=UTC)

rawDescription: How to store a naive datetime in Django 1.4

description: Store a naive datetime in Django 1.4


rawDescription: Querying portal_catalog using typed uuids instead of string uuids


code:
filehandler = TruncatedFileHandler("app.log", "w", 1000)
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.DEBUG, handlers=[filehandler])

logger = logging.getLogger('spam_application')

for i in range(100):
    logger.debug("a log line, number: %s", i)

rawDescription: Limit Python log file

description: Limit Python log file


code:
from datetime import datetime
from time import strptime
dt = datetime(*strptime(s, "%d/%m/%Y-%H:%M:%S")[0:6])

rawDescription: Django - String to Date - Date to UNIX Timestamp


code:
df = pd.DataFrame.from_dict(d, orient='index').stack().reset_index(1, drop=True).to_frame().reset_index()
df.columns = ['name', 'link']

rawDescription: Reorder a dictionary to fit a data frame


code:
process = subprocess.Popen(['/usr/local/bin/tesseract', path, 'outfile', '-l', 'rus'],
                           stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

rawDescription: How to add options to python subprocess

description: Add options to python subprocess


code:
def to_list(text):
    parsed = ast.literal_eval(text)
    if isinstance(parsed, basestring):
        return [parsed]
    return list(parsed)

from_to = {frm: to_list(to) for frm, to in re.findall('^var ([A-Z]{3})_Destinations.*?\((.*?)\)', text, flags=re.M)}
# {'BHX': ['ORK', 'DUB', 'SNN'], 'ABZ': ['DUB']}

rawDescription: Regex to return 2 groups

description: Regex to return 2 groups


code:
from itertools import groupby

paragraphs = (list(g) for empty, g in groupby(txt, lambda l: not len(l)) if not empty)

rawDescription: Grouping strings by paragraph

description: Grouping strings by paragraph


code:
import multiprocessing
import time

def readSerial(d):
    d["test"] = []
    for i in range(100):
        l = d["test"]
        l.append(i)
        d["test"] = l
        time.sleep(1)

def doGUI(d):
    while True:
        print(d)
        time.sleep(.5)

if __name__ == '__main__':
    with multiprocessing.Manager() as manager:
        sd = manager.dict()

        p = multiprocessing.Process(target=readSerial, args=(sd,))
        p.start()

        doGUI(sd)

rawDescription: How can I share an updated values in dictionary among different process?

description: Share an updated values in dictionary among different process


code: sys.path.insert(0, '/data-py/modules')

rawDescription: python + from <module> + how from - import know the PATH

description: Python + from <module> + how from - import know the PATH


code:
import yaml

with open('points.yml', 'r') as f:
     doc = yaml.load(f)

print([tuple(x) for x in doc['type']['points']])

rawDescription: Store and retreive coordinates using python and yaml


code:
from django.db import models
from django.conf import settings
from django.utils.hashcompat import md5_constructor

from openid.store.interface import OpenIDStore
import openid.store
from openid.association import Association as OIDAssociation
import time, base64

from myapp.common.db.accounts.models import Association, Nonce

class DjangoOpenIDStore(OpenIDStore):
    """
The Python openid library needs an OpenIDStore subclass to persist data
related to OpenID authentications. This one uses our Django models.
"""

    def storeAssociation(self, server_url, association):
        assoc = Association(
            server_url = server_url,
            handle = association.handle,
            secret = base64.encodestring(association.secret),
            issued = association.issued,
            lifetime = association.issued,
            assoc_type = association.assoc_type
        )
        assoc.save()

    def getAssociation(self, server_url, handle=None):
        assocs = []
        if handle is not None:
            assocs = Association.objects.filter(
                server_url = server_url, handle = handle
            )
        else:
            assocs = Association.objects.filter(
                server_url = server_url
            )
        if not assocs:
            return None
        associations = []
        for assoc in assocs:
            association = OIDAssociation(
                assoc.handle, base64.decodestring(assoc.secret), assoc.issued,
                assoc.lifetime, assoc.assoc_type
            )
            if association.getExpiresIn() == 0:
                self.removeAssociation(server_url, assoc.handle)
            else:
                associations.append((association.issued, association))
        if not associations:
            return None
        return associations[-1][1]

    def removeAssociation(self, server_url, handle):
        assocs = list(Association.objects.filter(
            server_url = server_url, handle = handle
        ))
        assocs_exist = len(assocs) > 0
        for assoc in assocs:
            assoc.delete()
        return assocs_exist

    def useNonce(self, server_url, timestamp, salt):
        # Has nonce expired?
        if abs(timestamp - time.time()) > openid.store.nonce.SKEW:
            return False
        try:
            nonce = Nonce.objects.get(
                server_url__exact = server_url,
                timestamp__exact = timestamp,
                salt__exact = salt
            )
        except Nonce.DoesNotExist:
            nonce = Nonce.objects.create(
                server_url = server_url,
                timestamp = timestamp,
                salt = salt
            )
            return True
        nonce.delete()
        return False

    def cleanupNonce(self):
        Nonce.objects.filter(
            timestamp__lt = (int(time.time()) - nonce.SKEW)
        ).delete()

    def cleaupAssociations(self):
        Association.objects.extra(
            where=['issued + lifetimeint < (%s)' % time.time()]
        ).delete()

    def getAuthKey(self):
        # Use first AUTH_KEY_LEN characters of md5 hash of SECRET_KEY
        return md5_constructor.new(settings.SECRET_KEY).hexdigest()[:self.AUTH_KEY_LEN]

    def isDumb(self):
        return False

rawDescription: Django + Google Federated Login

description: Django + Google Federated Login


rawDescription: Create multi-level index pandas dataframe from delimited string column


code:
from blist import blist

b = blist(["a", "b", "c", "e"])
insort(b, "f")
insort(b, "d")
print(b)
blist(['a', 'b', 'c', 'd', 'e', 'f'])

rawDescription: Python - efficiently find where something would land in a sorted list?


code: replacement = replacement.replace("\\", "\\\\")

rawDescription: Python re.sub: ignore backreferences in the replacement string


code:
@functools.total_ordering
class multiNode:
    def __init__(self, keyValue):
        self.__key = keyValue
    def setKey(self, keyValue):
        self.__key = keyValue
    def getKey(self):
        return self.__key
    def __eq__(self, other):
        if not isinstance(other, multiNode):
            return NotImplemented
        return self.__key == other.__key
    def __lt__(self, other):
        if not isinstance(other, multiNode):
            return NotImplemented
        return self.__key < other.__key

rawDescription: Python heapify by some attribute, reheapify after attribute changes


code:
import datetime
datetime.time.min
datetime.time.max

rawDescription: How to get the first and last second in python using datetime module

description: Get the first and last second in python using datetime module


code:
for name in tree.iter('name'):
    if name.text.lower() == nome.lower():
        c = Context({'id' : name.text})
        r1 = HttpResponse(t.render(c), mimetype='application/xml')
        return r1
 # move return indentation to match here, i.e after the for loop completes

rawDescription: if statement in django

description: If statement in django


code:
#!/usr/bin/python
"""Read cobol file and print all possible redefines."""
import sys
from itertools import product

def readfile(fname):
    """Read cobol file & return a master list of lines and namecount of redefined lines."""
    master = []
    namecount = {}
    with open(fname) as f:
        for line in f:
            line = line.rstrip(' .\t\n')
            if not line:
                continue
            words = line.split()
            n = int(words[0])
            if '=' in words or 'REDEFINES' in words:
                name = words[3]
            else:
                name = words[1]
            master.append((n, name, line))
            namecount[name] = namecount.get(name, 0) + 1
    # py2.7: namecount = {key: val for key, val in namecount.items() if val > 1}
    namecount = dict((key, val) for key, val in namecount.items() if val > 1)

    return master, namecount

def compute(master, skip=None):
    """Return new cobol file given master and skip parameters."""
    if skip is None:
        skip = {}
    seen = {}
    skip_to = None
    output = ''
    for n, name, line in master:
        if skip_to and n > skip_to:
            continue
        seen[name] = seen.get(name, 0) + 1
        if seen[name] != skip.get(name, 1):
            skip_to = n
            continue
        skip_to = None
        output += line + '\n'
    return output

def find_all(master, namecount):
    """Return list of all possible output files given master and namecount."""
    keys = namecount.keys()
    values = [namecount[k] for k in keys]
    out = []
    for combo in product(*[range(1, v + 1) for v in values]):
        skip = dict(zip(keys, combo))
        new = compute(master, skip=skip)
        if new not in out:
            out.append(new)
    return out

def main(argv):
    """Process command line arguments and print results."""
    fname = argv[-1]
    master, namecount = readfile(fname)
    out = find_all(master, namecount)
    print('\n'.join(out))

if __name__ == '__main__':
    main(sys.argv)

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

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


code:
from nltk import bigrams
bigrams('This is a test')

rawDescription: Can't Import Bigrams From NLTK Library

description: Can't Import Bigrams From NLTK Library


code:
import re

splitter = re.compile('[A-Z]+(?![a-z])|[A-Z]?[a-z]+|[^A-Za-z \t\r\n]+').findall
fix_tweet = lambda t: ' '.join(splitter(t))

rawDescription: Finding and combining acronyms in Python


code:
class Callable(type):
    def __call__(self, *args, **kw):
        return self._call(*args, **kw)

class yourfunc(object):
    __metaclass__ = Callable

    _numer_of_times = 0

    @classmethod
    def _call(cls, x, y):
        for i in range(x):
            for j in range(y):
                cls._number_of_time += 1

rawDescription: Static variable in python?

description: Static variable in python


code:
def get_dval(dict_, *args):
    try:
        for idx in args:
            dict_ = dict_[idx]
    except:
        return False

    return dict_

rawDescription: a python function that returns the value of a dictionary

description: A python function that returns the value of a dictionary


code:
application/api/resource.py
from application import db
...
db.doWhatEverYouWant()
...

rawDescription: Getting the database connection from application context with Flask-Restful


code:
def user(values=[1,2]):
    int_fields = (("first_16", c_int, 16),("second_16", c_int, 16)) # this is just an example to illustrate your class definition. int fields can be generated dynamically.
    int_class = int_factory(int_fields)
    int_obj = int_class(values[0], values[1])
    return int_obj

rawDescription: Setting _fields_ dynamically in ctypes.Structure


rawDescription: Python: add value and write output

description: Python: add value and write output


code:
from pypeg2 import *

class BooleanLiteral(Keyword):
    # Need to alter keyword regex to allow for quoted literal keywords
    K.regex=re.compile(r'"*\w+"*')
    grammar = Enum(K('OR'), K('AND'),K(r'"OR"'), K(r'"AND"'))

class LineFilter(Namespace):
    grammar = flag('inverted', "-"), name(), ":", attr('value', word)

class StringLiteral(str):
     quoted_string = re.compile(r'"[^"]*"')
     grammar = [word, quoted_string]

class LineExpression(List):
    grammar = maybe_some([(LineFilter,BooleanLiteral),
                          (StringLiteral,BooleanLiteral),
                          LineFilter,
                          StringLiteral])

test_string = ('filter34:43 "My oh my!!" Hello OR '
               'filter32:3232 "AND" "Goodbye cruel world"')

k = parse(test_string,LineExpression)

print('Input:')
print(test_string)
print('Parsed output:')
print('==============')
for component in k:
    print(component,type(component))

rawDescription: pypeg2 - can this expression be parsed using peg grammar?

description: Pypeg2 - can this expression be parsed using peg grammar


code:
from datetime import datetime
from time import strptime

rawDescription: Python get start and end date of the week


code:
{'preposition': '', 'amount': '1', 'name': 'banana', 'unit': ''}
{'preposition': 'of', 'amount': '100', 'name': 'sugar', 'unit': 'g'}
{'preposition': 'of', 'amount': '1', 'name': 'flour', 'unit': 'cup'}

rawDescription: A regular expression using a list of words


rawDescription: pygame circle not changing

description: Pygame circle not changing


code:
def lcount(keyword, fname):
    with open(fname, 'r') as fin:
        return sum([1 for line in fin if keyword in line])

rawDescription: Python - Search for Word In Line, Count it, Add It


code:
{'    lo': {'recv_bytes': '7056295',
            'recv_compressed': '0',
            'recv_drop': '0',
            'recv_errs': '0',
            'recv_fifo': '0',
            'recv_frame': '0',
            'recv_multicast': '0',
            'recv_packets': '12148',
            'trans_bytes': '7056295',
            'trans_carrier': '0',
            'trans_colls': '0',
            'trans_compressed': '0',
            'trans_drop': '0',
            'trans_errs': '0',
            'trans_fifo': '0',
            'trans_packets': '12148'},
 '  eth0': {'recv_bytes': '34084530',
            'recv_compressed': '0',
            'recv_drop': '0',
            'recv_errs': '0',
            'recv_fifo': '0',
            'recv_frame': '0',
            'recv_multicast': '0',
            'recv_packets': '30599',
            'trans_bytes': '6170441',
            'trans_carrier': '0',
            'trans_colls': '0',
            'trans_compressed': '0',
            'trans_drop': '0',
            'trans_errs': '0',
            'trans_fifo': '0',
            'trans_packets': '32377'}}

rawDescription: How can I parse the output of /proc/net/dev into key:value pairs per interface using Python?

description: Parse the output of /proc/net/dev into key:value pairs per interface using Python


code: any(word in string for word in lst)

rawDescription: Determining if a query is in a string

description: Determining if a query is in a string


code:
# check if string A ends with string B
def endswith(A, B):
   return A.endswith(B)

# check if string A equals to string B
def stringsequal(A, B):
   return A == B

rawDescription: Dropdown box representing a method call on a string


code: divisibleBySeven = [num for num in inputList if meetsCondition(num)]

rawDescription: Return Subset of List that Matches Condition