code:
def data_to_python(data_file_name):
    with open(data_file_name,'r') as f:
        data = []
        first = True
        for line in f:
            if first:
                first = False
                datanames = line.split('\t')
            else:
                temp = {}
                for i,item in enumerate(line.split('\t')):
                     temp[datanames[i]] = item
                data.append(temp)
    return data

def searchByYear(data,year):
    temp = []
    for entry in data:
        if entry['Dato'].endswith(str(year)):
            temp.append(entry)
    return temp

rawDescription: Write average weather data from a year given by user to a text file


code:
soup = BeautifulSoup(content)
soup.find("span", {"class": "egV2_archivedDateEnded"})
soup.find("span", {"class": "egV2_archivedDateEnded"}).next
soup.find("span", {"class": "egV2_archivedDateEnded"}).next.next

rawDescription: parsing meta tag with Beautiful Soup and Python

description: Parsing meta tag with Beautiful Soup and Python


code: add_one = lambda x: x + 1

rawDescription: Python dictionaries and select case

description: Python dictionaries and select case


rawDescription: Python List Help (Find Biggest number)

description: Python List Help (Find Biggest number)


code:
def printLocations(s, target):
    '''
    s is a string to search through, and target is the substring to look for.
    Print each index where the target starts.
    For example:
    >>> printLocations('Here, there, everywherel', 'ere')
    1
    8
    20
    '''

    repetitions = s.count(target)
    index = -1
    for i in range(repetitions):
        index = s.find(target, index+1)
        print(index)

def main():
    phrase = 'Here, there, everywhere!'
    print('Phrasez', phrase)
    for target in ['ere', 'er', 'e', 'eh', 'zx']:
        print('finding:', target)
        printLocations(phrase, target)
    print('All done!')

main()

rawDescription: Print Location of a string

description: Print Location of a string


rawDescription: How to reference a regex match as a variable in python

description: Reference a regex match as a variable in python


rawDescription: Extract LSB bit from a Byte in python

description: Extract LSB bit from a Byte in python


code:
someday = Day()
Day.SetSunRise(someday, some_sunrise_time)

rawDescription: How do I refer indirectly to a method defined in a class when I have multiple ojects

description: Refer indirectly to a method defined in a class when I have multiple ojects


code:
#!/usr/bin/env python
from subprocess import call

dir = r"C:\Program Files (x86)\GlobalMapper15"
cmdline = "global_mapper.exe script.gms variable"
rc = call(cmdline, cwd=dir) # run `cmdline` in `dir`

rawDescription: How to open a program with cmd.exe from Python?

description: Open a program with cmd.exe from Python


code:
def replace_char(astr, old_char, new_char):
    if astr == "":
        return astr
    elif astr[0] == old_char:
        return new_char + replace_char(astr[1:], old_char, new_char)
    else:
        return astr[0] + replace_char(astr[1:], old_char, new_char)

rawDescription: Python string recursion

description: Python string recursion


code:
import wx

class BrightnessController(wx.Frame):
    def __init__(self, parent, title):
        super(BrightnessController, self).__init__(parent, title=title,
                                                   size=(330, 100))
        self.SetMinSize((330, 100))
        self.SetMaxSize((330, 100))
        self.Show()

if __name__ == '__main__':
    app = wx.App()
    BrightnessController(None, title='Brightness Controller')
    app.MainLoop()

rawDescription: How to disable resizing in wx python widget?

description: Disable resizing in wx python widget


code: df['detail'] = 'file_' + df.index.map(str)

rawDescription: Concatenate index and string to new column


code:
def get_score(player):
    score = player.points
    for child in children:
        score += get_score(child)*.1
    return score

rawDescription: Calculate score in a pyramid score system


code:
foo = list(
    dateutil.rrule.rrule(dateutil.rrule.DAILY,
                         dtstart=datetime.date(2012, 2, 19),
                         until=datetime.date(2015, 2, 19))
)

rawDescription: Chunking dates into mangeable groups w/ python


rawDescription: column names and types for insert operation in sqlalchemy

description: Column names and types for insert operation in sqlalchemy


code: index = post_indices.get(a_tuple, pre_indices.get(a_tuple))

rawDescription: fast data comparison in python

description: Fast data comparison in python


code: super(Worker, self).__init__()

rawDescription: How to call constuctor from superclass

description: Call constuctor from superclass


code:
class User(object):
    def __init__(self, id=None, name=None):
        self.id = id
        self.name = name

user = User(1, 'name_1')
assert 1 == user.id

user_list = [user, User(2, 'name_2')]
assert any(2 == u.id for u in user_list)

rawDescription: Using __contains__ on a list of custom class objects


code:
dict1 = {'A': []}
dict1['A'].append(1)
dict1

rawDescription: Adding a item into a a dictionary in Python


rawDescription: How to realize a very big int matrix with 5 string columns in numpy (python3)?

description: Realize a very big int matrix with 5 string columns in numpy (python3)


rawDescription: How to append a vector to a matrix in python

description: Append a vector to a matrix in python


code:
def request_exit_status(self, data):
    """
    When the server sends the command's exit status, record it for later
    delivery to the protocol.

    @param data: The network-order four byte representation of the exit
        status of the command.
    @type data: L{bytes}
    """
    (status,) = unpack('>L', data)
    if status != 0:
        self._reason = ProcessTerminated(status, None, None)

rawDescription: How do I (can I?) get the exit status from a command?


rawDescription: Python 2.7: reading from .txt to matrix

description: Python 2.7: reading from .txt to matrix


code:
(data - data.round()).nonzero()
(array([2, 3]),)

rawDescription: How can I get index of elements which are not integer

description: Get index of elements which are not integer


code:
templates.append(u"blog/blog_post_list_%s.html" %
                          unicode(category.slug))

rawDescription: Customizing Mezzanine

description: Customizing Mezzanine


code:
from calendar import monthrange
monthrange(2011, 2)

rawDescription: How do we determine the number of days for a given month in python


rawDescription: How to replace unicode characters in string with something else python?

description: Replace unicode characters in string with something else python


code:
import re
from random import choice

def replace_random(src, frm, to):
    matches = list(re.finditer(frm, src))
    replace = choice(matches)
    return src[:replace.start()] + to + src[replace.end():]

rawDescription: Replace a random instance of a substring in a string


code:
unique = [''.join(x)  for x in set(list(zip(StringA, StringB)))]
unique

rawDescription: Finding unique combinations of two strings in python


code:
from dateutil import tz
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc_time = (epoch_start + delta).replace(tzinfo=from_zone)
utc_time.astimezone(to_zone)

rawDescription: Convert Long Int Timestamp to Date/Time

description: Convert Long Int Timestamp to Date/Time


code: print(pth[pth.rindex("/") + 1:])

rawDescription: extract substring from string, python

description: Extract substring from string, python


code:
import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np
import datetime as dt
import time

n=20
duration=1000
now=time.mktime(time.localtime())
timestamps=np.linspace(now,now+duration,n)
dates=[dt.datetime.fromtimestamp(ts) for ts in timestamps]
datenums=md.date2num(dates)
values=np.sin((timestamps-now)/duration*2*np.pi)
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=25 )
ax=plt.gca()
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(datenums,values)
plt.show()

rawDescription: plotting unix timestamps in matplotlib

description: Plotting unix timestamps in matplotlib


code: parent = ('    ' if comment['parent'] == cid-1 else commit['parent']) if 'parent' in commit else '<no parent>'

rawDescription: nested if-else as one-liners

description: Nested if-else as one-liners


code:
class Foo():

    # add class dictionary mapping uids to foos
    uid_to_foo = {}

    def __init__(self, uid):
        self.uid = uid
        self.__hash = hash(self.uid)

        # add to class-level mapping
        Foo.uid_to_foo[uid] = self

    def __hash__(self):
        return self.__hash

    def __eq__(self, other):
        return self.__hash == other.__hash

rawDescription: Find item in set via hash

description: Find item in set via hash


rawDescription: Random word generator termination condition malfunctioning


code:
def __anonimous(word):
    return word
__decorator = gets_arg_from(the_list)
print_func = __decorator(__anonimous)

rawDescription: Decorator which conditionally activates another decorator?


code:
foo.func_defaults = (2, 3)
foo()

rawDescription: Change default arguments of function in python


code:
import re

startflag = False
with open('report.txt','r') as infile:
    with open('abx.txt','w') as outfile:
        outfile.write('Date|Time|Name|Account|Specimen|Source|Antibiotic\n')
        for line in infile:
            if '---------------' in line:
                if startflag:
                    outfile.write('|'.join((date, time, name, account, spec, source, anti))+'\n')
                else:
                    startflag = True
                continue
            if 'Activity' in line:
                startflag = False

            acc_name = re.findall('HH\d+ \w+,\w+', line)
            if acc_name:
                account, name = acc_name[0].split(' ')

            date_time = re.findall('(?<=Coll: ).+(?= Recd:)', line)
            if date_time:
                date, time = date_time[0].split('-')

            source_re = re.findall('(?<=Source: ).+',line)
            if source_re:
                source = source_re[0].strip()

            anti_spec = re.findall('^ +(?!Source)\w+ *\w+ + \S+', line)
            if anti_spec:
                stripped_list = anti_spec[0].strip().split()
                anti = stripped_list[-1]
                spec = ' '.join(stripped_list[:-1])

rawDescription: Python: How to loop through blocks of lines and copy specific text within lines


code:
def pairs(t):
    a, b = tee(t)
    next(b)
    for ind, (t1, t2) in enumerate(zip(a, b)):
        it = iter(t2)
        nxt = next(it)
        for ele in t1:
            n = next(it)
            yield [(ind, ele), (ind + 1, nxt)]
            yield [(ind, ele), (ind + 1, n)]
            nxt = n

from pprint import pprint as pp
pp(list(pairs(t)),compact=1)

rawDescription: Convert tree nodes to coordinates of endpoints of edges


code:
from sympy import *
x, y, eta = symbols('x y eta', real=True)
re(integrate(1/(x - y + I*eta), (x, -1, 1))).simplify().subs({eta: 0})
# -> log(Abs(-y + 1)/Abs(y + 1))

rawDescription: Python: Find principal value of an integral numerically


code:
import csv
import json

import pandas as pd
from pandas.io.json import json_normalize

with open('sample.csv') as fh:
    rows = csv.reader(fh, delimiter='|')
    header = next(rows)

    # "transpose" the data. `data` is now a tuple of strings
    # containing JSON, one for each row
    idents, dists, data = zip(*rows)

data = [json.loads(row) for row in data]
df = json_normalize(data)
df['ids'] = idents
df['dists'] = dists

rawDescription: Extract nested JSON embedded as string in Pandas dataframe


code:
import csv
import datetime

my_dict = {
  '20140311': {
    '1030': {
      'total_price': 9421626, 'end': 6.76, 'high': 6.85, 'start': 6.78, 'low': 6.67, 'volumn': 1396431
    },
    '1130': {
      'total_price': 5042807, 'end': 6.86, 'high': 6.91, 'start': 6.76, 'low': 6.76, 'volumn': 735220
    },
    '1400': {
      'total_price': 5410292, 'end': 6.79, 'high': 6.9, 'start': 6.88, 'low': 6.76, 'volumn': 792890
    },
    '1500': {
      'total_price': 6470290, 'end': 6.83, 'high': 6.85, 'start': 6.79, 'low': 6.74, 'volumn': 954111
    }
  }
}

def initialize_keys():
  for dict1 in my_dict.itervalues():
    for dict2 in dict1.itervalues():
      return dict2.keys()

