code:
import sys

# Be safe and define a maximum of frames we're trying to walk up
MAX_FRAMES = 20

def save_to_interactive(dct):
    n = 0
    # Walk up the stack looking for '__name__'
    # with a value of '__main__' in frame globals
    for n in range(MAX_FRAMES):
        cur_frame = sys._getframe(n)
        name = cur_frame.f_globals.get('__name__')
        if name == '__main__':
            # Yay - we're in the stack frame of the interactive interpreter!
            # So we update its frame globals with the dict containing our data
            cur_frame.f_globals.update(dct)
            break

rawDescription: save variable to interactive namespace from python debugger

description: Save variable to interactive namespace from python debugger


code:
G = sm.Lambda(x, sqrt(x) + 1)
expr.subs(F, G)

rawDescription: placeholder functions in sympy

description: Placeholder functions in sympy


code:
a = [7, 11, 24, 38]

b=0
b = [sum(a[:k]) for k in range(1+len(a))]

print(a)
print(b)

rawDescription: incremental sum a list of numbers in Python 2.7

description: Incremental sum a list of numbers in Python 2.7


code:
if queryset.count() > 10:
  queryset = KleedkamerIndeling.objects.filter(gametimedate__gte=datetime.now())[:10]

rawDescription: django queryset filter datetimefield

description: Django queryset filter datetimefield


code: import dis

rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


code: sl = sorted(data, key=lambda l:l[1])

rawDescription: Finding similar data and putting them on separate list


code:
import hashlib
import Pk_lookup

hash = hashlib.sha256()
hash.update(str(pk)) # pk has been defined previously
pk_digest = hash.digest()

lookup = Pk_lookup(hashed_pk=pk_digest,key=pk)
lookup.save()

rawDescription: django, python and link encryption

description: Django, python and link encryption


code:
for child in parent.child_set.all():
    do_something()

rawDescription: Django backwards relation

description: Django backwards relation


code:
s = "*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON "\
    "{0:%d/%b/%y} AT {0:%H:%M:%S} ***\n\n"
s.format(datetime.datetime.now())

rawDescription: How do I convert date to Day/Month/Year (20/Jan/2012) in python

description: Convert date to Day/Month/Year (20/Jan/2012) in python


code:
class Helper(threading.Thread):
  def __init__(self, directory):
    super(Helper, self).__init__()
    self.directory = directory
    self.start()

  def run(self):
    for path, folders, files in os.walk(self.directory.path):
      for f in files:
          self.directory.files.append(os.path.join(path, f))

      for d in folders:
          self.directory.dirs.append(Directory(os.path.join(path, d), self.directory.interval, self.directory.do))

    self = None

class Directory(threading.Thread):
  def __init__(self, path, interval=5, do=None):
    super(Directory, self).__init__()
    self.path = path
    self.files, self.dirs = ([], [])
    self.interval = interval
    self.last_update = 0
    self.helper = None

    self.do = do # One flag to stop refreshing all instances
    if do == None:
      self.do = True

  def run(self):
    while self.do:
      self.refresh()
      time.sleep(self.interval)

  def refresh(self):
    # Only start a refresh if there self.helper is done and directory was changed
    if not self.helper and self.has_changed():
      self.last_update = int(time.time())
      self.helper = Helper(self)

  def has_changed(self):
    return int(os.path.getmtime(self.path)) > self.last_update

rawDescription: updating file path list in a fast changing directory

description: Updating file path list in a fast changing directory


code:
from myapp.storage import uploads_storage
f = uploads_storage.open(new_files, 'r')

rawDescription: Opening a data file from the media directory in Django


code: dataset = np.random.normal(mu, std, size=(n, len(rule)))

rawDescription: Numpy - Matrix Generation from list comprehension


code: screen_rect = screen.get_rect()

rawDescription: Sequential image presentation in Pygame

description: Sequential image presentation in Pygame


code:
location_attribute = '{%s}noNameSpaceSchemaLocation' % NS
elem = etree.Element('TreeInventory', attrib={location_attribute: 'Trees.xsd'})
etree.tostring(elem, pretty_print=True)

rawDescription: Python: adding namespaces in lxml

description: Python: adding namespaces in lxml


code:
def search(pattern, string, flags=0):
    """Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found."""
    return _compile(pattern, flags).search(string)

rawDescription: How does Python's regex pattern caching work?


code:
import functools
from suds.mx.appender import *
legacy_append = suds.mx.appender.ObjectAppender.append
@functools.wraps(legacy_append)
def _patch_object_append(self, parent, content):
    object = content.value
    if self.optional(content) and footprint(object) == 0:
        return
    child = self.node(content)
    for item in object:
         cont = Content(tag=item[0], value=item[1])
         if item[0] == '_text_':
            child.setText(item[1])
            continue

         Appender.append(self, child, cont)
    parent.append(child)

suds.mx.appender.ObjectAppender.append= _patch_object_append

rawDescription: How to convert dict to suds complex suds type

description: Convert dict to suds complex suds type


code:
df = sqlContext.createDataFrame(
    [(1, "a"), (2, "b"), (3, "c"), (4, "d")], ("k", "v"))
df.rdd.takeSample(False, 1, seed=0)
## [Row(k=3, v='c')]

rawDescription: How take a random row from a PySpark DataFrame?


code:
stocks = {}
for line in idata.split("\r\n"):
    if line == '':
        continue

    stock, price, volume, stime = line.split(',')
    stock = stock[1:-1]
    price = float(price)
    volume = int(volume)
    stime = stime[1:-1]

    stocks[stock] = (price, volume, stime)

rawDescription: Python change data into sequence

description: Python change data into sequence


code:
for option,value in my_section_items:
    _config.set(my_section_new_name, option, value)

rawDescription: Python - How to change the name of a section use configparser?


code:
d[tuple(['foo', 'bar'])] = 'baz'
d['foo', 'bar']
d['bar', 'foo']

rawDescription: How to use a list of strings [which may contain any character] as keys?

description: Use a list of strings [which may contain any character] as keys


code: jpy = web.get_data_fred('DEXJPUS')

rawDescription: How can get ' USDJPY'(currency rates) with pandas and yahoo finance?


rawDescription: Alias for dictionary operation in Python


code:
def series(x, pattern):
    pattern = [pattern[i:i+2] for i in range(0, len(pattern), 2)]
    start = x
    results = []
    for k in pattern:
        for i in range(5):
            start = eval('start+%s' %(k))
            results.append(start)
    return results

rawDescription: Data Manipulation in accordance with a Pattern in Python


code:
import sys
sys.path.append("framework")

import game

rawDescription: Organizing source code in python

description: Organizing source code in python


code: infos = infos[1:]

rawDescription: Storing multiple lines from a file to a variable using a delimiter


rawDescription: Why does the 'is' operator say these methods aren't the same?


code:
numpy.genfromtxt(fhandle, delimiter='\t',
    dtype={'names':('Time', 'Identifier', 'Value'),
           'formats':('datetime64[ns]', 'S50', 'f8')})

rawDescription: quick parsing of csv-like file

description: Quick parsing of csv-like file


code:
condition.acquire()
remove_myself_from_queue()
condition.notify()
condition.release()

rawDescription: Python - Best practices to queue / dequeue threads


code:
from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel

class User(EndpointsModel):
    email = ndb.StringProperty()
    ...

rawDescription: Query endpoint user by email

description: Query endpoint user by email


code: df.groupby(['date', 'location']).apply(lambda sdf: sdf if len(sdf) > 1 else None).reset_index(drop=True)

rawDescription: Choosing particular rows from pandas dataframe


code:
from fabric import env
env.key_filename = '/path/to/priv/key'

rawDescription: Using fabric to copy file from one remote server to another remote server?


code:
class BaseAdder(object):
    def add(self, a, b):
        return a + b

class NonReturningAdder(BaseAdder):
    def add(self, a, b):
        super(NonReturningAdder, self).add(a, b)

class ReturningAdder(BaseAdder):
    def add(self, a, b):
        return super(ReturningAdder, self).add(a, b)

rawDescription: What is the difference between `super(...)` and `return super(...)`?


code:
my_list = ['name.13','name.1', 'name.2','name.4', 'name.32']
sorted(my_list, key=lambda a: (int(a.split('.')[1])))

rawDescription: What is the best way to sort this list?

description: What is the best way to sort this list


code:
l = [[('reviewtext', 'IN'), ('this', 'DT'), ('movie', 'NN'), ('was', 'VBD'), ('great', 'JJ'), ('and', 'CC'),
      ('fun', 'NN'), ('i', 'PRP'), ('really', 'RB'), ('enjoyed', 'VBD'), ('this', 'DT'), ('awesome', 'NN'),
      ('movie', 'NN')],
     [('reviewtext', 'IN'), ('it', 'PRP'), ('was', 'VBD'), ('fun', 'VBN'), ('but', 'CC'), ('long', 'RB')],
     [('reviewtext', 'IN'), ('i', 'PRP'), ('loved', 'VBD'), ('the', 'DT'), ('new', 'JJ'), ('movie', 'NN'), ('my', 'PRP$'), ('brother', 'NN'), ('got', 'VBD'), ('sad', 'JJ'), ('and', 'CC'), ('unhappy', 'JJ'), ('at', 'IN'), ('the', 'DT'), ('end', 'NN')]]

def match(l,p1,p2,p3):
    for sub in l:
        # avoid index error and catch last three elements
        end = len(sub) - 1
        for ind, (a, b) in enumerate(sub, 1):
            if ind == end:
                break
            if b == p1 and sub[ind][1] == p2 and sub[ind + 1][1] == p3:
                yield ("{} {} {}".format(a, sub[ind][0], sub[ind + 1][0]))

print(list(match(l,"JJ","CC","JJ")))

rawDescription: How do I extract patterns from lists of POS tagged words? NLTK

description: Extract patterns from lists of POS tagged words? NLTK


rawDescription: How to remove escape sequence like '\xe2' or '\x0c' in python

description: Remove escape sequence like '\xe2' or '\x0c' in python


code: cbar = plt.colorbar(CF, ticks=lvls, format='%.2f', spacing='proportional')

rawDescription: matplotlib contour plot: proportional colorbar levels in logarithmic scale

description: Matplotlib contour plot: proportional colorbar levels in logarithmic scale


code:
def transpose(g):
    return map(list, zip(*g))

rawDescription: Creating a 2d Grid in Python

description: Creating a 2d Grid in Python


code:
import _mssql
con = _mssql.connect(server='server', user='user', password='password', database='default')

id = get_next(con)
while current_id:
     start_function(id)
     id = get_next(con)
else:
    print("ALL DONE")

rawDescription: While mssql query returns an affected ID use it in a while loop


code:
df = df.reset_index()
df.columns=['sponsor', 'num_bills']

rawDescription: How to assign a value_count output to a dataframe

description: Assign a value_count output to a dataframe


code: list_display = ['html_stripped', ...]

rawDescription: Rich text editor in Django admin - Hiding the HTML tags in the change list


code:
import pprint
pprint.pprint(dicts)

rawDescription: Sort Dictionary of Dictionaries on multiple child dictionary values


code:
with open('Output.txt', 'w') as f:
    f.write("Random numbers are: \n")
    for _ in xrange(500):
        f.write("%s,%s,%s,%s,%s,%s\n" % (rn(), rn(), rn(), rn(), rn(), rn()))

