code:
class LevelFormatter(logging.Formatter):
    def __init__(self, fmt=None, datefmt=None, level_fmts={}):
        self._level_formatters = {}
        for level, format in level_fmts.items():
            # Could optionally support level names too
            self._level_formatters[level] = Formatter(fmt=format, datefmt=datefmt)
        # self._fmt will be the default format
        super(LevelFormatter, self).__init__(fmt=fmt, datefmt=datefmt)

    def format(self, record):
        if record.levelno in self._level_formatters:
            return self._level_formatters[record.levelno].format(record)

        return super(LevelFormatter, self).format(record)

rawDescription: python logging: Different formatters for the same log file

description: Python logging: Different formatters for the same log file


rawDescription: DataFrame.index.levels shows "extra" values after paring down dataframe


code:
#define AF_INET         2       /* Internet IP Protocol         */
#define AF_INET6        10      /* IP version 6                 */
#define AF_PACKET       17      /* Packet family                */

rawDescription: Python, How to get all external ip addresses with multiple NICs


code:
class LineTerminatorTranslator(object):
    def __init__(self, orig, terminator, buffer=2048):
        self._orig = orig
        self._terminator = terminator
        self._buffer = buffer

    def __iter__(self):
        terminator = self._terminator
        buffer = ''

        if hasattr(self._orig, 'read'):
            # read in chunks, rather than in lines, where possible
            iterator = iter(lambda: self._orig.read(self._buffer), '')
        else:
            iterator = iter(self._orig)

        while True:
            try:
                while terminator not in buffer:
                    buffer += next(iterator)
            except StopIteration:
                # done, yield remainder
                yield buffer
                return
            entries, _, buffer = buffer.rpartition(terminator)
            for entry in entries.split(terminator):
                yield entry

rawDescription: can I use the csv module when the end of record marker is not a new line?

description: Use the csv module when the end of record marker is not a new line


code:
class DelayComponents(object):
    '''
    Delay Components Class
    '''

    ATTRS = ['prop_delay', 'trans_delay', 'proc_delay', 'queue_delay']

    def __init__(self, **delays):
        '''
        Constructor
        '''
        for attr in self.ATTRS:
            setattr(self, attr, round(float(delays.get(attr, 0)), 2))

    @property
    def delay(self):
        return sum(getattr(self, attr, 0) for attr in self.ATTRS)

rawDescription: Building variable dependencies

description: Building variable dependencies


code:
a_list = ['mood1', 'mood2', 'mood3', 'dep1', 'dep2', 'dep3']
b_list = ['pre', '6month']
result = ['{}_{}'.format(a, b) for b in b_list for a in a_list]
result

rawDescription: Python: How do I add a suffix to the end of each list element?


code:
# The diamond size
l = 9

# Initialize first row; this will create a list with a
# single element, the first row containing a single star
rows = ['*']

# Add half of the rows; we loop over the odd numbers from
# 1 to l, and then append a star followed by `i` spaces and
# again a star. Note that range will not include `l` itself.
for i in range(1, l, 2):
    rows.append('*' + ' ' * i + '*')

# Mirror the rows and append; we get all but the last row
# (the middle row) from the list, and inverse it (using
# `[::-1]`) and add that to the original list. Now we have
# all the rows we need. Print it to see what's inside.
rows += rows[:-1][::-1]

# center-align each row, and join them
# We first define a function that does nothing else than
# centering whatever it gets to `l` characters. This will
# add the spaces we need around the stars
align = lambda x: ('{:^%s}' % l).format(x)

# And then we apply that function to all rows using `map`
# and then join the rows by a line break.
diamond = '\n'.join(map(align, rows))

# and print
print(diamond)

rawDescription: Hollow Diamond in python

description: Hollow Diamond in python


code: df = pd.concat([esh[esh.index < roll_date], esm[esm.index >= roll_date]])

rawDescription: Build Back Adjusted Continous Futures contract from Historical Data


code:
[
    ['35104', 'Angelica Alvarado\n669 66th St.\nSpringfield, OR 97478\n5412322525', 'JJ-CribSheet-Cheetah-PK-PRT', 'Cheetah Pink Print Microsuede Crib Sheet', '1']
]

rawDescription: How to extract information from text using regexes in Python?

description: Extract information from text using regexes in Python


code:
def create_dict_from_variables(first_name, second_name):
    return something_from(first_name, second_name)

rawDescription: create dictionary from list of variables

description: Create dictionary from list of variables


code:
from collections import Counter
def mode_function2(lst):
    counter = Counter(lst)
    _,val = counter.most_common(1)[0]
    return [x for x,y in counter.items() if y == val]

rawDescription: Finding multiple modes in a tuple list - python


code:
def show_loading(parent, title, message=None, maximum=100):
    if not message:
        message = title

    # A class for the return value.
    class LoadingObject(object):
        def __init__(self, dialog):
            self.dialog = dialog
            self.is_done = False

        def done(self):
            if not self.is_done:
                self.dialog.Destroy()
                self.is_done = True

        def pulse(self, message):
            self.dialog.Pulse(message)

        def progress(self, current, message=None):
            # Don't allow the progress to reach 100%, since it will freeze the
            # dialog.
            if current >= maximum:
                current = current - 1

            if message is not None:
                self.dialog.Update(current, message)
            else:
                self.dialog.Update(current)

    # Create the progress dialog.
    dlg_style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME
    dlg = wx.ProgressDialog(
        title, message, parent=parent, style=dlg_style, maximum=maximum
    )
    dlg.Pulse()

    # Wait just a little bit to allow the progress dialog to initialize.
    wx.MilliSleep(50)

    # Return an instance of the LoadingDialog with the progress dialog attached.
    return LoadingObject(dlg)

rawDescription: How can I get the ProgressDialog to close before I open my MessageBox?

description: Get the ProgressDialog to close before I open my MessageBox


rawDescription: How to get turtle graphics to not show turtle while its being drawn?

description: Get turtle graphics to not show turtle while its being drawn


code:
# Disable weak or insecure ciphers by default
# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
# Enable a better set of ciphers by default
# This list has been explicitly chosen to:
#   * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
#   * Prefer ECDHE over DHE for better performance
#   * Prefer any AES-GCM over any AES-CBC for better performance and security
#   * Then Use HIGH cipher suites as a fallback
#   * Then Use 3DES as fallback which is secure but slow
#   * Disable NULL authentication, NULL encryption, and MD5 MACs for security
#     reasons
_DEFAULT_CIPHERS = (
    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
    '!eNULL:!MD5'
)

rawDescription: python ssl ssl.SSLError: [SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:590)

description: Python ssl ssl.SSLError: [SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:590)


code:
resp = ul.urlopen(url).read()
type(resp)

rawDescription: writing persian text into a text file in the way which could be read in python

description: Writing persian text into a text file in the way which could be read in python


rawDescription: Square detection with aberrations in edges and 1 missing corner


code: averages = [float(sum(values)) / len(values) for key, values in pairs]

rawDescription: python: access multiple values in the value portion of a key:value pair

description: Python: access multiple values in the value portion of a key:value pair


code:
def application(environ, start_response):
    start_response('200 OK', [
        ('Content-Type', 'text/html')
    ])
    return ['Hello World']

if __name__ == '__main__':
    logger = logging_middleware(application)
    from wsgiref.simple_server import make_server
    httpd = make_server('', 1234, logger)
    httpd.serve_forever()

rawDescription: Debug/Monitor middleware for python wsgi applications