with open('mycsvfile.csv', 'wb') as f:
  w = csv.DictWriter(f, ['datetime'] + initialize_keys())
  w.writeheader()
  for datestr, dict1 in my_dict.iteritems():
    for timestr, dict2 in dict1.iteritems():
      whole_row = {}
      whole_row['datetime'] = datetime.datetime\
                .strptime(datestr + timestr, '%Y%m%d%H%M')\
                .strftime('%Y/%m/%d %H:%M')
      whole_row.update(dict2)
      w.writerow(whole_row)

rawDescription: How to save stock data to csv file using python

description: Save stock data to csv file using python


rawDescription: Replacing pandas column with a subset of itself through regex


code: logger.error('oops caused by %s' % exc)

rawDescription: Logging Format Interpolation

description: Logging Format Interpolation


code:
djs = DisjointSet()
all_values = set()
for key, values in my_dict.items():
    all_values.add(key)
    all_values.update(values)
    for val in values:
        l1 = djs.find(key)
        l2 = djs.find(val)
        if l1 != l2:
            djs.union(l1, l2)

roots = {djs.find(x) for x in all_values}
print("The number of disjoint sets is:", len(roots))

rawDescription: In Python, count unique key/value pairs in a dictionary


rawDescription: Python - slice array until certain condition is met


rawDescription: Python:How to split file into chunks by the occurrence of the header word


code:
logger = logging.getLogger()
hipchat_logger = logging.getLogger("hipchat")

rawDescription: Not able to log to two different places using Python logging module


code:
import uuid
from sqlalchemy.types import TypeDecorator, VARCHAR

class UUID4(TypeDecorator):
    """Portable UUID implementation

    >>> str(UUID4())
    'VARCHAR(36)'
    """

    impl = VARCHAR(36)

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        else:
            if not isinstance(value, uuid.UUID):
                return str(uuid.UUID(value))
            else:
                # hexstring
                return str(value)

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid.UUID(value)

rawDescription: Python-Sqlalchemy Binary Column Type HEX() and UNHEX()


code:
import re
f_sym_st = "(sin(x0))**2+exp(x1)*cos(x2)"
f_opt_st = re.sub(r"\bx(\d+)", r"x[\1]", f_sym_st)
f_opt_st

rawDescription: Replace a string dynamically in Python

description: Replace a string dynamically in Python


code:
(y,z) <--- tuple
q <--- variable

rawDescription: How to call a function which returns multiple values

description: Call a function which returns multiple values


code:
for char in postfix_expression:
    if char in OperatorFunctions:
        stack.append(OperatorFunctions[char](stack.pop(), stack.pop()))
    else:
        stack.append(char)

rawDescription: Python operators

description: Python operators


code:
for data in soup.find_all('td', attrs={'class': 'yfnc_tabledata1'})[0:6]:
    print (data.text)

rawDescription: Python webscrape text inside of multiple tags


code:
# find indices where LL is "A" or "C"
ind = np.array([True, False, True])
LL[ind]

rawDescription: Logical vector as index in Python?

description: Logical vector as index in Python


code:
delegate = MyDelegate()
tree = QTreeWidget()
tree.setItemDelegate(delegate)

rawDescription: How to set the icon-size in a QTreeWidget?

description: Set the icon-size in a QTreeWidget


rawDescription: Parse valid JSON object or array from a string


code: timedelta(**{time_unit: num})

rawDescription: Pass time unit as a variable to the keyword argument in time delta function.


code:
def f():
 for i in range(0,100):
   if i:
     pass
def g():
 for i in range(0,100):
   if i != 0:
     pass
from dis import dis
dis(f)
dis(g)

rawDescription: in python why if rank: is faster than if rank != 0:

description: In python why if rank: is faster than if rank != 0:


code:
class TwoKindsInputReader(InputReader):
    _APP_PARAM = "_app"
    _KIND1_PARAM = "kind1"
    _KIND2_PARAM = "kind2"
    MAPPER_PARAMS = "mapper_params"

    def __init__(self, reader1, reader2):
        self._reader1 = reader1
        self._reader2 = reader2

    def __iter__(self):
        for u in self._reader1:
            for e in self._reader2:
                yield (u, e)

    @classmethod
    def from_json(cls, input_shard_state):
        reader1 = DatastoreInputReader.from_json(input_shard_state[cls._KIND1_PARAM])
        reader2 = DatastoreInputReader.from_json(input_shard_state[cls._KIND2_PARAM])

        return cls(reader1, reader2)

    def to_json(self):
        json_dict = {}
        json_dict[self._KIND1_PARAM] = self._reader1.to_json()
        json_dict[self._KIND2_PARAM] = self._reader2.to_json()
        return json_dict

    @classmethod
    def split_input(cls, mapper_spec):
        params = mapper_spec.params
        app = params.get(cls._APP_PARAM)
        kind1 = params.get(cls._KIND1_PARAM)
        kind2 = params.get(cls._KIND2_PARAM)
        shard_count = mapper_spec.shard_count
        shard_count_sqrt = int(math.sqrt(shard_count))

        splitted1 = DatastoreInputReader._split_input_from_params(app, kind1, params, shard_count_sqrt)
        splitted2 = DatastoreInputReader._split_input_from_params(app, kind2, params, shard_count_sqrt)
        inputs = []

        for u in splitted1:
            for e in splitted2:
                inputs.append(TwoKindsInputReader(u, e))

        #mapper_spec.shard_count = len(inputs) #uncomment this in case of "Incorrect number of shard states" (at line 408 in handlers.py)
        return inputs

    @classmethod
    def validate(cls, mapper_spec):
        return True #TODO

rawDescription: MapReduce on more than one datastore kind in Google App Engine


code:
import numpy as np
arr = np.arange(1,10)
mask = np.ones(arr.shape,dtype=bool)
mask[5]=0
arr[mask]

rawDescription: Index all *except* one item in python

description: Index all *except* one item in python


rawDescription: Finding multiple minimums and adding new column in pandas


rawDescription: Downloaded filename with Google App Engine Blobstore


code: r = requests.get("https://example-jira.com/step-auth-gss", auth=requests_kerberos.HTTPKerberosAuth())

rawDescription: JIRA REST API and kerberos authentication


rawDescription: Can dictionary keys be forced to a particular order?


rawDescription: Not sure how to parse this

description: Not sure how to parse this


code:
frame['a'].shift()
frame['a'].shift().fillna(False)  # actually this is not needed, but perhaps clearer

rawDescription: doing calculations in pandas dataframe based on trailing row

description: Doing calculations in pandas dataframe based on trailing row


rawDescription: How to search & replace in Python?

description: Search & replace in Python


code: import subprocess

rawDescription: Python: Spawning another program

description: Python: Spawning another program


code:
def multifind(strg, gram):
    positions = []
    end = len(strg)
    pos = 0
    while pos < end:
        pos = strg.find(gram, pos)
        if pos == -1:
            break
        positions.append(pos)
        pos += 1
    return positions

rawDescription: How to find recurring patterns on a hexdump?

description: Find recurring patterns on a hexdump


code:
# place a text box in lower left in axes coords
ax.text(0.05, 0.05, textstr, transform=ax.transAxes, fontsize=14,
    verticalalignment='bottom', bbox=props)

rawDescription: How to put text inside a box on a plot in matplotlib

description: Put text inside a box on a plot in matplotlib


code:
def in_stock(self):
    if 'destroyed' and 'permanent_retrieval' not in self.itemstatushistory_set.latest().status.description:
        return True

rawDescription: Django query: Want to count an empty value


code:
from django.db import models
from solo.models import SingletonModel

class SiteConfiguration(SingletonModel):
    site_name = models.CharField(max_length=255, default='Site Name')
    maintenance_mode = models.BooleanField(default=False)

    def __str__(self):
        return u"Site Configuration"

    class Meta:
        verbose_name = "Site Configuration"

rawDescription: django rest-framework singleton ViewSet

description: Django rest-framework singleton ViewSet


rawDescription: Python - Count number of times function passes through decorator


code:
chunk = np.random.randint(256, size=(1000, 1000))

def count_chunk(chunk):
    rows, cols = chunk.shape
    col_idx = np.arange(cols) * 256
    counts = np.bincount((col_idx[None, :] + chunk).ravel(),
                         minlength=256*cols)
    return counts.reshape(-1, 256)

def count_chunk_by_rows(chunk):
    counts = np.zeros(chunk.shape[1:]+(256,), dtype=np.int)
    indices = np.arange(chunk.shape[-1])
    for row in chunk:
        counts[indices, row] += 1
    return counts

rawDescription: Efficiently indexing numpy array with a numpy array


rawDescription: Python: Nested If Looping

description: Python: Nested If Looping


code: dict.fromkeys((tuple(i) for i in [[1,2],[3,4]]), 0)

rawDescription: How do I make a list a key value in a dictionary?

description: Make a list a key value in a dictionary


rawDescription: Iterating over multiple lists simultaneously in Python


code:
fig, ax = plt.subplots()
b = customized_box_plot(percentiles, ax, redraw=True, notch=0, sym='+', vert=1, whis=1.5)
plt.show()

rawDescription: Is it possible to draw a matplotlib boxplot given the percentile values instead of the original inputs?


code:
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
     globals()[var_name] = None

rawDescription: Easier way to assign a value to multiple global variables in a function


code:
def mkdt(d):
    ll = []
    for k,v in d.items():
        if isinstance(v,np.ndarray):
            ll.append((k,v.dtype))
        else:
            ll.append((k,mkdt(v)))
    return ll

In [176]: np.dtype(foo(d))
Out[176]: dtype([('a', '<i4'), ('b', [('b1', '<f8'), ('b2', [('c', '<i4')])])])

rawDescription: numpy structured array from arbitrary-level nested dictionary

description: Numpy structured array from arbitrary-level nested dictionary


code:
import pandas as pd
df = pd.read_csv("sample.csv", names="date time price mag signal".split())
v=df["signal"]=="S"
t=df["time"]=="4:45"
u=df["signal"]!="S"
df[t]
df["price"][t]
df["price"][v | (u & t)]

rawDescription: List Comprehension Loop

description: List Comprehension Loop


code:
from decimal import *

ratings_data = [(Decimal('3.6813'),), (Decimal('3.6816'),),
                (Decimal('3.6804'),), (Decimal('3.6794'),),
                (Decimal('3.6789'),), (Decimal('3.6791'),)]

adjusted = [float(i[0]) for i in ratings_data]  # The important line

rawDescription: Formatting of MySQL data using python

description: Formatting of MySQL data using python


rawDescription: operation in arrays

description: Operation in arrays


code:
number = int(input('What number do you want to start with? '))

while number > 9:
    decompose_helper, number = number, 0
    while decompose_helper: # != 0 is implied
        number += decompose_helper % 10
        decompose_helper = decompose_helper // 10

print('Result is', number)

rawDescription: How to add numbers in an integer

description: Add numbers in an integer


rawDescription: Python - Remove duplicate key from a list of dictionaries


code:
def parseline(l):
    sp = l.split('=')
    return sp[0], int(sp[1]) if len(sp) > 1 else None

rawDescription: Extracting specific variables of a line with linecache


rawDescription: Joining MultiIndexed Pandas Dataframes for Another MultiIndexed Dataframe


code:
for k, v in PointsOfInterest.iteritems():
    if k in mypkt.Text:
        v[1] += 1

rawDescription: Python incrementing a Dictionary value entry held within a list


code:
get_distinct_values("ccol.csv", 0)
get_distinct_values("ccol.csv", 1)
get_distinct_values("ccol.csv", 2)

rawDescription: reading a csv with python and handling blanks

description: Reading a csv with python and handling blanks


code:
def ask_for_directory(self):
    while not self.directory_path:
        self.directory_path = filedialog.askdirectory(mustexist=True, title=self.dialog_title)
        if self.directory_path:
            if not os.access(self.directory_path, os.R_OK):
                self.directory_path = None
                if not messagebox.askretrycancel(title=self.dialog_title, message="Can't read directory."):
                   break
        else:
            break