rawDescription: Write multiple values into text file in Python?


rawDescription: Print single word from Parsed Json text

description: Print single word from Parsed Json text


code: driver.execute_script("arguments[0].style = {visibility: 'visible'};", file_input)

rawDescription: Selenium + Python - After clicking on a button, how to I catch the pop up window (specifically, an upload image pop up)


code:
# graph: Graph we are operating on
# node: Node we are starting from
# hops: Number of hops we can still do (edges we can take)
def findPaths(graph, node, hops):
    # if no further hops should be done, we were successful and
    # can end the recursion
    if hops == 0:
        yield []
        return

    # if the node is not in the graph, we cannot go further, so
    # the current path is invalid
    if node not in graph:
        return

    # for every node we can reach from the current
    for n in graph[node]:
        # find all paths we can take from here
        for path in findPaths(graph, n, hops - 1):
            # and concat the edge names
            yield [graph[node][n]] + path

rawDescription: How to get the list of edge values corresponding to all possible paths of a particular length in a graph in Python?

description: Get the list of edge values corresponding to all possible paths of a particular length in a graph in Python


code: mylist = filter(any, mylist)

rawDescription: Remove items from array

description: Remove items from array


code: blokk = [[] for _ in range(15)]

rawDescription: How can I add different elements to a list in a list? Python 3

description: Add different elements to a list in a list? Python 3


code:
def bisect_left(a, x, lo=0, hi=None, key=None):
    if key is None: key = lambda v: v
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if key(a[mid]) < x: lo = mid+1
        else: hi = mid
    return lo

rawDescription: Searching an attribute_A in a attribute_B-sorted list


rawDescription: Python Regex re.compile clarification

description: Python Regex re.compile clarification


code:
request = webapp.Request({
    "wsgi.input": StringIO.StringIO(),
    "METHOD": "POST",
})
response = webapp.Response()
handler = MyHandler()
handler.initialize(request, response)
handler.post()

rawDescription: Simulating a Google App Engine File Upload in Python


code:
padded
out

rawDescription: Generalize stacking of array elements' neighbors into 3-D array


code:
dis.dis(func1)
dis.dis(func2)

rawDescription: Efficient ways to duplicate array/list in Python


code:
y = numpy.array(x)
y[0:n] = 0

rawDescription: How to set first N elements of array to zero?

description: Set first N elements of array to zero


code:
from fabric.api import run
def runmyprogram():
    run('./program.sh')

rawDescription: remotely start Python program in background

description: Remotely start Python program in background


code: v != '' or v != {} or v is not None

rawDescription: Removing values from dict in python

description: Removing values from dict in python


code:
urlpatterns = [
    url(r'^users/(?P<pk>\d+)/', UserIdRetrieve.as_view()),
    url(r'^users/by-username/(?P<username>\w+)/', UserUsernameRetrieve.as_view())
]

rawDescription: Django Rest required parameters in URL

description: Django Rest required parameters in URL


rawDescription: Can I open an application using python during run time

description: Open an application using python during run time


code:
map = Code("function() {"
    "emit({"
        "ts : new Date(new Date((this.ts - (this.ts % (60 * number))) * 1000).setSeconds(0))"
    "}, 1);"
"}")

rawDescription: MongoDB MapReduce, Date and % operator

description: MongoDB MapReduce, Date and % operator


code: smallest = next(sorted_iterator)

rawDescription: Few questions on generator expressions and speed efficient alternatives


rawDescription: Merging pandas dataframes on multiple conditions (python/pandas)


code:
class AccessLog:
    @staticmethod
    def sendLog(interval, worker_functions, iterations=1):
        def call_worker_functions():
            for f in worker_functions:
                f(*worker_functions[f])
        for i in range(iterations):
            threading.Timer(interval * i, call_worker_functions).start()

rawDescription: Pass self class parameter python

description: Pass self class parameter python


code:
M = coo_matrix((repeat(1,n_features), (range(n_features), buckets)),
               shape=(n_features,n_desired_features))
X_new = X_train.dot(M)

rawDescription: scikit-learn HashingVectorizer on sparse matrix

description: Scikit-learn HashingVectorizer on sparse matrix


rawDescription: simplifying routine in python with numpy array or pandas

description: Simplifying routine in python with numpy array or pandas


code:
class Fecha(datetime.date):
    def __new__(cls, year, month, day, status):
        instance = super(Fecha, cls).__new__(cls, year, month, day)
        instance.status = status
        return instance

rawDescription: Extending a class in Python 3 and construct it with __init__


code: os.environ['TZ'] = self.TIME_ZONE

rawDescription: Does django mess up with python's datetime?


rawDescription: Using class/static methods as default parameter values within methods of the same class


code: g = g.sortlevel()

rawDescription: Multi-Index Sorting in Pandas

description: Multi-Index Sorting in Pandas


code:
from collections import defaultdict

friends = defaultdict(set)
friendpairs =  [[0,1], [0,4], [0,3], [0,432], [1,232], [1,2], [2,444], [2,12]]

for f1,f2 in friendpairs : friends[f1].add(f2)

friendOfFriends = dict( (guy,fr.copy()) for guy,fr in friends.iteritems())

for f1 in friendOfFriends:
    for f2 in friends[f1]:
        friendOfFriends[f1].update(friends[f2])

rawDescription: Python List Contraction

description: Python List Contraction


code: import numpy

rawDescription: Find dependencies in a python source/script


code:
the_player_1 = player1(50, 100)
the_player_2 = player2(200, 50, the_player_1)

rawDescription: Using a Class's pygame.rect inside another class


code:
y = np.array([sin(x), 3*sin(x), sin(x)+1])
m = y.mean(axis=0)
s = y.std(axis=0)

rawDescription: By Python. making standard deviation and mean lines with different graphes


rawDescription: Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc


code:
from lxml import etree
from io import StringIO

def testFilter():
  xslt_root = etree.XML('''\
  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="TimeStamp"/>

  </xsl:stylesheet>
  ''')

  transform = etree.XSLT(xslt_root)

  f = StringIO(unicode('<?xml version="1.0"?><ComponentData><DataSet name="one">  <TimeStamp timeStampValue="2014"/></DataSet><DataSet name="two"><TimeStamp timeStampValue="2015"/></DataSet></ComponentData>'))
  doc = etree.parse(f)
  result_tree = transform(doc)

  print(str(result_tree))

if __name__=='__main__':
  testFilter()

rawDescription: Filtering xml: XSLT with lxml in python

description: Filtering xml: XSLT with lxml in python


rawDescription: Print lines with numbers infront

description: Print lines with numbers infront


rawDescription: How do I use regular expressions in Python with placeholder text?

description: Use regular expressions in Python with placeholder text


rawDescription: Assign multiple values of a list

description: Assign multiple values of a list


rawDescription: Why does Sympy cut off polynomial terms with small coefficients?


code:
import wx
import wx.grid

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Manager")
        sizer = wx.BoxSizer(wx.VERTICAL)

        overall = wx.grid.Grid(self)
        overall.CreateGrid(5,2)
        sizer.Add(overall, 0, flag=wx.EXPAND)

        self.SetSizer(sizer)
        self.Fit()

app = wx.App(False)
MainFrame().Show()

app.MainLoop()

rawDescription: How to put the wx.grid into a GridBagSizer, with scroll bar

description: Put the wx.grid into a GridBagSizer, with scroll bar


rawDescription: Delete column from pandas DataFrame

description: Delete column from pandas DataFrame


code:
annotations = open('annotation', 'r')
abundances = open('abundance', 'r').readlines()     # read the file into memory, otherwise you'd have to "rewind" the file for each inner loop.

with open('contig_numbers', 'r') as f:
   keywords = [line.strip() for line in f]

for annotation in annotations:     # use meaningful variable names
   for keyword in keywords:
      if annotation.startswith(keyword+" "):    # the +" " is neccessary to avoid clashes with 'contig-2' and 'contig-27'
         for abundance in abundances:
             if abundance.startswith(keyword+" "):
                 print (annotation.strip()+"\t"+abundance.strip())
                 break
         else:              # Python magic: executed when the for loop is not left by a break, but because the iterator is empty.
             print(annotation.strip())

rawDescription: Search for a word in two files and print the the two lines with tabular separation


code:
def __get__(self, obj, objtype):
    return Wrapper(self, obj)

rawDescription: Modifying a cooldown decorator to work for methods instead of functions


code: joined = [[lst[0], listBstrings[lst[1], lst[2]]] + lst[1:] for lst in listA]

rawDescription: Python join two nested lists

description: Python join two nested lists


rawDescription: Python For In Loop Matrix for User Input


code:
globals().update({name: value
                  for name, value in vars(imported_foo).items()
                  if not name.startswith('_')})

rawDescription: Python import lib analogue to "import * from XXX"


rawDescription: String to unicode code point escpe sequences in Python


code:
from sqlalchemy.sql import text

Table.query.filter(text('name ~ :reg')).params(reg='foo')

rawDescription: SQLAlchemy + PostgreSQL + PG regex

description: SQLAlchemy + PostgreSQL + PG regex


code:
s = "H\u00eatres et \u00e9tang".decode("unicode_escape")
s.encode("latin1")

rawDescription: Converting a latin string to unicode in python


code:
def do_quiz(num_questions=10):
    return sum(do_question() for i in range(1, num_questions + 1))

rawDescription: Finding something that checks if a particular Arithmetic answer is correct


code: dummies

rawDescription: How to generate dummy variables for only specific values in a column?

description: Generate dummy variables for only specific values in a column


code:
@api.multi
def distance_to_search1(self):
    #some other code
    return {
        'name': _('Contacts in this range'),
        'type': 'ir.actions.act_window',
        'res_model': 'res.partner',
        'view_type': 'form',
        'view_mode': 'tree',
        'view_id': self.env.ref('contact_geolocation.distance_range_search_view_tree').id,
        'domain': [('id', 'in', filtered_partner_ids)],
    }

rawDescription: Why my tree view is not loading in Odoo 9?


rawDescription: nested loop with array indexing in numpy

description: Nested loop with array indexing in numpy


code:
if len(string1) == len(string2):
    count_diffs = 0
    for a, b in zip(string1, string2):
        if a!=b:
            if count_diffs: return False
            count_diffs += 1
    return True

rawDescription: Returns True if the two strings only differ by one character


rawDescription: NumPy: 2D array from a list of arrays and scalars


code:
import os
import re

pattern = 'Put your actual pattern here'

# For a different directory, change the . to whatever the directory should be
for filename in os.listdir('.'):
    if not re.match(pattern, filename):
        print("Bad filename: ", filename)

rawDescription: Verify file names by standard

description: Verify file names by standard


code:
from collections import Counter

def isAnAnagram(word, user):
    word_counter = Counter(word)
    input_counter = Counter(user)
    return all(count <= input_counter[key] for key, count in word_counter.items())

rawDescription: Python strings with anagrams

description: Python strings with anagrams


code:
ticket_info = jsonresponse.get('tickets')
ticket_info

rawDescription: How to parse JSON data in scrapy

description: Parse JSON data in scrapy


code:
import serial
import numpy as np
import cv2

# dummy function
def nothing(x):
    pass

# Track bar window
cv2.namedWindow('thresh')