code:
dateTime = QLineEdit();
dateTime.setValidator(QRegExpValidator(QRegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")));
myTableWidget.setCellWidget(row, column, dateTime);

rawDescription: How to set the column text format of QTableWidget?

description: Set the column text format of QTableWidget


code: (int(x) if x else 0)

rawDescription: How to replace empty string with zero in comma-separated string?

description: Replace empty string with zero in comma-separated string


code:
df
df.sort(["quarter", "week"])

rawDescription: Sorting rows in csv file using Python Pandas


code:
rutils = importr("utils")
rgraphics = importr('graphics')

rawDescription: QGIS: How to run R directly in python console?


code:
from itertools import chain, combinations
def partition(iterable):
    n = len(input_list)
    b, mid, e = [0], list(range(1, n)), [n]
    getslice = input_list.__getitem__
    splits = (d for i in range(n) for d in combinations(mid, i))
    return [[input_list[sl] for sl in map(slice, chain(b, d), chain(d, e))]
            for d in splits]

rawDescription: Python - get all in order splits of a string


rawDescription: How to identify approximately (threshold defined) continuous non null data using pandas?

description: Identify approximately (threshold defined) continuous non null data using pandas


code:
THRESHOLD = 0.01

from scipy.interpolate.interpnd import _ndim_coords_from_arrays
from scipy.spatial import cKDTree

# Construct kd-tree, functionality copied from scipy.interpolate
tree = cKDTree(xy)
xi = _ndim_coords_from_arrays(tuple(grid), ndim=xy.shape[1])
dists, indexes = tree.query(xi)

# Copy original result but mask missing values with NaNs
result3 = result2[:]
result3[dists > THRESHOLD] = np.nan

# Show
plt.figimage(result3)
plt.show()

rawDescription: How to set a maximum distance between points for interpolation when using scipy.interpolate.griddata?

description: Set a maximum distance between points for interpolation when using scipy.interpolate.griddata


code:
def upload(self, q):
    for payload in iter(q.get, None):  # Keep getting from the queue until a None is found
        filePath, params, destUrl = payload
        # do stuff

def write_pdf(pdf_file_info, q):
   # write a pdf to disk here
   q.put((filepath, params, destUrl))  # Send work to the uploader
   # Move on with whatever comes next.

if __name__ == '__main__':
    pdf_queue = multiprocessing.Queue()

    # Start uploader
    upload_proc = multiprocessing.Process(upload, args=(pdf_queue,))
    upload_proc.start()

    # Start pdf writers
    procs = []
    for pdf in pdfs_to_write:
         p = multiprocessing.Process(write_pdf, args=(pdf, pdf_queue))
         p.start()
         p.append(procs)

    # Wait for pdf writers and uploader to finish.
    for p in procs:
        p.join()
    pdf_queue.put(None) # Sending None breaks the for loop inside upload
    upload_proc.join()

rawDescription: Properly Designing a Multiprocessing.Manager Custom Object


code: my_bool = '01'[my_boolean]

rawDescription: Is multiple type-casting in python bad?

description: Is multiple type-casting in python bad


code:
class ATimesTwo(A):
    @A.foo.setter
    def foo(self, val):
        self._foo = val * 2

rawDescription: Overriding properties in python

description: Overriding properties in python


code:
url = 'http://www.astro.keele.ac.uk/jkt/debcat/'
df = pd.read_html(url, header=0)
df1 = df[1]
df1.head()

rawDescription: Cleaning HTML tables with Pandas

description: Cleaning HTML tables with Pandas


code:
def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    pass

rawDescription: Python call __init__() method only one time


code:
('cat', 'dog')
('cat', 'fish')
('cat', 'rabbit')
('cat', 'horse')
('cat', 'bird')
('cat', 'frog')
('cat', 'mouse')
('dog', 'fish')
('dog', 'rabbit')
('dog', 'horse')
('dog', 'bird')
('dog', 'frog')
('dog', 'mouse')
('fish', 'rabbit')
('fish', 'horse')
('fish', 'bird')
('fish', 'frog')
('fish', 'mouse')
('rabbit', 'horse')
('rabbit', 'bird')
('rabbit', 'frog')
('rabbit', 'mouse')
('horse', 'bird')
('horse', 'frog')
('horse', 'mouse')
('bird', 'frog')
('bird', 'mouse')
('frog', 'mouse')

rawDescription: getting every possible combination in a list

description: Getting every possible combination in a list


code:
contents = [
'01/01/2015 7:30:10 a.m. Tag off : 16 Address Ave     $1.00   $26.00',
'01/01/2015 7:40:17 a.m. Tag on : 127 Address St           $27']
print_durations(calculate_durations(contents))

rawDescription: Python putting certain texts into a dictionary from a large string


rawDescription: Why does Python remove the last character of a string?


rawDescription: PHP to python pack('H')

description: PHP to python pack('H')


rawDescription: Python memory usage: Which of my objects is hogging the most memory?


code:
df = pd.DataFrame()
chunksize = 10**5

for t in pd.read_csv(filename, usecols=['A','B'], chunksize=chunksize):
    df = pd.concat([df, t.drop_duplicates()], ignore_index=True).drop_duplicates()

print(df.groupby(['A'])['B'].nunique())

rawDescription: Counting unique rows in each group after group by using read_csv with chunk


rawDescription: Find index of last true value in pandas Series or DataFrame


code:
unsorted = [[1, 0], [2, 0], [3, 0], [4, 2], [5, 2], [6, 5], [7, 6], [8,0]]
sortList = []
sortDict = {}

for x in unsorted:
    if x[1] != 0:
        if x[1] in sortDict:
            sortDict[x[1]].append(x[0])
        else:
            sortDict[x[1]] = [x[0]]

for x in unsorted:
    if x[1] == 0:
        sortList.append(x)
    if x[0] in sortDict:
        sortList.extend([[y, x[0]] for y in sortDict[x[0]]])

print(sortList)

rawDescription: Python sorting a list of pairs

description: Python sorting a list of pairs


code:
with open ('c:\\temp\\input_file') as fi, open('c:\\temp\\output_file', 'w') as fo:
    fo.write('\n'.join(reversed(fi.read().splitlines())))

rawDescription: Python 3 Writing Input file in reverse order to output file


rawDescription: Context dependent split of a string in python


code:
cmds.button(label = 'enable the float field', command = partial(enableFloatField, my_float_field))
cmds.button(label = 'disable the float field', command = partial(disableFloatField, my_float_field))

rawDescription: enable or disable a field in maya ui with python

description: Enable or disable a field in maya ui with python


code: line = [int(num) for num in line]

rawDescription: Class and Array Problems

description: Class and Array Problems


rawDescription: How to bypass base-8 number identification in python?

description: Bypass base-8 number identification in python


rawDescription: Calculating the difference in dates in a Pandas GroupBy object


rawDescription: How to handle multiple user type in Django

description: Handle multiple user type in Django


code:
def __init__( self, value, parent= None, children= None ):
    if children is None: children= []

rawDescription: recursively editing member variable: All instances have same value

description: Recursively editing member variable: All instances have same value


code: return {x: doc[x] * log(len(_corpus) / dic[x]) for x in doc}

rawDescription: Implementation of TFIDF weighting scheme


code: flights = dict((f.pop('flight_id'), f) for f in flights)

rawDescription: How do I use a dictionary value as a key name in another dictionary?

description: Use a dictionary value as a key name in another dictionary


rawDescription: What's the most Pythonic XHTML/HTML parser/generator/template module that supports DOM like access?


rawDescription: Converting irregularly time stamped measurements into equally spaced, time-weighted averages


code:
seen = set()
seen.add([1,2])
seen.add(tuple([1,2]))

rawDescription: Remove Duplicates in two-dimensional array while maintaining sequence


code: re.sub(r'\b[^aeoui]*', '', inputstring, flags=re.I)

rawDescription: python Using Regular Expression to find letters in a string

description: Python Using Regular Expression to find letters in a string


code:
def group_by_start(inputlist, n):
    return [res[0] if len(res) == 1 else res for k, g in groupby(inputlist, key=itemgetter(slice(n))) for res in (list(g),)]

rawDescription: Python. How to make list from another list by mark?


code:
cities = []
while True:
    city = raw_input("Enter a city you've been to (or press enter to exit): ")
    if city == '':  # no input -- this is your sentinel
        break  # leave the loop
    else:
        cities.append(city)

rawDescription: How to index a user input list in Python 2.x?

description: Index a user input list in Python 2.x


code:
from distutils.core import setup,Extension
from distutils.cygwinccompiler import Mingw32CCompiler
from pprint import pprint

module1 = Extension('demo', sources = ['demo.c'])

m32 = Mingw32CCompiler()
pprint (vars(m32))

setup (name = 'PackageName',
   version = '1.0',
   description = 'This is a demo package',
   ext_modules = [module1])

rawDescription: Get the commands distutils passes to the compiler


rawDescription: Dividing an Dataframe by an measure with overlapping indexes results in NAN


code: counts = Counter(tuple(item[1:]) for item in lst)

rawDescription: Append feature frequency to existing list


code:
def palindromic_substrings(s):
    if not s:
        return [[]]
    results = []
    for i in range(len(s), 0, -1):
        sub = s[:i]
        if sub == sub[::-1]:
            for rest in palindromic_substrings(s[i:]):
                results.append([sub] + rest)
    return results

rawDescription: Find all combinations of palindromic substrings


code:
s = 'string with %%substring1%% and %%substring2%%'
import re
re.findall('(%%.*?%%)', s, re.DOTALL)

rawDescription: How to make Python's findall regular expression method inclusive

description: Make Python's findall regular expression method inclusive


code:
paths = {
    'video': '/home/dbs/public_html/download/codex/codex.html',
    'audio': '/home/dbs/public_html/download/audio/audio_player.html',
    'visual': '/home/dbs/public_html/download/visual/visual.html'
}

files += [path for key, path in paths.iteritems() if key in mylist]

rawDescription: Python "and if" equivalent

description: Python "and if" equivalent


code:
import re
line = '/path/including whitespace/to/file.cpp function_name 1234 <any_content>'
r = re.match(r'(?P<File>.+?\.cpp) (?P<Function>\w+) (?P<Linenum>[0-9]+) (?P<Content>.*)$', line)
r.groupdict()
r.groups()

rawDescription: regular expression for tokenizing a white-space-delimitated string

description: Regular expression for tokenizing a white-space-delimitated string


code: print(all(validations.get(k, lambda x: False)(v) for (k, v) in d.items()))

rawDescription: Python: Validating each values in dictionary


code:
def show_only_some(x, pos):
    s = str(int(x))
    if s[0] in ('2','5'):
        return s
    return ''

ax.xaxis.set_minor_formatter(plt.FuncFormatter(show_only_some))

rawDescription: Matplotlib so log axis only has minor tick mark labels at specified points. Also change size of tick labels in colorbar


code:
import os, subprocess

os.environ['ATESTVARIABLE'] = 'value'
value = subprocess.check_output('echo $ATESTVARIABLE', shell=True)
assert 'value' in value

rawDescription: How to control process environment variable in Python?

description: Control process environment variable in Python


code:
class MM(MutableMapping):
  __delitem__, __getitem__, __iter__, __len__, __setitem__ = (None,) *5
  __slots__ = ()
MM().__dict__

rawDescription: How would I implement a dict with Abstract Base Classes in Python?


code:
dictOne = dict(arrayOne)
dictTwo = dict(arrayTwo)

rawDescription: Merging 2d arrays

description: Merging 2d arrays


code: ir.py -h

rawDescription: Argparse mutally exclusive by subgrouping


code:
foo, rest = re.split(r"\s{2,}",  line, 1)
bar = re.search(r"[^\\]*\.(?:php|html?)\b", rest).group(0)

rawDescription: String parsing in Python, regular expression?


code:
loader = GdkPixbuf.PixbufLoader.new_with_type('pnm')
loader.write(contents)
pixbuf = loader.get_pixbuf()
loader.close()

rawDescription: Displaying an image with Pygobject and Python 3 from in-memory data


code:
def MyFunc():
    l1 = ['my', 'first', 'list']
    l2 = ['another', 'list']
    return l1, l2

main_list, second_list = MyFunc()

print(main_list)
print(second_list)

rawDescription: items not appending to list, or list returning as empty in python?

description: Items not appending to list, or list returning as empty in python


code:
# validation starts here
validation = browser.find_element_by_xpath("//*[@id='action-select-all']/span/span").text
if validation != "Select All (1)": # or anything that is a falsy validation
    browser.find_element_by_xpath("//*[@id='content-column']/div[4]/form/div[1]/span/span[1]").click()
    continue
# validation finish here

rawDescription: Insert a new action only if the loop restart because of the while


code:
def get_position(sensor):
    try:
        return sensor.geolocate()
    except AttributeError:
        return None

rawDescription: Discussion of multiple inheritance vs Composition for a project (+other things)


code:
from collections import OrderedDict as OD
attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))

rawDescription: Reverse AND inverse python3.x OrderedDict efficiently


code:
import itertools
l = [['a','b', 'c'], 'd','e', ['f', 'g']]
for index, value in enumerate(itertools.chain.from_iterable(l), 1):
    print(index, value)

rawDescription: Python: print list of list in a specified format


code:
df2 = df2.set_index(['Region', 'Branch'])
df2 = df2.stack()
df2 = df2.reset_index(name = 'Count')

df2 = df2.rename(columns={'level_2':'Master Product Name'})

rawDescription: Python Code for Merging Two Spreadsheets that is similar to the "Index-Match-Match" function in Excel


code:
from bisect import bisect
import re

with open("test.txt") as f:
    r = re.compile("(\d+)")
    for line in f:
        a, b = line.lstrip("0123456789. ").split(">> ")
        a_keys = [int(i.group()) for i in r.finditer(a)]
        b_keys =  [int(i.group()) for i in r.finditer(b)]
        a = a.strip("()\n").split(",")
        b = b.strip("()\n").split(",")
        for ele, s in zip(a, a_keys):
            ind = bisect(b_keys, s, hi=len(b) - 1)
            print("{} -> {}".format(ele, b[ind]))

rawDescription: Combine words with nearest index

description: Combine words with nearest index


rawDescription: Plot specific column after DataFrame aggregation


code:
for filename in os.listdir('.'):
    if any(fnmatch.fnmatch(filename, pattern)
           for pattern in ['buffer*', 'grid*', 'OSMroads*',
                           'newCostSurface*','standsLine*', 'standsReprojected*']):
        os.remove(filename)

rawDescription: Delete files with different names in Python


code: integral = np.trapz(ft[105:121])

rawDescription: Calculating Area Under Individual Peaks in Python After FFT


code:
df[df.Cost_Type == 1]
df[df.Cost_Type == 1].groupby("Factory")["Cost"].sum()

rawDescription: Python - sumif from csv

description: Python - sumif from csv


code:
def checkQuarter(self):
    self.quarterIndex = 0
    index = None
    for i in xrange(4):
        if self.quarterMins[i] > 0:
            index = i
            break
    if index is None:
        return False
    self.quarterIndex = index
    self.playerMins = -4 + index

rawDescription: How would you code this? Should I use a loop or keep it how I have it coded?


rawDescription: Python Error with producing key of max of mins


code: if obj2 is not obj: raise PicklingError(...)

rawDescription: Python multiprocessing Pool Interaction With Namespace At Creation