rawDescription: How do I hook into tkinters FileDialog?

description: Hook into tkinters FileDialog


code:
import time
time.sleep.__module__

rawDescription: eventlet.greenthread.sleep VS time.sleep in monkey-patched environment

description: Eventlet.greenthread.sleep VS time.sleep in monkey-patched environment


code:
line = 'hello world'
' '.join([word[::-1] for word in line.split()])

rawDescription: How do I reverse each word in a string, but in the same sentence order?

description: Reverse each word in a string, but in the same sentence order


code:
x = (x > 9 and 1) or x
x = 1 or x # or gets short-circuited so second expression is not evaluated
x = 1

rawDescription: Zero assignement in inline comparison

description: Zero assignement in inline comparison


code:
# file: test.py
from itertools import ifilter, islice

def OP(l):
    true_found = False
    for v in l:
        if v and not true_found:
            true_found=True
        elif v and true_found:
             return False #"Too Many Trues"
    return true_found

def DavidRobinson(l):
    return l.count(True) == 1

def FJ(l):
    return len(list(islice(ifilter(None, l), 2))) == 1

def JonClements(iterable):
    i = iter(iterable)
    return any(i) and not any(i)

def moooeeeep(l):
    true_found = False
    for v in l:
        if v:
            if true_found:
                # found too many True's
                return False
            else:
                # found the first True
                true_found = True
    # found zero or one True value
    return true_found

rawDescription: How can I check that a list has one and only one truthy value?

description: Check that a list has one and only one truthy value


code:
import yaml

config_list = ( 'sleep 200', '[sh, -xc, "echo $test\'  test\' >> /etc/hosts"]')
results = {'properties': []}
run_cmd = results['properties']
for i in range(len(config_list)):
    run_cmd.append(config_list[i])

with open("f2.yml", "w") as yaml_file:
    yaml_file.write(yaml.dump(results, default_flow_style=False, allow_unicode=True))

yaml_file.close()

yaml_file2 = open('f2.yml', 'r')
data = yaml_file2.read()
print(yaml.load(data))

rawDescription: escape characters and strings

description: Escape characters and strings


code:
from multiprocessing import *
import time

def main():
    array, loops = list(range(1000)), 1000
    variable = Value('I')
    p = Process(target=sample, args=(array, loops, variable))
    p.start()
    while variable.value < 1000:
        print('Still less than 1000')
        time.sleep(0.005)
    print('Must be at least 1000')
    p.join()
    print('Value is', variable.value)

def sample(array, loops, variable):
    for number in range(loops):
        variable.value = number * 10
    print('Sample is done')

if __name__ == '__main__':
    main()

rawDescription: Return value while executing paralel processes with python


code:
def __iter__(self):
    # Remember, self is our UnorderedList.
    # In order to get to the first Node, we must do
    current = self.head
    # and then, until we have reached the end:
    while current is not None:
        yield current
        # in order to get from one Node to the next one:
        current = current.next

rawDescription: Python Linked List with Nodes. Iterable

description: Python Linked List with Nodes. Iterable


code:
from maya import cmds

def getHistoryShape(name):
    history = cmds.listHistory(name)
    filteredShape = cmds.ls(history, shapes=1)[0]
    return filteredShape

def drawHelix(radius, length, coils):
    cyl = cmds.cylinder( ch=True, radius=radius, ax=(0,1,0),
                         hr=float(length)/float(radius) )

    # build a curve on the cylinders surface
    crv = cmds.curveOnSurface(cyl[0], d=1,
                              uv=[(0,0),(length, coils*4)],
                              k=[0,1])
    # make a duplicate that is visible
    crv = cmds.duplicateCurve(ch=1, rn=0, local=1)

    # tell maya to ignore the cylinder as a piece of geometry
    shape = getHistoryShape(cyl[0])
    cmds.setAttr(shape+'.intermediateObject', 1)

    cmds.rename(cyl[0],'helix1')
    return crv

rawDescription: Maya Variable Concatenation

description: Maya Variable Concatenation


code:
childid = []
for cmdline in cmdlines:
  p = subprocess.Popen(cmdline.split())
  childid[p.pid] = cmdline

rawDescription: Execute and monitor multiple instances of external program in Python


code:
class Wrapper(object):
    '''
    Object wrapper class.
    This a wrapper for objects. It is initialiesed with the object to wrap
    and then proxies the unhandled getattribute methods to it.
    Other classes are to inherit from it.
    '''
    def __init__(self, obj):
        '''
        Wrapper constructor.
        @param obj: object to wrap
        '''
        # wrap the object
        self._wrapped_obj = obj

    def __getattr__(self, attr):
        # see if this object has attr
        # NOTE do not use hasattr, it goes into
        # infinite recurrsion
        if attr in self.__dict__:
            # this object has it
            return getattr(self, attr)
        # proxy to the wrapped object
        return getattr(self._wrapped_obj, attr)

rawDescription: Python: How to extend a huge class with minimum lines of code?


code:
a = ['hi','helllo']
print(' '.join(a))

rawDescription: How to use this for loop to get expected result in python

description: Use this for loop to get expected result in python


code:
import utils_num as UN
print(UN.isclose([1e10,1e-7], [1.00001e10,1e-8]))

rawDescription: How do I install numpy/core/numeric.py file on my machine; I want isclose()

description: Install numpy/core/numeric.py file on my machine; I want isclose()


code:
from ctypes import *

class Test(Structure):
    _fields_ = [('size',c_int),
                ('arr',c_int*0)]

dll = CDLL('x')

Test_alloc = dll.Test_alloc
Test_alloc.argtypes = [c_int]
Test_alloc.restype = POINTER(Test)

Test_free = dll.Test_free
Test_free.argtypes = [POINTER(Test)]
Test_free.restype = None

t = Test_alloc(10)
print(t.contents.size)
arr = cast(t.contents.arr,POINTER(c_int))
for i in range(t.contents.size):
    print(arr[i])
Test_free(t)

rawDescription: does python ctypes supports size-0 array?

description: Does python ctypes supports size-0 array


code:
from PyQt4 import QtCore, QtGui
import sys

class Polyhedra(QtGui.QMainWindow):

    def __init__(self):
        super(Polyhedra, self).__init__()

        self.initUI()

    def initUI(self):

        # Poly names
        self.pNames = QtGui.QLabel(self)
        polyNameInput = QtGui.QLineEdit(self)
        # polyName entry
        polyNameInput.textChanged[str].connect(self.onChanged)

        # Polytype selection
        self.defaultPolyType = QtGui.QLabel("Random polyhedra", self)
        polyType = QtGui.QComboBox(self)
        polyType.addItem("Random polyhedra")
        polyType.addItem("Spheres")
        polyType.addItem("Waterman polyhedra")
        polyType.activated[str].connect(self.onActivated)

        # Layout
        widget = QtGui.QWidget()
        vbox = QtGui.QVBoxLayout(widget)
        vbox.addWidget(polyNameInput)
        vbox.addWidget(self.pNames)
        vbox.addWidget(polyType)
        vbox.addWidget(self.defaultPolyType)
        vbox.addStretch()

        # Set up window
        self.setGeometry(500, 500, 300, 300)
        self.setWindowTitle('Pyticle')
        self.layout().addWidget(widget)
        self.show()

    # Combo box
    def onActivated(self, text):

        self.defaultPolyType.setText(text)
        self.defaultPolyType.adjustSize()

    # Poly names
    def onChanged(self, text):

        self.pNames.setText(text)
        self.pNames.adjustSize()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Polyhedra()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt QVBoxLayout and missing widgets?

description: PyQt QVBoxLayout and missing widgets


rawDescription: How to convert characters of a string from lowercase to upper case and vice versa without using string functions in python?

description: Convert characters of a string from lowercase to upper case and vice versa without using string functions in python


code:
yourQTextEdit.setStyleSheet ('''
    QTextEdit {
        font: 10pt "Consolas";
    }
''')

rawDescription: text formatting in qtextedit in pyqt

description: Text formatting in qtextedit in pyqt


code: df[df['A'].apply(lambda x: x in given)]

rawDescription: How to use boolean indexing for substring relation in pandas dataframe?

description: Use boolean indexing for substring relation in pandas dataframe


code:
with open('file_name', 'r+') as my_file: # this automatically closes it
    lines = my_file.readlines()
    # now, rewrite the data
    for line in lines:
        my_file.write(line.title())

rawDescription: Python code not writing into file

description: Python code not writing into file


rawDescription: How to get all values from Python tuple keys from dictionaries into one list?

description: Get all values from Python tuple keys from dictionaries into one list


code:
alist = [1, 2, 3]
one, two, three = alist
one
two
three

rawDescription: Multiple values for key in dictionary in Python


code:
fractions = []
sum = 0.0
for i in range(1, 56):
    fraction = 2 ** i
    if sum + (1.0 / fraction) <= 0.1:
        fractions.append(fraction)
        sum += 1.0 / fraction

fractions

description: Why 10 // .01 = 999.0


code:
v = CountVectorizer(ngram_range=(1, 2))
pprint(v.fit(["an apple a day keeps the doctor away"]).vocabulary_)

rawDescription: Understanding the `ngram_range` argument in a CountVectorizer in sklearn


code:
seg = 5
img2_array = img2_array.tolist()
img_grouped = np.array([img2_array[0][x:x+seg] for x in range(0,len(img2_array),seg)])

rawDescription: Group pixels in an Image array, in Python


code:
# -*- coding: cp1252 -*-
import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup

def match_both(arg):
    if arg == "listGrid-price" or arg == "listGrid-price-outOfStock":
        return True
    return False

def not_review(arg):
    if not arg:
        return arg
    return "Write a review" not in arg

page = urllib2.urlopen('http://www.att.com/shop/wireless/devices/smartphones.deviceListGridView.xhr.flowtype-NEW.deviceGroupType-Cellphone.paymentType-postpaid.packageType-undefined.html?taxoStyle=SMARTPHONES&showMoreListSize=1000').read()
soup = BeautifulSoup(page)
soup.prettify()
with open('AT&T_2012-12-28.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price"])
    items = soup.findAll('a', {"class": "clickStreamSingleItem"},text=not_review)
    prices = soup.findAll('div', class_=match_both)
    for item, price in zip(items, prices):
        textcontent = u' '.join(price.stripped_strings)
        if textcontent:
                spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") ,unicode(item.string).encode('utf8').replace('â„¢','').replace('Â®','').strip(),textcontent])

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


code:
import pandas as pd
df = pd.DataFrame(dict(labels=idx, values=values))
df

rawDescription: getting median of particular rows of array based on index

description: Getting median of particular rows of array based on index


code:
from itertools import combinations_with_replacement

fangs = list(combinations_with_replacement(range(min, max), n))

rawDescription: Pythonic way to generate a tuple of length n


rawDescription: Shuffling two lists separately in Python


code:
def get_rank(infile):
    m = re.search(r'(?:\((\d+)\))[^()]*', infile)
    if m:
        return int(m.group(1))
    return 0
infiles = filter(os.path.isfile, os.listdir(os.getcwd()))
infiles = [os.path.join(os.getcwd(), f) for f in infiles if f.endswith('.txt')]
filerank = (get_rank(infile) for infile in infiles)
renames = zip(filerank, infiles, rename_files)
renames.sort(key=lambda x: x[0])
for _, infile, outfile in renames:
    os.rename(infile, outfile + ".pdb")

rawDescription: Rename files based on an input list Python


code:
s = 'def outer():\n    ' + '\n    '.join(code.strip().split('\n'))
exec(compile(s, '<str>', 'exec').co_consts[0], {}, {})

rawDescription: C Python: Running Python code within a context


code: values_set = set(d.viewvalues())

rawDescription: Reversing dictionary: time and space

description: Reversing dictionary: time and space


code: counters = numpy.array([DATA[letter] for peptide in peptides for letter in peptide])

rawDescription: Generate a three dimensional array in python by iterating through a list


code: plt.xticks(plt.xticks()[0], labels)

rawDescription: How to change ticks in matplotlib when saving to a figure?

description: Change ticks in matplotlib when saving to a figure


rawDescription: remove empty numpy array

description: Remove empty numpy array


code:
import example
foo1 = example.Foo("abc")
foo2 = example.Foo("abc")
foo3 = example.Foo("def")
assert(foo1 == foo1)
assert(foo1 == foo2)
assert(foo1 is not foo2)
assert(foo1 != foo3)
foo1.value = foo3.value
assert(foo1 != foo2)
assert(foo1 == foo3)

rawDescription: Boost Python overriding equality operator


code:
import pyMyDB
import Driving

m = pyMyDB.MyDB()

m.Driving.GetTachometerReading()

rawDescription: Access parent object from submodule

description: Access parent object from submodule


code:
symbols = [0, 4, 5, 3, 1, 1, 7, 6, 5, 2, 6, 2]
BitArray().join(BitArray(uint=x, length=3) for x in symbols)
_.tobytes()

rawDescription: How to pack arbitrary bit sequence in Python?

description: Pack arbitrary bit sequence in Python


code:
class Dispatcher(object):

    def __init__(self, caller, name):
        self.name = name
        self.caller = caller

    def __call__(self, *a, **ka):
        print('Call on Dispatcher registered!',
              'Will create method on',
              self.caller.__class__.__name__,
              'now.')
        setattr(self.caller, self.name, self.mock)
        return getattr(self.caller, self.name)(*a, **ka)

    @classmethod
    def mock(cls, *a, **ka):
        return 'Some default value for newly created methods.'

class MyClass(object):

    def __getattr__(self, attr):
        return Dispatcher(self, attr)

instance = MyClass()
print(instance.new_method, '\n')
print(instance.new_method(), '\n')
print(instance.new_method(), '\n')
print(instance.other_method)

rawDescription: Is possible to create a non-existent method when it is called in Python?


code:
ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)
ts.to_pydatetime()