# Track bars
cv2.createTrackbar('lH','thresh', 0, 180, nothing)
cv2.createTrackbar('lS', 'thresh', 0, 255, nothing)
cv2.createTrackbar('lV', 'thresh', 0, 255, nothing)
cv2.createTrackbar('uH', 'thresh', 0, 180, nothing)
cv2.createTrackbar('uS', 'thresh', 0, 255, nothing)
cv2.createTrackbar('uV', 'thresh', 0, 255, nothing)

# capture video
cap = cv2.VideoCapture(0)

while True:
    # Read from camera
    source, frame = cap.read()
    if not source:
        break

    # converting image color to HSV color space
    cv2.cvtColor(frame, cv2.COLOR_RGB2HSV, frame, 0)

    # Getting values from track bars
    lH = cv2.getTrackbarPos('lH', 'thresh')
    uH = cv2.getTrackbarPos('uH', 'thresh')
    lS = cv2.getTrackbarPos('lS', 'thresh')
    uS = cv2.getTrackbarPos('uS', 'thresh')
    lV = cv2.getTrackbarPos('lV', 'thresh')
    uV = cv2.getTrackbarPos('uV', 'thresh')

    lowerb = np.array([lH, lS, lV], np.uint8)
    upperb = np.array([uH, uS, uV], np.uint8)

    frame = cv2.inRange(frame, lowerb, upperb)
    cv2.flip(frame, 1, frame)
    cv2.imshow('thresh', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

rawDescription: Why doesn't OpenCV's inRange function convert my HSV image to Binary?


code:
for arr in data.itervalues():
    np.putmask(arr, np.abs(arr)<.01, np.nan)

rawDescription: looping dictionaries of {tuple:NumPy.array}

description: Looping dictionaries of {tuple:NumPy.array}


rawDescription: Pivot String column on Pyspark Dataframe


rawDescription: Combinations of weighted elements in a set where weighted sum equal to fixed integer (in python)


code:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
    json.dump([], f)

rawDescription: Appending data to a json file in Python

description: Appending data to a json file in Python


code:
def searchNestedKey(outerdict, key):
    for nesteddict in outerdict.itervalues():
        if key in nesteddict:
            return nesteddict[key]

rawDescription: Python: How to get a value of sub key in Hash Table?


code:
arguments = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
plain_list = [ j for i in arguments for j in i ]
plain_list
plain_list = []
for i in arguments:
    for j in i:
        plain_list.append(j)
plain_list

rawDescription: list iteration with 'i for j in' that I never saw

description: List iteration with 'i for j in' that I never saw


code: mat = coo_matrix((newdata, (newrows, newcols)), shape = ((mat.shape)[0]+1, (mat.shape)[1]))

rawDescription: Adding a sparse vector to a sparse array in python is too slow


code:
outcsv.writerows(row for row in incsv if look_for1 in row[col] and
                                        look_for2 in[col])

rawDescription: Apply changes to several files in the same directory


rawDescription: Drop row and column of a dataframe that contains the non-zero minimum


code:
br.open(URL)
res = mechanize._form.ParseString(FORM_HTML, BASE_URL)
br.form = res[1]
#continue as if the form was on the page and selected with .select_form()
br['username'] = 'foo'
br['password'] = 'bar'
br.submit()

rawDescription: python mechanize - submit custom form

description: Python mechanize - submit custom form


code:
pthread_join(pthread_id, NULL);
PyEval_RestoreThread(mainThreadState);
Py_Finalize();

rawDescription: Python threads in C

description: Python threads in C


code:
def update(self):
    self.data1.set(random.randint(1,10))
    self.data1_Var.after(200, self.update)

    self.data2.set(random.randint(1,10))
    self.data2_Var.after(200, self.update)

rawDescription: python - Tkinter not responding when simultaneously updating multiple labels

description: Python - Tkinter not responding when simultaneously updating multiple labels


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))

axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))

for ax in axes:
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                xytext=(0, -15), textcoords='offset points',
                ha='right', va='top')
plt.show()

rawDescription: Python/Matplotlib - How to put text in the corner of equal aspect figure


code:
#!/usr/bin/env python

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from findtree import findtree

# Image files to process
fname = ['nmzwj.png', 'aVZhC.png', '2K9EF.png',
         'YowlH.png', '2y4o5.png', 'FWhSP.png']

# Initialize figures
fgsz = (16,7)
figthresh = plt.figure(figsize=fgsz, facecolor='w')
figclust  = plt.figure(figsize=fgsz, facecolor='w')
figcltwo  = plt.figure(figsize=fgsz, facecolor='w')
figborder = plt.figure(figsize=fgsz, facecolor='w')
figthresh.canvas.set_window_title('Thresholded HSV and Monochrome Brightness')
figclust.canvas.set_window_title('DBSCAN Clusters (Raw Pixel Output)')
figcltwo.canvas.set_window_title('DBSCAN Clusters (Slightly Dilated for Display)')
figborder.canvas.set_window_title('Trees with Borders')

for ii, name in zip(range(len(fname)), fname):
    # Open the file and convert to rgb image
    rgbimg = np.asarray(Image.open(name))

    # Get the tree borders as well as a bunch of other intermediate values
    # that will be used to illustrate how the algorithm works
    borderseg, X, labels, Xslice = findtree(rgbimg)

    # Display thresholded images
    axthresh = figthresh.add_subplot(2,3,ii+1)
    axthresh.set_xticks([])
    axthresh.set_yticks([])
    binimg = np.zeros((rgbimg.shape[0], rgbimg.shape[1]))
    for v, h in X:
        binimg[v,h] = 255
    axthresh.imshow(binimg, interpolation='nearest', cmap='Greys')

    # Display color-coded clusters
    axclust = figclust.add_subplot(2,3,ii+1) # Raw version
    axclust.set_xticks([])
    axclust.set_yticks([])
    axcltwo = figcltwo.add_subplot(2,3,ii+1) # Dilated slightly for display only
    axcltwo.set_xticks([])
    axcltwo.set_yticks([])
    axcltwo.imshow(binimg, interpolation='nearest', cmap='Greys')
    clustimg = np.ones(rgbimg.shape)
    unique_labels = set(labels)
    # Generate a unique color for each cluster
    plcol = cm.rainbow_r(np.linspace(0, 1, len(unique_labels)))
    for lbl, pix in zip(labels, Xslice):
        for col, unqlbl in zip(plcol, unique_labels):
            if lbl == unqlbl:
                # Cluster label of -1 indicates no cluster membership;
                # override default color with black
                if lbl == -1:
                    col = [0.0, 0.0, 0.0, 1.0]
                # Raw version
                for ij in range(3):
                    clustimg[pix[0],pix[1],ij] = col[ij]
                # Dilated just for display
                axcltwo.plot(pix[1], pix[0], 'o', markerfacecolor=col,
                    markersize=1, markeredgecolor=col)
    axclust.imshow(clustimg)
    axcltwo.set_xlim(0, binimg.shape[1]-1)
    axcltwo.set_ylim(binimg.shape[0], -1)

    # Plot original images with read borders around the trees
    axborder = figborder.add_subplot(2,3,ii+1)
    axborder.set_axis_off()
    axborder.imshow(rgbimg, interpolation='nearest')
    for vseg, hseg in borderseg:
        axborder.plot(hseg, vseg, 'r-', lw=3)
    axborder.set_xlim(0, binimg.shape[1]-1)
    axborder.set_ylim(binimg.shape[0], -1)

plt.show()

rawDescription: How to detect a Christmas Tree?

description: Detect a Christmas Tree


rawDescription: Django: Grouping and ordering across foreign keys with conditions


code:
def decorate_sort_undecorate(iterable, key):
    # 1: decorate:
    decorated = [(key(elem), index, elem) for index, elem in enumerate(iterable)]

    # 2: sort:
    decorated.sort()

    # 3: undecorate:
    return [elem for key_, index, elem in decorated]

rawDescription: How can I sort by single criterion?

description: Sort by single criterion


code: [Foo() for i in range(3)]

rawDescription: Star operator (*) applied to lists and integers


code:
import logging

def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    return logger

rawDescription: Python: logging module - globally

description: Python: logging module - globally


code:
def reparse(tree=samp):
  stack = [-1]
  result = []
  for line in tree:
    equals, rest = relinelev.match(line).groups()
    linelev = len(equals)
    while linelev < stack[-1]:
      result[-1] += ')'
      curlev = stack.pop()
    if linelev == stack[-1]:
      result[-1] += ')'
    else:
      stack.append(linelev)
    result.append('(%s' % clean(rest))
  while stack[-1] >= 0:
    result[-1] += ')'
    stack.pop()
  return ' '.join(result)

rawDescription: converting a treebank of vertical trees to s-expressions

description: Converting a treebank of vertical trees to s-expressions


code:
idx = 1
number = 10
result = filter(func(idx, number), listoflists)

rawDescription: How to pick lines containg numbers in given positions on the line with python

description: Pick lines containg numbers in given positions on the line with python


code:
from BeautifulSoup import BeautifulSoup
from pprint import pprint

markup = '''

Rep Armey, Richard K. [TX-26]
 - 11/9/1999

Rep Davis, Thomas M. [VA-11]
 - 11/9/1999

Rep DeLay, Tom [TX-22]
 - 11/9/1999
 '''

soup = BeautifulSoup(markup)

rawDescription: How would I get the text AFTER a link in Python with BeautifulSoup?


code: filelist = os.listdir(os.path.expanduser('~') + '/testing/;xterm;/blabla')

rawDescription: How to avoid Shell Injection with a path variable and wait for command exist?

description: Avoid Shell Injection with a path variable and wait for command exist


code:
from yourapp.app import app
from yourapp.urls import mapper
# We need to import the mapper to cause the URLs to be mapped.

if __name__ == "__main__":
    app.run()

rawDescription: How to have different py files to handle different routes?

description: Have different py files to handle different routes


code:
with open('file1.tsv') as F:
    next(F, None)
    filelist = [line.strip('\n').split('\t') for line in F]

rawDescription: Python: reading line from file with different types of variables


code:
client = Client.objects.get(pk=123)
addresses = Addres.objects.filter(content_object=client)

rawDescription: Django creating relation one-to-many

description: Django creating relation one-to-many


rawDescription: Ordering of query parameters in pyramid.request object


code:
from functools import wraps
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # do some stuff
        retval = func(*args, **kwargs)
        # do more stuff
        return retval
    return wrapper

rawDescription: How to decorate a parent class and make child classes use it? python

description: Decorate a parent class and make child classes use it? python


code:
from django.db import models

class Reporter(models.Model):
    # ...
    pass

class Article(models.Model):
    reporter = models.ForeignKey(Reporter)

rawDescription: Get comments of Post (one to many relation)


code:
def draw(ax,x,y):

    ax.scatter(x,y)

rawDescription: What is an idiomatic way to specify a matplotlib figure and axes to a function?


code: eastern = timezone('US/Eastern')

rawDescription: How do I print a Python datetime in the local timezone?

description: Print a Python datetime in the local timezone


rawDescription: one liner for conditionally replacing dictionary values

description: One liner for conditionally replacing dictionary values


code:
import os

_module_directory = os.path.dirname(os.path.abspath(__file__))

rawDescription: Sqlite query returns different results from different classes


code: box.insert(0, "Value 1")    # Set default text at cursor position 0.

