code:
class MyTableName(Base):
    __tablename__ = "mytablename2"
    test_column = Column(Unicode(2),
                         primary_key=True)
    test_column2 = Column(Unicode(2, collation='utf8_bin'))
#                                    ^^^^^^^^^^^^^^^^^^^^

rawDescription: enforce column encoding with sqlalchemy

description: Enforce column encoding with sqlalchemy


rawDescription: Pivoted pandas dataframe to dictionary

description: Pivoted pandas dataframe to dictionary


rawDescription: Dynamic list of booleans python

description: Dynamic list of booleans python


rawDescription: Python regular expressions: match a range of numbers with a separator


code:
li=[]
for i in (2,5):
   li.append(linecache.getline('/tmp/lines.txt', i).strip())

li

rawDescription: numpy - Python - Selectively import parts of the .txt file

description: Numpy - Python - Selectively import parts of the .txt file


code:
import pickle

target_object = {some_value:3, other_value:4}
target_file = open("1.txt", "w")
pickle.dump(target_object, target_file)

rawDescription: Define object from text file

description: Define object from text file


code:
class Example(Declarative):
    id = Column(Integer, primary_key=True)
    datum = Column(String(65))
    __order__ = ('id', 'datum')

    def __init__(self, *args, **kwargs):
        cls_ = type(self)
        kwargs.update(zip(cls_.__order__, args))
        for k in kwargs:
            if not hasattr(cls_, k):
                raise TypeError(
                    "%r is an invalid keyword argument for %s" %
                    (k, cls_.__name__))
            setattr(self, k, kwargs[k])

rawDescription: Is there a shortcut for creating __init__ functions based on class attributes?


rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code:
self.progress = ttk.Progressbar(frame, orient='horizontal',
                                length =200, mode='determinate',maximum=1.)

rawDescription: Status bar for csv file read

description: Status bar for csv file read


rawDescription: Separating file extensions using python os.path module


code: choices = [(random.choice("abcdefg"), random.uniform(0,50)) for i in xrange(2500)]

rawDescription: Probability distribution in Python

description: Probability distribution in Python


code:
r"""
Seconds to perform 1000000 Ok-match/Bad-no-match loops:
Method  Ok-time  Bad-time
1        1.054    1.190
2        1.830    1.636
3        4.364    4.577
"""

rawDescription: Efficient way to search for invalid characters in python


code:
x = [[1,2,3], [4,5,6], [7,8,9]]
import itertools as it
[x for x in it.product (*x) ]

rawDescription: Print out all combinations of elements in an array of arrays


code: utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = ms, hours =-5)

rawDescription: Convert datetime fields in Chrome history file (sqlite) to readable format


code:
def three_tokens(s):
    tokens = s.split('-', 2)
    return tokens + [''] * (3 - len(tokens))

rawDescription: Concise way to split a string into a list of fixed number of tokens


code:
import sys
sys.path.append('/path/to/your.egg')
from your_module import func
func()

rawDescription: Python: How do i get the name of the current archive?


code:
def unique_mapping(mappings):
    addedIds = set()
    for m in mappings:
        mId = m['id']
        if mId not in addedIds:
            addedIds.add(mId)
            yield m

rawDescription: Extracting unique items from a list of mappings


rawDescription: How can I do strtok()-type parsing in Python?

description: Do strtok()-type parsing in Python


rawDescription: Way of easily finding the average of every nth element over a window of size k in a pandas.Series? (not the rolling mean)


code:
for i, dataset in enumerate(groups):
    groups[i] = dataset[:n]

rawDescription: PANDAS: Trim multiple data frames

description: PANDAS: Trim multiple data frames


code:
import calendar
list(calendar.day_name)

rawDescription: Rendering Text Calendar

description: Rendering Text Calendar


code: df1['close'] = s1.reindex(df1.index, method='bfill')

rawDescription: How to join 2 pandas time series

description: Join 2 pandas time series


code:
setattr(Doc, 'VAR', val)
setattr(Doc, 'VAR2', val2)
Doc.save()

rawDescription: How to update from json a Mongoengine DynamicDocument

description: Update from json a Mongoengine DynamicDocument


code:
def display_objects(request, filters, orders, template_name, **kwargs):

    objects = Object.objects.all()
    for filter in filters:
        objects = objects.filter(('%s__%s' % (filter['field'], filter['relationship']), kwargs.get(filter['field'])))
    for order in orders:
        objects = objects.order_by('-' if 'descending' in order else '' + order['field'])
    # render objects to template with context
    pass

rawDescription: Filtering QuerySet based on captured URL parameters in Django?


rawDescription: python pandas - map using 2 columns as reference

description: Python pandas - map using 2 columns as reference


code:
prob_t = [0,0,0]       #initialise
for a in range(nActions):
    prob_t[a] = np.exp(Q[state][a]/temperature)  #calculate numerators

#numpy matrix element-wise division for denominator (sum of numerators)
prob_t = np.true_divide(prob_t,sum(prob_t))

rawDescription: Is there a better way than this to implement Softmax Action Selection for Reinforcement Learning?


code:
def is_valid(str1,list1):
    return str1 in list1
words=["BAD","CAB","BEC"]
def generate2(words,letters):
    answers=[]
    [[answers.append(''.join(x).upper()) for x in itertools.permutations(letters,length) if ''.join(x).upper() in words] for length in range(2,len(letters)+1)]
    #print(answers)
    return answers

rawDescription: Need help making a permutation faster

description: Need help making a permutation faster


code:
def bspleval(x, knots, coeffs, order, debug=False):
    '''
    Evaluate a B-spline at a set of points.

    Parameters
    ----------
    x : list or ndarray
        The set of points at which to evaluate the spline.
    knots : list or ndarray
        The set of knots used to define the spline.
    coeffs : list of ndarray
        The set of spline coefficients.
    order : int
        The order of the spline.

    Returns
    -------
    y : ndarray
        The value of the spline at each point in x.
    '''

    k = order
    t = knots
    m = alen(t)
    npts = alen(x)
    B = zeros((m-1,k+1,npts))

    if debug:
        print('k=%i, m=%i, npts=%i' % (k, m, npts))
        print('t=', t)
        print('coeffs=', coeffs)

    ## Create the zero-order B-spline basis functions.
    for i in range(m-1):
        B[i,0,:] = float64(logical_and(x >= t[i], x < t[i+1]))

    if (k == 0):
        B[m-2,0,-1] = 1.0

    ## Next iteratively define the higher-order basis functions, working from lower order to higher.
    for j in range(1,k+1):
        for i in range(m-j-1):
            if (t[i+j] - t[i] == 0.0):
                first_term = 0.0
            else:
                first_term = ((x - t[i]) / (t[i+j] - t[i])) * B[i,j-1,:]

            if (t[i+j+1] - t[i+1] == 0.0):
                second_term = 0.0
            else:
                second_term = ((t[i+j+1] - x) / (t[i+j+1] - t[i+1])) * B[i+1,j-1,:]

            B[i,j,:] = first_term + second_term
        B[m-j-2,j,-1] = 1.0

    if debug:
        plt.figure()
        for i in range(m-1):
            plt.plot(x, B[i,k,:])
        plt.title('B-spline basis functions')

    ## Evaluate the spline by multiplying the coefficients with the highest-order basis functions.
    y = zeros(npts)
    for i in range(m-k-1):
        y += coeffs[i] * B[i,k,:]

    if debug:
        plt.figure()
        plt.plot(x, y)
        plt.title('spline curve')
        plt.show()

    return(y)

rawDescription: Getting spline equation from UnivariateSpline object


rawDescription: How to Split a delimiter string and store it as array in python?


code:
class IEnhancedDocumentViewerSchema(IGlobalDocumentViewerSettings):
    """
    Use all the fields from the default schema, and add various extra fields.
    """

    folder_location = schema.TextLine(
        title=u"Default folder location",
        description=u'This folder will be created in the Plone root folder. '
                    u'Plone client must have write access to directory.',
        default=u"files_folder")

rawDescription: Plone - Override Zope Schema fields

description: Plone - Override Zope Schema fields


code:
a = [1, 2, 3, 4]
b = [1, 2, 3, 4, 5, 6]
c = [1, 2]

lists = (a, b, c)

result = [sum(el) for el in itertools.izip_longest(*lists, fillvalue=0)]

rawDescription: Pythonic way to add a list of vectors

description: Pythonic way to add a list of vectors


code:
gt = geotiff.GetGeoTransform()
minx = gt[0]
miny = gt[3] + width*gt[4] + height*gt[5]
maxx = gt[0] + width*gt[1] + height*gt[2]
maxy = gt[3]

rawDescription: calculate latitude and longitude from a geotiff image

description: Calculate latitude and longitude from a geotiff image


code:
import codecs

class CriticalSection:
    def __init__(self,fileName):
        self.mutex = threading.Lock()
        self.fileDesc = codecs.open(fileName,mode='w',encoding='utf-8')
    def __del__(self):
        del self.mutex
        self.fileDesc.close()
    def write(self,data):
        self.mutex.acquire()
        self.fileDesc.write(data)
        self.mutex.release()

rawDescription: Threading advice for web crawler - scheduling with single list


code:
text_list = []
current = []
for line in line_list:
    if line.get('id', '').startswith('en'):
        if current:
            text_list.append(' '.join(current))
            current = []
    current.append(line.text)
if current:
    text_list.append(' '.join(current))

rawDescription: Combine items in a list until an item containing specific text is found?


code:
result = ""
while not result.endswith("\n"): result += sock.recv(1)

rawDescription: Python socket to send rows of data

description: Python socket to send rows of data


code: ''.join('{} {} {};'.format(v[0], v[1], k+1) for k,v in enumerate(zip(minValueRange, maxValueRange)))

rawDescription: Python: How to create new variable in each iteration of a for loop?


code:
from mpmath.libmp import MPZ, bitcount
from mpmath import mp

def bsplit(p, q, a, b):
    if b - a == 1:
        if a == 0:
            P = p
            Q = q
        else:
            P = p * p
            Q = q * 2
        B = MPZ(1 + 2 * a)
        if a % 2 == 1:
            B = -B
        T = P
        return P, Q, B, T
    else:
        m = a + (b - a) // 2
        P1, Q1, B1, T1 = bsplit(p, q, a, m)
        P2, Q2, B2, T2 = bsplit(p, q, m, b)
        T = ((T1 * B2) << Q2) + T2 * B1 * P1
        P = P1 * P2
        B = B1 * B2
        Q = Q1 + Q2
        return P, Q, B, T

def atan_bsplit(p, q, prec):
    """computes atan(p/2^q) as a fixed-point number"""
    if p == 0:
        return MPZ(0)
    # FIXME
    nterms = (-prec / (bitcount(p) - q) - 1) * 0.5
    nterms = int(nterms) + 1
    if nterms < 1:
        return MPZ(0)
    P, Q, B, T = bsplit(p, q, 0, nterms)
    if prec >= Q:
        return (T << (prec - Q)) // B
    else:
        return T // (B << (Q - prec))

def atan_fixed(x, prec):
    t = MPZ(x)
    s = MPZ(0)
    q = 1
    while t:
        q = min(q, prec)
        p = t >> (prec - q)
        if p:
            s += atan_bsplit(p, q, prec)
            u = (t << q) - (p << prec)
            v = (MPZ(1) << (q + prec)) + p * t
            t = (u << prec) // v
        q *= 2
    return s

def atan1(x):
    prec = mp.prec
    man = x.to_fixed(prec)
    return mp.mpf((atan_fixed(man, prec), -prec))