rawDescription: Converting between datetime and Pandas Timestamp objects


code:
days = max(timedelta(days=1),
           datetime.strptime(todate, "%Y-%m-%d") -
           datetime.strptime(fromdate, "%Y-%m-%d"))

rawDescription: How do i make the calculation as 1 day when subtracting same two dates

description: Make the calculation as 1 day when subtracting same two dates


code:
from itertools import product, ifilter
gen = product((0,1,2,3), repeat=4)
res = ifilter(lambda x: sum(x) < 4, gen)
res = list(res) # converting to list only at the end

rawDescription: Combination of combinations that cut of with the sum of 4


code:
ud = {}
ud['first'] = 1
ud['second'] = 2
ud['third'] = 3
ud.values()

rawDescription: Dictionary values are not ordered python


code:
x=np.arange(12).reshape(3,4,order='C')
y=x.T
x.__array_interface__
y.__array_interface__

rawDescription: When will numpy copy the array when using reshape()


code:
myapp/admin.py
from django.contrib import admin

from .models import *

admin.site.register(A)
admin.site.register(B)
admin.site.register(C)

rawDescription: Joining multiple tables for a single report in Django


code: [('Host', 'www.perdu.com'), ('Connection', 'keep-alive'), ('Cache-Control', 'max-age=0'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8'), ('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36'), ('DNT', '1'), ('Accept-Encoding', 'gzip,deflate,sdch'), ('Accept-Language', 'en-US,en;q=0.8,es;q=0.6,fr;q=0.4'), ('',)]

rawDescription: Split list with colon seperated items into list of tuples


code:
TABWIDTH=8
def my_len(s):
    return len(s.expandtabs(TABWIDTH))

def pad_with_tabs(s,maxlen):
    return s+"\t"*((maxlen-len(s)-1)/TABWIDTH+1)

rawDescription: Python tabstop-aware len() and padding functions


rawDescription: re.match (regular expression) in python: matching issue

description: Re.match (regular expression) in python: matching issue


code:
import dis

def test():
    name = 'test'
    tdict = {}
    tdict[name] = 0
    tdict[name] += 1
    tdict[name] += 1

dis.dis(test)

rawDescription: Python interpreted code optimisation

description: Python interpreted code optimisation


code:
from redis_cache import get_redis_connection
con = get_redis_connection('default')
con

rawDescription: Django connection to Redis

description: Django connection to Redis


code:
def reverse(PB={'l': 3, 'y':1, 'u':2}):
    PB['l'] += 4

    print(PB)

reverse()
reverse()
reverse()

rawDescription: problems with dict.keys not printing a list but printing the view of the list

description: Problems with dict.keys not printing a list but printing the view of the list


code:
results = []

for jj in range(len(lst) - 1):
    if lst[jj] != ')' and lst[jj+1] == '(':
        parens = 0
        results.append([lst[jj]])
        substring = lst[jj:]
        for ii, ch in enumerate(substring):
            if ch == '(':
                parens += 1
                if parens == 1:
                    results[-1].append(substring[ii+1])
            elif ch == ')':
                parens -= 1
                if parens < 0:
                    break

rawDescription: How to iterate over a list of strings and do pattern matching?

description: Iterate over a list of strings and do pattern matching


code: import os.walk as walk

rawDescription: from ... import OR import ... as for modules

description: From ... import OR import ... as for modules


rawDescription: How to avoid printing scientific notation in python without adding extra digits?

description: Avoid printing scientific notation in python without adding extra digits


code: import networkx as nx

rawDescription: How to do shortest path algorithm for unweighted graph?

description: Do shortest path algorithm for unweighted graph


code:
class MyForm(Form):
    name = StringField(u'Full Name', widget=AngularJSTextInput())

rawDescription: Custom attributes for Flask WTForms

description: Custom attributes for Flask WTForms


code:
import StringIO
f = StringIO()
image.save(f, 'PNG')

f.seek(0) # return the StringIO's file pointer to the beginning of the file

# again this assumes you already connected and logged in
ftp.storbinary("STOR remote_filename.png", f)

rawDescription: PIL.Image.save() to an FTP server

description: PIL.Image.save() to an FTP server


code:
for row in A.T:
    if max(row)>0:
        new_data.append([item*1./max(row) for item in row])
    else:
        new_data.append(row)

rawDescription: Python: Divide values in cell by max in each column


code:
myint = 979
mystr = str(myint)
mystr

rawDescription: How to manipulate digits within an integer/string?

description: Manipulate digits within an integer/string


code:
lines = """{sdfsdfsdfsdfsdf}{sdfsdfsdfsfsdfsdf}{dfsdfsdfsdfsdfsf}{dfsdfsdfsfsdfsd}"""

print("\n".join([line+"}" for line in lines.split("}")][:-1]))

{sdfsdfsdfsdfsdf}
{sdfsdfsdfsfsdfsdf}
{dfsdfsdfsdfsdfsf}
{dfsdfsdfsfsdfsd}

import  re

print("\n".join(re.findall("(\{.*?\})",lines)))

{sdfsdfsdfsdfsdf}
{sdfsdfsdfsfsdfsdf}
{dfsdfsdfsdfsdfsf}
{dfsdfsdfsfsdfsd}

rawDescription: Python to extract parts of data from a file


code:
__setitem__
__delitem__

rawDescription: How to wrap a python dict?

description: Wrap a python dict


code:
thechan = Score.objects.filter(content=44)[0]
thechan.custom_score = 2
thechan.save()

rawDescription: Why can't I save an object in Django?

description: Why can't I save an object in Django


rawDescription: Trouble pivoting / reshaping a pandas dataframe


rawDescription: Call nosetests as a scons task.

description: Call nosetests as a scons task.


rawDescription: Python: Round time to the nearest second and minute


fieldnames: ['type', 'precision', 'width', 'data']

rawDescription: How to store a python dict in Postgresql hstore

description: Store a python dict in Postgresql hstore


code:
print ("hello "
        "world"
        "!")

rawDescription: Python Indentation

description: Python Indentation


code:
tokens = [t for t in uglyTokens if t.encode('utf-8') not in \
          [b'\xc3\xa2\xc2\x80\xc2\xa2', \
           b'\xc3\xa2\xc2\x80\xc2\x99']]

rawDescription: python3 How do I identify / handle unwanted unicode from scraped web page?

description: Python3 How do I identify / handle unwanted unicode from scraped web page


code:
from_number = request.REQUEST.get('From', None)
body = request.REQUEST.get('Body', None)
user = User.objects.get(username=from_number)
quiz = Quiz.objects.get(message=body)
user_quiz = QuizUser.objects.get(user=user, quiz=quiz)
# ... your code ...

rawDescription: Series of Questions without database with Django/Twilio


code: soup.find('b', text='Recommended length of visit:').next_sibling

rawDescription: Scrapy xpath get text of an element that starts with <


code:
import itertools

for numbers in itertools.product([0, 1], repeat=3):
    print(numbers)

rawDescription: Making a list with every possible combination of 0's and 1's in Python


code:
import subprocess
import shlex
import re
url='http://url/1video.mp4'
proc=subprocess.Popen(shlex.split('ffmpeg -i {f}'.format(f=url)),
                      stdout=subprocess.PIPE,
                      stderr=subprocess.PIPE)
dimensions=None
for line in proc.stderr:
    match=re.search(r'(\d+x\d+)',line)
    if match:
        dimensions=match.group(1)
        break
print(dimensions)

rawDescription: Convert complex command into python subprocess


code:
from numpy import array
a = array( [2,3,4] )

rawDescription: How to save a list as numpy array in python?

description: Save a list as numpy array in python


code:
database = {
    "stocks": [
        {
            "group": "Information Technology",
            "data": {
                "portfolio_average_weight": "5.985",
                "portfolio_total_return": "27.948"
            },
            "name": "Google Inc"
        },
        {
            "group": "Information Technology",
            "data": {
                "portfolio_average_weight": "2.896",
                "portfolio_total_return": "24.292"
            },
            "name": "Mastercard Inc"
        }
    ]
}

rawDescription: CSV to JSON Python, Append Group Category to Dictionary


code: findall("%s.*" % name, info)[0]

rawDescription: python 2.2 find string after linebreak

description: Python 2.2 find string after linebreak


code:
class fakemodule(object):

    @staticmethod
    def method(a, b):
        return a+b

import sys
sys.modules["package.module"] = fakemodule

rawDescription: Can I "fake" a package ( or at least a module ) in python for testing purposes?


code: self.c = tk.Checkbutton(..., command=self.enable)

rawDescription: Tkinter: Checkbox variable is always zero


code: df = pd.DataFrame.from_dict({'number': ['50'], 'box': [[]]})

rawDescription: Pandas Dataframe from dict with empty list value


rawDescription: Why this regular expression pattern matches even an extra character in string?


code:
import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset('iris')

length_plot = sns.barplot(x='sepal_length', y='species', data=iris)
plt.savefig('ex1.pdf')
plt.clf()
width_plot = sns.barplot(x='sepal_width', y='species', data=iris)
plt.savefig('ex2.pdf')

rawDescription: Stop seaborn plotting multiple figures on top of one another


rawDescription: Removing "unnamed: #" when writing to CSV using pandas


code:
from cx_Freeze import setup, Executable
files = ['flower.svg']
includes = ['sip', 'PyQt4.QtCore']
setup(
        name = 'Example',
        version = '1.337',
        description = 'Allows user to see what I did there.',
        author = 'something',
        options = {'build_exe': {'include_files':files, 'includes':includes}},
        executables = [Executable('testapp.py')])

rawDescription: Images not showing when running a frozen pyqt app on another computer


code:
class MyView(APIView):
    renderer_classes = (EmberJSONRenderer, )
    # ...

rawDescription: Override JSONSerializer on django rest framework


code: reason = [', '.join(k for k, b in zip(tups, x) if b) for x in zip(*tups.values())]

rawDescription: Filter a tuple with another tuple in Python


code:
# Python - preferred way
squares_of_odds = [x * x for x in a if x % 2 == 1]

# Python - alternate way
map(lambda x: x * x, filter(lambda x: x % 2 == 1, a))

rawDescription: Python list comprehensions nodejs/javascript


code:
np.unique(q)
np.unique(q2)

rawDescription: Numpy.unique - getting output with consistent depth


code:
mult_list = list(map(int, input("Enter numbers seperated by a comma: ").split(',')))
num = 1
for i in mult_list:
    num *= i
print(num)

rawDescription: Using lambda with user input list

description: Using lambda with user input list


code:
# test.py
print("Here!")

def foo():
    print("There!")

rawDescription: when does admin.autodiscover() get executed (python newbie)

description: When does admin.autodiscover() get executed (python newbie)


code:
totaltime = 0.0

while True:
    try:
        new_time = float(input("How long will this task take?\n> "))
        totaltime += new_time
        break
    except ValueError:
        print("You must enter a valid number, written as (H.M).")

rawDescription: If statement looking for float is not working


code:
original_list = [1, 3, 5, 7, 9]
lines_to_write = [2, 4, 6, 8, 10]  # Lines you want to write the results in
total = 0
sum_list = list()

# Get the list of cumulative sums
for element in original_list:
    total = total + element
    sum_list.append(total)
# sum_list = [1, 4, 9, 16, 25]

# Open and read the file
with open('numbers.txt', 'rw+') as file:
    file_lines = file.readlines()
    for element, line in zip(sum_list, lines_to_write):
        file_lines[line-1] = '{}\n'.format(element)
    file.seek(0)
    file.writelines(file_lines)

rawDescription: Adding one element from a list to next,after that to next etc


code:
from extensions import celery, db
from flask.globals import current_app
from celery.signals import task_postrun

@celery.task
def do_some_stuff():
    current_app.logger.info("I have the application context")
    #you can now use the db object from extensions

@task_postrun.connect
def close_session(*args, **kwargs):
    # Flask SQLAlchemy will automatically create new sessions for you from
    # a scoped session factory, given that we are maintaining the same app
    # context, this ensures tasks have a fresh session (e.g. session errors
    # won't propagate across tasks)
    db.session.remove()

rawDescription: How to use Flask-SQLAlchemy in a Celery task

description: Use Flask-SQLAlchemy in a Celery task


rawDescription: simple prediction using Pearson correlation and linear regression with python

description: Simple prediction using Pearson correlation and linear regression with python


code:
for k in (t_dict.viewkeys() & values_to_remove.viewkeys()):
    t_dict[k] -= values_to_remove[k]

rawDescription: Remove values from lists of values in a dictionary


code:
xmin, xmax = self.get_xlim3d() / self.pbaspect[0]
ymin, ymax = self.get_ylim3d() / self.pbaspect[1]
zmin, zmax = self.get_zlim3d() / self.pbaspect[2]

rawDescription: Setting aspect ratio of 3D plot

description: Setting aspect ratio of 3D plot


code:
from multiprocessing import Process, Event

class MyProcess(Process):
    def __init__(self, event, *args, **kwargs):
        self.event = event
        Process.__init__(self, *args, **kwargs)

    def run(self):
        Process.run(self)
        self.event.set()

class PythonHelper(object):
    @staticmethod
    #with your fix
    def run_in_parallel(*functions):
        event = Event()
        processes=[]
        for function in functions:
            process=MyProcess(event, target=function)
            process.start()
            processes.append(process)
        # wait for any process to complete
        event.wait()
        # one process completed
        # terminate all child processes
        for process in processes:
            process.terminate()
        for process in processes:
            process.join()

class Logger(object):
    def run_numbers_1(self):
        for i in range(90000):
            print("1 number: {}".format(i))
    def run_numbers_2(self):
        for i in range(10000):
            print("2 number: {}".format(i))
    def run_logger(self):
        PythonHelper.run_in_parallel(self.run_numbers_1,self.run_numbers_2)

if __name__=="__main__":
    logger=Logger()
    logger.run_logger()

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

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


code: min(d, key=lambda v: abs(v - x))

rawDescription: Python X-axis nearest point

description: Python X-axis nearest point


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

n = 100
x = 1.*np.arange(n)
y = np.random.rand(n)
prop = x**2

fig = plt.figure(1, figsize=(5,5))
ax  = fig.add_subplot(111)
plot_colourline(x,y,prop)

rawDescription: Color line by third variable - Python

description: Color line by third variable - Python


code:
import matplotlib.pyplot as plt

plt.ion()

# plt.plot something

rawDescription: How to plot on Pandas Python

description: Plot on Pandas Python


code:
df["TradeDate"] = pd.to_datetime(df["TradeDate"])
df = df.sort(["Symbol", "TradeDate"])
df

rawDescription: Can I apply a function that uses 'shift' on a grouped data frame, and return a simple data frame from pandas?

description: Apply a function that uses 'shift' on a grouped data frame, and return a simple data frame from pandas


code:
PyOS_snprintf(version, sizeof(version), "%.80s (%.80s) %.80s",
              PY_VERSION, Py_GetBuildInfo(), Py_GetCompiler());

rawDescription: Where is the Python startup banner defined?


code: ['Theone Normalperson', 'Someone Middlename MacIntyre']

rawDescription: Using Regex to 'Clean Up' a List of Names


code:
def delete(request):
    values = request.POST.getlist(u'vehicle')
    # Handling goes here.

rawDescription: Jquery and Django multiple checkbox

description: Jquery and Django multiple checkbox


rawDescription: Set properties for specific patch in matplotlib.collections.PathCollection


code:
class PersonForm(ModelForm):
    ...

    class Meta:
        widgets = {'person_interests': BootstrapCheckboxSelectMultiple,
                   'person_psycho': forms.HiddenInput}
        model = Person

rawDescription: Add css class from database to manytomany field


code: [(u'May 11, 2016 at 17:21', 'http://oilprice.com/Latest-Energy-News/World-News/Oil-Hits-6-Month-High-on-Crude-Inventory-Draw.html'), (u'May 11, 2016 at 16:56', 'http://oilprice.com/Latest-Energy-News/World-News/Nigerian-President-Lashes-Out-At-UK-Over-Stolen-Assets.html'), (u'May 11, 2016 at 15:41', 'http://oilprice.com/Latest-Energy-News/World-News/Germany-Ups-Gazprom-Imports-by-19-percent-in-Q1.html'), (u'May 11, 2016 at 15:39', 'http://oilprice.com/Latest-Energy-News/World-News/Solar-Hits-Millionth-Installation-In-The-US-Faster-Growth-Ahead.html'), (u'May 11, 2016 at 14:14', 'http://oilprice.com/Latest-Energy-News/World-News/OPEC-Production-Up-140000-Bpd-in-April.html'), (u'May 11, 2016 at 14:03', 'http://oilprice.com/Latest-Energy-News/World-News/Tullow-Ghana-Oil-Production-Down-by-More-Than-50.html'), (u'May 11, 2016 at 13:47', 'http://oilprice.com/Latest-Energy-News/World-News/Tesla-To-Complete-Model-3-Design-By-End-June.html'), (u'May 11, 2016 at 12:30', 'http://oilprice.com/Latest-Energy-News/World-News/Iraqi-Kurds-Boost-Oil-Exports-to-Turkey.html'), (u'May 11, 2016 at 11:57', 'http://oilprice.com/Latest-Energy-News/World-News/Security-Services-Raid-Headquarters-of-Ukraines-Largest-Gas-Company.html'), (u'May 11, 2016 at 10:59', 'http://oilprice.com/Latest-Energy-News/World-News/Oil-Up-3-AS-EIA-Reports-34M-Barrel-Crude-Inventory-Drop.html')]

rawDescription: Python and beautifulSoup: scraping two values - url and date and having the return results paired


code: subprocess.call(cmd, shell=True)

rawDescription: How execute script from command prompt in python


code:
for obj_id in g_tree.nodes():
    g_tree.node[obj_id] = g.node[obj_id]

rawDescription: Unable to generate network data in tree format while retaining node attributes


code:
import sys, os, shutil

# awkward kludge to include BigPackage.SmallSubset by hand without having to include the rest of BigPackage
src = [ os.path.join( x, 'BigPackage', 'SmallSubset.py' ) for x in sys.path ]
src = [ x for x in src if os.path.isfile( x ) ][ 0 ]
shutil.copyfile( src, 'BigPackageSmallSubset.py' )
import BigPackageSmallSubset

options = { 'py2exe': { 'excludes' : [ 'BigPackage' ], 'includes' : [ 'BigPackageSmallSubset' ], 'compressed' : True, }, }

# setup( ..., options=options, ... )

os.remove( 'BigPackageSmallSubset.py' )
os.remove( 'BigPackageSmallSubset.pyc' )

rawDescription: py2exe: excluding parts of a package that wants to import all its parts

description: Py2exe: excluding parts of a package that wants to import all its parts


code:
from bs4 import BeautifulSoup, SoupStrainer, ResultSet

my_document = """

Some Heading

A paragraph.

    A link

A paragraph.

A paragraph.

A paragraph.

A paragraph.

    A link
    A link

A paragraph.

test

"""

def search(tag, attrs):
    if tag == "p" and "myclass" in attrs.get("class", []):
        return tag

    if attrs.get("id") in ["first", "third", "loner"]:
        return tag

parse_only = SoupStrainer(search)

soup = BeautifulSoup(my_document, "html.parser", parse_only=parse_only)

print(soup.prettify())

rawDescription: How to get "subsoups" and concatenate/join them?

description: Get "subsoups" and concatenate/join them


rawDescription: Python Recursion Double letters

description: Python Recursion Double letters


code:
def high_bitscores(a,qid,thresh=0.9):
    valid = a[a['queryid'] == qid]
    return valid[valid['bitscore'] >= valid['bitscore'].max()*thresh]

rawDescription: Extract highest values of numpy structured array


code:
from pyparsing import Word, alphas
greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
hello = "Hello, World!"
print (hello, "->", greet.parseString( hello ))

rawDescription: Parsing a lightweight language in Python


rawDescription: Parsing Text Document Lines in Python on Wildcards/Patterns


rawDescription: Strings, ints and leading zeros

description: Strings, ints and leading zeros


code:
class Example(object):
    def __getitem__(self, item):
        return self._getitem(item)

example = Example()
setattr(example, '_getitem', lambda x: 1)
example['something']
example2 = Example()
setattr(example2, '_getitem', lambda x: 2)
example['something']
example2['something']

rawDescription: Setting special methods using setattr()

description: Setting special methods using setattr()


code:
with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)

rawDescription: Reading binary file in Python and looping over each byte


code:
s = "HowAre\youDoing"
s

rawDescription: operate with python '\' special character in a string

description: Operate with python '\' special character in a string


code:
p = subprocess.Popen(args)
pid = p.pid

rawDescription: How to run a file and get the hwnd using win32 in python?

description: Run a file and get the hwnd using win32 in python


code:
def func(a, b):
    return a+b

rawDescription: how to link multiple python scripts

description: Link multiple python scripts


code: getHashValue(filename, 'md5')

rawDescription: Unable to pass a variable to function

description: Unable to pass a variable to function


code:
def addImageKey(dataPart):
    if dataPart.has_key('imagekey'):
        dataPart['viewurl'] = '/view?imagekey=%s' %dataPart['imagekey']
    return dataPart

decoded_with_viewurl = json.loads(myString, object_hook = addImageKey)

rawDescription: Editing Existing JSON in Python

description: Editing Existing JSON in Python


rawDescription: Sort a file according to values in first column


code:
def inner_function(x):
    soma = 0
    linf = 1

    while linf <= x:
        soma += linf + 1
        linf += 1

    return soma

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


code:
def metagen():
    def innergen():
        yield 1
        yield 2
        yield 3

    for i in range(3):
        r = innergen()
        yield r

        for _ in r: pass

rawDescription: python generator of generators?

description: Python generator of generators


rawDescription: Nth Fibonacci number for n as big as 10^19?


rawDescription: How to add filter to group_by query

description: Add filter to group_by query


code: [ a[0].values()[0] for a in d['array'] ]

rawDescription: Python: The best way to get complex dictionary values


code: re.sub("Apples\r", "Apples: 1\r", fruits)

rawDescription: Appending to a line

description: Appending to a line


code: time > datetime.time(17) and time < datetime.time(5)

rawDescription: Python: Schedule job to run between two predefined times


rawDescription: how many logical operator can we use in a statement in python?

description: How many logical operator can we use in a statement in python


code:
from collections import Counter
seq = [['a','b','a','c'], ['a','b','c','d']]
Counter(x for xs in seq for x in set(xs))

rawDescription: Using Counter with list of lists

description: Using Counter with list of lists


code:
def add_sizes(strings):
    temp = []
    for i in strings:
        temp.append((i, (len(i))))
    return temp

rawDescription: Transforming a string in a list

description: Transforming a string in a list


code:
class Sends(models.Model):
    ...

    @classmethod
    def delete_entrie(cls, del_id):
        cls.objects.filter(id=del_id).delete()

rawDescription: how to delete a record by using a class method?

description: Delete a record by using a class method


code:
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit ... consequat."
# assume s continues after the "..."
v = list("aeiou")
isVowel = [l in v for l in s]
v_dict = {}
max_win_size = 100
if max_win_size > len(s): max_win_size = len(s)

for i in range(1, max_win_size):
    v_dict[i] = [0,] * (i+1)
    curr_vowels = sum(isVowel[:i])
    v_dict[i][curr_vowels]  += 1
    for curr_pos in range(1, len(s)-i):
        # add next letter position and subtract letter falling out of window
        curr_vowels += isVowel[curr_pos + i] - isVowel[curr_pos - 1]
        v_dict[i][curr_vowels] += 1

rawDescription: Reduce repeated string search from quadratic to faster


code:
import theano
import theano.tensor as T

x = T.fvector()
p = T.as_tensor_variable([(x ** i).sum() for i in range(5)])

j = T.jacobian(p, x)

f = theano.function([x], [p, j])

rawDescription: theano (python): elementwise gradient

description: Theano (python): elementwise gradient


code:
import threading
class WriteThread(threading.Thread):
    def __init__(self, text, output):
        threading.Thread.__init__(self)
        self.text = text
        self.output = output
    def run(self):
        output.write(text)

with open("output.txt", "a+") as f:
    # Create threads
    thread_a = WriteThread("foo", f)
    thread_b = WriteThread("bar", f)
    # Start threads
    thread_a.start()
    thread_b.start()

rawDescription: How to make mechanize script multthread in python

description: Make mechanize script multthread in python


code:
global i
i=0

def make_ship(length):
    global i
    ship = []
    ship_tmp = []
    ship_row = random_row(board, length)
    ship.append(ship_row)
    ship_col = random_col(board, length)
    ship.append(ship_col)
    if randint(0,1) == 0:
        while i<length:
            ship_tmp.append(ship[:])
            ship[0] += 1
            for ship in ship_tmp:
                if ship in ship_all:
                    make_ship(length)
                else:
                    ship_all.append(ship)
                    i+=1
    else:
        while i<length:
            ship_tmp.append(ship[:])
            ship[1] += 1
            for ship in ship_tmp:
                if ship in ship_all:
                    make_ship(length)
                else:
                    ship_all.append(ship)
                    i+=1

rawDescription: Recursion in python didn't work out

description: Recursion in python didn't work out


code: new_dict = {k: v[2] for k, v in py_dict.iteritems()}

rawDescription: New pandas dataframe column using values from python dictionary


code:
@export(IOperation)
class Fibonacci(IOperation):
    def Execute(self, n):
        n = int(n)
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return self.Execute(n-1) + self.Execute(n-2)

    @property
    def Name(self):
        return "fib"

    @property
    def Usage(self):
        return "fib n -- calculates the nth Fibonacci number"

rawDescription: Using MEF to Import components Exported by IronPython or other DLR languages?


code:
def load_and_call(package_path, module_class, method_name, _module_cache={}):
    module_name, class_name = module_class.split(".")
    py_path = os.path.join(package_path, module_name + ".py")
    module_globals = _module_cache.setdefault(py_path, {})
    if not module_globals:
        execfile(py_path, module_globals)
    return getattr(module_globals[class_name](), method_name, lambda: None)()

rawDescription: python, instance dynamic module.class from given path package and call dynamic method

description: Python, instance dynamic module.class from given path package and call dynamic method


code: checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]