rawDescription: Default text as well as list textvariable Entry widget Tkinter


code:
plot.text(0.05, 0.95, df2['example'],
     horizontalalignment='left',
     verticalalignment='center',
     transform = ax.transAxes, visible=False)

rawDescription: Python -- how to plot calculated number on chart without properties detail


code:
inp="({A,B,CC},{(A,B),(B,CC),(CC,A)})"
nodes,edges = inp[2:-3].split('},{(')
graph = dict([(i,set([edge[edge.index(i)-1] for edge in map(lambda x:x.split(','), edges.split('),(')) if i in edge])) for i in nodes.split(',')])

rawDescription: Converting string into dictionary containing sets


code:
import shlex, subprocess
p = subprocess.Popen(slex.split("""ffmpeg.exe -f dshow -y -video_size 1920x1080 -rtbufsize 1404000k -r 30 -i video="HD Video 2 (TC-2000HDMI Card)" -threads 2 -vcodec copy -ar 48000 -ac 1 -acodec pcm_s16le -t 60 c:/output.avi"""))

rawDescription: Running an executable with multiple parameters in python


code: type(self).immutable_attr = True

rawDescription: Mutating objects referenced by class attributes through instance methods


code:
appr = df.pivot_table( cols='name',
                       rows='date',
                       values='tag',
                       aggfunc=len ).fillna( 0 )

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


rawDescription: Using list as a data type in a column (SQLAlchemy)


rawDescription: Python: Grouped constants with possibility to iterate over group


code:
import os
from sys import argv

run, filename = argv

fin = open(filename)
fout = open(filename + '.tmp', 'w')
lines = f.readlines()
for line in lines:
    fout.write(line[1:])
fout.close()
fin.close()
os.rename(filename + '.tmp', filename)

rawDescription: remove first char from each line in a text file

description: Remove first char from each line in a text file


rawDescription: Pyspark: using filter for feature selection


rawDescription: python string split based on "\"

description: Python string split based on "\"


code:
# Retrieving Form POST Data
fi = request.files.get("file")

# print "Rotating File (if needed)"
fi = fix_orientation(fi)

# print "Uploading to S3"
push_to_s3(photo=fi, filename=filename)

rawDescription: Is there a cleaner way to rotate smartphone images uploaded via flask before pushing to S3?


code: text.split()  # str.split remove space characters

rawDescription: Read Word from a Unicode Line instead of Char


code: [list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]

rawDescription: How to group similar items in a list?

description: Group similar items in a list


rawDescription: How to generate 2d numpy array?

description: Generate 2d numpy array


code: df["timedif"] = df.groupby(["MachineName", "LocalIPAddress"])["DateTime"].diff()

rawDescription: IPython "Column not found error"

description: IPython "Column not found error"


code:
(coords[0] + coords[1]) % 2
~(coords[0] + coords[1]) % 2

rawDescription: Slicing Pandas DataFrame with a Checkerboard Pattern


code:
import itertools

person1=[1,1,0,1,1,0,1,1,1]
syncs = [sum(v) for _, v in itertools.groupby(person1)]

rawDescription: Compute the number of consecutive identical values in a list


code:
def getcr():
    connection = sqlite3.connect('/Users/someuser/Documents/tmp/Chrome/History')
    cursor = connection.cursor()
    get_time = list(cursor.execute("""SELECT last_visit_time FROM urls"""))
    get_url = list(cursor.execute("""SELECT url from urls"""))
    stripped_time = []
    crf = open ('/Users/someuser/Documents/tmp/cr/cr_hist.txt','w' )
    itr = iter(get_time)
    itr2 = iter(get_url)

    while True:
        try:
            newdate = str(itr.next())
            stripped1 = newdate.strip(' (),L')
            ms = int(stripped1)
            utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = ms, hours =-5)
            stripped_time.append(str(utctime))
            newurl = str(itr2.next())
            stripped_url = newurl.strip(' ()')
            stripped_time.append(str(stripped_url))
            crf.write('\n')
            crf.write(str(utctime))
            crf.write('\n')
            crf.write(str(newurl))
            crf.write('\n')
            crf.write('\n')
            crf.write('********* Next Entry *********')
            crf.write('\n')
        except StopIteration:
            break

    crf.close()

    shutil.copy('/Users/someuser/Documents/tmp/cr/cr_hist.txt' , '/Users/parent/Documents/Chrome_History_Logs')
    os.rename('/Users/someuser/Documents/Chrome_History_Logs/cr_hist.txt','/Users/someuser/Documents/Chrome_History_Logs/%s.txt' % formatdate)

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


code:
def maxagent(gamestate, depth):
    actions = gamestate.getLegalActions(0)
    filteredactions = filter(lambda action: action != Directions.STOP, actions)
    # alternatives:
    #    filteredactions = filter(Directions.STOP.__ne__, actions)
    #    filteredactions = (a for a in actions if a != Directions.STOP)
    bestaction = max(filteredactions,
                     key=lambda action: self.minvalue(
                                          gamestate.generateSuccessor(0, action),
                                          depth, 1
                                        ))
    return bestaction

rawDescription: list query, functions in function

description: List query, functions in function


code:
i=np.ones(5,bool)    # array of True
i[[1,2]]=False       # falsify the forbidden ones
np.where(i)[0][:2]   # get the first 2 true indices

rawDescription: Python Numpy get 2 Indexes which are not in a Blacklist


code:
def floodfill (chars, x, y):
        try:
                if chars [y] [x] == 'x': return
                chars [y] [x] = 'x'
                for xoff, yoff in ( (0, 1), (0, -1), (1, 0), (-1, 0) ):
                        floodfill (chars, x + xoff, y + yoff)
        except: pass

rawDescription: Recursive Function to change both <x and y> in a matrix?


code:
def read_graph(lines):
    g = {}
    for line in lines:
        words = line.split()
        if words[1] == '.':
            words = words[:1]
        g[words[0]] = words[1:]
    return g

def dump_graph(g):
    out = []
    def dump(key):
        for k in g[key]:
            dump(k)
        if key not in out:
            out.append(key)
    for k in g:
        dump(k)
    return out

rawDescription: Algorithm implementation in python

description: Algorithm implementation in python


rawDescription: Python script waiting for some program being launched and then starting another program. (Windows)


rawDescription: SearchCtrl in wxPython looks different

description: SearchCtrl in wxPython looks different


code:
import sys
from PyQt4 import QtCore, QtGui

class TextEditorDlg(QtGui.QDialog):
    def __init__(self, parent=None):
        super(TextEditorDlg, self).__init__(parent)
        self.resize(500, 400)

        self.button = QtGui.QPushButton(self)
        self.button.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)
        self.lineEdit = QtGui.QLineEdit(self)
        self.textEdit = QtGui.QTextEdit(self)
        self.textEdit.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)

        self.grid = QtGui.QGridLayout(self)

        # Use the row-span and column-span arguments!
        self.grid.addWidget(self.button, 0, 0, 3, 1)
        self.grid.addWidget(self.lineEdit, 3, 0, 1, 3)
        self.grid.addWidget(self.textEdit, 4, 0, 1, 3)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = TextEditorDlg()
    myapp.show()
    sys.exit(app.exec_())

rawDescription: Can't change size within layout

description: Can't change size within layout


code:
class Actual(object):
    def __init__(self, a, c, e):
        self.a = a
        self.c = c
        self.e = e

rawDescription: Python create list of objects from list of 2 elements lists


code:
def func_wrapper(f, cache_size=10):
    evals = {}
    last_points = collections.deque()

    def get(pt, which):
        s = pt.tostring() # get binary string of numpy array, to make it hashable
        if s not in evals:
            evals[s] = f(pt)
            last_points.append(s)
            if len(last_points) >= cache_size:
                del evals[last_points.popleft()]
        return evals[s][which]

    return functools.partial(get, which=0), functools.partial(get, which=1)

rawDescription: scipy.optimize.fmin_bfgs single function computes both f and fprime

description: Scipy.optimize.fmin_bfgs single function computes both f and fprime


code:
while q.peek().timestamp <= now():
    process(q.pop())

rawDescription: Implementing a Timer in Python

description: Implementing a Timer in Python


code: (i.some_attribute for i in items)

rawDescription: What does pythonic mean?

description: What does pythonic mean


code:
objects = model.indexer.search(q_wc).flags(djapian.resultset.xapian.QueryParser.FLAG_WILDCARD).prefetch()
objects = objects.filter(state=1)

rawDescription: Djapian - filtering results

description: Djapian - filtering results


rawDescription: Passing arguments to the generic views Django queryset


code:
class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        ...
        self._subwindow = None

    def open_new(self):
        if self._subwindow is None:
            self._subwindow = NewWidget(self)
            self._subwindow.resize(200, 50)
            # move it next to the main window
            pos = self.frameGeometry().topLeft()
            self._subwindow.move(pos.x() - 250, pos.y())
        self._subwindow.show()
        self._subwindow.activateWindow()

rawDescription: PyQt : Prevent a window to be opened several times


rawDescription: Regex and Octal Characters

description: Regex and Octal Characters


code:
def csr_stack(vectors):
    data = np.concatenate([vec.data for vec in vectors])
    indices = np.concatenate([vec.indices for vec in vectors])
    indptr = np.cumsum([0] + [vec.nnz for vec in vectors])
    return sps.csr_matrix((data, indices, indptr), shape=(len(vectors),
                                                          vectors[0].shape[1]))
import itertools as it
def lil_stack(vectors):
    indptr = np.cumsum([0] + [vec.nnz for vec in vectors])
    data = np.fromiter(it.chain(*(vec.data[0] for vec in vectors)),
                       dtype=vectors[0].dtype, count=indptr[-1])
    indices = np.fromiter(it.chain(*(vec.rows[0] for vec in vectors)),
                          dtype=np.intp, count=indptr[-1])
    return sps.csr_matrix((data, indices, indptr), shape=(len(vectors),
                                                          vectors[0].shape[1]))

rawDescription: mongodb to python sparse matrix, how to make it faster?

description: Mongodb to python sparse matrix, how to make it faster


code:
from itertools import tee, izip_longest
a = ['a', 'b', 'c', 'd']
it1, it2 = tee(iter(a))
next(it2)  # discard this first value
[(x,y) for x,y in izip_longest(it1, it2)]

rawDescription: Implement lookahead iterator for strings in Python


code: block = lines[start:start+10]

rawDescription: Why while loop is sticking at raw_input? (python)


code:
import itertools

#open the file for read
with open("sample.txt", "r") as fp:
     values = fp.readlines()

#Get the values split with ","
data = [map(int, line.split(",")) for line in values]
numbers = list(itertools.chain(*data)) #Ensuring if its having many lines then concatenate

rawDescription: Sending multiple POST data in Python

description: Sending multiple POST data in Python


code:
populations = {'juvenile':  10,
               'adult':     10,
               'senile':    1
               }
survivals = {'juvenile':    1,
             'adult':       1,
             'senile':      0}
birth_rate = 2
generations = 5

def update_population(pops):
    juvie = pops['adult'] * birth_rate
    adults = pops['juvenile'] * survivals['juvenile']
    seniles = pops['adult'] * survivals['adult'] + (pops['senile'] * survivals['senile'])
    return {k:v for k,v in zip(['juvenile','adult','senile'],[juvie,adults,seniles])}