def asin1(x):
    x = mpf(x)
    return atan1(x/sqrt(1-x**2))

rawDescription: Fastest possible method for the arcsin function on small, arbitrary floating-point values


code:
def create_list_rec(tree, items=[], queue=[]):
    """
    >>> tree = BinaryTree(2, BinaryTree(29, BinaryTree(26)), BinaryTree(4, None, BinaryTree(2, BinaryTree(9))))
    >>> create_list_rec(tree)
    [2, 29, 4, 26, None, None, 2, None, None, None, None, None, None, 9, None]

    """
    if not items and not queue:
        return create_list_rec(None, [], [tree])

    copy = queue[:]
    queue = []

    for item in copy:
        if item is None:
            items.append(None)
            queue.append(None)
            queue.append(None)
        else:
            items.append(item.key)
            queue.append(item.left)
            queue.append(item.right)

    if all((x is None for x in queue)):
        return items

    return create_list_rec(items, queue)

rawDescription: python list from python binary tree

description: Python list from python binary tree


code:
import sys
import ctypes

if sys.version_info[0] > 2:
    unicode = str

def decode_utf16_from_address(address, byteorder='little',
                              c_char=ctypes.c_char):
    if not address:
        return None
    if byteorder not in ('little', 'big'):
        raise ValueError("byteorder must be either 'little' or 'big'")
    chars = []
    while True:
        c1 = c_char.from_address(address).value
        c2 = c_char.from_address(address + 1).value
        if c1 == b'\x00' and c2 == b'\x00':
            break
        chars += [c1, c2]
        address += 2
    if byteorder == 'little':
        return b''.join(chars).decode('utf-16le')
    return b''.join(chars).decode('utf-16be')

class c_utf16le_p(ctypes.c_char_p):
    def __init__(self, value=None):
        super(c_utf16le_p, self).__init__()
        if value is not None:
            self.value = value

    @property
    def value(self,
              c_void_p=ctypes.c_void_p):
        addr = c_void_p.from_buffer(self).value
        return decode_utf16_from_address(addr, 'little')

    @value.setter
    def value(self, value,
              c_char_p=ctypes.c_char_p):
        value = value.encode('utf-16le') + b'\x00'
        c_char_p.value.__set__(self, value)

    @classmethod
    def from_param(cls, obj):
        if isinstance(obj, unicode):
            obj = obj.encode('utf-16le') + b'\x00'
        return super(c_utf16le_p, cls).from_param(obj)

    @classmethod
    def _check_retval_(cls, result):
        return result.value

class UTF16LEField(object):
    def __init__(self, name):
        self.name = name

    def __get__(self, obj, cls,
                c_void_p=ctypes.c_void_p,
                addressof=ctypes.addressof):
        field_addr = addressof(obj) + getattr(cls, self.name).offset
        addr = c_void_p.from_address(field_addr).value
        return decode_utf16_from_address(addr, 'little')

    def __set__(self, obj, value):
        value = value.encode('utf-16le') + b'\x00'
        setattr(obj, self.name, value)

rawDescription: How to work with UTF-16 in python ctypes?

description: Work with UTF-16 in python ctypes


rawDescription: Split string into list, then split list into list of lists


code:
def rtf_encode_char(unichar):
    code = ord(unichar)
    if code < 128:
        return str(unichar)
    return '\\u' + str(code if code <= 32767 else code-65536) + '?'

def rtf_encode(unistr):
    return ''.join(rtf_encode_char(c) for c in unistr)

rawDescription: Outputting unicode text to an RTF file in python


code:
seen = set()
hashable = lambda d: frozenset(d.items())
unique = [d for d in dictlist if hashable(d) not in seen and not seen.add(hashable(d))]

rawDescription: Is there a python builtin to extract the 'set' of unhashable objects from a list, using 'is' comparison?


code:
nested_dictionary = outer_dictionary['a']
nested_dictionary['f']

rawDescription: Dictionary as value in dictionary

description: Dictionary as value in dictionary


code:
dict = {'one': 1, 'two': 2}
repr(dict)

rawDescription: Write variable to file, including name

description: Write variable to file, including name


code:
# array of stimulus parameters, with dimensions (n_params, p1, p2, p3, p4, p5)
print(sorted_params.shape)
# (5, 2, 3, 4, 5, 6)

# to check that the sorting worked as expected, we can look at the values of the
# 5th parameter when all the others are held constant at 0:
print(sorted_params[4, 0, 0, 0, 0, :])
# [0 1 2 3 4 5]

# ... and the 1st parameter when we hold all the others constant:
print(sorted_params[0, :, 0, 0, 0, 0])
# [0, 1]

# ... now let the 1st and 2nd parameters covary:
print(sorted_params[:2, :, :, 0, 0, 0])
# [[[0 0 0]
#   [1 1 1]]

#  [[0 1 2]
#   [0 1 2]]]

rawDescription: Reorganizing an MxN 2D array of datapoints into an N-dimensional array


code:
idx.ix[0] = 0
df = df.set_index(idx.cumsum(), append=True)

rawDescription: MultiIndexing in pandas based on column conditions


code:
import random
dice = [random.randint(1, 6) for x in range(4)]
sum(sorted(dice)[1:])

rawDescription: Is there a more efficient way to organize random outcomes by size in Python?


code: list(takewhile(lambda x: x[1]==max_,  items))

rawDescription: Selecting all top words in Python list using Counter


code:
exec("do something");
header("Location: success.php");

rawDescription: PHP post to url

description: PHP post to url


rawDescription: Traversing a Graph in Breadth First in Python Using a List of List


code:
def top(x):
    x.set_index('User', inplace=True)
    df = pd.DataFrame({'Max1Name':[],'Max2Name':[],'Max1Value':[],'Max2Value':[]})
    df.index.name='User'
    df.loc[x.index.values[0],['Max1Name', 'Max2Name']] = x.sum().nlargest(2).index.tolist()
    df.loc[x.index.values[0],['Max1Value', 'Max2Value']] = x.sum().nlargest(2).values
    return df

DF1.groupby('User').apply(top).reset_index(level=1, drop=True).reset_index()

rawDescription: Pandas: find column name and value with max (and second max) value for each row


code:
import Tkinter as tk

def serial_ports():
    for port in list('ABCDE'):
        yield port

OPTIONS = list(serial_ports())

class App(object):
    def __init__(self, master, **kwargs):
        self.master = master
        self.var = tk.StringVar()
        self.var.set('Port')
        self.option = tk.OptionMenu(master, self.var, *OPTIONS)
        self.option.pack()

root = tk.Tk()
app = App(root)
root.mainloop()

rawDescription: Populate Tkinter OptionMenu with list of unknown length, i.e. list of serial ports


code: tuple(i.next() for i in iterators)

rawDescription: Find changed or new rows in two lists of lists


code:
isinstance(d, dict)
isinstance(d, (dict, collections.MutableMapping))

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


code:
class SingleTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        parts = data.rsplit(" ")
        if (parts[0] != "GET"):
            self.request.close()
            return

        url = parts[1].split("?")[1]
        qv = parse_qs(url)
        ...

rawDescription: Android, HTTP GET not returning

description: Android, HTTP GET not returning


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

# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e

plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()

rawDescription: pyplot: loglog() with base e

description: Pyplot: loglog() with base e


rawDescription: How can Python's regular expressions work with patterns that have escaped special characters?


code:
def combine(*args):
  # Create a list of dictionaries from the arrays we passed in, since we are
  # going to use dictionaries to solve the problem.
  dicts = [ dict(a) for a in args ]

  # Create a list of names by looping through all dictionaries, and through all
  # the names in each dictionary, adding to a master list of names
  names = []
  for d in dicts:
    for name in d.keys():
      names.append(name)

  # Remove duplicates in our list of names by making it a set
  names = set(names)

  # Create a result dict to store results in
  result = dict()

  # Loop through all the names, and add a row for each name, pulling data from
  # each dict we created in the beginning
  for name in names:
    result[name] = [ d.get(name, 0) for d in dicts ]

  # Return, secure in the knowledge of a job well done. :-)
  return result

# Use the function:
resultDict = combine(arrayOne, arrayTwo, arrayThree)

rawDescription: Merging 2d arrays

description: Merging 2d arrays


rawDescription: How to add elements individually in tuple?

description: Add elements individually in tuple


rawDescription: Pandas Adding new column from result of groupby


code:
from collections import Counter
ec = Counter()
for x, vs in synonyms.items():
    for v in vs:
        ec[x] += word_count.get(v, 0)
print(ec) # Counter({'bear': 6, 'beer': 8})

rawDescription: Aggregating and Renaming Keys in Dictionary


code:
def merge_buffers(dupes):
    merged = {}
    for item in dupes:
        # create tuple key, so all entries with same key will be appended here
        key = (item['name1'], item['len1'])
        if not key in merged:
            merged[key] = []
        merged[key].append(item['buffer'])
    return merged

rawDescription: python filter out pseudo-duplicates by merging the differing values

description: Python filter out pseudo-duplicates by merging the differing values


code:
def aStarSearch(problem, heuristic):
    closed = []
    # A* uses the total cost up to current node + heuristic to goal to decide priority
    def cost_func(tup):
        node, cost_so_far, directions = tup   # unpack argument tuple
        return cost_so_far + heuristic(node, problem) # I'm guessing at heuristic's API

    fringe = PriorityQueueWithFunction(cost_func)
    fringe.push((problem.getStartState(), 0, []))

    while not fringe.isEmpty():
        node, cost, directions = fringe.pop()

        if problem.isGoalState(node):
            return directions

        if not (node in closed):
            closed.append(node)

            for node, direction, step_cost in problem.getSuccessors(node):
                fringe.push((node, cost + step_cost, directions + [direction]))

    if fringe.isEmpty():
        return []

rawDescription: Why is my A* Search returning the same expanded space as my UniformCostSearch?


rawDescription: Reverse AND inverse python3.x OrderedDict efficiently


code: begin = {key:[item for item in begin[key] if item != 'nope'] for key in begin}

rawDescription: removing a certain element from a list in a dictionary's value

description: Removing a certain element from a list in a dictionary's value


rawDescription: Round pandas data frame/series

description: Round pandas data frame/series


code:
data = np.bincount(inv_idx, weights=data)
x,y,z = XYZ[uniq_inds].T

rawDescription: Summing and removing repeated elements of Numpy Arrays


code:
if __name__ == '__main__':
    # the workers main function is called and then 5 seconds sleep
    worker = PeriodicThread(interval=5)
    worker.start()

    try:
       # this is to keep the main thread alive
       while True:
           sleep(1)
    except (KeyboardInterrupt, SystemExit):
        worker.terminate()

rawDescription: Python Threading not stopping

description: Python Threading not stopping