rawDescription: Cannot understand how to get data from checklistbox in wxpython


code: column = ord(letter) - ord('A')

rawDescription: In python, how would I go about linking user input to a index in a list?


code:
line = gca().get_lines()[n]
xd = line.get_xdata()
yd = line.get_ydata()

rawDescription: How to extract data from matplotlib plot

description: Extract data from matplotlib plot


code:
mask = (df['Actor']=='s')
df['Activity'] = df[mask]['Behavior']
df.ix[mask, 'Behavior'] = np.nan

rawDescription: Combining two columns from two dataframes; same indices but different lengths


rawDescription: Finding trigrams for entire corpus with NLTK


rawDescription: Python: itertools.islice not working in a loop


code:
data = open(in_filename,'rb').read()
out_file = open(out_filename,'wb')

rawDescription: python file copy gives larger file

description: Python file copy gives larger file


code:
class PickalableC(C, PickalableSWIG):

    def __init__(self, *args):
        self.args = args
        C.__init__(self)

rawDescription: How to make my SWIG extension module work with Pickle?

description: Make my SWIG extension module work with Pickle


code: df.query("B in ['two', 'three']")

rawDescription: Getting multiple DataFrame cross-sections


rawDescription: how to verify a hash in python?

description: Verify a hash in python


code: bool_list[:] = [False] * len(bool_list)