counter = 0
while counter < generations:
    populations = update_population(populations.copy())
    total_population = sum(populations.values())

    print("Juvenile: ",populations['juvenile'])
    print("Adult: ",populations['adult'])
    print("Senile: ",populations['senile'])
    print("Total: ",total_population)
    counter += 1

rawDescription: Setting new variables in a while loop with calculations PYTHON


code:
def compare_to_many(srcs, test):
    return map(lambda x: compare(x, test), srcs)

rawDescription: Comparing string differences to a list of strings


code:
listB = list(listA)
listB = listA[:]  # Or

rawDescription: Pairwise addtion of two lists mutating one of the source lists


rawDescription: Python: Sorted representation of dict of lists, sorted by number of elements in list, after removing duplicates


rawDescription: Check whether each row of a matrix is in another matrix [Python]


code:
triang = tri.Triangulation(x, y, [[3,2,1],[1,2,0]])

# alternatively:
triang = tri.Triangulation(x, y, [[3,2,0],[1,3,0]])

rawDescription: Shifting the triangles order to match colormap


code:
def ping(url):
    if os.system("ping " + url) == 0:
        return 'Online!'
    else:
        return 'Offline!'

rawDescription: Skype4py !command with arguments

description: Skype4py !command with arguments


code:
tips = Tips.objects.filter(my_filters)
user_favorite_tips = request.user.favoritedtip_set.values_list('pk', flat=True)
tips = [{'tip': tip,
         'is_favorite': tip.pk in user_favorite_tips and True or False}
         for tip in tips]

rawDescription: Marking favorites in django object set

description: Marking favorites in django object set


code:
import os
from sys import path
from django.core import serializers

fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))
fixture_filename = 'initial_data.json'

def load_fixture(apps, schema_editor):
    fixture_file = os.path.join(fixture_dir, fixture_filename)

    fixture = open(fixture_file, 'rb')
    objects = serializers.deserialize('json', fixture, ignorenonexistent=True)
    for obj in objects:
        obj.save()
    fixture.close()

def unload_fixture(apps, schema_editor):
    "Brutally deleting all entries for this model..."

    MyModel = apps.get_model("yourapp", "ModelName")
    MyModel.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
        ('yourapp', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(load_fixture, reverse_code=unload_fixture),
    ]

rawDescription: Loading initial data with Django 1.7 and data migrations


code:
def application(environ, start_response):
    start_response(status, headers)
    return ['content block 1',
            'content block 2',
            'content block 3']

rawDescription: WSGI: what's the purpose of start_response function


code:
for i in range(1, 4):
    print('{0:0>3}'.format(i))

rawDescription: How do I count and PRINT digits that start with triple figures such as 001,002,003,004 etc. in python?

description: Count and PRINT digits that start with triple figures such as 001,002,003,004 etc. in python


rawDescription: Passing a variable from one function to another function


code: add8(*(intTObin8(1) + intTObin8(1) + [0]))

rawDescription: How to pass multiple params to function in python?

description: Pass multiple params to function in python


code: res

rawDescription: Merging a list of dicts in python based on common element


rawDescription: Python: remove multiple character in list of string


code: presents = presents.split(',')

rawDescription: re.findall - Getting a list of items from a comma delimited string

description: Re.findall - Getting a list of items from a comma delimited string


rawDescription: Storing the values of an iteration to a numpy array - Python, Numpy


code:
xlApp = win32com.client.gencache.EnsureDispatch('Excel.Application')
import win32com.client.constants as cc
XlDirectionDown = cc.xlDown

rawDescription: Specify range as only selecting filled cells/ending at empty cell Python


code:
from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(616, 276)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.treeView = QtGui.QTreeView(self.centralwidget)
        self.treeView.setObjectName(_fromUtf8("treeView"))
        self.horizontalLayout.addWidget(self.treeView)
        self.treeView_2 = QtGui.QTreeView(self.centralwidget)
        self.treeView_2.setObjectName(_fromUtf8("treeView_2"))
        self.horizontalLayout.addWidget(self.treeView_2)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.verticalLayout.addWidget(self.pushButton)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 616, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.treeView1 , QtCore.SIGNAL("clicked (const QModelIndex&)") , self.clickedTree1)
        QtCore.QObject.connect(self.treeView2 , QtCore.SIGNAL("clicked (const QModelIndex&)") , self.clickedTree2)
        QtCore.QObject.connect(self.pushButton , QtCore.SIGNAL("clicked()"),self.pushed)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "PushButton", None, QtGui.QApplication.UnicodeUTF8))

    def clickedTree1(self,index):
        self.node = index.internalPointer()
        self.Tree = 1

    def clickedTree2(self,index):
        self.node = index.internalPointer()
        self.Tree = 2

    def pushed(self):
        print("You select item in treeView{0} ".format(self.Tree) + node.name())

rawDescription: PyQt 2 trees and button

description: PyQt 2 trees and button


rawDescription: format python output to json

description: Format python output to json


code:
def basic_2(a, b, c):
    n= 0
    for k, m in enumerate(a):
        nm= n+ m
        c[k, :m], n= b[n: nm], nm

rawDescription: fastest way to arrange data in python numpy based on list

description: Fastest way to arrange data in python numpy based on list


code:
import string

def LetterChanges(s):
    orig = string.letters
    new = string.ascii_lowercase[1:] + 'a' + string.ascii_uppercase[1:] + 'A'
    for vowel in 'aeiou':
        new = new.replace(vowel, vowel.upper())

    table = string.maketrans(orig, new)
    return s.translate(table)

rawDescription: How to solve this Python puzzle in a much more elegant manner?

description: Solve this Python puzzle in a much more elegant manner


rawDescription: $unwind with group and count

description: $unwind with group and count


rawDescription: Deterministic and non uniform long string generation from seed


code:
def get_queryset(self):
    self.shop = Shop.objects.get(name=self.kwargs['shop_name'])
    Offer = self.shop.get_offers_model()
    return Offer.objects.all()

rawDescription: django ListView specifying variable available for all methods inside the class

description: Django ListView specifying variable available for all methods inside the class


code: s = ''.join(data)                # lists are faster than generators in this use case

rawDescription: When is not a good time to use python generators?


rawDescription: get prime numbers from numpy array

description: Get prime numbers from numpy array


code: url = serviceurl + '?' + urllib.urlencode({'sensor':'false', 'address':  address})

rawDescription: Calling a JSON API

description: Calling a JSON API


code: clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)

rawDescription: How can I get a list of all classes within current module in Python?

description: Get a list of all classes within current module in Python


code:
import builtins
def sorted(services):
    return builtins.sorted(services, key=lambda s: s.sortkey())

rawDescription: can a python function call a global function with the same name?

description: Can a python function call a global function with the same name


code:
class ElementRemovingTestCase(unittest.TestCase):
    def tearDown(self):
        self.removeElements()

rawDescription: Calling a function after or before tearDown of each unit testcase


rawDescription: Adding an array in numpy at a specified location


code:
file_names = 'hi_file.txt', 'name_file.txt', 'welcome_file.txt'
my_strings = 'hi friend', 'whats your name', 'you welcome'

for (text, fname) in zip(my_strings, file_names):
    with open(fname, 'w') as f:
        f.write(text)

rawDescription: How to paste texts into a list of files in python

description: Paste texts into a list of files in python


rawDescription: How to perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python?

description: Perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python


code:
def string_similarity(string):
    len_string = len(string)
    total = len_string # similarity with itself
    i = 0
    while True:
        i = string.find(string[0], i+1)
        if i == -1:
            break
        n = 0
        for n in xrange(1, len_string-i):
            if string[i+n] != string[n]:
                break
        else:
            n += 1

        total += n
    return total

rawDescription: How to optimize this python script further?

description: Optimize this python script further


code:
texts = brown.tagged_words()[:10000]
word_counts = Counter(texts)
word_counts[('need', 'NN')]
word_counts[('needs', 'NNS')]
word_counts[('hit', 'NN')]
word_counts[('hits', 'NNS')]

rawDescription: How to check if a word is more common in its plural form rather than in it's singular form in an array of words (with Python/NLTK)?

description: Check if a word is more common in its plural form rather than in it's singular form in an array of words (with Python/NLTK)


code: string = ''.join('[%s]' % self.obj[x] for x in self.obj)

rawDescription: Simplification of iterating

description: Simplification of iterating


code:
def __init__(self, onEvent1=None, onEvent2=None):
    self.OnEvent1 = onEvent1
    self.OnEvent2 = onEvent2

def aLoop(self):
    ...
    #in case of event1
    if self.OnEvent1 is not None:
        self.OnEvent1()
    ...
    #in case of event2
    if self.OnEvent2 is not None:
        self.OnEvent2()

rawDescription: I need a delegate class?

description: I need a delegate class


code: random.seed(a=None, version=2)

rawDescription: How does Python seed the Mersenne twister


code:
r=redis.Redis('')
r.hmset('ClientID:127.0.0.1', {'test':'1', 'status':'success'})
r.hmget('ClientID:127.0.0.1',['test','status'])

rawDescription: redis, python and a storing information

description: Redis, python and a storing information


code: np.arange(n) + np.repeat(idx_unique_objIDs - csum + occupations, occupations)

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
class cell(object):
     def my_idx(self,grid):
         return grid.keys()[grid.values().index(self)]

rawDescription: python, dictionary value is object, can that object access its own key value from a function within itself?

description: Python, dictionary value is object, can that object access its own key value from a function within itself


code:
numbers = [(1, 2), (3, 4), (5, 6)]
for args in numbers:
    print(*args)

rawDescription: How do I pass tuples elements to a function as arguments in python?

description: Pass tuples elements to a function as arguments in python


code: h = logging.handlers.SysLogHandler(address='/var/run/syslog', facility=syslog.LOG_LOCAL1)

rawDescription: How can I log from Python to syslog with either SysLogHandler or syslog on Mac OS X *and* Debian (7)

description: Log from Python to syslog with either SysLogHandler or syslog on Mac OS X *and* Debian (7)


code:
classAverages={}
for student in classScores:
    classAverages[student] = sum(classScores[student]) / len(classScores[student])

for student in sorted(classAverages, key=classAverages.get, reverse=True):
    print(student, "Average:", classAverages[student])

rawDescription: Sorting a dictionary by average of list in value


code:
def groupby_sorted(my_list):
    """if items in my_list are unhashable"""
    from itertools import groupby
    return [e for e, g in groupby(sorted(my_list))]

def preserve_order_encountered(my_list):
    """elements in argument must be hashable - preserves order encountered"""
    from collections import OrderedDict
    return list(OrderedDict.fromkeys(my_list))

rawDescription: How do I remove identical items from a list and sort it in Python?

description: Remove identical items from a list and sort it in Python


code: new = [{k:(d[k].split(';')if(d[k] and k in ok2split)else d[k])for k in d}for d in products]

rawDescription: Convert a colon separated string to a list - within a list of dictionaries... (Python)


code:
data = np.linspace(0,10,50)
starts = np.array([0,10,21])
length = 5

rawDescription: How to efficiently index into a 1D numpy array via slice ranges

description: Efficiently index into a 1D numpy array via slice ranges


code:
import re