code:
a='
My example text
'
file=open("a.html","w")
file.write(a+'\n')
file.close

rawDescription: How to print a python variable with a html content as a 'page' in terminal?

description: Print a python variable with a html content as a 'page' in terminal


code:
while True:
    time.sleep(5)
    print_time()

rawDescription: run python scheduler continuously

description: Run python scheduler continuously


code:
schema = Schema({'ID': Use(int, error='ID should be an int'),
                 'FILE': Or(None, Use(open, error='FILE should be readable')),
                 object: object})

rawDescription: docopt + schema validation

description: Docopt + schema validation


code:
search =DBSession.query(
    func.count(ExtendedCDR.uniqueid).label("CallCount"),
    func.sum(ExtendedCDR.duration).label("TotalSeconds"),
    ExtendedCDR,ExtensionMap)
search = search.filter(or_(
    ExtensionMap.exten == ExtendedCDR.extension,
    ExtensionMap.prev_exten == ExtendedCDR.extension))
search = search.filter(between(ExtendedCDR.start, datebegin, dateend))
search = search.filter(ExtendedCDR.extension.in_(SelectedExtension))
search = search.group_by(ExtendedCDR.extension)
search = search.order_by(func.count(ExtendedCDR.uniqueid).desc())

rawDescription: Can I dynamically change order_by attributes in my query call?

description: Dynamically change order_by attributes in my query call


code: INIT = open(os.path.join(HERE, '{0}.py'.format(PACKAGE_NAME))).read()

rawDescription: setuptools dependency and import issue

description: Setuptools dependency and import issue


code:
[dict(contact, phoneNumbers=[
    dict(phone_dict, phone=phone_dict['phone'].replace('-', ''))
    for phone_dict in contact['phoneNumbers']])
 for contact in list_of_dicts]

rawDescription: Updating a value in a dictionary inside a dictionary


code: tree = ET.parse(pathToFile, OrderedXMLTreeBuilder())

rawDescription: Can ElementTree be told to preserve the order of attributes?


code:
s2 = re.compile("^DATA_ARRAY (.*?};)", re.DOTALL|re.MULTILINE)
result = re.sub(s2, "DATA_ARRAY newData", inputData)

rawDescription: Replace with re.sub AFTER matching pattern


code: draw.arc((startx,starty, endx,endy), startangle, endangle)

rawDescription: How to output unicode characters and lines into an image file? -python

description: Output unicode characters and lines into an image file? -python


code:
import curses