rawDescription: Python: Alter elements of a list

description: Python: Alter elements of a list


code:
buttons = {}
for button in buttons_to_make:
    name, action = button
    buttons[name] = action()

rawDescription: Pyqt4 accessing objects when creating a dynamic form


code:
lookup = {'application': ApplicationTable,
          'database': DatabaseTable,
          'item': ItemTable}

rawDescription: Form a variable from a string without dictionary


rawDescription: Update initial condition in ODE solver each time step


code:
df['col1'] = df.index.get_level_values(0)
df['col2'] = df.index.get_level_values(1)
df

rawDescription: how to create columns out of a multi-index in a pandas dataframe?

description: Create columns out of a multi-index in a pandas dataframe


code:
br = soup.select_one("div.address > a > br")
br.previous_sibling.strip()
br.next_sibling.strip()

rawDescription: BS4 How to get text without using .text?

description: BS4 How to get text without using .text


code:
s = 'this is a delicious apple pie'
pre, target, post = s.partition('delicious')
pre
target
post

rawDescription: How do I return a substring from the right of a specified word/phrase in Python?

description: Return a substring from the right of a specified word/phrase in Python


code:
from itertools import izip, tee
s = "The quick brown fox jumps over the lazy dog"
l = [0, 1, 8, 14, 18, 27, 43]

def get_slices(s, l):
    it1, it2 = tee(l)
    next(it2)
    for start, end in izip(it1, it2):
        yield s[start:end]

list(get_slices(s,l))

rawDescription: What's the pythonic way to cut a string at multiple positions?


code:
innames = ['file1.csv', 'file2.csv', 'file3.csv']
outname = 'out.csv'
with open_many(innames) as infiles, open(outname, 'w') as outfile:
    for infile in infiles:
        do_stuff(in_file)

rawDescription: Nested with blocks in Python, level of nesting variable


code: listofobj = [without_none_values(dict(zip(headers, sublist))) for sublist in listoflist]

rawDescription: How to quickly convert from items in a list of lists to list of dictionaries in python?

description: Quickly convert from items in a list of lists to list of dictionaries in python


code:
tr = "apple AND orange OR banana"
re.split(r'[A-Z]+',tr)

rawDescription: Python: how to split a string by multiple strings


code: temp = [num(x) for x in row]

rawDescription: How to create lists from csv files and cast columns to ints and floats

description: Create lists from csv files and cast columns to ints and floats


code:
import math as m
m.sin(x / 2.0) + m.sin(x * m.pi)
p = os.path
a = p.abspath(somepath)
d = p.dirname(somepath)

rawDescription: Can I define a scope anywhere in Python?

description: Define a scope anywhere in Python


code:
def tbdata(n):
    """ helper function """
    hdulist = pyfits.open(
                  ('/home/ssridhar/mock_test_files/Roncarelli_test'
                  '/roncarelli_dist_halo{0}.fits').format(n)
              )
    return hdulist[1].data

def sigma_num(n):
    fields = ['ra','dec','zcosmo','r200','m200','is_central','r']
    tbdata = tbdata(n)
    var = dict((f, tbdata.field(f)) for f in fields)
    N, r_hist = np.histogram(var['r'], bins=20, range=None, normed=False, weights=None)
    area = [math.pi*(R**2-r**2) for R, r in zip(r_hist[1:], r_hist)]
    return N/area

rawDescription: Shortening a Python program

description: Shortening a Python program


code:
if word < 1 or (word > 2 and word < 7) or word > 10:
    print('invalid')

rawDescription: How to format multiple 'or' conditions in an if statement in Python

description: Format multiple 'or' conditions in an if statement in Python


rawDescription: python - reading file, modifiing it and saving, but it is saved with no modifications. why?

description: Python - reading file, modifiing it and saving, but it is saved with no modifications. why


code:
plt.suptitle('Title', fontsize=14)
plt.xlabel('Number', fontsize=12)
plt.ylabel('Freq', fontsize=12)

rawDescription: Make histogram in python with list

description: Make histogram in python with list


code: while not s[0].isalpha(): s = s[1:]

rawDescription: Most Pythonic was to strip all non-alphanumeric leading characters from string


code:
c = 'Long string'
d = 'Long string'
c is d
c = intern(c)
d = intern(d)
c is d

rawDescription: Checking if for-loop variable resides at two indexes of a list


code:
u, inv = np.unique(x, return_inverse=True)
u
inv

rawDescription: Finding the difference between two numpy structured arrays


code:
import datetime
from itertools import groupby
from operator import attrgetter
list_of_dts = [
    datetime.datetime(2012,1,1,0,0,0),
    datetime.datetime(2012,1,1,0,1,0),
    datetime.datetime(2012,1,1,1,8,0),
    datetime.datetime(2012,1,2,0,5,0),
    datetime.datetime(2012,1,2,1,4,0),
]
[list(g) for k, g in groupby(list_of_dts, key=attrgetter('hour'))]
grouped = {}
for dt in list_of_dts:
    grouped.setdefault(dt.hour, []).append(dt)

[grouped[hour] for hour in sorted(grouped)]
from pprint import pprint
pprint(_)

rawDescription: Split list of datetime by hours using python


rawDescription: For loop in Scrapy returns full response multiple times