for file in glob.glob('*.log'):
    with open(file) as f:
        contents = f.read()
    if 'FIRMWARE_VERSION = "' in contents:
        print (file + '='+ re.search(r'FIRMWARE_VERSION ="([\d.]+)"',contents).group(1))

rawDescription: Find string in log files and return extra characters


code:
hour = range(1, 25)
activity = np.random.randint(1, 10, 24)
df = pd.DataFrame({'hour': hour, 'activity': activity})
df.plot('hour', 'activity', kind='bar');

rawDescription: How to plot histogram with data prepared in Pandas DataFrame?

description: Plot histogram with data prepared in Pandas DataFrame


rawDescription: Python "R Cut" function

description: Python "R Cut" function


code:
import sys
from PyQt4 import QtGui, QtCore
from helloworld import Ui_Window

class Window(QtGui.QWidget, Ui_Window):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.button.clicked.connect(self.handleButton)

    def handleButton(self):
        print('Hello World')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Hello world in pyqt?

description: Hello world in pyqt


code:
with open('input.txt') as f, open('output.txt', 'w') as out:
    for line in f:
        line = line.split()  #splits the line on whitespaces and returns a list
        #sort the list based on the integer value of the item on the left side of the `:`
        line.sort(key = lambda x: int(x.split(':')[0]))
        out.write(" ".join(line) + '\n')

rawDescription: sorting numbers into ascending order on a line

description: Sorting numbers into ascending order on a line


code:
def mergeDictsOverwriteEmpty(d1, d2):
    res = d2.copy()
    for k,v in d2.items():
        if k not in d1 or d1[k] == '':
            res[k] = v
    return res

rawDescription: Python: Dictionary merge by updating but not overwriting if value exists


code: then_expr if condition else else_expr

rawDescription: How to use defaultdict to create a dictionary with a lambda function?

description: Use defaultdict to create a dictionary with a lambda function


code:
import sys
import threading
from PySide import QtCore, QtGui

class Dialog(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        button = QtGui.QPushButton("test")
        layout = QtGui.QVBoxLayout()
        layout.addWidget(button)
        self.setLayout(layout)

app = QtGui.QApplication(sys.argv)
toast = Dialog()
toast.show()

t = threading.Thread(target = lambda: app.exec_())
t.daemon = True
t.start()
print("App freezes the main process!")
input()

rawDescription: How to stop qt app from freezing the main program?

description: Stop qt app from freezing the main program


code:
df = pd.read_csv("vd.csv", sep="\s+")
d2 = pd.melt(df, id_vars="day")
d2["sample"] = d2.groupby(["variable", "day"])["day"].rank("first")
d3 = d2.pivot_table(index=["variable", "sample"], columns="day")

rawDescription: Stacking and shaping slices of DataFrame (pandas) without looping


code:
df = pd.DataFrame({
'value' : [4,2,5,6,7,8,6,5,4,1,2,4],
'date': fread_year_month(dt.datetime(2015, 1, 1),dt.datetime(2015, 12, 1)),
'stock': ['amzn']*12
},columns=[
'value', 'date', 'stock'] )

df2 = pd.DataFrame({
'value' : [1]*11,
'date': fread_year_month(dt.datetime(2015, 1, 1),dt.datetime(2015, 11, 1)),
'stock': ['msft']*11
},columns=[
'value', 'date', 'stock'] )

df = df.append(df2)

df.set_index(['stock', 'date'], inplace=True)

rawDescription: pandas, slice multi-index df with multiple conditions

description: Pandas, slice multi-index df with multiple conditions


code:
longind = max(dataList.values(), key=len).index
df = df.loc[longind]

rawDescription: Resampling and merging data frame with python


code:
import csv
from collections import defaultdict

d = defaultdict(list)
fields = ["USER","URL","LOADS","ACT"]

with open('file.csv', 'rU') as the_file:
    rows = csv.DictReader(the_file, delimiter=",",fieldnames=fields)
    rows.next()

    for row in rows:
        data = (int(row['LOADS']),int(row['ACT']))
        d[row['URL']].append(data)

rawDescription: Stumped - In Python obtaining unique keys with multiple associated values from a list of ditionaries


code:
# loop forever
while True:
    for r in right:
        if stack.endswith(r):
            stack = stack.replace(r, left[right.index(r)])

            # now break out of the for-loop rerunning while
            break
    # the else is run when all r in right are consumed
    else:
        # this break is not in a for loop; it breaks the while
        break

rawDescription: how to reset pointer of list in for loop after a condition becomes true in python?

description: Reset pointer of list in for loop after a condition becomes true in python


code:
userx, domain, type = win32security.LookupAccountName ("", "your.user")
usery, domain, type = win32security.LookupAccountName ("", "other.user")

dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 2032127, userx) # Full control
dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 1179785, usery) # Read only

sd.SetSecurityDescriptorDacl(1, dacl, 0)   # may not be necessary
win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)

rawDescription: How to authorize/deny write access to a directory on Windows using Python?

description: Authorize/deny write access to a directory on Windows using Python


code: from .script1 import myclass

rawDescription: How to import class name python

description: Import class name python


rawDescription: How to convert datetime in Pacific timezone to UTC timestamp?

description: Convert datetime in Pacific timezone to UTC timestamp


code:
formatdt(datetime.datetime(2014, 4, 1))
formatdt(datetime.datetime.now())

rawDescription: Python 3.4: how to add zero milliseconds and change their formatting


code:
import asyncio

dsn = "..."

async def create_foo(settings):
    foo = Foo(settings)
    await foo._init()
    return foo

class Foo(object):
    def __init__(self, settings):
        self.settings = settings

    async def _init(self):
        self.pool = await create_pool(dsn)

async def main():
    settings = "..."
    foo = await create_foo(settings)

rawDescription: How to set class attribute with await in __init__

description: Set class attribute with await in __init__


code:
from urllib import quote_plus

def speak(text):
    import pydshow
    words = text.split()
    temp = []
    stuff = []
    while words:
        temp.append(words.pop(0))
        if len(temp) == 24:
            stuff.append(' '.join(temp))
            temp = []
    stuff.append(' '.join(temp))
    for i in stuff:
        pydshow.PlayFileWait('http://api.ispeech.org/api/rest?apikey=8d1e2e5d3909929860aede288d6b974e&format=mp3&action=convert&voice=ukenglishmale&text='+quote_plus(i))

if __name__ == '__main__':
       speak('Hello. This is a text-to speech test.')

rawDescription: Listening to the Output of a Web Application


rawDescription: String formatting of timedeltas in Pandas


code:
from ctypes import *

def encipher(v, k):
    y=c_uint32(v[0]);
    z=c_uint32(v[1]);
    sum=c_uint32(0);
    delta=0x9E3779B9;
    n=32
    w=[0,0]

    while(n>0):
        sum.value += delta
        y.value += ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]
        z.value += ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]
        n -= 1

    w[0]=y.value
    w[1]=z.value
    return w

def decipher(v, k):
    y=c_uint32(v[0])
    z=c_uint32(v[1])
    sum=c_uint32(0xC6EF3720)
    delta=0x9E3779B9
    n=32
    w=[0,0]

    while(n>0):
        z.value -= ( y.value << 4 ) + k[2] ^ y.value + sum.value ^ ( y.value >> 5 ) + k[3]
        y.value -= ( z.value << 4 ) + k[0] ^ z.value + sum.value ^ ( z.value >> 5 ) + k[1]
        sum.value -= delta
        n -= 1

    w[0]=y.value
    w[1]=z.value
    return w

rawDescription: Python TEA implementation

description: Python TEA implementation