code:
new_dragon = True
while new_dragon:
    print(' ')
    print ('While adventuring you have met a scary looking dragon')
    print('Without hesitation you jump to fight it off!')
    print('=============================================')
    print(' ')
    drgn = drgnGen() #generate a dragon
    fighting = True
    while fighting:
        message = []
        roll = random.randint(0,1)
        if roll == 0:
           message.append("the dragon hits you for %s points" %drgn[1])
           char[0] = char[0] - drgn[1]
           if isNotDead(char) :
               message.append("you have %s health left!" %char[0])
           else:
               message.append("you're dead!Game Over")
               fighting = False
               new_dragon = False
        else:
            message.append("you hit the dragon for %s points"%char[1])
            drgn[0] = drgn[0] - char[1]

            if drgn[0] >0:
                message.append("the dragon have %s health left!" %drgn[0])
            else:
                char[2]+= XP
                message.append("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
                levelUp(char,(xpIncrement(char[2],xpLevels,char)))
                continue_flag = False
        for m in message:
            print (m)
        print ('')
        if fighting:
            r = input("Press enter to continue or enter q to quit")
            if r is 'q':
                fighting = False

rawDescription: how to get out of my game while game ending conditions are not met?

description: Get out of my game while game ending conditions are not met


code:
import RDF
parser = RDF.Parser(name="rdfxml")
model = RDF.Model()
parser.parse_into_model(model, "file:./align.rdf", None)

rawDescription: how to load Alignment format in python?

description: Load Alignment format in python


code:
class SFTPSession(SSHChannel):
    name = 'session'

    def channelOpen(self, whatever):
        d = self.conn.sendRequest(
            self, 'subsystem', NS('sftp'), wantReply=True)
        d.addCallbacks(self._cbSFTP)

    def _cbSFTP(self, result):
        client = FileTransferClient()
        client.makeConnection(self)
        self.dataReceived = client.dataReceived
        self.conn._sftp.callback(client)

rawDescription: twisted conch filetransfer

description: Twisted conch filetransfer


code:
p = Popen(...)
t = Timer(3, p.kill) # kill in 3 seconds
t.start()
p.communicate(...)
t.cancel() # no need to kill, the process is dead already

rawDescription: Setting a timeout during a loop in Python?


code:
self.central_widget = QtGui.QWidget()
self.setCentralWidget(self.central_widget)

rawDescription: Change my Qdialog to QMainWindow

description: Change my Qdialog to QMainWindow


code: struct.unpack('<I', bytes + '\0')

rawDescription: How to read integers from a file that are 24bit and little endian using Python?

description: Read integers from a file that are 24bit and little endian using Python


code:
import numpy as np

def _t_area(a, b, c):
    ab = b - a
    ac = c - a
    return 0.5 * np.linalg.norm(np.cross(ab, ac), axis=2)

def t_area(x, y, surface, dx):
    a = np.zeros((x.shape[0], y.shape[0], 3), dtype=float)
    b = np.zeros_like(a)
    c = np.zeros_like(a)
    d = np.zeros_like(a)

    a[...,0] = x
    a[...,1] = y
    a[...,2] = surface[:-1,:-1]

    b[...,0] = x + dx
    b[...,1] = y
    b[...,2] = surface[1:,:-1]

    c[...,0] = x
    c[...,1] = y + dx
    c[...,2] = surface[:-1,1:]

    d[...,0] = bp[...,0]
    d[...,1] = cp[...,1]
    d[...,2] = surface[1:,1:]

    # are you sure you didn't mean 0.25???
    return 0.5 * (_t_area(a, b, c) + _t_area(d, b, c) + _t_area(b, a, d) + _t_area(c, a, d))

nx, ny = 250, 250

dx = np.random.random()
x = np.random.random((nx, ny))
y = np.random.random((nx, ny))
surface = np.random.random((nx+1, ny+1))

tri_area = t_area(x, y, surface, dx)

rawDescription: More efficient way to loop?

description: More efficient way to loop


code: results = [value for value in values]

rawDescription: How to create an array with size increasing with the iteration

description: Create an array with size increasing with the iteration


code: data_sets[i] = open(input("Please enter the file path a data set: "))

rawDescription: How to create a number of variables from a number entered by user

description: Create a number of variables from a number entered by user


code:
{key: {k: v for sublist in value for k, v in sublist} for key, value in dic1.items()}
pprint(_)

rawDescription: Converting a nested tuples into nested dictionaries


rawDescription: How To Hide Tkinter python Gui

description: How To Hide Tkinter python Gui


rawDescription: Python/Regex - Expansion of Parentheses and Slashes


code: full_links = [x[:3] + str(number) + x[3:] for x in full_links]

rawDescription: Insert a character into a url

description: Insert a character into a url


code:
x = np.ma.array(100+np.arange(9), mask=[0,1,0,0,0,1,1,1,0]).reshape((3,3))
i = np.nonzero(~np.ma.getmask(x))   # get the indices of the unmasked items
np.vstack((i, x[i]))  # build an array with the indices and elements together

rawDescription: Numpy array with position

description: Numpy array with position


code:
keywords = []
for url in google.search('sleep', num=2, stop=1):
    article = Article(url)
    article.download()
    article.parse()
    article.nlp()

    keywords += article.keywords

print(keywords)

rawDescription: How to take output from iterating, store that in a dictionary

description: Take output from iterating, store that in a dictionary


rawDescription: Pass bash file list to python CLI function


code: a_dict = dict((v, i) for i, v in enumerate(a))

rawDescription: Sort python list with order of another, larger list


code:
S="Hello"
id(S)
S+=" World"
id(S)

rawDescription: What happens to a immutable object in python when its value is changed?


rawDescription: add method with a specific name to already created class instance

description: Add method with a specific name to already created class instance


code:
import subprocess
def play_music_file(filename):
    subprocess.call(('mplayer', filename))

rawDescription: Issue to play a mp3 file with a Python script from Arduino data


code:
class Sample(Base):
    __tablename__="Sample"
    X=Column(Integer, primary_key=True)
    Y=Column(Integer)
    Z=Column(Integer)

rawDescription: Bulk import/load csv to sqlite using Python


rawDescription: accumulate numpy array for just one column

description: Accumulate numpy array for just one column


rawDescription: Defining a color in python

description: Defining a color in python


code:
def next_morris(number):
    return ''.join('%s%s' % (len(list(group)), digit)
                   for digit, group in itertools.groupby(str(number)))

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


code:
df.plot(x='cpu', y='wait', kind='scatter',
    c=[cmap.get(c, 'black') for c in df.category])

rawDescription: scatter plot by category in pandas

description: Scatter plot by category in pandas


code:
import syntax
b = syntax.Block()
l = syntax.List()

rawDescription: Conveniently import several classes from modules in a Python package


code: form = TaskForm(request.user)

rawDescription: How to get the foreign keys related to drop down only of that user in Django ModelForm

description: Get the foreign keys related to drop down only of that user in Django ModelForm


code:
self.text = tk.Text(frameLabel, ...)

# ...

new = self.queue.get()
self.text.delete(1.0, 'end')
self.text.insert('end', new)

rawDescription: converting code from Tkinter TEXT to Tkinter LABEL

description: Converting code from Tkinter TEXT to Tkinter LABEL


rawDescription: Converting all numbers in a python list to 1 or 0


rawDescription: Convert string of 0s and 1s to byte in Python


rawDescription: Finding a pattern inside a string in Python


rawDescription: python: iterate through dynamic list

description: Python: iterate through dynamic list


code: seperators = re.compile(r'(%s)' % '|'.join(a))

rawDescription: Replacing characters in a long string to split it, to keep the 'seperators'


rawDescription: Defining large list-within- list array

description: Defining large list-within- list array


code:
def flatten(aDict, output=None):
    if output is None:
        output = {}
    for key in aDict:
        if isinstance(aDict[key], dict):
            flatten(aDict[key], output)
        output[key] = aDict[key]
    return output

rawDescription: Single dictionary of fewer keys from a multi level dictionary


code: myList.extend(map(lambda x: changeVal(x), myList))

rawDescription: How to efficiently modify all elements of a list of lists and add them to the existing list of lists

description: Efficiently modify all elements of a list of lists and add them to the existing list of lists


code:
import heapq
import random
l1 = [random.randrange(100) for _ in range(100)]
l2 = [random.randrange(100) for _ in range(100)]
heapq.nlargest(10, (((a - b), a, b) for a, b in zip(l1, l2)))

rawDescription: finding n largest differences between two lists

description: Finding n largest differences between two lists


code:
arrow_image = ''
background_color = (1, 0, 0, 0.5)

rawDescription: Color does not affect Kivy Bubble background


code:
class Planificador(Frame):
    def __init__(self,master):
        Frame.__init__(self, master)
        self.master = master
        self.initUI()

    def initUI(self):
        self.master.title("Planner")
        self.frameOne = Frame(self.master)
        self.frameOne.grid(row=0,column=0)
        self.frameTwo = Frame(self.master)
        self.frameTwo.grid(row=0, column=1)
        self.frameThree = Frame(self.master)
        self.frameThree.grid(row=0, column=2)

        self.frameFour = Frame(self.master)
        self.frameFour.grid(row=1,column=0, sticky=N)
        self.frameFive = Frame(self.master)
        self.frameFive.grid(row=1, column=1)
        self.frameSix = Frame(self.master)
        self.frameSix.grid(row=1, column=2, sticky=N)

        self.frameSeven = Frame(self.master)
        self.frameSeven.grid(row=2,column=0)
        self.frameEight = Frame(self.master)
        self.frameEight.grid(row=2, column=1, sticky=S)
        self.frameNine = Frame(self.master)
        self.frameNine.grid(row=2, column=2)

        self.start_date_menu()

    def start_date_menu(self):
        initial_num_dates = int(raw_input("Number of dates?"))
#        initial_num_dates = 5
        self.DATE_MENU_ROW = 0  # initial date menu grid row
        self.COL_WIDTH = 10  # width of each subcolumn of dates

        for frame in (self.frameFour, self.frameSix):
            self.textoprioridad = Label(frame, text="Day in",
                                        width=self.COL_WIDTH, justify="center")
            self.textoprioridad.grid(row=self.DATE_MENU_ROW, column=0)
            self.lotestext = Label(frame, text="Day out", width=self.COL_WIDTH,
                                   justify="center")
            self.lotestext.grid(row=self.DATE_MENU_ROW, column=1)

        self.dates = [self.create_date_entry(date_index)
                        for date_index in xrange(initial_num_dates)]

        self.anadirpiezas = Button(self.frameEight, text="add more",
                                   command=self.addpieza, width=self.COL_WIDTH)
        self.anadirpiezas.grid(row=0, column=3)

    def addpieza(self):
        self.dates.append(self.create_date_entry(len(self.dates)))

    def create_date_entry(self, date_index):
        # create and return seq of two pairs of button, stringvar for a date
        menu_col = date_index % 2  # left/right column of the date frame
        menu_row = self.DATE_MENU_ROW + date_index/2 + 1
        frame = self.frameSix if menu_col else self.frameFour
        pairs = []
        for col in 0, 1:
            pairs.append(StringVar(value="--------"))
            pairs.append(Button(frame, textvariable=pairs[-1],
                                width=self.COL_WIDTH,
                                command=lambda v=pairs[-1]: self.fnCalendar(v)))
            pairs[-1].grid(row=menu_row, column=col)
        return tuple(pairs)

    def fnCalendar(self, datebar):
        tkCalendar(self.master, year, month, day, datebar)

rawDescription: Python Tkinter issue trying to show Calendar dates with StringVar()


code:
def gen(n, k):
    for indices in itertools.combinations(range(n), k):
        l = [0] * n
        for i in indices:
            l[i] = 1
        yield(l)

rawDescription: How to generate these vectors quickly in Python?

description: Generate these vectors quickly in Python


rawDescription: Special Character Pattern Matching in Python


code:
d = {'pKey_b': 'vb1', 'pKey_e': 've1', 'pKey_c': 'vc1', 'pKey_a': 'va1', 'pKey_d': 'vd1'}
[i for k, v in sorted(d.iteritems()) for i in (k, v)]
from itertools import chain
list(chain.from_iterable(item for item in sorted(d.iteritems())))
list(chain.from_iterable(sorted(d.iteritems())))

rawDescription: Generator-expression, getting the same results of using append or extend in a for-loop


code: temp_board[final_index] = level

rawDescription: Numpy masked array modification

description: Numpy masked array modification


code: new_account = Account(owner=current_user, id=current_user.user_id(), name='Some Name')

rawDescription: NDB using Users API to form an entity group


code:
def row():
    with open(filename, 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        cursor = db.execute("SELECT * FROM mytable")
        writer.writerow([i[0] for i in cursor.description])
        for row in cursor:
            writer.writerow(row)

def rows():
    with open(filename, 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        cursor = db.execute("SELECT * FROM mytable")
        writer.writerow([i[0] for i in cursor.description])
        writer.writerows(cursor)

def rowsall():
    with open(filename, 'w') as f:
        writer = csv.writer(f, delimiter='\t')
        cursor = db.execute("SELECT * FROM mytable")
        writer.writerow([i[0] for i in cursor.description])
        writer.writerows(cursor.fetchall())

rawDescription: Fastest way to write database table to file in python


rawDescription: Merge three csv files with same headers in Python


code: tuple(x for sublist in base_lists for x in sublist)

rawDescription: Converting a list of lists to a tuple in Python


rawDescription: How can I add an element at the top of an OrderedDict in python?

description: Add an element at the top of an OrderedDict in python


code:
from bs4 import BeautifulSoup

import requests

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

soup = BeautifulSoup(cont)

h5s = soup.find_all("h5",limit=6)
for h5 in h5s:
    # find first table after
    table = h5.find_next("table")
    # find all h3 elements in that table
    for h3 in table.select("h3"):
        print(h3.text)
        img = h3.find_next("img")
        print(img["src"])
        print(img["title"])
        print(img.find_next("p").text)
    print()

rawDescription: Parsing a tag in HTML

description: Parsing a tag in HTML


rawDescription: Adding Lists Elements to 'Mega List'

description: Adding Lists Elements to 'Mega List'


code:
class Card:
    def __init__(self, suit = 0, rank = 2):
        self.suit = suit
        self.rank = rank
    #Two class attributes that are helpful in determining suit/rank
    ranklist = ['narf', 'Ace', 'Two', 'Three', 'Four', 'Five', \
    'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
    suitlist = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    def __eq__(self, other):
        if not isinstance(other, Card): return False
        return self.suit == other.suit and self.rank == other.rank
    def __repr__(self):
        return (self.ranklist[self.rank] + " of " + self.suitlist[self.suit])

rawDescription: Card Game Simulation list.remove

description: Card Game Simulation list.remove


code:
a = np.random.random((5, 5))
a *= np.tri(*a.shape)
a

rawDescription: How to fill upper triangle of numpy array with zeros in place?

description: Fill upper triangle of numpy array with zeros in place


code:
class ContactAdmin(admin.ModelAdmin):
    ...
    def get_changelist(self, request, **kwargs):
        return ContactChangeList

rawDescription: Amending URL for "list_display_links" in Django 1.6 admin change list


code: ( df > 0 ).sum(axis=1)

rawDescription: python pandas conditional count across columns

description: Python pandas conditional count across columns


code:
import threading
if commmand == "hi":
   t = threading.thread(target=say_hi, name='Saying hi') #< Note that I did not actually call the function, but instead sent it as a parameter
   t.daemon = True
   t.start() #< This actually starts the thread execution in the background

rawDescription: run a python program on a new thread

description: Run a python program on a new thread


code:
fields = ('updated', 'expires', 'created',
    ('request', ('incident', 'reason', ('inputter', ('username',)))))

rawDescription: Django Piston: How can I exclude nested fields from handler results? Is it even possible?


rawDescription: Dynamically create inheriting object with name from external source


code:
class Foo(IntEnum):
    bam = 0
    bar = 1
Foo.bam
json.dumps(Foo.bam)

rawDescription: Django API passing class/field names, not values associated with them


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

def main():
    Person = namedtuple('Person', 'name')
    p = Person(name='joe', age=25)
    print(p)

def namedtuple(typename, field_names, verbose=False, rename=False):
    base = collections.namedtuple('Base', field_names, verbose, rename)
    return type(typename, (base,), {
        '__slots__': (),
        '__new__': lambda cls, *args, **kwargs: base.__new__(cls, *args, **{
            key: value for key, value in kwargs.items()
            if key in base._fields})})

if __name__ == '__main__':
    main()

rawDescription: Make namedtuple accept kwargs

description: Make namedtuple accept kwargs


code: obj = classList[x]()

rawDescription: How to create instance of a class through list

description: Create instance of a class through list


code:
import os, argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', action='store_true')
parser.add_argument('dir', nargs='?', default=os.getcwd())
parser.parse_args('somedir -v'.split())
parser.parse_args('-v'.split())
parser.parse_args(''.split())
parser.parse_args(['somedir'])
parser.parse_args('somedir -h -v'.split())

rawDescription: Argparse optional positional arguments?

description: Argparse optional positional arguments


code: dict(zip(a,b +[None]*(len(a)-len(b))))

rawDescription: set value to None zipping two lists into dictionary

description: Set value to None zipping two lists into dictionary


code:
from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments or blank lines before the __future__ line.

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    __builtins__.print('hello',end='')
    return __builtins__.print(*args, **kwargs)

print ("hello there")
print (" hi again")

rawDescription: Appending to every printed message

description: Appending to every printed message


code:
for message in mbox:
    post = {
       'From' : message['From'],
       'To' : message['To'],
       'Date' : message['Date'],
       'Subject' : message['subject'],
       'Body' : getbody(message)
    }
    stackf = getattachements(message)
    if len(stackf) > 0:
        mapped = map(lambda x: { "OrginalName": x[0], "ExportPath": x[1] }, stackf )
        post['Attachement'] = mapped

    collection.insert_one(post)

rawDescription: Insert nested value in mongodb using python


code:
import asyncio

l = asyncio.Lock()
check_lock = asyncio.Lock()

async def test():
    async with check_lock:
        print('locked' if l.locked() else 'unlocked')
        task = asyncio.ensure_future(l.acquire())  # only create task
        await asyncio.sleep(0)  # return control to event loop, it allows lock to be locked before task completed
        print('now', 'locked' if l.locked() else 'unlocked')  # would be printed immediately

    await task  # and now we can await for task done
    await asyncio.sleep(1)
    l.release()

async def main():
    await asyncio.gather(test(), test())

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: Is there any way to guarantee asyncio.Task will be started immediately?


rawDescription: Automatic (whisker-sensitive) ylim in boxplots


code:
import sys, os

opts = (
    'STACKEXCHANGE_CLIENT_ID',
    'STACKEXCHANGE_CLIENT_SECRET'
)

module = sys.modules[__name__]
for o in opts:
    setattr(module, o, os.getenv(o))

rawDescription: Reducing variable name duplication when using os.getenv


code:
import sys
sys.modules['os']

rawDescription: Can hasattr work on a Module?

description: Can hasattr work on a Module


rawDescription: Create a column with a random number for each exact match of two columns in pandas dataframe


code:
import re

regex = re.compile(r""" # r'' means that \n and the like is two chars
                        # '\\','n' and not a single newline character

    ( # begin capturing group #1; you can get it: regex.match(text).group(1)
      ^   # match begining of the string or a new line if re.MULTILINE is set
      .*  # match zero or more characters except newline (unless
          # re.DOTALL is set)
      def # match string 'def'
      \W* # match zero or more non-\w chars i.e., [^a-zA-Z0-9_] if no
          # re.LOCALE or re.UNICODE
    ) # end capturing group #1

    (\w+) # second capturing group [a-zA-Z0-9_] one or more times if
          # no above flags

    \W*   # see above

    \(    # match literal paren '('
      (.*)  # 3rd capturing group NOTE: `*` is greedy `.` matches even ')'
            # therefore re.match(r'\((.*)\)', '(a)(b)').group(1) == 'a)(b'
    \)    # match literal paren ')'
     :    # match literal ':'
    """, re.VERBOSE|re.DEBUG)

rawDescription: Python RegEx Meaning

description: Python RegEx Meaning


code:
class MultiKeyDict(object):

    def __init__(self, **kwargs):
        self._keys = {}
        self._data = {}
        for k, v in kwargs.iteritems():
            self[k] = v

    def __getitem__(self, key):
        try:
            return self._data[key]
        except KeyError:
            return self._data[self._keys[key]]

    def __setitem__(self, key, val):
        try:
            self._data[self._keys[key]] = val
        except KeyError:
            if isinstance(key, tuple):
               if not key:
                  raise ValueError(u'Empty tuple cannot be used as a key')
               key, other_keys = key[0], key[1:]
            else:
               other_keys = []
            self._data[key] = val
            for k in other_keys:
                self._keys[k] = key

    def add_keys(self, to_key, new_keys):
        if to_key not in self._data:
            to_key = self._keys[to_key]
        for key in new_keys:
            self._keys[key] = to_key

    @classmethod
    def from_dict(cls, dic):
        result = cls()
        for key, val in dic.items():
            result[key] = val
        return result

rawDescription: Python Map(Dict) with multiple indexes

description: Python Map(Dict) with multiple indexes


code: [map(dict.get, range(1, 6)) for _ in range(10)]

rawDescription: How to get values from a map and set them into a numpy matrix row?

description: Get values from a map and set them into a numpy matrix row


code:
import numpy as np

def make_spot_origin_3d(x0,y0,z0):
    d = np.linspace(-50, 50, 200)
    r = np.zeros(d.shape*3)

    ix = np.searchsorted(d, (x0, y0, z0))
    r[tuple(ix)] = 1

    return r

r = make_spot_origin_3d(45.7, -7.1, 2.9)

rawDescription: How to set the origin of a volumetric spot knowing its coordinates origin?

description: Set the origin of a volumetric spot knowing its coordinates origin


code:
df = pd.DataFrame([[0,1,2]])
df
df._update_inplace(df.append([[3,4,5]]))
df

rawDescription: Issue with appending to DataFrame if empty


rawDescription: Search inside ipython history

description: Search inside ipython history


code: sorted([k, sorted(v)] for k, v in d3.items())

rawDescription: How to Merge and Format Lists

description: Merge and Format Lists


code:
style = '<style>.dataframe td { text-align: right; }</style>'
HTML( style + df.to_html( formatters=frmt ) )

rawDescription: How to format IPython html display of Pandas dataframe?

description: Format IPython html display of Pandas dataframe


code:
from fbxmpp import SendMsgBot

# The "From" Facebook ID
jid = '511501255@chat.facebook.com'

# The "Recipient" Facebook ID, with a hyphen for some reason
to = '-1000023894758@chat.facebook.com'

# Whatever you're sending
msg = 'Hey Other Phil, how is it going?'

xmpp = SendMsgBot(jid, to, unicode(msg))

xmpp.credentials['api_key'] = '123456'
xmpp.credentials['access_token'] = 'your-access-token'

if xmpp.connect(('chat.facebook.com', 5222)):
    xmpp.process(block=True)
    print("Done")
else:
    print("Unable to connect.")

rawDescription: Send a Facebook Message with XMPP using Access Tokens in Python


code:
import os, os.path
from scrapy.contrib.pipeline.images import ImagesPipeline

class SessionImagesPipeline(ImagesPipeline):
    def item_completed(self, results, item, info):
        # iterate over the local file paths of all downloaded images
        for result in [x for ok, x in results if ok]:
            path = result['path']
            # here we create the session-path where the files should be in the end
            # you'll have to change this path creation depending on your needs
            target_path = os.path.join((item['session_path'], os.basename(path)))

            # try to move the file and raise exception if not possible
            if not os.rename(path, target_path):
                raise ImageException("Could not move image to target folder")

            # here we'll write out the result with the new path,
            # if there is a result field on the item (just like the original code does)
            if self.IMAGES_RESULT_FIELD in item.fields:
                result['path'] = target_path
                item[self.IMAGES_RESULT_FIELD].append(result)

        return item

rawDescription: How to download scrapy images in a dyanmic folder

description: Download scrapy images in a dyanmic folder


code:
p = np.array("p_x1y1z1 p_x2y1z1 p_x3y1z1 p_x4y1z1 p_x1y2z1 p_x2y2z1 p_x3y2z1 p_x4y2z1".split())
p

rawDescription: numpy create 3D array from indexed list

description: Numpy create 3D array from indexed list


rawDescription: How to remove extra content in table cell using BeautifulSoup

description: Remove extra content in table cell using BeautifulSoup


code:
for element in tagall:
    print(",".join(element))

rawDescription: How to split pyodbc.row into a list of its values

description: Split pyodbc.row into a list of its values


code:
def dynamic_update(self):
    pass

rawDescription: overriding matplotlib's panning tool (wx)

description: Overriding matplotlib's panning tool (wx)


code:
mn = count*(count + 1.) * 0.25
se = count*(count + 1.) * (2. * count + 1.)

rawDescription: One-sided Wilcoxon signed-rank test using scipy


code: final_dict = {k: [v[1] for v in vs] for k, vs in groups}

rawDescription: flip keys and values in dictionary python

description: Flip keys and values in dictionary python


code:
class T1(DeclarativeBase):
    __tablename__ = 't1'

    __table_args__ = {'mysql_engine': 'InnoDB'}

    id = Column(u'id', Integer, primary_key=True)
    some_int = Column('some_int', Integer)
    some_str = Column('some_str', String(45))

    def __init__ (self, some_int, some_str):
        self.some_int = some_int
        self.some_str = some_str

rawDescription: SQLAlchemy: filtering multiple column values in a subquery


code: np.multiply.outer(x, y).T

rawDescription: Multiplication of two arrays in numpy

description: Multiplication of two arrays in numpy


code:
import os
os.environ['http_proxy'] = 'http://user:password@localhost:8888'
import urllib2
req = urllib2.Request('http://www.blah.com')
f = urllib2.urlopen(req)

rawDescription: What's the format for urllib2 request proxies?


rawDescription: How to convert a Python datetime.datetime.utctime() to an Obj-C NSDate, and back again?

description: Convert a Python datetime.datetime.utctime() to an Obj-C NSDate, and back again


code:
def bigram_db():
    cursr.execute("SELECT * FROM trainedGrammar")
    txt = ""
    for row in cursr:
        txt += row[0]
    return txt

rawDescription: Store output of for loop into single variable


code:
from re import compile

# your code to choose file

line_format = compile(r"\s*\(\s*'([^']*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
file = open(emp_choice + ".txt")
line = file.readline()   # read the first line only
match = line_format.match(line)
if match:
    name, weeks_worked, weekly_payment = match.groups()
else:
    raise Exception('Could not match %s' % line)

# your code to update information

rawDescription: Read from text file and assign data to new variable


code:
import lxml.etree as ET

content='''\
<text>
    The 40-Year-Old Virgin is a 2005 American buddy comedy
    film about a middle-aged man's journey to finally have sex.

The plot

    Andy Stitzer (Steve Carell) is the eponymous 40-year-old virgin.

Cast

Soundtrack

External Links

</text>
'''

text=ET.fromstring(content)
print(text.text)

rawDescription: Regarding regular expressions and XML

description: Regarding regular expressions and XML


rawDescription: Django get current view in template

description: Django get current view in template


code:
from collections import namedtuple

Employee = namedtuple("Employee",
                      "name title number salary")

boss = Employee("Michael Scott", "Regional Manager", 3, 50000.00)
print(repr(boss))
print(vars(boss))

rawDescription: Python: When printing the contents of a class, I can't understand the order they're being printed in


code:
import datetime as dt
import matplotlib.dates as mdates
from matplotlib import pyplot
from random import randint

array1 = ['2014-10-28', '2014-11-17', '2014-09-29', '2014-10-17', '2014-10-22']
array2 = [1,4,5,6,9]

dates = ["2014-{month:0>2d}-{day:0>2d}".format(month=m, day=d) for m in [1,5] for d in range(1,32)]
dates = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
freqs = [randint(0,4) for _ in dates]

fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(dates, freqs, "ro")

fig.autofmt_xdate()

pyplot.show()

rawDescription: How do i get the x axis to only show my data i want to plot? Instead of it including labels with no plots?

description: Get the x axis to only show my data i want to plot? Instead of it including labels with no plots


code:
#_*_coding: utf-8_*_
import requests
import BeautifulSoup as bs
import csv
import calendar as cal
import datetime as dt

url = 'http://www.meteoprog.sk/sk/fwarchive/Bratislava/'

rawDescription: Scraping historic data with Python from a specific website - table created out of a form with many rows with isolated header. Automation needed


code:
c.executemany(
      """INSERT INTO breakfast (name, spam, eggs, sausage, price)
      VALUES (%s, %s, %s, %s, %s)""",
      [
      ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
      ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
      ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
      ] )

rawDescription: How to use python mysqldb to insert many values at once

description: Use python mysqldb to insert many values at once


code:
locate('datetime.date')
d = locate('datetime.date')
d(2015, 4, 23)

rawDescription: Lexical cast from string to type

description: Lexical cast from string to type


code:
a = ["car", "plane", "truck", "motorcycle", "jet", "train"]
b = ["plane", "jet"]
c = [i for i, v in enumerate(a, start=1) if v not in b]
print(c)

rawDescription: Subtract List B from List A but keeping the List A index


rawDescription: Does ipython notebook 'run all cells' execute simultaneously or in sequence?


rawDescription: How to do a general "search bar" search across multiple SQLAlchemy models

description: Do a general "search bar" search across multiple SQLAlchemy models


code: np.multiply.accumulate(np.arange(x, x + N))

rawDescription: Generate a sequence keeping previous element in next element python


rawDescription: Python Shortest path between 2 points

description: Python Shortest path between 2 points


code:
'a' 'href' 'http://google.com'
'a' 'id' '100'
'a' 'href' 'heise.de/'

rawDescription: example for using streamhtmlparser

description: Example for using streamhtmlparser


code:
for i in indices:
    status[i] = guess

rawDescription: Replace list object based on indexes of another list (Python)


code:
drawCustom = {
  Bubble.GAUCHE: 'drawString',
  Bubble.CENTRE: 'drawCentredString',
  Bubble.JUSTIFIE: 'drawAlignedString',
  Bubble.DROITE: 'drawRightString',
}
func = getattr(p, drawCustom[bubble])
func(100, 100, "Hello world.")

rawDescription: Python: how to call a method coming from an array?


code:
def checkstocklevel(socklevel):
    #maybe do something (I don't know if there is more code in your function)
    if stocklevel < 1:
        print("Sorry, this product is out of stock")
        f = open("receipts","a")
        f.write(code)
        f.write(" Product Out Of Stock\n")
        f.close()
        return False,stocklevel
    #...
    return True,stocklevel

rawDescription: How To Skip Functions?

description: How To Skip Functions


rawDescription: Why isn't my dictionary printing correctly?


code: get_nth_pow('eht', 34)

rawDescription: finding nth combination (incremental approach) of letters (list)

description: Finding nth combination (incremental approach) of letters (list)


code:
with open('textfile','r') as f:
    lines=[L[:-1] for L in f.readlines()]

rawDescription: Reading lines in text files using python


code:
from PIL import Image

def sprite_mask(img, bg_point=(0, 0)):
    width, height = img.size
    im = img.load()

    bg = im[bg_point]
    mask_img = Image.new('L', img.size)
    mask = mask_img.load()
    for x in xrange(width):
        for y in xrange(height):
            if im[x, y] != bg:
                mask[x, y] = 255
    return mask_img, bg

rawDescription: PySide: Separating a spritesheet / Separating an image into contiguous regions of color


code:
d={}
for i,j in enumerate(new):
  d.setdefault(j,[]).append(i)

d

rawDescription: Python optimize how to find duplicate value and value index in a list


code:
gps = GPS()
gps.process_gprmc_data(data)
print_gps = PrintGPS()
print_gps.process_gprmc_data(data)

rawDescription: How to get inheritance to work from parent to child class python34

description: Get inheritance to work from parent to child class python34


code: total = sum(abs(med-i) for i in lst)

rawDescription: Python: Unsorted/Sorted Lists Return Different Values?


code:
def printgcd2(name, a, b):
   f = open(name, "wt")
   s = ""
   h = { }
   for i in range(a, b + 1):
      s = "{}\t{}".format(s, i)
   f.write("{}\n".format(s))
   for i in range(a, b + 1):
      s = "{}".format(i)
      for j in range (a, b + 1):
         k = gcd(i, j)
         s = "{}\t{}".format(s, k)
         h[i, j] = k
      f.write("{}\n".format(s))
   f.close()
   return h

rawDescription: Print (or output to file) table of number of steps for Euclid's algorithm


rawDescription: How to get a response of multiple objects using rest_framework and Django

description: Get a response of multiple objects using rest_framework and Django


code:
from scipy.spatial.distance import cdist

dist = cdist(data, C, metric='euclidean')
dist_idx = np.argmin(dist, axis=1)

rawDescription: More efficient way to get nearest center


code:
path = os.path.join(directoryChosen, n)
target = os.path.join(directoryChosen, newname)

rawDescription: Renaming a folder in Python

description: Renaming a folder in Python


code:
#Golf Scores

# main module/function
def main():

# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
    infile = open('golf.txt', 'r')

# reads the player array from the file
    name = infile.readline()

    while name != '':

# reads the score array from the file
        score = infile.readline()

# strip newline from field
        name = name.rstrip('\n')
        score = score.rstrip('\n')
# prints the names and scores
        print(name + " scored a " + score)

# read the name field of next record
        name = infile.readline()

# closes the file
    infile.close()

# calls main function
main()

rawDescription: Golf scores python program

description: Golf scores python program


rawDescription: universal method for working with currency with no rounding, two decimal places, and thousands separators

description: Universal method for working with currency with no rounding, two decimal places, and thousands separators


code:
foreign_naive = datetime.datetime(2012, 3, 11, 6, 0, 0)
foreign_timezone = 'US/Eastern'
foreign_dt = pytz.timezone(foreign_timezone).localize(foreign_naive)
timestamp = time.mktime(foreign_dt).astimezone(pytz.utc).timetuple()
local_dt = datetime.datetime.fromtimestamp(timestamp)

rawDescription: Using pytz to convert from a known timezone to local


code:
import datetime
s = 'Fri Aug 17 12:34:00 2012 +0000'
import iso8601
timezone = iso8601.iso8601.parse_timezone('{}:{}'.format(tz[:3], tz[3:]))
datetime.datetime.strptime(datetimetext, '%a %b %d %H:%M:%S %Y').replace(tzinfo=timezone)
from dateutil import parser
parser.parse(s)

rawDescription: Comparing dates in Python - how to handle time zone modifiers


rawDescription: In Pandas, is there a way to divide a cell by all other cells in a column?


code:
psimaps_vec = np.sum(featureParams*features[..., None, None], axis=2, keepdims=True) + transitiveParams
psimaps_vec[-2] += psimaps_vec[-1] - transitiveParams
psimaps_vec = psimaps_vec[:-1]

rawDescription: How to eliminate for-loop and use list comprehension when using numpy array?

description: Eliminate for-loop and use list comprehension when using numpy array


code:
params = ",".join(["?" for i in range(len(my_list))])
statement = """SELECT * FROM MyTable
 WHERE date > ?
   AND (item1 IN (%s) OR item2 IN (%s))""" % (params, params)
bindings = [my_date] + my_list + my_list
cursor.execute(statement, bindings)

rawDescription: SQL either of two values in a list

description: SQL either of two values in a list


code:
x = sympy.Symbol('x', commutative=False)
y = sympy.Symbol('y', commutative=False)
sympy.sympify('3*x*y - y*x - 2*x*y', locals={'x':x, 'y':y})

rawDescription: Non-commutative sympify (or simplify)

description: Non-commutative sympify (or simplify)


code:
# On Python 3.3+, you can force a sync to disk first, minimizing the amount of
# dirty pages to drop as much as possible:
os.sync()

with open('/proc/sys/vm/drop_caches', 'w') as f:
    f.write("1\n")

rawDescription: How to clear my caches?

description: Clear my caches


code:
import urllib.parse
formdata = urllib.parse.parse_qs('ugq_no=2')
formdata
formdata['ugq_no']
formdata['ugq_no'][0]

rawDescription: How to get request.environ values in python?

description: Get request.environ values in python


code:
with open(sys.argv[1], 'r') as r:
    for curline in r:
        sift = string.split(curline, ' ')
        ip = sift[1]

    ...

rawDescription: Any way to optimize/properly refine this <50 line script?


code: assignId("ahahah")

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


code:
class MyClass:
    ids_list = range(300)

    def main(self):
        pool = multiprocessing.Pool(3)

        def kill_pool(err_msg):
            print(err_msg)
            pool.terminate()

        for osm_id in self.ids_list:
            pool.apply_async(self.handle_country_or_region,
                             kwds=dict(country_id=osm_id),
                             error_callback=kill_pool)

        pool.close()
        pool.join()

    def handle_country_or_region(self, country_id=None, queue=None):
        pass  # here I do some task

rawDescription: Cant stop\kill all processes at once produced by multiprocessing.Pool


code: [i * j for j, i in enumerate(S)]

rawDescription: What is correct python syntax for this kind of list comprehension?


code: transactional.reset_index(inplace = True, drop=True)

rawDescription: How to reset an unordered index to an ordered one in python?

description: Reset an unordered index to an ordered one in python


code:
def my_view(request):
    if request.method == 'POST':
        form = UploadForm(files=request.FILES)
        if form.is_valid():
            form.process()
            return ...

rawDescription: Django upload for processing

description: Django upload for processing


rawDescription: How can I make a siren noise in Python?

description: Make a siren noise in Python


code:
class AllManyToManyQuerySet(models.QuerySet):
    def filter_all_many_to_many(self, attribute, *args):
        qs = self
        for arg in args:
            qs = qs.filter(**{attribute: arg})
        return qs

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

rawDescription: Django filter filter with lists

description: Django filter filter with lists


code:
base = datetime.datetime(2000, 1, 1)
arr = numpy.array([base + datetime.timedelta(hours=i) for i in xrange(24)])

rawDescription: How can I make a python numpy arange of datetime

description: Make a python numpy arange of datetime


code:
newList = []
for x in oldList:
    for _ in range(2):
        newList.append(x)

rawDescription: Python: duplicating each element in a list


code:
fruits = ["apple", "banana", "guava", "grapes"]
colour = ["red", "yellow", "green", "black"]
[{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]

rawDescription: Convert list to list of dictionaries in python


code:
from __future__ import print_function

import numpy as np

nred = 12
ngreen = 4
nblue = 18

m = 15

red = np.random.hypergeometric(nred, ngreen + nblue, m)
green = np.random.hypergeometric(ngreen, nblue, m - red)
blue = m - (red + green)

print("red:   %2i" % red)
print("green: %2i" % green)
print("blue:  %2i" % blue)

rawDescription: Numpy drawing from urn

description: Numpy drawing from urn


code:
True or ''
True or 'foo'
False or ''
False or 'foo'
'' or True
'' or False
'bar' or True
'bar' or False
True and ''
True and 'foo'
False and ''
False and 'foo'
'' and True
'' and False
'bar' and True
'bar' and False

rawDescription: Python - Interesting boolean and string behavior


code: pd.DataFrame({'nodes': np.unique(df)})

rawDescription: Pandas reformatting multiple columns into one.


code:
{
    'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
    'icy-br': '128, 128',
    'Pragma': 'no-cache',
    'icy-name': 'ChecheInternationalRadio',
    'ice-audio-info': 'bitrate=128;samplerate=44100;channels=2',
    'Cache-Control': 'no-cache',
    'icy-genre': 'medellin',
    'Content-Type': 'audio/mpeg',
    'icy-description': 'Esta es una Emisora suena solo Exitos Una selecta programacion musical con los mejores artistas y canciones de todos los tiempos. Transmitiendo desde medellin Colombia.',
    'icy-pub': '1',
    'Accept-Ranges': 'none',
    'icy-url': 'http://cheche-international-radio.playtheradio.com/',
    'Server': 'Icecast 2.3.3-kh8'
}

rawDescription: How do I close a request to a streaming radio stream url?

description: Close a request to a streaming radio stream url


rawDescription: Splitting a string with delimiters and conditions


code: ''.join(x for x in 'make IT camel CaSe'.title() if not x.isspace())

rawDescription: CamelCase every string, any standard library?


code:
abcd
rreverse(bcd) + a
(rreverse(cd) + b) + a
((rreverse(d) + c) + b) + a
(((rreverse('') + d) + c) + b) + a
'' + d + c + b + a
d + c + b + a
dc + b + a
dcb + a
'dcba'

rawDescription: Need help understanding a recursive solution to reverse a List


rawDescription: Working with binary in Python, Splitting numbers


code:
minus_seven_dirs = [d for d in os.listdir(os.getcwd())
    if os.path.isdir(d) and d.startswith(minus_seven)]

rawDescription: How to move into multiple directories Python

description: Move into multiple directories Python


code:
ml = max(map(len, lists))
ml       #length of the longest list in lists
[sum(x) for x in zip(*map(lambda x:x+[0]*ml if len(x)<ml else x, lists))]

rawDescription: Sum lists with different lengths

description: Sum lists with different lengths


code:
var1, var2 = [s.strip() for s in text.split(u"\xb7")]
# -> u'2 rooms', u'USD 0'

rawDescription: beautifulsoup 4 + python: string returns 'None'

description: Beautifulsoup 4 + python: string returns 'None'


code:
from itertools import chain
with open("in.txt") as f:
    lines = list(chain.from_iterable(x.split() for x in f))
    with open("in.txt","w") as f1:
        for ind, line in enumerate(lines,1):
            if not line in lines[:ind-1]:
                f1.write(line+"\n")

rawDescription: Merge Columns and Remove Duplication

description: Merge Columns and Remove Duplication


code:
import BeautifulSoup
import re

content='''

Volume 14

Issue 1, September 2011

Volume 13

Issue 2, December 2010

Issue 1, November 2011

'''

last_volume=13
last_issue=1

soup=BeautifulSoup.BeautifulSoup(content)
results = soup.find('ul', attrs={'class' : 'bobby'})
for a_string in results.findAll('a', text=re.compile('Issue')):
    volume=a_string.findPrevious(text=re.compile('Volume'))
    volume=int(re.search(r'(\d+)',volume).group(1))
    issue=int(re.search(r'(\d+)',a_string).group(1))
    href=a_string.parent['href']
    if (volume>last_volume) or (volume>=last_volume and issue>last_issue):
        print(volume,issue,href)

rawDescription: Python and Beautiful Soup - Search for tag a, return following tag b's until tag A is found


rawDescription: Is it possible getting all parameters of a field


code:
def input_and_print(question):
  s = input("{} ".format(question))
  print("You entered: {}".format(s))

input_and_print("What is your name?")

rawDescription: How to define a variable inside the print function?

description: Define a variable inside the print function


code:
#renamed stat to player, the point of the object shouldn't be to hold just the stats, should hold all information
#pertaining to the player / dicer
class Dicer():
    #levelm, totalexp, health removed from constructor
    def __init__(self, name, role, health, attack, defense):
        self.name = name #changed Name to name
        self.level = 1
        self.totexp = 0
        self.role = role #changed Role to role
        self.health = health
        self.attack = attack
        self.defense = defense
        self.exp = 0

    #instance function to print the stats of the dicer
    def print_info(self):
        print(
            "Here is your Dicer's information:\nDicer's name: {0}\nLevel: {1}\nExperience: {2}\nRole:"\
            " {3}\nRole Stats:\nHealth: {4}\nAttack: {5}\nDefense: {6}".format(self.name, self.level, self.totexp, self.role, self.health, self.attack, self.defense)
        )
def choose_name():
    while(True):
        Name = input("What is your Dicer's name?:\n").title()
        if(any(Bad_Words in Name.lower() for Bad_Words in [])):
            print("That's an inappropriate name! Try again")
        elif(len(Name) < 3):
            print("That name is too short! Try again.")
        elif(len(Name) > 16):
            print("That name is too long! Try again.")
        else:
            #you have to return the name so you can use it later
            return Name

def choose_role():
    #removed all the lambdas here
    Roles = {
   'mage': (100, 40, 10), #(Health, Attack, Defense)
   'warrior': (100, 30, 20),
   'gunner': (100, 20, 30),
   'archer': (100, 10, 40)
   }

    while(True):
        Role = input("What role do you want to be?\nChoices:\n1. Mage\n2. Warrior\n3. Gunner\n4. Archer\n").title()
        if(Role.lower() in (Roles)):
            #don't just return None, return the name of the role and it's 3-tuple stats
            #returning the role and it's stats from a function is not the best way to do this
            return Role, Roles[Role.lower()]
        else:
            print("That's not a role! Try again.")

dicer_name = choose_name()
dicer_role_name, dicer_role_stats = choose_role()

#create a dicer using the stats returned from chose_role() function
mainDicer = Dicer(dicer_name, dicer_role_name, dicer_role_stats[0], dicer_role_stats[1], dicer_role_stats[2])
mainDicer.print_info()

rawDescription: How Do I Fix My Code So It Can print() Out The Results I Want?


code: l = [(0, pi) for i in range(12)]

rawDescription: how to create a list of identical tuples in python

description: Create a list of identical tuples in python


code:
class MutableObject(Mutable, object):
    @classmethod
    def coerce(cls, key, value):
        return value

    def __getstate__(self):
        d = self.__dict__.copy()
        d.pop('_parents', None)
        return d

    def __setstate__(self, state):
        self.__dict__ = state

    def __setattr__(self, name, value):
        object.__setattr__(self, name, value)
        self.changed()

class Path(MutableObject):
    def __init__(self, style, bounds):
        super(MutableObject, self).__init__()
        self.style = style
        self.bounds = bounds

class Bound(MutableObject):
    def __init__(self, l, t, r, b):
        super(MutableObject, self).__init__()
        self.l = l
        self.t = t
        self.r = r
        self.b = b

rawDescription: PickleType with Mutable Tracking in SqlAlchemy


code:
from operator import itemgetter
itemgetter(*indices[:3])(pop)
itemgetter(*indices[3:])(pop)

rawDescription: Random division of list to two complementary sublists


code:
characters = ['Č', 'č', 'Š', 'š', 'Ž', 'ž']
codecs = ['cp852', 'iso8859_2', 'cp1250', 'mac_latin2', 'utf-8', 'utf_16_le', 'utf_16_be']

for letter in characters:
    for codec in codecs:
        decCodePoint = int.from_bytes(letter.encode(codec), byteorder='big') #code point integer
        print(letter + ' ' + codec + ' ' + str(decCodePoint) + ' ' + str(hex(decCodePoint)) + ' ' + str(oct(decCodePoint))) #i also convert decimal integer to hexadecimal and octal

rawDescription: How to find integer representing code point of special character? TypeError: ord() expected a character, but string of length 2 found

description: Find integer representing code point of special character? TypeError: ord() expected a character, but string of length 2 found


code:
class TagListField(Field):
    widget = TextInput()

    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []

class PostForm(Form):
    title = StringField(u'title', validators=[DataRequired()])
    body = StringField(u'Text', widget=TextArea())
    pub_date = DateTimeField(u'date create')
    topic = QuerySelectField(query_factory=enabled_topics, allow_blank=True)
    tags = TagListField(u'Tags') # here you use your custom field

    # a method to set the tags
    def fill_tags(self, tags):
        self.tags.data = tags
    # and from the view that is creating the form you send the list of tags

rawDescription: How to send query results to a WTForm Field?

description: Send query results to a WTForm Field


code: plt.thetagrids([theta * 15 for theta in range(360//15)])

rawDescription: Polar heatmaps in python

description: Polar heatmaps in python


code:
from glob import iglob
from os.path import basename

@app.route(...)
def list_images():
    pngs = iglog('img/*.png')                  # An iterator of 'img/1.png', 'img/2.png', ...
    pngs = (basename(png) for png in pngs)     # Strip the directory name
    return render_template('list_images.html', # A normal jinga template
                           pngs=pngs)          # That gets the iterator of names as argument

rawDescription: Using png files from a folder for flask app


code:
for i in range(nphones):
           rbuttons[i].SetLabel(voice1.phones[i].name)
           rbuttons[i].Show()

vm_idx = nphones
rbuttons[vm_idx].SetLabel('Voicemail')
rbuttons[vm_idx].Show()

rawDescription: Dynamic wx.RadioButtons

description: Dynamic wx.RadioButtons


code: rows = [row for row in filereader if row in filterSubstrings]

rawDescription: Python: simple csv substring filter

description: Python: simple csv substring filter


code: print(kf.format("{:t{}}  {}", key, ':', value))

rawDescription: Print string left aligned with fixed width and suffix


rawDescription: Order record array by unique occurances

description: Order record array by unique occurances


code:
class SubmitInput(Input):
    """
    Renders a submit button.

    The field's label is used as the text of the submit button instead of the
    data on the field.
    """
    input_type = 'submit'

    def __call__(self, field, **kwargs):
        kwargs.setdefault('value', field.label.text)
        return super(SubmitInput, self).__call__(field, **kwargs)

rawDescription: Does SubmitField need a validator?

description: Does SubmitField need a validator


code:
class PersistedGraph(nx.Graph):
    def __init__(self, data=None, node_dict_factory=None, adjlist_dict_factory=None, edge_attr_dict_factory=None,
                 **attr):
        if node_dict_factory:
            self.node_dict_factory = node_dict_factory
        if adjlist_dict_factory:
            self.adjlist_dict_factory = adjlist_dict_factory
        if edge_attr_dict_factory:
            self.edge_attr_dict_factory = edge_attr_dict_factory
        nx.Graph.__init__(self, data, **attr)

rawDescription: NetworkX extensibility for custom storage of nodes/edges


code:
def check_password(raw_password, enc_password):
    """
    Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.
    """
    algo, salt, hsh = enc_password.split('$')
    return hsh == get_hexdigest(algo, salt, raw_password)

rawDescription: Python's safest method to store and retrieve passwords from a database


rawDescription: How to map a arabic character to english string using python

description: Map a arabic character to english string using python


code:
with app.request_context(environ):
    ...

rawDescription: Is it possible to clone a request to use it later?


rawDescription: Summing over lists in python - is there a better way?


code:
from subprocess import  check_call

check_call(["sudo","convert","imgIn.jpg", "-posterize","2","imgOut.jpg"])

check_call([ "sudo",'convert', 'imgIn.jpg', '-matte', '(', '+clone', '-fuzz', '57%', '-opaque', 'black', '-transparent', 'blue', ')', '-compose', 'DstOut', '-composite', 'imgOut.jpg'])

rawDescription: ImageMagick code in Python script

description: ImageMagick code in Python script


code:
strings = ["Hi Dude", "Dude", "ok Dude"]
dictionary = {}
for i, item in enumerate(strings):
    for word in item.split():
        try:
            dictionary[word].append(i)
        except KeyError:
            dictionary[word] = [i]

rawDescription: Inverse Index comprehension

description: Inverse Index comprehension


rawDescription: Python list sorting dependant on if items are in another list


code:
def removeitem():
    fr = open('Bmi.csv', 'r')
    removed_lines = listbox.curselection()
    #  ^ just get line numbers with ^ this
    lines = fr.readlines()
    fr.close()
    fr = open("Bmi.csv","w")
   # ^ you use the variable fr here but f below...
    for i,line in enumerate(lines):
        if i not in removed_lines:
             # ^ use in operator since removed_lines is a tuple
             # it is worth noting that this has the advantage of working if multiple lines are selected
            f.write(line)
          # ^ this is f but the file is fr
          #I'm pretty sure this one is a typo
    listbox.delete(ANCHOR)
    # ^ this may not work if multiple lines are selected
    fr.close()

rawDescription: Delete Line in Csv file from selected line in Listbox


code: "Please go away, DND".replace('DND', 'do not disturb')

rawDescription: Swapping "words" in a list of strings in Python


code:
fruit = set(("apple", "banana"))
green = set(("apple", "sometree", "someplant", "otherplant"))
nature = set(("apple", "banana", "sometree", "someplant", "otherplant"))
tree = set (("sometree",))
wood = set (("sometree", "someplant", "otherplant"))

In [90]: fruit.intersection(nature)
Out[90]: set(['apple', 'banana'])

In [91]: fruit.intersection(nature).intersection(green)
Out[91]: set(['apple'])

In [92]: green.intersection(wood).intersection(nature)
Out[92]: set(['sometree', 'someplant', 'otherplant'])

In [93]: green.intersection(wood).intersection(nature).intersection(tree)
Out[93]: set(['sometree'])

rawDescription: Python: data structure to index sets to find supersets?


code:
import re
obj = re.compile('{.*?: (\d*?)}')
with open('datafile.txt', 'r') as f:
    data = f.read()
s = set(obj.findall(data))

rawDescription: Python- find the unique values from a large json file efficienctly


code:
class A(object):
    def __new__(cls, obj):
        if isinstance(obj, cls):
            return obj
        rv = object.__new__(cls)

        # everything you would normally put in __init__
        # goes here instead
        rv._obj = obj
        return rv

    # for instance:
    def __repr__(self):
        return "A({})".format(repr(self._obj))

rawDescription: How to prevent a wrapper object wrapping itself?

description: Prevent a wrapper object wrapping itself


code:
increment = Counter(dict.fromkeys(x, n))
y = x + increment

rawDescription: How to add N to every value of a Counter? - python

description: Add N to every value of a Counter? - python


rawDescription: Generate summed up ranges from a list

description: Generate summed up ranges from a list


code:
now = time.time()
hunger = lambda: time.time() > now + 60

rawDescription: How could I set a boolean value to True, and make it so if a condition is met, it becomes False, but only for a certain amount of time?


code:
def get_absolute_url(self):
   return reverse('gallery:gallery_detail', kwargs={'slug': self.slug, 'parent_slug': self.parent.slug})

rawDescription: Django-CMS apphooks menu and reverse

description: Django-CMS apphooks menu and reverse


code:
import json
from pprint import pprint

output = '''[data extract]Set-Cookie: JSESSIONID=12buplms5odzt;Path=/config
Transfer-Encoding: chunked
Closing connection #0
 SSLv3, TLS alert, Client hello (1):
} [data not shown]
{"sip_domains":{"prefix":[{"name":""}],"domain":[{"name":"k200.com"},{"name":"zinga.com"},{"name":"rambo.com"}]},"sip_security":{"level":2},"sip_trusted_hosts":{"host":[]},"sip_proxy_mode":{"handle_requests":1}}'''

output = json.loads( output.split("\n")[-1] )

pprint( output )

rawDescription: extracting the output using python

description: Extracting the output using python


rawDescription: How to check python codes by reduction?

description: Check python codes by reduction


code:
args.add_argument('-w','--width', const=84, default=80, type=int,
              help='The width of the menu.', nargs='?')
args.add_argument('-l','--length', const=28, default=24, type=int,
              help='The length of the menu.', nargs='?')

rawDescription: How to give a python program two optional command-line integer arguments?

description: Give a python program two optional command-line integer arguments


code:
def parse_assignedzip_numberpolygon(s):
    return [map(float, coord.split(",")) for coord in s.split()]

def proc_data_dict(d):
    new_d = d.copy()
    new_d['assignedzip_numberpolygon'] = parse_assignedzip_numberpolygon(d['assignedzip_numberpolygon'])
    return new_d

rawDescription: Preparing a list from a dictionary in python


code: df['new_column'] = df.apply(my_fxn, axis=1)

rawDescription: What is the `pandas` way to create a column in a dataframe by operating on each row?


code:
with open('new.html', 'w') as f: # with will auto create file and close after writing
    f.write(html)

rawDescription: Creating an HTML page from python

description: Creating an HTML page from python


code:
import random, string
KEYLEN = 15
prefix = "car"
key = prefix + "".join(random.choice(string.letters+string.digits) for _ in range(KEYLEN))

rawDescription: Generate randon and uniques ids in django


code: #!/usr/bin/env python

rawDescription: How can I eliminate the need of the command 'python' when running a python file in terminal?

description: Eliminate the need of the command 'python' when running a python file in terminal


code:
p = "Scanning sequence ID\:\s*(?P<label>[A-Z0-9]+\_[A-Z0-9]+).*?(?P<start_value>\d+)\s+\S+\s+\S+\s+\S+\s+(?P<sequence>\S+)"
re.findall(p,s, re.DOTALL)

rawDescription: How to extract start and end sites based on capital letter in a sequence?

description: Extract start and end sites based on capital letter in a sequence


code:
class A(object):
    some_field = None
    def __new__(cls, val):
        cls.some_field = val
        return cls

class B(A(123)): pass

rawDescription: Class (not instance) constructor

description: Class (not instance) constructor


code:
import numpy as np

a_in = np.memmap('foreman_cif.yuv', mode='readonly')
a_out = np.memmap('py_10bpp.yuv', mode='write', shape=2*len(a_in))
a_out[::2] = a_in << 2
a_out[1::2] = a_in >> 6

rawDescription: python performance dealing with binary files

description: Python performance dealing with binary files


code:
values = numpy.random.randint(0, 20, 10)
values
bins = numpy.linspace(-1, 21, 23)
bins
pos = numpy.digitize(values, bins)
pos

rawDescription: assigning points to bins

description: Assigning points to bins


code:
[any(x) and not all(x) for x in zip(*d['o1414'])]
Out[60]: [True, False, False]

rawDescription: Difference between multiple elements in list with same string . Python 2.7


code:
def run ( self ):
    print ( "Register Timer-Thread: " + self.sThreadName )
    while True:
        hTimer = threading.Timer ( self.iThreadInterval, print_time, ( self.sThreadName ) )
        hTimer . start ( )

rawDescription: Why I should use threading.Timer instead of a Loop + Sleep?


code:
rect = pygame.Rect(25, 25, 100, 50)
sub = screen.subsurface(rect)
pygame.image.save(sub, "screenshot.jpg")

rawDescription: How to take screenshot of certain part of screen in Pygame

description: Take screenshot of certain part of screen in Pygame


rawDescription: syntactic whitespaces with pyparsing's operatorPrecedence

description: Syntactic whitespaces with pyparsing's operatorPrecedence


code:
def is_solvable(index, board, visited=None):
    if visited is None:
        visited = []

    if index == len(board) - 1:
        return True
    elif index in visited:
        return False
    elif index < 0 or index >= len(board):
        # out of bounds
        return False
    else:
        visited.append(index)
        value = board[index]
        left = is_solvable(index - value, board, visited)
        right = is_solvable(index + value, board, visited)
        return left or right

rawDescription: python recursion jumping to last cell

description: Python recursion jumping to last cell


rawDescription: new list from specific index of multidimension list?

description: New list from specific index of multidimension list


code:
import timeit
import enum
class Result(enum.Enum):
    lose = -1
    draw = 0
    win = 1

timeit.timeit('outcome = Result.lose', 'from __main__ import Result')
timeit.timeit('outcome = lose', 'from __main__ import Result; lose = Result.lose')

rawDescription: How to use Python 3.4's enums without significant slowdown?

description: Use Python 3.4's enums without significant slowdown


code: yourDict = dict(zip(xrange(1, len(yourList)+1), yourList))

rawDescription: Reading from a plain text file

description: Reading from a plain text file


code:
@api.model
def get_age_comp(self):
    self.search([('gender','=','m'), ('status', '=', 'underage'),
                 ('birth_date', '<=', date.today() - relativedelta(years=20))
                ]).write({'status': 'getCard'})

rawDescription: Automated Action Birthday =19

description: Automated Action Birthday =19


code:
my_str = 'soooo hiiiii whyyyy done'
import re
regex = re.compile(r"(.)\1{2}")
[word for word in my_str.split() if regex.search(word)]

rawDescription: string contains elongated words

description: String contains elongated words


code:
from optparse import Option, OptionError, OptionParser

class MyOption(Option):
    def _set_opt_strings(self, opts):
        for opt in opts:
            if len(opt) < 2:
                raise OptionError(
                    "invalid option string %r: "
                    "must be at least two characters long" % opt, self)
            elif len(opt) == 2:
                self._short_opts.append(opt)
            else:
                self._long_opts.append(opt)

class MyOptionParser(OptionParser):
    def _process_args(self, largs, rargs, values):
        while rargs:
            arg = rargs[0]
            if arg == "--":
                del rargs[0]
                return
            elif arg[0:2] == "--":
                self._process_long_opt(rargs, values)
            elif arg[:1] == "-" and len(arg) > 1:
                if len(arg) > 2:
                    self._process_long_opt(rargs, values)
                else:
                    self._process_short_opts(rargs, values)
            elif self.allow_interspersed_args:
                largs.append(arg)
                del rargs[0]
            else:
                return

rawDescription: parsing non GNU-standard options using optparse in python

description: Parsing non GNU-standard options using optparse in python


code: d = dict(zip(chars,cipher))

rawDescription: Python Lists Comparison & Print

description: Python Lists Comparison & Print


code:
with open('foo.csv') as f:
    for row in csv.DictReader(f):
        cursor.execute('''INSERT INTO Product (ProductID, Name, UOM)
                          VALUES (:ProductID, :Name, :UOM)''', row)
        for alias in row['Alias'].split(';'):
            cursor.execute('''INSERT INTO ProductAlias (Name, Alias)
                              VALUES (?, ?)''', row['Name'], alias)

rawDescription: Import single csv file with one data field going to separate table


code:
def __setattr__(self, attr, val):
    try:
        obj = object.__getattribute__(self, attr)
    except AttributeError:
        # This will be raised if we are setting the attribute for the first time
        # i.e inside `__init__` in your case.
        object.__setattr__(self, attr, val)
    else:
        if hasattr(obj, '__set__'):
            obj.__set__(self, val)
        else:
            object.__setattr__(self, attr, val)

rawDescription: Why is the Descriptor not getting called when defined as instance attribute?


code:
import numpy as np

data = numpy.load('myMD.dat')
xpos1 = data['xpos1']
# et cetera

rawDescription: save simulation data in python

description: Save simulation data in python


rawDescription: Why won't my for loop work? (Python)

description: Why won't my for loop work? (Python)


code:
def window_to_bitmap(window):
    width, height = window.GetSize()
    bitmap = wx.EmptyBitmap(width, height)
    wdc = wx.WindowDC(window)
    mdc = wx.MemoryDC(bitmap)
    mdc.Blit(0, 0, width, height, wdc, 0, 0)
    return bitmap

rawDescription: get a widgets dc in wxpython

description: Get a widgets dc in wxpython


code:
from django.shortcuts import render
from django.http import HttpResponseRedirect

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        # ContactForm was defined in the the previous section
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render(request, 'contact.html', {
        'form': form,
    })

rawDescription: Django - A bit lost with forms

description: Django - A bit lost with forms


rawDescription: Why can I call all these methods that aren't explicitly defined in a class?


code:
for form in track_formset.ordered_forms:
    data = form.cleaned_data
    # Do what you want with the data

rawDescription: Validate Django forms for user specified dynamically generated fields


code:
y = textranges_freq['smstext']
xlabels = textranges_freq['buckets']
def makebar(y, xlabels, xlabel, ylabel, title):
    bar_width = 0.50
    x = np.arange(len(y))
    fig, ax = plt.subplots()
    ax.bar(x, y, width=bar_width)
    ax.set_xticks(x+(bar_width/2.0))
    ax.set_xticklabels(xlabels)
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    plt.show()

rawDescription: How to write a function for barchart in python?

description: Write a function for barchart in python


code:
class SettingsTest(TestCase):
    def setUp(self):
        user = User.objects.create(username='felipe', email='something@aol.com')
        self.settings = Settings.objects.create(...)
        self.profile = Profile.objects.create(short_name='Felipe',
                                              name='Felipe',
                                              user=user,
                                              settings=self.settings)

rawDescription: Automatically creating a OneToOneField when accessed


code:
A = Matrix(np.arange(12).reshape(3, 4))
(2 * A).array

rawDescription: Duplicating Python int * numpy.array behavior


code:
from pprint import pprint
l = [{'name': 'John', 'age': 23},
     {'name': 'Steve', 'age': 35},
     {'name': 'Helen'},
     {'name': 'George'},
     {'name': 'Jessica', 'age': 23}]
l.sort(key=lambda d: 'age' in d)
pprint(l)

rawDescription: How to reorder a list in Python based on its content

description: Reorder a list in Python based on its content


code:
classes = ('colore1', 'colore2', 'colore3', 'colore4', 'colore5', 'colore6', 'colore7', 'colore8', 'colore9', 'colore10')
dict(zip(set(test_input), classes))

rawDescription: python dict.fromkeys with function as parameter

description: Python dict.fromkeys with function as parameter


code:
opfmeta = []
for key, person in ophav.items():
    opfmeta.append('<dc:creator role="' + key + '">' + ' & '.join(person) + '</dc:creator>')

rawDescription: Looping over a list within a dict

description: Looping over a list within a dict


rawDescription: Microsecond accurate timestamp in python?


code:
# Inside your models.py
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

class MyModel(models.Model):
    field1 = models.TextField()
    field2 = models.IntegerField()

@receiver(pre_save, sender=MyModel)
def mymodel_save_handler(sender, **kwargs):
    logging.debug("======================================")

rawDescription: Django pre_save signal does not work

description: Django pre_save signal does not work


code:
import nltk
def tokenize(sentences):
    for sent in nltk.sent_tokenize(sentences.lower()):
        for word in nltk.word_tokenize(sent):
            yield word

nltk.Text(tkn for tkn in tokenize('mary had a little lamb.'))
text = nltk.Text(tkn for tkn in tokenize('mary had a little lamb.'))

rawDescription: How to find collocations in text, python

description: Find collocations in text, python


code:
choice = input()
choice = choice.lower()
if choice == 'yes':
    dev_debug = 1
    break

rawDescription: Text Game - Convert input text to lowercase - Python 3.0


code: driver = webdriver.PhantomJS()

rawDescription: Using selenium at hosted app?

description: Using selenium at hosted app


code:
inFile = open(r"\path\to\names.txt", 'r')

required = "HS"
valid = []

for line in inFile:
    name = line.split()[-1]

    if name[0].upper() in required:
        valid.append(line)

outFile = open(r"\path\to\validNames.txt", 'w')

for line in valid:
    outFile.write(line)

rawDescription: Trying to read all lines in a file and pick out the ones that begin with 'H' or 'S'


rawDescription: Best way to remove similar points in a list of points

description: Remove similar points in a list of points


rawDescription: removing pairs of elements from numpy arrays that are NaN (or another value) in Python

description: Removing pairs of elements from numpy arrays that are NaN (or another value) in Python


code:
FFF = zeros(N)
for i in range(300):
    FFF += fftcoeffs[i]*np.exp(2*pi*i*freqs[i]*t)
plt.plot(t, FFF)
plt.show()

rawDescription: Manually inverting FFT using Numpy

description: Manually inverting FFT using Numpy


code:
my_honeycomb = [[]] # a list containing an empty list
level = 0
ind = 0
for letter in input('Enter your string:\n\n\t'):
    if ind > level * 6: # check if index is valid for this level
        level += 1
        ind = 1
        my_honeycomb.append([]) # go to the next level
    my_honeycomb[level].append(letter) # add letter to current level
    ind += 1 # advance to next index

rawDescription: Storing data in a hexagonal grid for word search Python


code:
import csv
from itertools import zip_longest

n=10
with open('/tmp/rawdata.txt','r') as fin, open('/tmp/out.csv','w') as fout:
    reader=csv.reader(fin)
    writer=csv.writer(fout)
    source=(e for line in reader for e in line)
    for t in zip_longest(*[source]*n):
        writer.writerow(list(e for e in t if e))

rawDescription: How to create a new list or new line after a certain number of iterations

description: Create a new list or new line after a certain number of iterations


code:
def count_digits(n):
    if n == 0:
        return 1
    count_list = []
    while n > 0:
        count_list.append(n % 10)
        n = n // 10
    return len(count_list)

rawDescription: Counting digits of number with no string operations


rawDescription: Parsing and reformatting CSV/text data using Python


code: import csv

rawDescription: Parse Specific Text File to CSV Format with Headers


code:
#decorator is declared outside of class and type dict is passed in as an argument
def type_handler(name, type_dict):
    def wrapper(f):
        type_dict[name] = f
        return f
    return wrapper

class MyClass(object):

    types = {}

    @type_handler('a', types)
    def foo_a(self, a):
        pass

    @type_handler('b', types)
    def foo_b(self, b):
        pass

rawDescription: Class level decorator

description: Class level decorator


code:
from itertools import product

for x1, x2, x3, x4 in product(*(range(i+1) for i in maxvalues)):
    t.append((x1, x2, x3, x4))

rawDescription: Python: finding all tuples with constrained elements that add up to a constant


code:
def read_graph_from_file(filename):

   txtfile = open(filename, "rU")

   node_memory = 0
   neighbour_list = 0

   lst = []

   for entry in txtfile:
       entry_without_newline = entry.replace('\n',"")
       columns = entry_without_newline.replace(','," ")
       columns = columns.split(" ")
       number_of_columns = len(columns)

       if number_of_columns == 2:
           neighbour_list = columns
           neighbour_list.sort()

           if node_memory == float(neighbour_list[0]):
               y = neighbour_list[1]
               lst.append(y)
   return lst

rawDescription: Python - converting multiple lines to one