code:
class Crack(object): # convention is to use capitalized class names

    def __init__(self, z1, z2, coeffs):
        self.z1 = z1
        self.z2 = z2
        self.coeffs = np.array(coeffs)
        self.n = len(coeffs)

    def __repr__(self):
        return "Crack(z1=%s, z2=%s, coeffs=%s)" % (self.z1,
                                                   self.z2,
                                                   self.coeffs)
    def get_big_Z(self, little_z):
        # this may not need to be its own function, unless you
        # use it separately from get_potential()
        return little_z - 0.5 * (self.z2 - self.z1)

    def get_potential(self, z):
        Z = self.get_big_Z(z)
        return (np.sum(np.arange(self.n) * self.coeffs *
                       (1.0 / (np.sqrt(Z - 1.0) * np.sqrt(Z + 1.0))) *
                       ((Z - np.sqrt(Z - 1.0) * np.sqrt(Z + 1.0)) **
                       np.arange(self.n))) *
                (2.0 / (self.z2 - self.z1))
                )

rawDescription: python: iterate using a class method

description: Python: iterate using a class method


code:
from scipy.interpolate import UnivariateSpline

#raw data
data = np.genfromtxt('ww.txt')

plt.plot(np.gradient(data), '+')

spl = UnivariateSpline(np.arange(len(data)), np.gradient(data), k=5)
spl.set_smoothing_factor(1000)
plt.plot(spl(np.arange(len(data))), label='Smooth Fct 1e3')
spl.set_smoothing_factor(10000)
plt.plot(spl(np.arange(len(data))), label='Smooth Fct 1e4')
plt.legend(loc='lower left')

max_idx = np.argmax(spl(np.arange(len(data))))
plt.vlines(max_idx, -5, 9, linewidth=5, alpha=0.3)

rawDescription: Fixing inflexion point estimate using python


code: list_of_lists = [list(k) for k in list_of_tuples]

rawDescription: Fastest way to remove all multiple occurrence items from a list?


code: acct    = rec[ 84:104 ].decode('latin1')

rawDescription: Writing accented characters to Oracle

description: Writing accented characters to Oracle


code:
tree.xpath('//*[name() = "x:html"]')
# [<Element {http://www.w3.org/1999/xhtml}html at 0x103b8d848>]

rawDescription: XPath Child Traversal Methods and Performance


code:
from PyQt4 import QtGui, QtCore

class MyFrame(QtGui.QGraphicsView):
    def __init__( self, parent = None ):
        super(MyFrame, self).__init__(parent)

        self.setScene(QtGui.QGraphicsScene())

        # add some items
        x = 0
        y = 0
        w = 45
        h = 45
        pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green))
        brush = QtGui.QBrush(pen.color().darker(150))

        item = self.scene().addEllipse(x, y, w, h, pen, brush)
        item.setFlag(QtGui.QGraphicsItem.ItemIsMovable)

if ( __name__ == '__main__' ):
    app = QtGui.QApplication([])
    f = MyFrame()
    f.show()
    app.exec_()

rawDescription: Python PyQt: How can I move my widgets on the window with mouse?


rawDescription: Python: Parse String as Date with Formatting


code:
import subprocess
import os
import json