# Thanks, http://www.ipsum-generator.com
ipsum = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer
nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla
quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent
mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum
lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent
per conubia nostra, per inceptos himenaeos.'''

try:
    # Standard startup. Probably don't need to change this
    stdscr = curses.initscr()
    curses.cbreak()
    curses.noecho()
    stdscr.keypad(1)

    # Silly program to write to the screen,
    # wait for either <ENTER> or <Q>.
    # On <ENTER>, mess with the screen.
    # On <Q>, exit.
    stdscr.addstr(0, 0, ipsum)
    stdscr.move(0, 0)
    stdscr.refresh()
    i = 0
    j = 0

    while 1:
        c = stdscr.getch()
        if c == ord('q'):
            exit(0)
        if c == curses.KEY_ENTER or c == 10 or c == 13:
            i += 1
            if i % 3 == 0:
                stdscr.addstr(0, 0, ipsum.lower())
            if i % 3 == 1:
                stdscr.addstr(0, 0, ipsum.upper())
            if i % 3 == 2:
                stdscr.addstr(0, 0, ipsum)
            stdscr.move(0, 0)
        if c == curses.KEY_DOWN:
            y, x = stdscr.getyx()
            maxy, maxx = stdscr.getmaxyx()
            stdscr.move((y+1) % maxy, x)
        stdscr.refresh()

finally:
    # Standard shutdown. Probably don't need to change this.
    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()

rawDescription: Interpreting "ENTER" keypress in stdscr (curses module in Python)


code: invalidChars = set(string.punctuation.replace("_", ""))

rawDescription: How to check a string for a special character?

description: Check a string for a special character


rawDescription: Django: Change URL's keyword argument on current language


code:
import subprocess
process = subprocess.Popen(['your_command', 'arg1', 'arg2'])

rawDescription: How to generate Wireshark/tcpdump traces

description: Generate Wireshark/tcpdump traces


code:
try:
    output = subprocess.check_output(['find','.','-name','__main__.py'])
except subprocess.CalledProcessError:
    output = '' # fallback output

rawDescription: How do i get list of subdirectories contains specific file (ie. '__main__.py) using Python

description: Get list of subdirectories contains specific file (ie. '__main__.py) using Python


rawDescription: Python Challenge #2 Elimination

description: Python Challenge #2 Elimination


code:
request = Request(
            url="http://www.exito.com/products/0000293501259261/Arroz+Fortificado?cid=&page=",
            cookies={'selectedCity': 'AR'}
          )

rawDescription: Scrapy -- scrappy not returning information from a html tag


rawDescription: JSON output from Google Drive admin SDK activity.list()


code: [s.strip() for s in data_string.splitlines()]

rawDescription: String split on new line, tab and some number of spaces


rawDescription: Python pandas dataframe - any way to set frequency programmatically?


code:
class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile
        self.xml1 = self.extract_xml_from_zip("xml1")
        self.xml2 = self.extract_xml_from_zip("xml2")

    def extract_xml_from_zip(self,this_xml):
        # extract the request xml file from the zip_file in self.xzipfile
        return result

    def do_stuff(self):
        ...

rawDescription: Can I add methods into def __init__?

description: Add methods into def __init__


code:
json.dumps(object, sort_keys=True,indent=4, separators=(',', ': '),
           default=lambda o: {'machines' if k == '_machines' else k: v for k, v in o.__dict__.iteritems()})

rawDescription: json.dump object rename attribute before the dump

description: Json.dump object rename attribute before the dump


rawDescription: Can anyone provide a more pythonic way of generating the morris sequence?


code:
for i in range(0, len(a)-50000):
    current = current - a[i] + a[i+50000]

rawDescription: Python sum of N consecutive digits of a large number


code:
a_dict = {}
a_dict["set"] = {"1"} # creates a set and assign it to a_dict["set"]
type(a_dict["set"])
a_dict["string"] = "1" # Here a string value is assigned to a_dict["string"]
type(a_dict["string"])
int(a_dict["string"])
int(a_dict["set"])

rawDescription: Converting dictionary value to integer

description: Converting dictionary value to integer


rawDescription: Automatically truncate numpy arrays

description: Automatically truncate numpy arrays


code: start = end

rawDescription: Python: Range() as a dictionary value

description: Python: Range() as a dictionary value


code: bl = MyArray(bl)

rawDescription: In python 3, how can I convert a function into an attribute


code:
def SingletonClass(cls):
    class Single(cls):
        __doc__ = cls.__doc__
        _initialized = False
        _instance = None

        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
            return cls._instance

        def __init__(self, *args, **kwargs):
            if self._initialized:
                return
            super(Single, self).__init__(*args, **kwargs)
            self.__class__._initialized = True  # Its crucial to set this variable on the class!
    return Single

rawDescription: Python conditional object instantiation

description: Python conditional object instantiation


code:
import itertools

for combo in itertools.combinations(range(1,10), 6):
    print(" ".join(str(c) for c in combo))

rawDescription: All 6-Number Permutations from a List

description: All 6-Number Permutations from a List


code:
class HelloClass(object):
    def print_label(self, parent):
        self.la = QtGui.QLabel("hello", parent)
        self.la.move(300, 100)
        self.la.show()

class DataClass(QtGui.QMainWindow):
    def __init__(self):
        super(DataClass, self).__init__()
        self.window()

    def window(self):
        ex = label.HelloClass()
        ex.print_label(self)

rawDescription: Creating widgets in a different class

description: Creating widgets in a different class


code:
pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
stride=1.1
[pies[x] for x in range(len(pies)) for x in [int(round(x*stride))] if x < len(pies)]

rawDescription: Python Array Index - Every X elements?

description: Python Array Index - Every X elements


rawDescription: Interpolate (or extrapolate) only small gaps in pandas dataframe


rawDescription: python select range from list of list

description: Python select range from list of list


code:
for i, s in enumerate(my_list): # work through items in list with index
    if s.endswith("%s"): # find an item to update
        my_list[i] = s % xyz.pop(0) # update with first item popped from xyz

rawDescription: append/insert a value/string to a list element dynamically in Python?

description: Append/insert a value/string to a list element dynamically in Python


code:
data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)

rawDescription: What is the proper way to format a multi-line dict in Python?


code:
class MyClass():
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        if not isinstance(other, MyClass):
            return NotImplemented
        return self.number == other.number

rawDescription: Is Python Object Instance a unique object in the language?


rawDescription: How can one configure flask to be accessible via public IP interface?


rawDescription: How can I have references of lists in Python

description: Have references of lists in Python


code:
s = ', '.join(a)
s
s.split(', ')

rawDescription: Convert a list of elements in a string

description: Convert a list of elements in a string


rawDescription: Numpy masked array modification

description: Numpy masked array modification


code:
import sys
import inspect
import collections
_stdout = sys.stdout

Record = collections.namedtuple(
    'Record',
    'frame filename line_number function_name lines index')

class MyStream(object):
    def __init__(self, target):
        self.target = target
    def write(self, text):
        if text.strip():
            record = Record(*inspect.getouterframes(inspect.currentframe())[1])
            self.target.write(
                '{f} {n}: '.format(f = record.filename, n = record.line_number))
        self.target.write(text)

sys.stdout = MyStream(sys.stdout)

def foo():
    print('Hi')

foo()

rawDescription: How do you find where a print statement is located?

description: Find where a print statement is located


code:
import csv

def read_csv(fobj):
    reader = csv.DictReader(fobj, delimiter=',')
    return {line['ID']: line['COUNT'] for line in reader}

with open('csv1.csv') as csv1, open('csv2.csv') as csv2, \
     open('csv3.csv') as csv3, open('out.csv', 'w') as out:
    data = [read_csv(fobj) for fobj in [csv1, csv2, csv3]]
    all_keys = sorted(set(data[0]).union(data[1]).union(data[2]))
    out.write('ID COUNT COUNT COUNT\n')
    for key in all_keys:
        counts = (entry.get(key, '') for entry in data)
        out.write('{}, {}, {}, {}\n'.format(key, *tuple(counts)))

rawDescription: Merge three csv files with same headers in Python


code:
l2norm = np.sqrt((X * X).sum(axis=1))
X / l2norm.reshape(5,1)
np.sqrt((_ * _).sum(axis=1))

rawDescription: Normalizing rows of a matrix python

description: Normalizing rows of a matrix python


code:
class Route(models.Model):
    #bunch of stuff
    pass
class Stop(models.Model):
    #bunch of stuff
    stop_times = models.ManyToManyField(through=StopTime)
class StopTime(models.Model):
    trip = models.ForeignKey(Trip)
    stop = models.ForeignKey(Stop)
    # bunch of additional meta about this M2M table
    pass
class Trip(models.Model):
    route = models.ForeignKey(Route)
    # bunch of stuff

rawDescription: How can I do this complex SQL query using Django ORM? (sub-query with a join)

description: Do this complex SQL query using Django ORM? (sub-query with a join)


code:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', transparent=True)

rawDescription: How to set opacity of background colour of graph wit Matplotlib

description: Set opacity of background colour of graph wit Matplotlib


rawDescription: Recursively getting all nested elements from a Dictionary


code: myPanel = wx.Panel(self, -1,style=wx.SIMPLE_BORDER)

rawDescription: Disablling scrolling of a scroll bar while keeping it visible in wxPython


code:
child_obj = Child()
bound_child_method = child_obj.child_method

rawDescription: [Python]Calling method(self)

description: [Python]Calling method(self)


rawDescription: Multiprocess tasks in python that can't be pickled?


rawDescription: csv parsing and manipulation using python

description: Csv parsing and manipulation using python


rawDescription: python substitute a substring with one character less

description: Python substitute a substring with one character less


rawDescription: Return DataFrame item using partial string match on rows pandas python


rawDescription: Create ASCII table from given list - Python


code: [('Folder1/Folder2\\ItemA', ['ItemA\\x.py']), ('Folder1/Folder2\\ItemB', ['ItemB\\y.py']), ('Folder1/Folder2\\ItemC', ['ItemC\\z.py']), ('Folder1/Folder2', ['Master.foo'])]

rawDescription: How to deploy to a new directory structure with setuptools

description: Deploy to a new directory structure with setuptools


code: [(a[i], a[i+1]) for i in range(0,len(a)-1,2) if a[i+1].startswith('$')]

rawDescription: From array create tuples on if condition python


code:
def main():
    side = 80
    n = int(input("How many lanes do would you want?\n"))

    race = turtle.Turtle()
    for cnt in range(n+1):
        race.forward(side)
        race.circle(side,180)
        race.forward(side)
        race.circle(side,180)
        side = side = side + 20
        race.penup() #Inside for loop.
        race.right(90)
        race.forward(20) #I think it should be 20...
        race.right(-90)
        race.backward(10)
        race.pendown()

main()

rawDescription: python use turtle draw a track n field race track

description: Python use turtle draw a track n field race track


code: x = [lambda: x for x in range(3)]

rawDescription: `x = [lambda: x for x in range(3)]`, what will `x[0]()` return?


code:
df = pd.read_csv(file, header=None, index_col='datetime',
                 parse_dates={'datetime': [1,2,3,4]},
                 date_parser=lambda x: pd.datetime.strptime(x, '%Y %m %d %H'))

rawDescription: Parse dates when year month day and hour are in separate columns using pandas in python


code: return [sublist for sublist in lst if all(item % 2 == 0 for item in sublist)]

rawDescription: Python - return the list of lists in lst that contain only integers?


code:
from snippets.models import Article
from snippets.serializers import ArticleSerializer
from rest_framework import generics

class ArticleList(generics.ListCreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

rawDescription: Django REST Framework: difference between views and viewsets?


rawDescription: compressing a string in C# and uncompressing in python

description: Compressing a string in C# and uncompressing in python


code: del fields[3], fields[4], fields[6]

rawDescription: removing blank lines python

description: Removing blank lines python


rawDescription: Compare list with multiple values

description: Compare list with multiple values


code:
count = {1: 1}

def recur(n):
    if n not in count:  # memoize
        count[n] = 1 + recur(n//2 if n % 2 == 0 else 3*n + 1)
    return count[n]

rawDescription: Longest Collatz Sequence- Memoization- Python- Iterative vs Recursive


rawDescription: Finding the intersection between two series in Pandas


rawDescription: Python: 3D list, sum columns

description: Python: 3D list, sum columns


code:
import unittest

class MyTestCase(unittest.TestCase):
    def test_one(self):
        print("One")
    def test_two(self):
        print("Two")

suite = unittest.TestSuite([MyTestCase('test_one'), MyTestCase('test_two')])

suite.run(unittest.TestResult())

rawDescription: Is it unconventional to override unittest.TestCase's init in Python


code: prjs = [e for e, in row]

rawDescription: Setting CheckListBox From MySQL Query

description: Setting CheckListBox From MySQL Query


code: drive_usage = drive_usage.split()

rawDescription: String in a list doesn't accept assignment


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

# OS Imports
import json

# Local Imports
from app import sockets
from app.functions import get_cpu_load, get_disk_usage, get_vmem

@sockets.route('/_socket_system')
def socket_system(ws):
    """
    Returns the system informations, JSON Format
    CPU, RAM, and Disk Usage
    """
    while True:
        message = ws.receive()
        if message == "update":
            cpu = round(get_cpu_load())
            ram = round(get_vmem())
            disk = round(get_disk_usage())
            ws.send(json.dumps(dict(received=message, cpu=cpu, ram=ram, disk=disk)))
        else:
            ws.send(json.dumps(dict(received=message)))

rawDescription: Flask : How to update and render a variable periodically?


rawDescription: Print out the whole directory tree

description: Print out the whole directory tree


code:
c = 0.1
pos = 100
myzeros=scipy.zeros((c*pos,c*pos))
myzeros1D = myzeros.ravel()
grid=scipy.ones((pos,pos))
grid1D = grid.ravel()
dist=sc.random.permutation(pos*pos)[:c*pos*c*pos]
grid1D[dist]=myzeros1D
myzeros = myzeros1D.reshape((c*pos,c*pos))
grid = grid1D.reshape((pos, pos))

rawDescription: scipy -- how to insert an array of zeros into another array with different dimensions

description: Scipy -- how to insert an array of zeros into another array with different dimensions


code:
from bs4 import BeautifulSoup, Tag
import requests

url = "http://www.presidency.ucsb.edu/ws/index.php?pid=111500"
response = requests.get(url)

soup = BeautifulSoup(response.content, "html5lib")
transcript = soup.find("span", class_="displaytext")
for item in transcript.find_all("b")[3:]:  # skipping first irrelevant parts
    part = [" ".join(sibling.get_text(strip=True) if isinstance(sibling, Tag) else sibling.strip()
                     for sibling in item.next_siblings)]
    for paragraph in item.parent.find_next_siblings("p"):
        if paragraph.b:
            break

        part.append(paragraph.get_text(strip=True))

    print(item.get_text(strip=True))
    print("\n".join(part))
    print("-----")

rawDescription: Pull text between two BeautifulSoup elements


rawDescription: Get argument names of callable objects in the way they are called


rawDescription: Webscraping with Xpath in Python

description: Webscraping with Xpath in Python


code: rect = image[i:i+h, j:j+w]

rawDescription: How to find mean value for a given part of an Image

description: Find mean value for a given part of an Image


hello: world

rawDescription: How do you read in a text (.txt) file as a .py file in Python 2.7?

description: Read in a text (.txt) file as a .py file in Python 2.7


code:
numpy.savetxt('outfile.txt', numpy.column_stack([
    array1.view(float).reshape(-1, 2),
    array2.view(float).reshape(-1, 2),
]))

array1, array2 = numpy.loadtxt('outfile.txt', unpack=True).view(complex)

rawDescription: How to save and load an array of complex numbers using numpy.savetxt?

description: Save and load an array of complex numbers using numpy.savetxt


code:
s = ('this string is soooo'
     'ooo loooong')

rawDescription: Line breaks in code within print statement causing spaces in values printed to screen


code:
stop = 5
urlcols = ["C","D","E","F","G"]
# Here i'm using an apply() to call the google search for each 'row'
# and a list is built for the urls return by search()
df[urlcols] = df["B"].apply(lambda fruit : pd.Series([url for url in
              search(fruit, stop=stop, pause=2.0)][:stop])) #get 5 by slicing

rawDescription: Pandas: Iterate on a column one row at a time to automate a google search?


code:
import re
info = ''' # return here
xxxxxxxx                            # return here
xxxx                                # return here
xxxxxx   target'''
re.findall(r'<a href="(.*?)".+?(.*?)', info, re.DOTALL)

rawDescription: I use regular expression to extract info from a web page in python, but fail when I meet "return"?


code: df['quarters'] = df.Date1.dt.quarter

rawDescription: Divide entire DataFrame based on dates in specific columns into quarterly dataframes


rawDescription: Can I create function using 'function' class?

description: Create function using 'function' class


code:
import pandas.rpy.common as rcom
rcom.convert_robj(pr)

rawDescription: Rpy2 and Pandas: join output from predict to pandas dataframe


code:
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans

#read data into pandas dataframe
df = pd.read_csv('household_power_consumption.txt', delimiter=';')

rawDescription: Sklearn.KMeans() : Get class centroid labels and reference to a dataset


code:
rankdata([0,1,1,2])
rankdata([0,1,1,2], method='min')
rankdata([0,1,1,2], method='dense')

rawDescription: Ranking a List of Numbers

description: Ranking a List of Numbers


code:
class Blah(object):
    ABC, DEF = range(2)

rawDescription: Using class attribute in method definition as argument?


Why does 9007199254740993 != 9007199254740993.0


code:
import pandas as pd
url = "http://biodev.extra.cea.fr/interoporc/files/study4932/srcInteractionsUsed.txt"
i1, i2 = 'ProteinAcA', 'ProteinAcB'
df1 = pd.read_table(url)  #1470 x 7 rows
df2 = df1.ix[:10].copy(deep=True) #11 x 7 rows
df2[i1] = df1.ix[:10][i2]
df2[i2] = df1.ix[:10][i1]
df2.index = range(1481,1492)
df = pd.concat([df1, df2]) #1481 x 7 rows
filter = df[df[i1] > df[i2]].select(lambda x: (
                           (df[i2] == df[i1].loc[x]) &
                           (df[i1] == df[i2].loc[x])).any() )

rawDescription: Pandas: filtering for unique strings in 2 columns


code:
name1 = os.path.basename(os.path.splitext('/tmp/helpers_image.tif')[0])
name2 = os.path.basename(os.path.splitext('/tmp/outputs/helpers_image.qml')[0])

rawDescription: Compare two filenames in different folders


code:
color_map = numpy.ndarray(shape=(256*256*256), dtype='int32')
color_map[:] = -1
for rgb, idx in color_codes.items():
    rgb = rgb[0] * 65536 + rgb[1] * 256 + rgb[2]
    color_map[rgb] = idx

def img_array_to_single_val(image, color_map):
    image = image.dot(numpy.array([65536, 256, 1], dtype='int32'))
    return color_map[image]

rawDescription: Replacing RGB values in numpy array by integer is extremely slow


code:
from rest_framework.response import Response
from rest_framework.utils.urls import replace_query_param

class CustomCoursePaginator(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        return Response({'count': self.page.paginator.count,
                         'next': self.get_next_link(),
                         'previous': self.get_previous_link(),
                         'courses': data})

    def get_next_link(self):
        if not self.page.has_next():
            return None
        page_number = self.page.next_page_number()
        return replace_query_param('', self.page_query_param, page_number)

    def get_previous_link(self):
        if not self.page.has_previous():
            return None
        page_number = self.page.previous_page_number()
        return replace_query_param('', self.page_query_param, page_number)

rawDescription: Django Rest Framework 3.1 breaks pagination.PaginationSerializer


code: import cv2

rawDescription: How to add the OpenCV library to my Python library?

description: Add the OpenCV library to my Python library


code:
def get_dictionary_word_list():
    # with context manager assures us the
    # file will be closed when leaving the scope
    with open('dictionary.txt') as f:
        for line in f.read().splitlines():
            # yield a tuple (key, value)
            yield tuple(line.split())

rawDescription: How to return a list of words from a text file in python

description: Return a list of words from a text file in python


code:
from wand.image import Image

with Image(filename=source_file, resolution=(RESOLUTION, RESOLUTION)) as img:
    pass

rawDescription: Wand + ImageMagick + Anaconda: "'wand' has no attribute 'image'"


rawDescription: How can I filter a Haystack SearchQuerySet for None on an IntegerField

description: Filter a Haystack SearchQuerySet for None on an IntegerField


code: sum(c1 != c2 for c1,c2 in zip(w1,w2))

rawDescription: Comparing two strings in python?

description: Comparing two strings in python


code:
df.loc[testdate,:] = pd.Series(list(adddata.values()), adddata.keys(), dtype='object')
df.dtypes

rawDescription: replacing a pandas dataframe row overwrites all columns' dtypes

description: Replacing a pandas dataframe row overwrites all columns' dtypes


code:
colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])

rawDescription: pandas plot dataframe barplot with colors by category

description: Pandas plot dataframe barplot with colors by category


code:
lines = []
while True:
    user_input = raw_input()
    if user_input.strip() == "": # empty line signals stop
        break
    lines.append(user_input)

rawDescription: Python equivalent of C++ getline()

description: Python equivalent of C++ getline()


code:
df2 = df.set_index('Date').groupby(['Code', 'ID']).resample('M', 'sum')
df2['Sum'].unstack([0,1]).plot()

rawDescription: calculate total events in month using pandas

description: Calculate total events in month using pandas


code: self.grid = [[None] * (great_x+1) for y in (great_y+1)]

rawDescription: Python Iterate Through List of Lists of Objects and Call a Method


code:
# calculate dendrogram
dendrogram = graph.community_edge_betweenness()
# convert it into a flat clustering
clusters = dendrogram.as_clustering()
# get the membership vector
membership = clusters.membership

rawDescription: Using iGraph in python for community detection and writing community number for each node to CSV


code:
from urllib2 import urlopen
inp = urlopen("<URL>")
with open("output","w") as out:
    inpList = inp.read().split()
    out.write('\n'.join(el for el in inpList if ';cr;' in el))

rawDescription: Python sorting by mask

description: Python sorting by mask


code: pprint(data)

rawDescription: Faster way to do a correspondence replace operation in python?


code: two_tier_dict_init(tier1, tier2, list)

rawDescription: Why are values of a two-level dictionary all pointing to the same object in Python 2.7?


code:
result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods,
                      NULL);

rawDescription: Who calls the metaclass

description: Who calls the metaclass


code:
if all(item in 'cat' for item in ['a', 'd']):  # Will evaluate to False
    win()

rawDescription: How to check if *either* character is in a string in Python?

description: Check if *either* character is in a string in Python


rawDescription: Positive integer from Python hash() function


code: not_done[['Category', 'Domain', 'Maintask']].drop_duplicates().groupby(['Category', 'Domain']).count()

rawDescription: How to do this pandas group by and count functionality?

description: Do this pandas group by and count functionality


code:
def chance_of_grass(height):
    if   height == 0: return  0
    elif height <= 3: return 30
    elif height <= 4: return 50
    elif height <= 7: return 80

    return 100

rawDescription: Problems with for loops for Tile Mapping in Python


code: current_timestamp() - expr("INTERVAL 1 HOUR")

rawDescription: PySpark add a column to a DataFrame from a TimeStampType column


code:
from itertools import count
idgen = count()

rawDescription: Spark: Using iterator lambda function in RDD map()


code:
from functools import wraps
from flask import render_template

def autorender(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        context = func(*args, **kwargs)
        return render_template('%s.html' % func.func_name, **context)
    return wrapper

rawDescription: Using flask/blueprint for some static pages


rawDescription: Mathemmatical formula for incremental breakdowns


code:
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

# The x and y data to plot
y = np.array([1,2,17,20,16,3,5,4])
x = np.arange(len(y))

# Threshold above which the line should be red
threshold = 15

# Create line segments: 1--2, 2--17, 17--20, 20--16, 16--3, etc.
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[-1]].reshape(-1, 2)

# Assign colors to the line segments
linecolors = ['red' if y_[0] > threshold and y_[1] > threshold else 'blue'
              for y_ in segments_y]

# Stamp x,y coordinates of the segments into the proper format for the
# LineCollection
segments = [zip(x_, y_) for x_, y_ in zip(segments_x, segments_y)]

# Create figure
plt.figure()
ax = plt.axes()

# Add a collection of lines
ax.add_collection(LineCollection(segments, colors=linecolors))

# Set x and y limits... sadly this is not done automatically for line
# collections
ax.set_xlim(0, 8)
ax.set_ylim(0, 21)

rawDescription: Python: Is it possible to change line color in a plot if exceeds a specific range?


code:
# create the dict first
gradescount = dict()

for student, totalmark in zip(list0, list3): # iterate directly over the lists
    percentage = (totalmark / 150) * 100
    if percentage >= 70:
        grade = "A"
    elif percentage >= 60:  #elif prevents extra tests
        grade = "B"
    elif percentage >= 50:
        grade = "C"
    elif percentage >= 45:
        grade = "D"
    else:
        grade = "No grade"

    # Increment appropriate grade counter
    gradescount[grade] = gradescount.get(grade, 0) + 1

    roundedpercentage = round(percentage)
    print("%s's percentage was %d%% and their grade was: %s" % (
            student,
            roundedpercentage,
            grade
    ))

rawDescription: Counting number of "passes" within a loop


code:
import csv

with open(inputfilename, newline='') as infh:
    reader = csv.reader(infh)
    for row in reader:
        if row[0] == 'John':
            print(row[1])

rawDescription: python: extracting values from csv file by row name

description: Python: extracting values from csv file by row name


code:
class Color(models.Model):
    name = models.CharField(max_length=255)

class Product(models.Model):
    colors = models.ManyToManyField(Color, related_name='colors')

rawDescription: Django filter filter with lists

description: Django filter filter with lists


code: a + small + number + of + strings + "is pretty fast"

rawDescription: Speed vs security vs compatibility over methods to do string concatenation in Python


code:
from django.http import HttpResponse
from openpyxl import Workbook
from openpyxl.writer.excel import save_virtual_workbook

workbook = Workbook()
worksheet = workbook.active

# ... worksheet.append(...) all of your data ...

response = HttpResponse(content=save_virtual_workbook(workbook), mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=myexport.xlsx'
return response

rawDescription: Return openpyxl workbook object as HttpResponse in django. Is it possible?


code: t.color('black', 'blue')

rawDescription: different fill and border using turtle

description: Different fill and border using turtle


code:
ts = (("Jackson",10,12,"A"),
      ("Ryan",10,20,"A"),
      ("Michael",10,12,"B"),
      ("Andrew",10,20,"B"),
      ("McKensie",10,12,"C"),
      ("Alex",10,20,"D"))
import itertools
import operator
by_class = operator.itemgetter(3)
tuple_grps = [list(grp) for key, grp in itertools.groupby(sorted(ts, key=by_class), key=by_class)]
tuple_grps

rawDescription: Python combinations no repeat by constraint


code:
ymax = round(max(y), -1) + 10
ymin = max(round(min(y), -1) - 10, 0)
ax.set_ylim(ymin, ymax)

rawDescription: How to set the ticks on a logarithmic axis in matplotlib

description: Set the ticks on a logarithmic axis in matplotlib


code:
class MyAction(argparse._StoreAction):
   def __call__(self, parser, namespace, values, option_string=None):
       # store option_string along with values in the namespace
       setattr(namespace, self.dest, [values,option_string])

rawDescription: Neatly pass positional arguments as args and optional arguments as kwargs from argpase to a function


rawDescription: numpy.bincount and numpy.argmax function pseudocodes

description: Numpy.bincount and numpy.argmax function pseudocodes


code:
import matplotlib
matplotlib.use('GTKAgg')

import matplotlib.pyplot as plt
import gobject

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

def draw1():
    plt.bar(0,2)
    plt.bar(2,4)
    ax.set_xlim((0,10))
    ax.set_ylim((0,10))
    fig.canvas.draw()
    return False

def draw2():
    plt.bar(4,3)
    plt.bar(6,7)

    ax.set_xlim((0,10))
    ax.set_ylim((0,10))
    fig.canvas.draw()
    return False

draw1()
gobject.timeout_add(1000, draw2)
plt.show()

rawDescription: How to keep the width of the bars the same no matter the number of bars we compare in the figure?

description: Keep the width of the bars the same no matter the number of bars we compare in the figure


code:
def translate(data,vec):
    tmp = data.copy()
    tmp["xyz"] += vect
    return tmp

rawDescription: Numpy array as a vector with a non-unique property


code: result = [i for i, ch in enumerate(s, start=1) if ch == '1']

rawDescription: Confused by the enumerate() function in tutorials


code:
top = ET.Element('AAA')
# by the way you need index, element on enumerate
for i, line in enumerate(collected_lines):
    child = ET.SubElement(top, line[0])
    child.text = line[1]

art = top
art.tag = 'ART'
top = ET.Element('AAA')
top.insert(1, art)

ET.tostring(top)
'<AAA><ART><TY> RPRT</TY><A1> Peter</A1><T3> Something</T3><ER> </ER></ART></AAA>'

rawDescription: Append to XML structure in python

description: Append to XML structure in python


code:
"""Show a shell command's output in a gtk.TextView without freezing the UI"""

import os
import locale
import subprocess
import shlex
import gi.repository.Gtk as gtk
from gi.repository import GObject
PIPE = subprocess.PIPE

encoding = locale.getpreferredencoding()

def utf8conv(x):
    return unicode(x, encoding).encode('utf8')

class MyWindow:
    def __init__(self):
        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC)
        textview = gtk.TextView()
        textbuffer = textview.get_buffer()
        sw.add(textview)
        win = gtk.Window()
        win.resize(300, 500)
        win.connect('delete-event', gtk.main_quit)

        self.button_sim = gtk.Button(u"Press me!")
        self.button_abort = gtk.Button("Abort")
        self.button_quit = gtk.Button("Quit")

        command = 'ls -R %s' % (os.getcwd(),)
        self.button_sim.connect(
            "clicked", self.on_button_clicked, textview, textbuffer, command)
        self.button_abort.connect("clicked", self.on_abort)
        self.button_quit.connect("clicked", self.main_quit)

        vbox = gtk.VBox()
        vbox.pack_start(self.button_sim, expand=False, fill=False, padding=0)
        vbox.pack_start(self.button_abort, expand=False, fill=False, padding=0)
        vbox.pack_start(self.button_quit, expand=False, fill=False, padding=0)
        vbox.pack_start(sw, expand=True, fill=True, padding=0)
        win.add(vbox)
        win.show_all()

    def read_output(self, view, buffer, command):
        yield True  # allow the UI to refresh
        proc = subprocess.Popen(
            shlex.split(command), stderr=PIPE, stdout=PIPE)
        while True:
            if self.job_aborted:
                print('user aborted')
                proc.terminate()
                break

            try:
                line = proc.stdout.readline()
                if line:
                    it = buffer.get_end_iter()
                    buffer.place_cursor(it)
                    buffer.insert(it, utf8conv(line))
                    view.scroll_to_mark(buffer.get_insert(), 0.1,
                                        use_align=False, xalign=0.5, yalign=0.5)

            except IOError:
                pass

            yield True

        yield False

    def on_button_clicked(self, button, view, buffer, command):
        self.job_aborted = False
        GObject.idle_add(self.read_output(view, buffer, command).next)

    def on_abort(self, button):
        self.job_aborted = True

    def main_quit(self, obj):
        self.job_aborted = True
        gtk.main_quit()

if __name__ == "__main__":
    app = MyWindow()
    gtk.main()

rawDescription: 'gi.repository.Gtk' object has no attribute 'gdk'


code:
class A(object):
    def __init__(self):
        self.name = ''             # these are instance
        self.children = []         # attributes

rawDescription: What's the best way of appending in a recursive method in Python?


code:
def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

rawDescription: How to get text of an element in Selenium WebDriver (via the Python api) without including child element text?

description: Get text of an element in Selenium WebDriver (via the Python api) without including child element text


code:
def f():
  return 'python', 'python!'
def g():
  return 'python', 'python!'
a, b = f()
c, d = g()
a is c
a == c
b is d
b == d

rawDescription: Why and where python interned strings when executing `a = 'python'` while the source code does not show that?


code: merged['newcol'] = merged.x * merged.a * merged.measurement

rawDescription: Python: multiply csv data together with dict()


code: import example

rawDescription: boost::python::class: programatically obtaining the class name

description: Boost::python::class: programatically obtaining the class name


code:
g = Group(name='g1', paths=[Path('blah', Bound(1,1,2,3)),
                            Path('other_style', Bound(1,1,2,3)),])

session.add(g)
db.session.commit()

g.name = 'g2'
assert g in db.session.dirty
db.session.commit()

g.paths[0].style = 'something else'
assert g in db.session.dirty

rawDescription: PickleType with Mutable Tracking in SqlAlchemy


code:
Record._get_collection().aggregate([
    # Match only those documents that would meet the condition
    { "$match": {
        "event_history": {
            "$elemMatch": {
                "$elemMatch": {"$in": [0] }
            }
        }
    }},

    # Unwind the event history array, top level
    { "$unwind": "$event_history" },

    # Make a copy of the inner array
    { "$project": {
        "account_id": 1,
        "event_history": 1,
        "status": 1,
        "copy": "$event_history"
    }},

    # Unwind that copy
    { "$unwind": "$copy" },

    # Match the numeric 0 elements only, filters non-matches
    { "$match": { "copy": 0 } },

    # Group back to the original document
    { "$group": {
        "_id": "$_id",
        "account_id": { "$first": "$account_id" },
        "event_history": { "$push": "$event_history" },
        "status": { "$first": "$status" }
    }}
])

rawDescription: MongoDB / MongoEngine - Query for Item in List


code:
@api.model
def new(self, values={}):
    """ new([values]) -> record

    Return a new record instance attached to the current environment and
    initialized with the provided ``value``. The record is *not* created
    in database, it only exists in memory.
    """
    record = self.browse([NewId()])
    record._cache.update(record._convert_to_cache(values, update=True))

    if record.env.in_onchange:
        # The cache update does not set inverse fields, so do it manually.
        # This is useful for computing a function field on secondary
        # records, if that field depends on the main record.
        for name in values:
            field = self._fields.get(name)
            if field:
                try:
                    for invf in field.inverse_fields:
                        invf._update(record[name], record)

                        #serarch this field for sub inverse fields
                        for ftmp in self[name]._fields:

                                f = self[name]._fields.get(ftmp)
                                if f and f != invf:
                                    for invf in f.inverse_fields:
                                        val = record[name]
                                        invf._update(record[name][ftmp], val)

                except:
                    pass

    return record

rawDescription: How to browse or search One2many field in Odoo?

description: Browse or search One2many field in Odoo


code: [['date1', 'http://signal1.com'], ['date2', 'http://signal2.com']]

rawDescription: Python: simple csv substring filter

description: Python: simple csv substring filter


code:
[[u'The', u'Fulton', u'County', u'Grand', u'Jury', u'said', u'Friday', u'an', u'investigation', u'of', u"Atlanta's", u'recent', u'primary', u'election', u'produced', u'``', u'no', u'evidence', u"''", u'that', u'any', u'irregularities', u'took', u'place', u'.'], [u'The', u'jury', u'further', u'said', u'in', u'term-end', u'presentments', u'that', u'the', u'City', u'Executive', u'Committee', u',', u'which', u'had', u'over-all', u'charge', u'of', u'the', u'election', u',', u'``', u'deserves', u'the', u'praise', u'and', u'thanks', u'of', u'the', u'City', u'of', u'Atlanta', u"''", u'for', u'the', u'manner', u'in', u'which', u'the', u'election', u'was', u'conducted', u'.'], ...]

[(u'The', 'DT'), (u'Fulton', 'NNP'), (u'County', 'NNP'), (u'Grand', 'NNP'), (u'Jury', 'NNP'), (u'said', 'VBD'), (u'Friday', 'NNP'), (u'an', 'DT'), (u'investigation', 'NN'), (u'of', 'IN'), (u"Atlanta's", 'JJ'), (u'recent', 'JJ'), (u'primary', 'JJ'), (u'election', 'NN'), (u'produced', 'VBN'), (u'``', '``'), (u'no', 'DT'), (u'evidence', 'NN'), (u"''", "''"), (u'that', 'WDT'), (u'any', 'DT'), (u'irregularities', 'NNS'), (u'took', 'VBD'), (u'place', 'NN'), (u'.', '.')]

rawDescription: Storing a POS tagged corpus

description: Storing a POS tagged corpus


code:
from django.db import models
from django.db.models.options import Options
from django.utils.translation import get_language
from django.utils.translation import ugettext_lazy as _

from transmeta import TransMeta, get_real_fieldname

class TranslatedOptions(Options):
    @property
    def ordering(self):
        lang = get_language()[:2]
        return [get_real_fieldname(f, lang) for f in self.orig_ordering]

    @ordering.setter
    def ordering(self, value):
        self.orig_ordering = value

class TransMetaOrdering(TransMeta):
    def __new__(cls, name, bases, attrs):
        new_class = super(TransMetaOrdering, cls).__new__(cls, name, bases, attrs)
        options = TranslatedOptions(None)
        for k, v in new_class._meta.__dict__.iteritems():
            setattr(options, k, v)
        new_class._meta = options
        return new_class

class StartupType(models.Model):
    __metaclass__ = TransMetaOrdering

    name = models.CharField(_("Name"), max_length=30)
    slug = models.SlugField(_("Slug"), max_length=30, editable=False)

    class Meta:
        verbose_name = _("Startup type")
        verbose_name_plural = _("Startup types")
        translate = (
            "name",
        )
        ordering = (
            "name",
        )

rawDescription: Is it possible to order a Django Model using the active language?


code:
def build_dict(A, y):
    for s in reversed(A):
        y = {s: y}
    return y

A = ['a1', 'a2', 'a3', 'a4', 'a5']
y = 'some value'
print(build_dict(A, y))

rawDescription: Converting a list to a nested dictionary?


code:
df = df.set_index(["resp", "vehicle", "color"])
df

rawDescription: Pandas stack/groupby to make a new dataframe


code: myDict = {x.index:x for x in xs}

rawDescription: Dynamically growing a python array when assigning to it


rawDescription: Are there any example data sets for Python?


code:
import random

output = ""
deliminator = "\n" #Put a line-break after each number
filepath = "mynumbers.txt"
i = 0
while i < 11:
# Get random number in range 10 through 20.
    n = random.randint(10, 20)
    print(n) #is this necessary?
    i += 1
    output += str(n) + deliminator

#Write the numbers to the file
with open(filepath, 'w') as file:
    file.write(output)

rawDescription: How do i write the integers that in this file to the mynumbers.txt file?

description: Write the integers that in this file to the mynumbers.txt file


code:
def test_check_with_too_high_pressure(self):
    instance = MagicMock()
    instance.sample_pressure.return_value=22
    alarm = Alarm(sensor=instance)
    alarm.check()
    self.assertTrue(alarm.is_alarm_on)

rawDescription: unittest.mock.patch a class instance, and set method return values

description: Unittest.mock.patch a class instance, and set method return values


rawDescription: Python 2.7+: What's the correct way to format a float in non-scientific notation with certain precision?


code:
class User(db.Model):
   id = db.Column(db.Integer, primary_key = True)
   name = db.Column(db.String(50), index=True, unique= True)
   email = db.Column(db.String(50),index=True, unique= True)

   friends = db.relationship('User', #defining the relationship, User is left side entity
        secondary = friends,
        primaryjoin = (friends.c.user_id == id),
        secondaryjoin = (friends.c.friend_id == id),
        lazy = 'dynamic'
    )

rawDescription: display friends name by Flask Many-to-many sqlalchemy

description: Display friends name by Flask Many-to-many sqlalchemy


code:
import re
import sys

_, infile, outfile = sys.argv

s_pat_row = r'''
    "([^"]+)"  # match column; this is group 1
    \s*,\s*  # match separating comma and any optional white space
    (\S+)  # match column; this is group 2
    \s*,\s*  # match separating comma and any optional white space
    "((?:\\"|[^"])*)"  # match string data that can include escaped quotes
'''
pat_row = re.compile(s_pat_row, re.MULTILINE|re.VERBOSE)

s_pat_clean = r'''[\x01-\x1f\x7f]'''
pat_clean = re.compile(s_pat_clean)

row_template = '"{}",{},"{}"\n'

with open(infile, "rt") as inf, open(outfile, "wt") as outf:
    data = inf.read()
    for m in re.finditer(pat_row, data):
        row = m.groups()
        cleaned = re.sub(pat_clean, ' ', row[2])
        words = cleaned.split()
        cleaned = ' '.join(words)
        outrow = row_template.format(row[0], row[1], cleaned)
        outf.write(outrow)

rawDescription: regex to delete whitespace in csv-file with quotes to separate text?

description: Regex to delete whitespace in csv-file with quotes to separate text


code: arduino.write('%d.%d' % (2, 3))

rawDescription: PySerial communication with variables

description: PySerial communication with variables


rawDescription: Pandas drops timestamp columns in resample


rawDescription: Extract a pair with same values in a list of dictionary in python


code: [(x,y) for y in numpy.arange(0, 0.3, 0.1) for x in range(5)]

rawDescription: how to iterate using itertools for iterables having different lengths in python?

description: Iterate using itertools for iterables having different lengths in python


code:
from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius('55001', 8)] # ('ZIP', radius in km)
radius_utf = [x.encode('UTF-8') for x in in_radius] # unicode list to utf list

rawDescription: Could I use python to retrieve a number of zip code within a radius


code:
fig, ax = plt.subplots()
ax.set_xlim(0, .25)
ax.set_ylim(-2.5, 2.5)
ax.set_title('beat frequencies')
lnA, = ax.plot([], [], color='r', label='A')
lnB, = ax.plot([], [], color='purple', label='B')
lnsum, = ax.plot([], [], color='k', label='signal')
ax.legend()
max_time = 3
rate = 8000
times = np.linspace(0,max_time,rate*max_time)

def beat_freq(f1=220.0, f2=224.0):

    A = np.sin(2*np.pi*f1*times)
    B = np.sin(2*np.pi*f2*times)
    sig = A + B

    lnA.set_data(times, A)
    lnB.set_data(times, B)
    lnsum.set_data(times, sig)

    plt.draw()

beat_freq(0, 0)

rawDescription: Is it possible to speed up interactive IPython Notebook plots by not generating new figures every time?


code:
import _Framework.DB

_Framework.DB.cursor = new_cursor
_Framework.DB.environment = new_environment

rawDescription: python package structure and global variables

description: Python package structure and global variables


code:
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

def exclude_function(filename):
    if filename in EXCLUDE_FILES:
        return True
    else:
        return False

mytarfile.add(..., exclude=exclude_function)

rawDescription: Python tarfile and excludes

description: Python tarfile and excludes


code:
from tkinter import *

# --- functions ---

def change_On_Off_state(*args):
    CheckVar1.set(*args)
    OnOff = Checkbutton(root, text="On", variable=CheckVar1, onvalue=1, offvalue=0, height=1, width=10, anchor=W, bg='Light Blue')
    OnOff.grid(row=4, column=2, padx=10, sticky=W)
    #CheckVar1.trace_variable("w", On_Off_state)

# --- main ----

root = Tk()

CheckVar1 = IntVar() # global

change_On_Off_state(1)

# "start the engine"
root.mainloop()

rawDescription: Checkbutton value constant

description: Checkbutton value constant


code: exc = colander.Invalid(form["identity_information"], "ID Number %s already exists in Database" % number)

rawDescription: Deform Inter-Field Validation not highlighting field


code: ['test 123 456 abcde', 'zzzzzzzzz']

rawDescription: get line of a predefined sentence that in a txt file line?

description: Get line of a predefined sentence that in a txt file line


rawDescription: WordNetLemmatizer not returning the right lemma unless POS is explicit - Python NLTK


code: dict((row[0], {"b": row[1], "c": row[2]}) for row in rows)

rawDescription: What's a better way to handle this in Python


rawDescription: Counting unique rows in each group after group by using read_csv with chunk


code:
import pandas as pd
import datetime

dateparse = lambda x: pd.datetime.strptime(x, '%m/%d/%Y')
df = pd.read_csv('Sample.csv',index_col='date', parse_dates=[0], date_parser=dateparse)

expd_gb = df.reset_index().groupby(['wholesaler', 'product'])['sales'].apply(pd.Series.expanding)
idx = df.reset_index().groupby(['wholesaler', 'product', 'date'])['sales'].count().index

cnct = pd.concat([expd_gb.iloc[n].mean().shift(1) for n in range(len(expd_gb))])
cnct.index = idx

cnct.to_csv('TotalAvg.csv')

rawDescription: How to find the average of previous sales at each time in python

description: Find the average of previous sales at each time in python


code:
import os
secs = raw_input()
os.system("sudo rtcwake off -s {}".format(secs))

rawDescription: Defining the command line arguments of a linux command in python


code:
class B(A):
    some_field = 123

class C(A):
    some_field = 123

rawDescription: Class (not instance) constructor

description: Class (not instance) constructor


code:
#get the account object based on your cookie
account = Account.get_by_id(self.request.cookies["user_id"])

#get your blog post id
blogpostid = "12341234214"

#check if it's the author
if is_author(blogpostid, account):
    do_whatever()

rawDescription: Checking if logged-in user is author of an entity that is currently being viewed


code: np.searchsorted(a, b) - 1

rawDescription: Using np.searchsorted to find the most recent timestamp


code:
import numpy as np
m_out = np.arange(50).reshape(25,2)
v = m_out[:,1]
eqn_out = np.arange(7, 18)
eqn_out

rawDescription: Using Python List Comprehension to match values that exist in a 2d array and simple list


code: Y=pdist(X, 'correlation')

rawDescription: hierarchical clustering on correlations in Python scipy/numpy?

description: Hierarchical clustering on correlations in Python scipy/numpy


code:
import matplotlib.ticker as ticker
def todate(x, pos, today=DT.date.today()):
    return today+DT.timedelta(days=x)
fmt = ticker.FuncFormatter(todate)
ax.xaxis.set_major_formatter(fmt)

rawDescription: replace numbers on X axis with dates when using line plot in matplotlib

description: Replace numbers on X axis with dates when using line plot in matplotlib


code:
def get_type(data):
    if isinstance(data, list):
        types = {get_type(item) for item in data}
        # If all elements of the list are of the same type
        if len(types) == 1:
            return next(iter(types))
        # if not, return "multiple"
        else:
            return "multiple"
    elif isinstance(data, str):
        # Check if the string has only numbers or it is a float number
        return "numeric" if data.isdigit() or is_float(data) else "character"
    elif isinstance(data, int) or isinstance(data, float):
        return "numeric"

rawDescription: Distinguish between 'character' and 'numeric' data types in Python


rawDescription: Sklearn trying to convert string list to floats


code: pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)

rawDescription: Pandas - conditionally select column based on row value


rawDescription: Find count of unique column elements after using groupby with pandas


code:
variable_to_use = None

def funcA():
    if variable_to_use is None:
        raise ValueError('You need to set module.variable_to_use before using this function')
    do_something_with(variable_to_use)

rawDescription: Passing a string to module "once"

description: Passing a string to module "once"


code: array = [i for i in array if i != 0]

rawDescription: Remove elements from a int array that have value 0 and save the deleted index


code:
#!/usr/bin/python2
# encoding: utf-8
from __future__ import print_function
import urllib2
import gzip
import zlib
import StringIO
import httplib
import socket

class CountingHTTPConnection(httplib.HTTPConnection):
    bytes_sent = 0

    def __init__(self, host, port=None, strict=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
        self._send = self.send
        self.send = self.counting_send
        httplib.HTTPConnection.__init__(self, host, port=None, strict=None,
                                        timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None)

    def counting_send(self, data):
            CountingHTTPConnection.bytes_sent += len(data)
            self._send(data)

class CountingHTTPHandler(urllib2.HTTPHandler):
    def http_open(self, req):
        return self.do_open(CountingHTTPConnection, req)

req = urllib2.Request('http://www.google.com')
opener = urllib2.build_opener(CountingHTTPHandler())
req.add_header('Accept-Encoding', 'gzip, deflate')

response = opener.open(req)
the_page = response.read()
print("Length before decompression:" + str(len(the_page)))
if response.info().get('Content-Encoding') == 'gzip':
    the_page = gzip.GzipFile(fileobj=StringIO.StringIO(the_page)).read()
elif response.info().get('Content-Encoding') == 'deflate':
    the_page = zlib.decompress(the_page)

print("Length after decompression:" + str(len(the_page)))
print("bytes sent: {}".format(CountingHTTPConnection.bytes_sent))

rawDescription: how can I get the total bytes sent and received using python 2.7?

description: Get the total bytes sent and received using python 2.7


rawDescription: Extracting part of a string

description: Extracting part of a string


code:
#!/usr/bin/env python3
from datetime import datetime, timedelta

now = datetime.now()
then = datetime.combine(now, datetime.strptime('15:30', '%H:%M').time())
minutes = (then - now) // timedelta(minutes=1)

rawDescription: How to subtract datenow from time string?

description: Subtract datenow from time string


code:
bar = next_bar
bar.next_bar = next_bar

rawDescription: Why is assigning to multiple targets (identifier/attribute) producing strange results?


code:
def get_age_comp(self, cr, uid, context=None):
    cr.execute('DELETE FROM stat;')
    cr.execute('''INSERT INTO stat(name, age)
                  SELECT name, date_part('years',age(birth_date))
                  FROM fci_student
                  WHERE gender='m'
                  AND date_part('years',age(birth_date)) > 18;''')

rawDescription: Automated Action Birthday =19

description: Automated Action Birthday =19


code: ip_list = [ip for s in [csv_ip, single_ip, empty_ip] for ip in (s.split(",") if s else [])]

rawDescription: Python Extend List Comprehension

description: Python Extend List Comprehension


rawDescription: How to insert unescaped html fragment in Beautiful Soup 4

description: Insert unescaped html fragment in Beautiful Soup 4


code: plt.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)

rawDescription: How do to tighten the bounds of my 'matplotlib' figures to be closer to my axes?


code:
def fast(df, col):
    A = df.sort(col).shift()
    last = A.iloc[-1].copy()
    A.loc[A[col] != A[col].shift(-1)] = np.nan
    A.iloc[-1] = last
    return A.drop(col, axis=1)

def slow(df, col):
    A = df.sort(col).groupby(col).shift()
    return A

rawDescription: Faster alternative to grouby/shift

description: Faster alternative to grouby/shift


code:
import glob
import os

id1 = '*'
logZip = glob.glob(os.path.join("c:/logs", id1, id2, '{}_log_{}_{}-00_{}.zip'.format(id1, dateID, hourID, id2)))

rawDescription: Python, how to substitute one level of a path for "anything" or "*"


code:
def dedup(lst):
    seen = set()
    result = []
    for item in lst:
        fs = frozenset(item)
        if fs not in seen:
            result.append(item)
            seen.add(fs)
    return result

res = []
s = "accggt agctta gggatc gactta ccttgg"
chks = s.split(" ");
for word in chks:
    for nextWord in chks:
        if word != nextWord:
            if [x == y for (x, y) in zip(word, nextWord)].count(True) == 0:
                res.append([word, nextWord])

print(dedup(res))

rawDescription: Compare strings and just keep those who have on same positions different characters


code:
def foo(*args):
    print('foo({0})'.format(args))

rawDescription: In Python, what are some examples of when decorators greatly simplify a task?


code:
[{'Album': 'My Beautiful Dark Twisted Fantasy',
  'Artist': 'Kanye West',
  'Name': 'Gorgeous (feat. Kid Cudi & Raekwon)'},
 {'Album': 'test Album', 'Artist': 'test Artist', 'Name': 'test name'}]

rawDescription: Parsing song names and the like from a XML file in Python


rawDescription: How to programmatically read and convert email in an image to text?

description: Programmatically read and convert email in an image to text


code:
a1.set_index(['group', 'product'])
print(a1)

#               date  performance
# group product
# x     y         z1            1
#       b         z2            2
# a     b         z3            3
#       c         z4            4

rawDescription: Consolidate data in numpy arrays

description: Consolidate data in numpy arrays


code:
f = lambda x,y=None: (x, [1]*x if y is None else y)
f(10, [1, 1, 1])
f(15)

rawDescription: Defining a Variable Inside a Lambda

description: Defining a Variable Inside a Lambda


code:
def name_list(text_file):
    file = open(text_file, 'r')
    list = []
    for line in file:
        first, last = line.split()
        list.append(Name(first, last))
    return list

rawDescription: How to implement list of names into a pre-made class?

description: Implement list of names into a pre-made class


code:
def __float__(self):
    return self.value

def __radd__(self, other):
    return other + self.value

rawDescription: Can I make a class which behaves like an immutable (float)?

description: Make a class which behaves like an immutable (float)


code:
def get_files(target):
    # Get file size and modified time for all files from the target directory and down.
    # Initialize files list
    filelist = []
    dirdict = {}
    # Walk the directory structure
    for root, dirs, files in os.walk(target):
        # Do not walk into directories that are mount points
        dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), dirs)
        for name in files:
            # Construct absolute path for files
            filename = os.path.join(root, name)
            # Test the path to account for broken symlinks
            if os.path.exists(filename):
                # File size information in bytes
                size = float(os.path.getsize(filename))
                # Get the modified time of the file
                mtime = os.path.getmtime(filename)
                # Create a tuple of filename, size, and modified time
                construct = filename, size, str(datetime.datetime.fromtimestamp(mtime))
                # Add the tuple to the master filelist
                filelist.append(construct)
                if root in dirdict.keys():
                    dirdict[root] += size
                else:
                    dirdict[root] = size
    return(filelist, dirdict)

rawDescription: How do you get total directory size in the same function that is getting all file sizes? (Python)

description: Get total directory size in the same function that is getting all file sizes? (Python)


code:
lines = []
for x in range(0, 2):
    line = []
    for item in dic:
        if item in abst:
            i = abst.index(item)
            line.append(data[x][i])
    lines.append(line)

rawDescription: how to print lists separately instead of merging them?

description: Print lists separately instead of merging them


code: all_sents = file_sent.read().replace('\n', '')

rawDescription: formatted Input from file in Python

description: Formatted Input from file in Python


code:
from io import StringIO
import csv, sys
newcik = '''\
66740,1800,1001463,1467373,896159
'''
search_file = '''\
1001385|NORTHWEST PIPE CO|10-Q|2015-05-06|edgar/data/1001385/0001193125-15-174814.txt
1001426|PERICOM SEMICONDUCTOR CORP|10-Q|2015-05-05|edgar/data/1001426/0001145443-15-000628.txt
1001463|Acacia Diversified Holdings, Inc.|10-K|2015-05-20|edgar/data/1001463/0001185185-15-001386.txt
1001463|Acacia Diversified Holdings, Inc.|10-K|2015-05-20|edgar/data/1001463/0001185185-15-001394.txt
1001463|Acacia Diversified Holdings, Inc.|10-Q|2015-05-20|edgar/data/1001463/0001185185-15-001388.txt
1001463|Acacia Diversified Holdings, Inc.|10-Q|2015-05-20|edgar/data/1001463/0001185185-15-001390.txt
1001463|Acacia Diversified Holdings, Inc.|10-Q|2015-05-20|edgar/data/1001463/0001185185-15-001392.txt
1001463|Acacia Diversified Holdings, Inc.|10-Q|2015-05-20|edgar/data/1001463/0001185185-15-001396.txt
'''
with StringIO(newcik) as reader2:
    reader2 = csv.reader(reader2)
    cik_values = next(reader2)  # first row

with StringIO(search_file) as f_in:
    reader = csv.reader(f_in, delimiter='|')
    writer = csv.writer(sys.stdout, delimiter='|')
    for line in reader:
        for cik in cik_values:
            if cik in line[-1]:  # test only the last column
                writer.writerow(line)

rawDescription: Python 3.4 : match from csv and return new csv with matched values


rawDescription: python libXML2 remove Item

description: Python libXML2 remove Item


code:
@pytest.fixture(scope='module', params=[load_dataset1, load_dataset2])
def data(request):
    loader = request.param
    dataset = loader()
    return dataset

rawDescription: Run same test on multiple datasets

description: Run same test on multiple datasets


code: func_proto = ctypes.WINFUNCTYPE(HRESULT, HWND)

rawDescription: Windows Common Item Dialog: ctypes + COM access violation


code:
count('input.txt', 'lines')
count('input.txt', 'words')
count('input.txt', 'chars')

rawDescription: Preffered way of counting lines, characters and words from a file as a whole in Python


rawDescription: Using python decorator with or without parentheses


code:
from itertools import groupby
from operator import itemgetter
from collections import deque

def gps(a):
    for k, v in groupby(a, key=itemgetter(2)):
        start, end = next(v), deque(v, maxlen=1).pop()
        yield [start[0],  end[1], end[2]]

rawDescription: Mapping diagonal elements recursively and check for condition, Python


code:
import pandas as pd

def rounded_ten(t):
    ''' add 5 minutes to the date first and then apply mathematical floor to the minute part.
    It's easier to apply mathematical floor operation on date parts instead of rounding because for example you cannot round up 58 seconds to 60 seconds but you can always apply floor and stay within the range.
    '''
    t=t+pd.Timedelta('5 minutes')
    return t.replace(minute=t.minute//10*10).replace(second=0)

rawDescription: How to round a datetime to ten minute datetime in a dataframe in Python

description: Round a datetime to ten minute datetime in a dataframe in Python


rawDescription: Create a list of lists / matrices from a text file in Python 3.4


rawDescription: How to_csv in Bluemix

description: How to_csv in Bluemix


code:
fig = plt.figure()
ax = plt.gca()
ax.plot(data['o_value'] ,data['time_diff_day'], 'o', c='blue', alpha=0.05, markeredgecolor='none')
ax.set_yscale('log')
ax.set_xscale('log')

rawDescription: python: scatter plot logarithmic scale

description: Python: scatter plot logarithmic scale


code: from itertools import product

rawDescription: Parameter study using python

description: Parameter study using python


rawDescription: How may I project vectors onto a plane defined by its orthogonal vector in Python?


code: [i.text.strip() for i in prices]

rawDescription: Python - I'm trying to create a simple web scraper for the steam market


code:
def listofdiags(diags):
    return [''.join(diags[i]) for i in sorted(diags)]

rawDescription: Diagonal Grid Traverse in Python

description: Diagonal Grid Traverse in Python


code:
  # calculate the weighing of the review for the current user criteria
  # give more importance to recent reviews

rawDescription: Algorithm process is slow

description: Algorithm process is slow


rawDescription: How can state stored in a python descriptor object be accessed outside the descriptor?


rawDescription: Passing variable length parameters to a function in python


rawDescription: Is there a more efficient way to append lines from a large file to a numpy array? - MemoryError


code:
task = shlex.split(s)
subprocess.check_call(task)

rawDescription: Handling directories with spaces Python subprocess.call()


code:
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read() # This is what is read from the file. In your case,
                       # it'll only read the contents of the webpage.

rawDescription: Script downloading file from filesonic

description: Script downloading file from filesonic


code:
import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

rawDescription: Calling pylab.savefig without display in ipython


code:
import wx
import wx.lib.scrolledpanel

class GUI(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Test app v1.0", style = wx.DEFAULT_FRAME_STYLE )
        self.Center()
        self.CreateStatusBar()
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.scroll = wx.ScrolledWindow(self, -1)
        self.scroll.SetScrollbars(1, 1, 600, 400)
        panelA = wx.lib.scrolledpanel.ScrolledPanel(self.scroll, -1, style=wx.SIMPLE_BORDER, size=(300,200))
        panelA.SetupScrolling()
        panelA.SetBackgroundColour('#EEE111')
        panelB = wx.lib.scrolledpanel.ScrolledPanel(self.scroll, -1, style=wx.SIMPLE_BORDER, size=(200,200))
        panelB.SetupScrolling()
        panelB.SetBackgroundColour('#Eaa222')
        mainSizer.Add(panelA, 1, wx.ALL|wx.EXPAND, 5)
        mainSizer.Add(panelB, 1, wx.ALL|wx.EXPAND, 5)
        self.scroll.SetSizer(mainSizer)

if __name__=='__main__':
    app = wx.App(0)
    frame = GUI().Show()
    app.MainLoop()

rawDescription: Add a vertical scrollbar to a wxFrame accross multiple wxPanels


code: re.findall('class (\w*)', a)

rawDescription: Extracting java main class name in python


code: total = sum(x * (1 - (x % 2 * 2)) for x in lst)

rawDescription: Add even numbers, subtract uneven numbers in Python


code:
def f(x, y, z):
    return list(product(range(x), range(y), range(z)))

rawDescription: Python: how to get this elegantly?

description: Python: how to get this elegantly


code:
foo = FooModel.objects.get(...)
foo.time = timedelta(seconds=foo.time)

rawDescription: Django Query Result Is NoneType?

description: Django Query Result Is NoneType


code:
y = NBA['W']
X = NBA[['PTS', 'oppPTS']]

rawDescription: Multiple linear regression in pandas statsmodels: ValueError


code:
team_id = 1
query = session.query(User.id).filter(~User.memberteams.any(Team.id == team_id))

rawDescription: How to query those Objects that are not joined (SQLAlchemy)

description: Query those Objects that are not joined (SQLAlchemy)


rawDescription: Removing looped new line?

description: Removing looped new line


code: fx = lambda z,y=999: [ "%0*d" % (len('%0d' % y), x) for x in range(y) if str(z) in str(x) ]

rawDescription: How to pad leading zero (in a function) dynamically?

description: Pad leading zero (in a function) dynamically


rawDescription: Python: get int value from a char string


code: print("Concat", "String")

rawDescription: Python print() output discrepancy

description: Python print() output discrepancy


code:
__all__ = ['SubModS', 'PluginBase']
from .meta_base import PluginBase
from .submod_s import SubModS

rawDescription: least burdensome technique for package submodule to see all classes of importer

description: Least burdensome technique for package submodule to see all classes of importer


code:
options = (self.room, self.floor, self.building)
location = [l for l in options if l is not None][:1]

rawDescription: Python: a better way to write a if-then block with join?


code:
from itertools import izip_longest
L1 = [1.1, 1.2, 1.3]
L2 = [2.1, 2.2, 2.3, 2.4]
L3 = [3.1, 3.2]
[x for sub in izip_longest(L1,L2,L3) for x in sub if x is not None]

rawDescription: Merge lists of different size with order


rawDescription: Determine if one range is within another


code:
# test.py
import numpy as np
from numpy.ctypeslib import ndpointer
import ctypes

_doublepp = ndpointer(dtype=np.uintp, ndim=1, flags='C')

_dll = ctypes.CDLL('dummy.dll')

_foobar = _dll.foobar
_foobar.argtypes = [ctypes.c_int, ctypes.c_int, _doublepp, _doublepp]
_foobar.restype = None

def foobar(x):
    y = np.zeros_like(x)
    xpp = (x.__array_interface__['data'][0]
      + np.arange(x.shape[0])*x.strides[0]).astype(np.uintp)
    ypp = (y.__array_interface__['data'][0]
      + np.arange(y.shape[0])*y.strides[0]).astype(np.uintp)
    m = ctypes.c_int(x.shape[0])
    n = ctypes.c_int(x.shape[1])
    _foobar(m, n, xpp, ypp)
    return y

if __name__ == '__main__':
    x = np.arange(9.).reshape((3, 3))
    y = foobar(x)

rawDescription: Pass a 2d numpy array to c using ctypes

description: Pass a 2d numpy array to c using ctypes


code:
setB = set(listB)
listC = [value if index not in setB else 0 for index, value in enumerate(listA)]

rawDescription: Update list elements based on a second list as index


code:
import os, os.path

fileiter = (os.path.join(root, f)
    for root, _, files in os.walk(dirtocheck)
    for f in files)
smallfileiter = (f for f in fileiter if os.path.getsize(f) < 200 * 1024)
for small in smallfileiter:
    os.remove(small)

rawDescription: Python script to loop through all files in directory, delete any that are less than 200 kB in size


code: s & (1 << x)  # is bit x set?

rawDescription: Generating a 10000 bit random sequence

description: Generating a 10000 bit random sequence


code:
element= dict_to_xml(my_dict)

from xml.dom import minidom

xml= ElementTree.tostring(element)
xml= minidom.parseString(xml)
xml= xml.toprettyxml(indent='  ')

rawDescription: Recursion: Nested dictionaries to XML(HTML)


code: nyval = int(not myval)

rawDescription: python how to "negate" value : if true return false, if false return true

description: Python how to "negate" value : if true return false, if false return true


code:
class ColoredRectangle(Rectangle):
    def __init__(self, rect, color):
        self.rect = rect
        self.color = color
    def __getattr__(self,attr):
        return getattr(self.rect,attr)
eve = Rectangle(3, 5)

rawDescription: Subclassing in python of instantiated superclass


rawDescription: Edit a list while comparing it to another list as constraints