code:
from subprocess import Popen, PIPE
p1 = Popen(["cat","/proc/meminfo"], stdout=PIPE)
p2 = Popen(["egrep", 'MemTotal|MemFree|Cached|SwapTotal|SwapFree|AnonPages|Dirty|Writeback|PageTables|HugePages_' ], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
p3 = Popen(["awk","{ print $2}"],stdin=p2.stdout,stdout=PIPE)
p2.stdout.close()
p4 = Popen(["pr", "-t", "-T", "--columns=15", "--width=240"],stdin=p3.stdout,stdout=PIPE)
p3.stdout.close()

output = p4.communicate()
print(output[0])

rawDescription: converting bash/shell line into python 2.6

description: Converting bash/shell line into python 2.6


code: map(None,*l)

rawDescription: Pass each nested list as an arg to map

description: Pass each nested list as an arg to map


code: t = soup.find('title')

rawDescription: Extracting text from a nested tags in XML using BeautifulSoup in python


code:
cat_columns = df.select_dtypes(['category']).columns
cat_columns
df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
df

rawDescription: Convert categorical data in pandas dataframe


code:
from engine_folder import engine_1, engine_2

class game:

  def __init__(self):
      self.engine_1 = engine_1.engine(self, ...)
      self.engine_2 = engine_2.engine(self, ...)
      #where engine_1.engine and engine_2.engine are
      #two classes that need to transfer data between
      #each other

  def run(self):
      self.engine_1.run()
      self.engine_2.run()

rawDescription: How to Link Multiple Classes Together Efficiently


code: replaced = markup.replace('<pre>', '<pre class="prettyprint">')

rawDescription: Wrap markdown code blocks with prettyprint classes in Python


rawDescription: Efficiently page query results

description: Efficiently page query results


code: den

rawDescription: How do I find the attribute to two separate words in Python?

description: Find the attribute to two separate words in Python


code: lines = [line.rstrip("\n") for line in open(infile) for infile in infiles]

rawDescription: From files to list of lines

description: From files to list of lines


code:
class AClass(object): pass
class BClass(object): pass
class CClass(object): pass

classList = {'a':AClass, 'b':BClass, 'c':CClass}

rawDescription: How to create instance of a class through list

description: Create instance of a class through list


code:
txt = input("Enter text: ")
for direction in 'from right', 'from left':  # do it twice
     txt = re.sub('[iI]', '', txt[::-1], count=1)
print(txt)

rawDescription: Remove first and last specific symbol

description: Remove first and last specific symbol


code: from matplotlib.patches import Rectangle

rawDescription: Choosing marker size in Matplotlib

description: Choosing marker size in Matplotlib


code:
import ckan.plugins.toolkit as tk
my_package = tk.get_action('package_show')({'id': 'my_package'})

rawDescription: How to add free-form tags to a CKAN package?

description: Add free-form tags to a CKAN package


code:
def factors(n):
    l = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            l.append(i)
            l.append(n//i)
    return l

rawDescription: list comprehension with multiple assignments

description: List comprehension with multiple assignments


rawDescription: Converting daily data in to weekly in Pandas


code:
{'_enabled': 'true',
 'foo': {'isdefault': 'false',
         'name': 'qa',
         'nested': {},
         'url': 'http://prod.example.com',
         'user': 'willow'},
 'instances': [{'isdefault': 'true',
                'name': 'dev',
                'url': 'http://dev.example.com',
                'user': 'buffy'},
               {'isdefault': 'false',
                'name': 'prod',
                'nested': {'more_nesting': {'even_more_nesting': ({}, {})}},
                'url': 'http://prod.example.com',
                'user': 'spike'},
               {'isdefault': 'false',
                'name': 'qa',
                'url': 'http://prod.example.com',
                'user': 'willow'}],
 'label': 'MyServers'}

rawDescription: How to scrub a dynamic python dictionary of specific keys?

description: Scrub a dynamic python dictionary of specific keys


rawDescription: Add value to Row for every column except one


code:
df
foo = lambda x: pd.Series(pd.qcut(x,10,labels=False),index=x.index)
df['ranks'] = df.groupby('Date')['V1'].apply(foo)
df

rawDescription: ranks within groupby in pandas

description: Ranks within groupby in pandas


rawDescription: Python add days in epoch time

description: Python add days in epoch time


code:
while guessesTaken < 6:
    if guess < number:
        print('Your guess is too low.')
    elif guess > number:
        print('Your guess is too high.')
    else:
        break

    guess = int(input('Try again: '))
    guessesTaken += 1

if guess == number:
    print('Good job! You guessed my number in {} guesses!'.format(guessesTaken))
else:
    print('Nope. The number I was thinking of was {}'.format(number))

rawDescription: Radius guessing game loop going wrong

description: Radius guessing game loop going wrong


code:
f = h5py.File('myfile.hdf5','r')
x_d = f['x_axis'][:]
y_d = f['values'][:]
sorted_y = y_d[numpy.argsort(x_d)]

rawDescription: numpy, h5py: How do I make an array sorted by one of its columns from a bigger one saved with h5py?

description: Numpy, h5py: How do I make an array sorted by one of its columns from a bigger one saved with h5py


code:
reduct(2, 8)
reduct(3, 8)
len(reduct(7, 8))

rawDescription: Python Itertools: Complex "product"

description: Python Itertools: Complex "product"


rawDescription: Python list max function when a list item is present


code:
a = [None,1,2,3,None,4,None,None]

start = next(ele for ele in a if ele is not None)
for ind, ele in enumerate(a):
    if ele is None:
        a[ind] = start
    else:
        start = ele
print(a)
[1, 1, 2, 3, 3, 4, 4, 4]

rawDescription: Replace None in list with leftmost non none value


code:
itertools.chain(list1, list2, list3)

iterables = [list1, list2, list3]
itertools.chain.from_iterable(iterables)

rawDescription: What is the difference between chain and chain.from_iterable in itertools?


code:
getcontext().prec = 5
getcontext().Emax = 2
a = Decimal("0.34")
b = Decimal("0.20")
assert a * b == Decimal("0.07")

rawDescription: Python decimal context for fixed point

description: Python decimal context for fixed point


code:
os.environ['TZ'] = ":Pacific/Auckland"
run("date")

rawDescription: How do I set remote server TimeZone via Fabric?

description: Set remote server TimeZone via Fabric


code:
from dateutil.relativedelta import relativedelta

def yearsago(years, from_date=None):
    if from_date is None:
        from_date = datetime.now()
    return from_date - relativedelta(years=years)

rawDescription: Python timedelta in years

description: Python timedelta in years


code:
counter = 0
while counter < 3:
    counter += 1

rawDescription: Python Loops Complication

description: Python Loops Complication


code: f1 = lambda f: (lambda a: a(a))(lambda b: f(lambda *args: b(b)(*args)))

rawDescription: Decoding a Cryptic Python statement

description: Decoding a Cryptic Python statement


code:
g = Graph.Ring(4, circular=False)
layout = [(0,0), (0,1), (1,1), (1,0)]
plot(g, layout=layout)

rawDescription: How to set the coordinates of nodes in Python Igraph

description: Set the coordinates of nodes in Python Igraph


code: pool =  mp.Pool(3)

rawDescription: python multiprocessing - select-like on running processes to see which have one have finished

description: Python multiprocessing - select-like on running processes to see which have one have finished


rawDescription: Get file syntax selection in sublime text 3 plugin


code:
class RecipeForm(forms.Form):
    Recipebase_id = forms.ModelChoiceField(queryset=Recipebase.objects.none())

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user') #Throws an error if user is not present
        super(RecipeForm, self).__init__(*args, **kwargs)
        qs = Recipebase.objects.filter(user=user)
        self.fields['Recipebase_id'].queryset = qs

rawDescription: How to filter model choice field options based on user in django?

description: Filter model choice field options based on user in django


code:
def parse_price(text):
    try:
        return float(re.search(r'\d*\.\d+', text).group())
    except (TypeError, ValueError, AttributeError):
        return None

price = []
for item in part.find(attrs={"class": re.compile('abc')}).contents:
    item = parse_price(item.string)
    if item:
        price.append(item)

rawDescription: How to extract tags from HTML using Beautifulsoup in Python

description: Extract tags from HTML using Beautifulsoup in Python


code:
for service in list_services:
    if service.name == 'compute':
        print(service.service_id)

rawDescription: Check for particular value from class object and get the value of another key


code:
old_f = sys.stdout
class F:
    def write(self, x):
        old_f.write(x.replace("\n", " [%s]\n" % str(datetime.now())))
sys.stdout = F()

rawDescription: Adding a datetime stamp to Python print

description: Adding a datetime stamp to Python print


code:
from PIL import Image
data = ""
for i in range( 128**2 ):
    data += chr(255) + chr(0) + chr(0)
im = Image.fromstring("RGB", (128,128), data)
im.save("test.png", "PNG")

rawDescription: Creating image through input pixel values with the Python Imaging Library (PIL)


code:
result = []
query_array = query[0].toarray()
for row in tfidf_matrix:
    result.append(cosine(row.toarray(), query_array))

rawDescription: Better way to map a function (cosine similarity) to each row in scipy.csr_matrix


code:
urlpatterns = patterns('',
    (r'^somesite/$', views.view),
    (r'^somesite/json$',  views.returnJSON),
)

rawDescription: Django : provide dynamically generated data as attachment on button press


Edwardsville

country: United States of America

description: few clouds

main: Clouds

message: accurate

rawDescription: Unable to format the output of a link in python


code:
def bar(x, y):
    return x+y
print(bar)
print(bar(2, 3))

rawDescription: Passing function returns as method parameters in Python


rawDescription: Selecting elements in an array based on what column and row they are in in order to complete a loop in python


code:
print(name)  # name
print(qty)  # qty

rawDescription: Add the elements value in a list

description: Add the elements value in a list


code:
import string
def all_letters(s):
    final = ""
    for char in s:
        if char in string.ascii_letters:
            final += char
    return final
In [78]: all_letters("Hell4208o@World.com")
Out[78]: 'HelloWorldcom'

rawDescription: Only letters function

description: Only letters function


rawDescription: Group DataFrame by entries X amount of time from each other


code:
def main(x,y,f):
  return f(x,y)**2

main(3, 5, func1)

rawDescription: Assign a numeric value that is returned from a function by using exec command


rawDescription: Using ElementTree to parse an XML string with a namespace


code:
import time
time.mktime(d.timetuple())

rawDescription: Converting Timestamps in Python to UNIX Timestamps


code:
def func():
    my_function(arg1, arg2)
aceptar = Button(root,text="Calcular", command=func)

rawDescription: How to call a parametized function with Tkinter in Python?

description: Call a parametized function with Tkinter in Python


code:
from pyspark.sql import DataFrame

DataFrame(simpleObject.exe(), ssqlContext)

rawDescription: How to use a Scala class inside Pyspark

description: Use a Scala class inside Pyspark


code: float(your_string[:-1]) / 100.0

rawDescription: Pythonic way to get .03 from 3%

description: Pythonic way to get .03 from 3%


rawDescription: Deleting and Redrawing Matplotlib Animation


code:
import sys
import os
# Do all files except the program name
for inpfn in sys.argv[1:]:
    # Name result files 'resized_<oldname>.pdf'
    # and put them in current directory
    shortname = os.path.basename(inpfname).rsplit('.',1)[0]
    outfn = 'resized_%s.pdf' % shortname
    subprocess.call(['inkscape', '-D', '-A', outfn, inpfn])

rawDescription: Inkscape extension in Python

description: Inkscape extension in Python


code:
def store(values):
   return {'AvgPositive':posNumAvg(values), 'AvgNonPos':negativeNumAvg(values), 'AvgAllNum':allNumAvg(values)}

rawDescription: Trying to learn how to python have, I am curious about appeand and dictionaries...am i doing this correctly?


code:
class MetaA(type):
    def __init__(cls, name, bases, clsdict):
        super(MetaA, cls).__init__(name, bases, clsdict)
        for base in bases:
            if hasattr(base, 'array'):
                cls.array = base.array + cls.array
                break

class A(object):
    __metaclass__ = MetaA
    array = [1]

    def __init__(self):
        pass

class B(A):
    array = [2, 3]

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

class C(B):
    array = [4]

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

rawDescription: Joining fields values

description: Joining fields values


code:
for i in mylist:
    tsg.SecurityGroupIngress = mksg(i['cidr'], i['proto'], [i['port']])

rawDescription: unexpected output while using list(and nested dictionary)

description: Unexpected output while using list(and nested dictionary)


rawDescription: Python decorating property setter with list


code:
from lxml.html import parse
import re

doc = parse('http://www.androidpolice.com').getroot()
links = []
img_list = []

for img in doc.cssselect('img'):
    links.append(img.get('src'))

for link in links:
    match = re.search(".*androidpolice\.com.*",link)
    if match:
        img_list.append(match.group(0))

for img in img_list:
    print(img)

rawDescription: Matched Pattern Returns Tuple Of Strings Instead Of A Match As A Whole


rawDescription: How to get non-csv lines in csv file

description: Get non-csv lines in csv file


code:
# initialize a table somehow
table = QTableWidget(parent)
table.setRowCount(1)
table.setColumnCount(1)

# create an cell widget
btn = QPushButton(table)
btn.setText('12/1/12')
table.setCellWidget(0, 0, btn)

rawDescription: Adding widgets to qtablewidget pyqt

description: Adding widgets to qtablewidget pyqt


code:
g = globals()
for i in range(10):
    g["karte" + str(i)] = karte()

rawDescription: python how to make dynamic object name

description: Python how to make dynamic object name


code:
bottom='off'
top='off'
left='off'
right='off'

rawDescription: Turning off ticks in matplotlib for all plots (using rc)


code:
import threading
import time
import logging

logger=logging.getLogger(__name__)

def f(lock,n):
    while True:
        with lock:
            logger.info(n)
            time.sleep(1)

def h(locks):
    while True:
        t=time.time()
        for n,lock in enumerate(locks):
            lock.acquire()
            t2=time.time()
            logger.info('h acquired {n}: {d}'.format(n=n,d=t2-t))
            t=t2
        t2=time.time()
        logger.info('h {d}'.format(d=t2-t))
        t=t2
        for lock in locks:
            lock.release()
        time.sleep(5)

logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')

locks=[]
N=5
for n in range(N):
    lock=threading.Lock()
    locks.append(lock)
    t=threading.Thread(target=f,args=(lock,n))
    t.start()

threading.Thread(target=h,args=(locks,)).start()

rawDescription: Pausing two Python threads while a third one does stuff (with locks?)


code:
a=x.A()
a.func()
b=x.B()
b.func()

rawDescription: Can @staticmethod's be inherited?

description: Can @staticmethod's be inherited


code:
self.selectionList = ['Jim', 'John', 'Harry', 'Charles']

def getSelection(self):
    sel = QtWidgets.QInputDialog.getItem(self, 'Text Selection Dialog', 'Select your name:', self.selectionList, current=0, editable=False)
    if sel[1]:
        username = sel[0]
        print(username)

rawDescription: link QInputDialog text to a variable

description: Link QInputDialog text to a variable


code:
f = open('some_file', 'w')
f.write('\n'.join(bin(ord(c))[2:].zfill(8) for c in data))
f.close()

rawDescription: Python Hex File Write

description: Python Hex File Write


code: isinstance(some_object, basestring)

rawDescription: Check if input is a list/tuple of strings or a single string


code:
class ABSerializer(serializers.ModelSerializer):

    class Meta:
        model = A
        fields = ['name', 'age', 'salary']

    salary = serializer.IntegerField(source='b.salary') # this is your related_name

rawDescription: Django rest framework one to one relation


code: df

rawDescription: Python - Unpivot data

description: Python - Unpivot data


rawDescription: python list tree indexing

description: Python list tree indexing


rawDescription: Color differences between contour and contourf in matplotlib


code:
for contact in contacts:
    if contact.first_name == 'Bob':
      print(contact.phone_number)

rawDescription: Program consisting of multiple classes

description: Program consisting of multiple classes


code: inner_dir_path = os.path.join(cur_directory_path, 'inner_dir')

rawDescription: Include entire directory in python setup.py data_files


code:
import decorator

@decorator.decorator
def wraps(f):
    def call(*args, **kw):
        print('in', f, args, kw)
        return f(*args, **kw)
    return call

def g():pass

@wraps
def f(a, b = 1, g = g, *args, **kw):
    pass

help(f)

rawDescription: python decorator with arguments of decorated function

description: Python decorator with arguments of decorated function


code:
#!/usr/bin/env python3

def process_ranks(player_ranks, rank_database):
    rank_map = dict(rank_database)
    return [rank_map[rank] for rank in player_ranks]

def main():
    # Sample data.
    player_ranks = ['old' + str(n) for n in range(4)]
    # Database contains more rank data than we will use.
    rank_database = [
      ('old' + str(n), 'new' + str(n)) for n in range(40)
      ]

    print("Original player ranks:")
    print(player_ranks)
    processed_ranks = process_ranks(player_ranks, rank_database)
    print("Processed player ranks:")
    print(processed_ranks)
    return

if "__main__" == __name__:
    main()

rawDescription: How to replace strings in a list using tuples of strings and their replacements?

description: Replace strings in a list using tuples of strings and their replacements


code:
import matplotlib.pyplot as plt
import urllib2

# load the image
img = plt.imread(urllib2.urlopen('http://upload.wikimedia.org/wikipedia/en/thumb/5/56/Matplotlib_logo.svg/500px-Matplotlib_logo.svg.png'))

# get the dimensions
ypixels, xpixels, bands = img.shape

# get the size in inches
dpi = 72.
xinch = xpixels / dpi
yinch = ypixels / dpi

# plot and save in the same size as the original
fig = plt.figure(figsize=(xinch,yinch))

ax = plt.axes([0., 0., 1., 1.], frameon=False, xticks=[],yticks=[])
ax.imshow(img, interpolation='none')

plt.savefig('D:\\mpl_logo.png', dpi=dpi, transparent=True)

rawDescription: Setting the size of the plotting canvas in Matplotlib


code:
def write_tecplot(outfile,Data):
    """
    The expected Data is a dictionary with one structured array: node and one simple array: face
    """
    N = Data["node"].shape[0]   #N is the number of nodes
    E = Data["face"].shape[0]  #E is the number of faces

    #Create the file and the main names
    with open(outfile+'.dat', 'w') as f:
        """ Write HEADER """
        f.write('TITLE = \"title\"\n')
        f.write('VARIABLES  = ')
        #initialize
        names = Data["node"].dtype.names

        #write variable names
        f.write(u'"'+'\",\"'.join(names)+'"\n')
        f.write('ZONE T="tecdata", N=%s, E=%s, ET=QUADRILATERAL, F=FEBLOCK\n\n'%(N,E))

#        Data_number =  len(Data["node"])     #Data_number is the

        """ WRITE DATA """
        #Write node data
        for name in names:
            n = Data["node"][name]
            for col_index in range(0,N,5):  #The tecplot data for each variable are saved within 5 columns
                f.write(",".join([str(v) for v in n[col_index:col_index+5]])+"\n")
            f.write("\n\n")

        face = Data["face"]
        for col_index in range(0,E,1):  #The tecplot data for each variable are saved within 5 columns
            f.write(",".join([str(v) for v in face[col_index]])+"\n")
        f.write("\n\n")

rawDescription: Reduce writing time of data

description: Reduce writing time of data


code:
# somewhere in your class
self.checkedList = set()

def buttonChecked(self, checked):
    button = self.sender()
    if checked:
        self.checkedList.add(button)
    else:
        if button in self.checkedList:
            self.checkedList.remove(button)

# when you create a new button
button.toggled.connect(self.buttonChecked)

rawDescription: Big number of pushbuttons and smart checking which is checked


code:
def new(inputfile,history_ends,
        historyjobs=historyjobs,targetjobs=targetjobs):

    # checking the file
    with open(inputfile,'r') as f:
        for line in f:
            job = map(int,line.split())
            (historyjobs if job[0]  < history_ends
             else targetjobs).append(job)

    while True:
        k = 0
        zhlistsub = [i for i, element in enumerate(historyjobs)
                     if element[3:6] == targetjobs[k][3:6] ]
        if zhlistsub:
            listcreate(*quickzh(zhlistsub))
        historyjobs.append(targetjobs.pop(0))
        if len(targetjobs)==0:
            break

rawDescription: To make the following code run faster?

description: To make the following code run faster


code: big_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, words)))