class ExifTool(object):

    sentinel = "{ready}\n"

    def __init__(self, executable="/usr/bin/exiftool"):
        self.executable = executable

    def __enter__(self):
        self.process = subprocess.Popen(
            [self.executable, "-stay_open", "True",  "-@", "-"],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        return self

    def  __exit__(self, exc_type, exc_value, traceback):
        self.process.stdin.write("-stay_open\nFalse\n")
        self.process.stdin.flush()

    def execute(self, *args):
        args = args + ("-execute\n",)
        self.process.stdin.write(str.join("\n", args))
        self.process.stdin.flush()
        output = ""
        fd = self.process.stdout.fileno()
        while not output.endswith(self.sentinel):
            output += os.read(fd, 4096)
        return output[:-len(self.sentinel)]

    def get_metadata(self, *filenames):
        return json.loads(self.execute("-G", "-j", "-n", *filenames))

rawDescription: Call exiftool from a python script?

description: Call exiftool from a python script


code: [[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]

rawDescription: Comparing 2 lists consisting of dictionaries with unique keys in python


code:
import codecs
with codecs.open("corpus.txt", encoding="utf-8") as fp:
    for line in fp:
        for word in line.split():
            process(word)

rawDescription: using unicode in python for Farsi

description: Using unicode in python for Farsi


code:
t = transpose(m)
t.append(baz)
transpose(t)

rawDescription: Does anyone have a better solution for 'iteratively' applying zip in Python?


rawDescription: What is the best way to perform an operation on several DataFrames?


code:
departments = {'1': 'I.T.',
               '2': 'Administration',
               '3': 'Human Resources',
               '4': 'Maintenance'}
re.sub(r'''\d+$''', lambda x: departments.get(x, "Unknown Dept"), file, flags=re.M)
# DONE!

rawDescription: What Regex to use in this example

description: What Regex to use in this example


rawDescription: NumPy: create bool array like "repeat" but in multiple dimensions


code:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.PhantomJS()
driver.get("https://kissanime.to")

# wait for title not be equal to "Please wait 5 seconds..."
wait = WebDriverWait(driver, 10)
wait.until(lambda driver: driver.title != "Please wait 5 seconds...")

print(driver.title)

rawDescription: How to parse a site that returns a different HTML <title>Please wait 5 seconds...</title>

description: Parse a site that returns a different HTML <title>Please wait 5 seconds...</title>


code:
input_chunks = split_input(user_input, 80)
for chunk in input_chunk:
    outFile.write(chunk + "\n")

rawDescription: How would one limit characters per line when printing a raw_input to a text file?


code:
nondupes = [{elem for elem in original if element_counts[elem] == 1}
            for original in allsets]

rawDescription: Subtraction over a list of sets

description: Subtraction over a list of sets


code:
s = 'Fox'
map(''.join, itertools.product(*zip(s.upper(), s.lower())))

rawDescription: Find all upper, lower and mixed case combinations of a string


code:
with open('resultfile', 'w') as wFile:
    wFile.write(line.rpartition('_')[-1])

rawDescription: Search for specific string, only copy part of string into another textfile


rawDescription: How to write a lot of nested 'for' loops (Recursively)

description: Write a lot of nested 'for' loops (Recursively)


code: freeze(a) == freeze(b)

rawDescription: Most pythonic way of ensuring a list of objects contains only unique items


code: x not in seen and True

rawDescription: Remove following duplicates in a tuple

description: Remove following duplicates in a tuple


code:
p = subprocess.Popen(['schroot', '-c', name, '-r', 'tee', '/tmp/file.txt'],
                     stdin=subprocess.PIPE,
                     stdout=open('/dev/null', 'w'),
                     stderr=sys.stderr)
p.stdin.write(text)
p.stdin.close()
rc = p.wait()
assert rc == 0

rawDescription: Writing files into chroot environment

description: Writing files into chroot environment


code:
if __name__ == "__main__":
    t1 = threading.Thread(name="Hello1", target=testForThread1) # tell thread what the target function is
    # notice no function call braces for the function "testForThread1"
    t1.start() # tell the thread to execute the target function

rawDescription: Python parallel threads

description: Python parallel threads


code:
q1 = multiprocesing.Queue()
q2 = multiprocesing.Queue()
pr1=Process(target=t1.method, args=(q1,))
pr2=Process(target=t2.method, args=(q2,))
pr1.start()
pr2.start()
out1 = q1.get()
out2 = q2.get()
t1.blah = out1
t2.blah = out2
pr1.join()
pr2.join()

rawDescription: Parallel execution of class methods

description: Parallel execution of class methods


code:
from unittest import skip

@skip("nose likes having good reasons")
def foo_test():
    pass

rawDescription: Unittests marked with @unittest.skip are not marked under nosetests


code:
tupList = [(2,16), (4, 42), (3, 23)]
tupList.sort(key = lambda tup: tup[1])
print(tupList)

rawDescription: Sorting tuples by element value in Python


code:
def application(environ, start_response):
    start_response('200 OK', [
        ('Content-Type', 'text/plain'),
    ])
    return ['Hello %s' % environ['REMOTE_USER']]

rawDescription: Passing apache2 digest authentication information to a wsgi script run by mod_wsgi


code:
S = QuoteHandle(SimpleQuote(100.0))
r = YieldTermStructureHandle(FlatForward(0, TARGET(), 0.03, Actual360()))
q = YieldTermStructureHandle(FlatForward(0, TARGET(), 0.01, Actual360()))
sigma = BlackVolTermStructureHandle(BlackConstantVol(0, TARGET(), 0.20, Actual360()))
process = BlackScholesMertonProcess(S,q,r,sigma)

rawDescription: Calculating EuropeanOptionImpliedVolatility in quantlib-python


code:
class Setting(Model):
    name = CharField()
    value = CharField()
    device = ForeignKey(Device, related_name='settings')

    settings_objects = DeviceSettingManager() # Notice the parenthesis

rawDescription: How to create a custom manager for related objects?

description: Create a custom manager for related objects


code:
xmin = min([min(x_list) for x_list in x_list_of_lists])-delta
xmax = max([max(x_list) for x_list in x_list_of_lists])+delta
plt.xlim(xmin, xmax)

rawDescription: Pyplot - automatically setting x axis range to min, max x values passed to plotting function


code:
def getTimeDifferenceFromNow(TimeStart, TimeEnd):
    timeDiff = TimeEnd - TimeStart
    return timeDiff.total_seconds() / 60

rawDescription: How to get the time difference in minutes in python for time expressed in this format?

description: Get the time difference in minutes in python for time expressed in this format


code:
from guids import generate_guid
generate_guid('bob')
generate_guid('bob')

rawDescription: Creating GUID by Python from bytes

description: Creating GUID by Python from bytes


code:
class model(object):
    @staticmethod
    def foobar(a_model):
        mu = a_model.sc.broadcast(a_model.get_mean())
        y = a_model.y
        def _foobar(x):
            return x - mu.value + y
        return _foobar

    def __init__(self, sc):
        self.sc = sc
        self.y = -1
        self.rdd = self.sc.parallelize([1, 2, 3])

    def get_mean(self):
        return self.rdd.mean()

    def run_foobar(self):
        self.data = self.rdd.map(model.foobar(self))

rawDescription: Proper handling of spark broadcast variables in a Python class


code:
def parse_list(mylist):
    for seq in mylist:
        if seq: #is not empty
            yield "\n".join(map(str,seq))

#with print function
print(*parse_list(stuff), sep="\n\n")

#old print statement (but still forward compatible)
print ("\n\n".join(parse_list(stuff)))

rawDescription: Print a new line in between a list in python


rawDescription: Python converting string to list and then some


code:
@lru_cache(5)
def foo():
    print('Executing foo...')

foo()
foo()
foo.cache_info()
foo.cache_clear()
foo()

rawDescription: How do I use cache_clear() on python @functools.lru_cache

description: Use cache_clear() on python @functools.lru_cache


code:
def parseNameInPluralForm():
    name = parseName()
    if name.ends_with("'s"): name.remove_from_end("'s")
    elif name.ends_with("s"): name.remove_from_end("s")
    return name

rawDescription: lexical analyse or series of regular expressions to parse unstructured text into structured form

description: Lexical analyse or series of regular expressions to parse unstructured text into structured form


code:
s.index = [" ".join([l1, l2]) for l1, l2 in s.index]
s

rawDescription: Pandas : how do I merge minute data rows in a timeseries


code: import planet as planetmodule

rawDescription: Python: Naming conventions for modules & variables when they could conflict


code:
from operator import itemgetter
f = itemgetter(0)
map(f, tuple_list)

rawDescription: Referring to the first element of all tuples in a list of tuples


code: func = lambda itm: itm

rawDescription: Extending grouping code to handle more general inputs


code:
#Setup 2 by 3 grid of subplots
fig, axs = plt.subplots(2,3,figsize=(width,height))

axs[0,0].plot(x, np.sinc(x))
axs[1,0].hist(y)
etc

rawDescription: Python on windows, open plot windows next to each other


code:
# In User class declaration
@classmethod
def create(cls, name, email):
  return cls(name=name, email=email)

# Use it
p = User.create("Fred", "fred@example.com")

rawDescription: Writing a __init__ function to be used in django model


code:
def fx(x, y):
    return x*y
df['new_column'] = np.vectorize(fx)(df['A'], df['B'])
df

rawDescription: Applying function with multiple arguments to create a new pandas column


code: memoize= [-1 for i in range(1000000)]

rawDescription: down to zero hackerrank getting time exceeded

description: Down to zero hackerrank getting time exceeded


code:
def f():
  return 'python'
def g():
  return 'python'
f() is g()

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


rawDescription: List in List (Usage of Range with for)

description: List in List (Usage of Range with for)


code:
from django.conf.urls import handler404
from myapp import views

handler404 = views.error_page

rawDescription: Django Rest Framework how to return detail not found on all invalid urls?


code:
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def media_url(value):
    """Searches for {{ MEDIA_URL }} and replaces it with the MEDIA_URL from settings.py"""
    return value.replace('{{ MEDIA_URL }}', settings.MEDIA_URL)
media_url.is_safe = True

rawDescription: Can't use {{MEDIA_URL}} in Django Flatpages?


code:
def parallel_main():
    import multiprocessing
    p = multiprocessing.Pool()
    x, data = generate_data(256, 262144)
    args = itertools.izip(itertools.repeat(x), data.T)
    model = p.imap(parallel_func, args, chunksize=500)
    sigma, mu, height = [np.array(item) for item in zip(*model)]
    prediction = gaussian(x, sigma, mu, height)

def parallel_func(args):
    return invert(*args)

rawDescription: How can I perform a least-squares fitting over multiple data sets fast?

description: Perform a least-squares fitting over multiple data sets fast


rawDescription: python numpy operation instead of for loops

description: Python numpy operation instead of for loops


code:
def nested_sum(L):
    total = 0
    for x in L:
        if isinstance(x, list):
            total += nested_sum(x)
        else:
            total += x
    return total

rawDescription: What would be the non-comprehension list way of doing this sum


rawDescription: javascript comparison operators

description: Javascript comparison operators


code:
def update_paddle(self, dir, dx):
    if dir=='left':
        self.x -= dx
    elif dir=='right':
        self.x += dx

rawDescription: How do I make the paddle move with the arrow keys?

description: Make the paddle move with the arrow keys


code:
size: self.parent.size
pos: self.parent.pos

rawDescription: How to center buttons in Kivy?

description: Center buttons in Kivy


rawDescription: Django: how do you serve media / stylesheets and link to them within templates


code:
gp = df.groupby('CloneID')
gp.apply(lambda x: x.to_csv('CloneID' + str(x.name) + '.txt'))

rawDescription: output multiple files based on column value python pandas

description: Output multiple files based on column value python pandas


rawDescription: python string including double quote character

description: Python string including double quote character


rawDescription: Convert this python dictionary into JSON format?


code:
browser.find_element_by_xpath(
    ".//*[contains(text(), '15 Minute Stream Flow Data: USGS (FIFE)')]"
).click()

rawDescription: Select check box using Selenium Python

description: Select check box using Selenium Python


code: dis.dis((i for i in range(4)).gi_code)

rawDescription: Difference between generator expression and generator function


code:
def grpavg(ws, df):
    i = df['word'].isin(ws)
    return df.loc[i, 'score'].sum() / len(ws)

from functools import partial
f = partial(grpavg, df=df1)
df3['avg-score'] = df3['words'].str.split().map(f)
df3

rawDescription: Python Pandas Lookup/Cross Referencing

description: Python Pandas Lookup/Cross Referencing


code:
txt = """  cat  val
0   a    1
1   a    6
2   a   12
3   b    2
4   b    5
5   b   11
6   c    4
7   c   22"""

import io

df = pd.read_csv(io.BytesIO(txt), delim_whitespace=True, index_col=0)
df["val_delt"] = (df.val - 5.5).abs()
idx = df.groupby("cat").apply(lambda df:df.index[df.val_delt.argmin()])
df.ix[idx, :]

rawDescription: How to use argmin with groupby in pandas

description: Use argmin with groupby in pandas


code:
if __name__ == '__main__':
    import argparse
    args = argparse.ArgumentParser()
    args.add_argument('--addr', type=str, default='0') #Are you sure you want a string '0'?
    args.add_argument('--tid', type=int, default=0) #type=int will ensure user cannot input somethin other than an int
    args.add_argument('--time', type=int, default=135000) #Look at datetime module if you need a timestamp.

    options = args.parse_args() #Parses user command line

    print("My options where : " + str(options))

rawDescription: Python: get key information from user's input


code:
from random import randint
l = [randint(0,1023) for _ in range(0,10)]
l
1 if 987 in l else 0
1 if 988 in l else 0

rawDescription: Populating a sparse list with random 1's


code:
def any_curr(s, curr="¥$€£"):
    return any(c in s for c in curr)

rawDescription: Determine if the string contains any currency sign?


code:
if funcname == 'a':
  func = lambda foo, bar: a()  # don't pass foo and bar
elif funcname == 'b':
  func = lambda foo, bar: bb(bar=bar)  # don't pass foo
elif funcname == 'c':
  func = lambda foo, bar: ccc(foo=foo)  # don't pass bar
# call it, uniformly
func(foo, bar)

rawDescription: Python: Passing conditional parameters by name


code:
from freeze import freezablelist as fl
a = fl([1,2,3])
a[1] = 'chicken'
a.freeze()
a[1] = 'tuna'
a[1:1] = 'tuna'

rawDescription: Freeze in Python?

description: Freeze in Python


code:
xs = sc.broadcast(rdd.collect())
pairs = rdd.flatMap(lambda y: [(x, y) for x in xs.value if x < y])
pairs.count()

## 45

rawDescription: Upper triangle of cartesian in spark for symmetric operations: `x*(x+1)//2` instead of `x**2`


code: [[td.findNext(text=True) for td in tr.findAll("td")] for tr in rows]

rawDescription: How do I extract table data in pairs using BeautifulSoup?

description: Extract table data in pairs using BeautifulSoup


code: next(reader)

rawDescription: What is the pythonic way to read CSV file data as rows of namedtuples?


code:
import os
import io
import zipfile

def extract(filename):
    z = zipfile.ZipFile(filename)
    for f in z.namelist():
        # get directory name from file
        dirname = os.path.splitext(f)[0]
        # create new directory
        os.mkdir(dirname)
        # read inner zip file into bytes buffer
        content = io.BytesIO(z.read(f))
        inner_zip = zipfile.ZipFile(content)
        for inner_zip in sub_zip.namelist():
            sub_zip.extract(inner_zip, dirname)

rawDescription: How to extract zip file recursively in Python

description: Extract zip file recursively in Python


rawDescription: How to check version of python package if no __version__ variable is set

description: Check version of python package if no __version__ variable is set


rawDescription: Why does setattr fail on a bound method

description: Why does setattr fail on a bound method


rawDescription: Parse timestamps containing different lengths Python


code:
code = """
myvar = 300
def func():
    return myvar

func()
"""
d = {}
eval(compile(code, "<str>", "exec"), d, d)

rawDescription: C Python: Running Python code within a context


rawDescription: How to generate a permutation of list of lists in python

description: Generate a permutation of list of lists in python


code:
for arg in arguments:
    lst = equal if '=' in arg else plain
    lst.append(arg)

rawDescription: Evaluating into two or more lists

description: Evaluating into two or more lists


code:
from apiclient.discovery import build

def build_service(credentials):
  http = httplib2.Http()
  http = credentials.authorize(http)
  return build('drive', 'v2', http=http)

rawDescription: How to request a File in Google Drive

description: Request a File in Google Drive


code:
x[y > x] = y[y > x]
#or
ind = y > x
x[ind] = y[ind]

rawDescription: Find the maximum x,y value fromn a series of images


code: search = int(raw_input("Please type SKU Number"))

rawDescription: Can't get python to read/display my variable


code:
from astropy.table import Table
table = Table.read('/path/to/text/file.txt', format='ascii')

rawDescription: Converting ASCII Table to FITS image

description: Converting ASCII Table to FITS image


code:
def my_view(request):
    ...
    form = MyForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            ...
            if request.POST["something_truthy"]:
                # Checkbox was checked
                ...

rawDescription: Django check if checkbox is selected

description: Django check if checkbox is selected


code:
class BlueManager(models.Manager):
    def get_query_set(self):
        return super(BlueManager, self).get_query_set().filter(colour='Blue')

class MyModel(models.Model):
     colour = models.CharField(max_length=64)
     blue_objects = BlueManager()

rawDescription: What is a "Manager" in django?

description: What is a "Manager" in django


code:
import somewhere

class TestClass():
    def test_function(self):
        pass

for name in getattr(somewhere, '__all__',
                    (n for n in dir(somewhere) if not n.startswith('_'))):
    setattr(TestClass, name, getattr(somewhere, name))

rawDescription: What is a better way of handling import *


rawDescription: beautifulsoup to retrieve the date

description: Beautifulsoup to retrieve the date


code:
if ("University" in string or "School" in string) and ("Business" in string or "Management" in string):
    ...

rawDescription: Better and concise way of writing this regex pattern to examine conjoined occurrence of these phrases?


code:
from lxml import etree
xml = """\
<?xml version="1.0" encoding="utf8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <rdf:li rdf:resource="urn:miriam:obo.chebi:CHEBI%3A37671"/>
</rdf:RDF>
"""
tree = etree.fromstring(xml)
ns = {'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'}
tree.xpath('//rdf:li/@rdf:resource', namespaces=ns)

rawDescription: Xpath select attribute of current node?

description: Xpath select attribute of current node


rawDescription: Slick way to reverse the (binary) digits of a number in Python?


code:
def is_line_ok(line):
    if "bad text1" in line:
        return False
    if "bad text2" in line:
        return False
    return True

rawDescription: What's the fastest way to remove duplicate lines in a txt file(and also some lines which contain specific strings) using python?


code:
import re

def replacer(match):
    if match.group(2) == 'u':
        return chr(int(match.group(3), 16))
    elif match.group(2) == 'x':
        return  # ...

re.sub(r'(\\(x|u)\{(.*?)\})', replacer, r'\x{abcd} foo \u{1212}')

rawDescription: Turning a unicode code point into a unicode character in Python


code:
data_in_the_bubble = driver.find_element_by_xpath("//*[@id='tooltiptext']")
hover_data = data_in_the_bubble.get_attribute("innerHTML")

rawDescription: How can I locate a onmouseover element using Selenium in Python?

description: Locate a onmouseover element using Selenium in Python


rawDescription: How to updating dict items inside a list of dicts

description: Updating dict items inside a list of dicts


rawDescription: compare few elements in list of tuples

description: Compare few elements in list of tuples


code: np.diff(index)/np.timedelta64(1, 'm')

rawDescription: getting seconds from numpy timedelta64

description: Getting seconds from numpy timedelta64


code:
a = []
while True:
    n = int(raw_input("Enter input- "))
    if n < 0:
        break
    a.append(n)

rawDescription: How to terminate input as a list when a negative integer is entered? (python)

description: Terminate input as a list when a negative integer is entered? (python)


code:
import pandas as pd
trips = pd.DataFrame({
  'start_station': ['a', 'c'],
  'end_station': ['b', 'a'],
})
trips.apply(pd.value_counts).fillna(0)

rawDescription: expand each row to multiple rows in pandas using dataframe.apply (similar to MapReduce)

description: Expand each row to multiple rows in pandas using dataframe.apply (similar to MapReduce)


code: projfiles['buildasm'] = ['#build/'+os.path.splitext(x)[0]+'.asm' for x in projfiles['a'] if x != 'baz.a']

rawDescription: python: how to get all members of an array except for ones that match a condition

description: Python: how to get all members of an array except for ones that match a condition