rawDescription: Replace all words from word list with another string in python


code:
f = sys._getframe()
f.f_locals['foo'] = 3
foo

rawDescription: Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter?


code:
import requests
from BeautifulSoup import BeautifulSoup
page = requests.get("https://www.google.dz/search?q=see")
soup = BeautifulSoup(page.content)
links = soup.findAll("a")

rawDescription: Python getting all links from a google search result page


code:
from django.db.models import Q

Track.objects.filter(Q(genre__genre='Rock') | Q(genre__parent__genre='Rock')).distinct()

rawDescription: Django Many-to-many query fulfilling a specific condition


code:
import pandas as pd

cols = ['ID', 'address', 'used_at']
df = pd.read_csv(r'avito_trend.csv', parse_dates=['used_at'], usecols=cols)

# sort DF by ID, Timestamp, address
df.sort_values(['ID','used_at','address'], inplace=True)

# adding helper columns: 'prev_address' and 'time_diff'
df['prev_address'] = df['address'].shift()
df['time_diff'] = df['used_at'] - df['used_at'].shift()

# exclude those where  `address` == `prev_address`
df = df[df['address'] != df['prev_address']]
# exclude those with `time_diff` > 10 minutes (please set desired value)
df = df[df['time_diff'] <= pd.Timedelta('10min')]

# group by (address, prev_address, df.used_at.dt.year) and count results
df[['ID','address','prev_address']] \
  .groupby(['address','prev_address', df.used_at.dt.year]) \
  .count() \
  .reset_index()

rawDescription: How to determine the priority actions for a every unique user using pandas

description: Determine the priority actions for a every unique user using pandas


code: filter(None, list)

rawDescription: ndb.get_multi() returning null entities

description: Ndb.get_multi() returning null entities


code:
print(x)
print(len(x))

rawDescription: What is the overhead of using a dictionary instead of a list?


code:
from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filepost import encode_multipart_formdata

def prepare_body_with_size(request, files):
    new_fields = []
    for name, filename, data, file_type in files:
        rf = RequestField(name=name, data=data, filename=filename)
        content_disposition = 'form-data; size=%d' % len(data)
        rf.make_multipart(content_disposition=content_disposition, content_type=file_type)
        new_fields.append(rf)

    body, content_type = encode_multipart_formdata(new_fields)
    request.headers['Content-Type'] = content_type
    request.body = body
    return request

rawDescription: Is there a Python HTTP client that lets you set the size in Content-Disposition for posting files?


code:
class YourModel(models.Model):
    textA = models.CharField(max_length=200,)
    textB = models.CharField(max_length=200,)
    ...

rawDescription: django how to insert a textbox input to sqlite database?

description: Django how to insert a textbox input to sqlite database


code:
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
    writer = csv.DictWriter(cache, ["text", "area", "date", "id"])
    writer.writerows(datares['results'])

rawDescription: Formatting data returned from twitter api utilizing python in a csv file?


code:
import io
import pandas as pd

df = pd.read_csv(io.StringIO('\n'.join("1,1,6;3,6,2;3,3,1;".split(';'))), header=None)

print(df)

rawDescription: Convert a single string formatted as a csv file into a pandas dataframe


rawDescription: Adding counters deletes keys

description: Adding counters deletes keys


rawDescription: sum squared values in FreqDist, python

description: Sum squared values in FreqDist, python


code:
import regex
m = regex.sub(r'(?<=^|[\S\s])%(?= |$)', r'PCT', '% foo%bar % foo% bar%')
m

rawDescription: Python - string replacement, re.match and re.sub in a single operation (replace a char if at end of a string)


code: [list(y) for x,y in itertools.groupby(C, operator.itemgetter(0,1))]

rawDescription: Python: Finding number of same lists occurrences and averaging


code: data.get(test, {}).get('AS')

rawDescription: Am I thinking correctly about Python Dictionaries


code:
group_list = [g for k,g in grouped]
group_list[2]
group_dict = dict(list(grouped))
group_dict[1]

rawDescription: How to split pandas dataframe based on difference of values in a column

description: Split pandas dataframe based on difference of values in a column


code:
import os
files=[]
for file in os.listdir("C:/"):
    if file.endswith(".jpeg"):
        files.append(os.path.join(os.getcwd(), file))

for x in files:
    item = QtGui.QListWidgetItem()
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap(_fromUtf8(x)), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    item.setIcon(icon)
    self.listWidget.addItem(item)

rawDescription: Populating list with images in PYQT

description: Populating list with images in PYQT


code: f['new_str'] = f.xx.fillna('') + f.yy.fillna('')

rawDescription: Concatenating two series with None value (pandas DataFrame)?


code: strm2 = driver.Stream()

rawDescription: Returning to host code in pyCUDA after asynchronous kernel launch


code: df['timeseries'] = pd.to_datetime(df.Date + ' ' + df.Time, unit='ms')

rawDescription: Python: Assigning timestamps to dataframe using separate date and time values in dataset


code:
import gtk
import gobject
import os
from subprocess import Popen, PIPE
import fcntl

wnd = gtk.Window()
wnd.set_default_size(400, 400)
wnd.connect("destroy", gtk.main_quit)
label = gtk.Label()
label.set_alignment(0, 0)
wnd.add(label)
wnd.show_all()
sub_proc = Popen("ping -c 10 localhost", stdout=PIPE, shell=True)
sub_outp = ""

def non_block_read(output):
    ''' even in a thread, a normal read with block until the buffer is full '''
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.read()
    except:
        return ''

def update_terminal():
    label.set_text(label.get_text() + non_block_read(sub_proc.stdout))
    return sub_proc.poll() is None

gobject.timeout_add(100, update_terminal)
gtk.main()

rawDescription: Show terminal output in a gui window using python Gtk


rawDescription: Python 2D table lookup by labels

description: Python 2D table lookup by labels