code:
lst = Singleton(42)
lst[0]
len(lst)

rawDescription: Generating 3 billion-th element of a sequence in python


code: x >> y

rawDescription: Hack the in operator to return non booleans


rawDescription: Jaccard distance - union and intersection of lists


code:
Modify_List_col = ['mary_02', 'peter_03']
df

rawDescription: Modify certain cells depending on given conditions using pandas


code: print(printObj)

rawDescription: What is the difference between these codes, and what does the repr do?


code:
from jwkest import long_to_base64
long_to_base64(65537)

rawDescription: Get the big-endian byte sequence of integer in Python


code:
future = asyncio.run_coroutine_threadsafe(protocol.stop, loop=loop)
future.result()  # wait for results

rawDescription: Multi-threaded asyncio in Python

description: Multi-threaded asyncio in Python


code:
def wrap_scale_methods(cls):
    Base = cls.__base__
    def factor_scale(f):
        def wrapper(self, *args, **kwargs):
            scaled = Base.__mul__(self, FACTOR)
            result = f(scaled, *args, **kwargs)
            if isinstance(result, Base):
                result = type(self)(result/FACTOR)
            return result
        return wrapper
    for methodname in cls._scale_methods:
        setattr(cls, methodname, factor_scale(getattr(Base, methodname)))
    return cls

@wrap_scale_methods
class FactorComplex(complex):
    _scale_methods = '__str__ __mul__ __div__ __add__ __sub__'.split()
    def __repr__(self):
        return '%s(%s)' % (type(self).__name__, complex.__repr__(self)[1:-1])

rawDescription: An inheritance example in Python

description: An inheritance example in Python


code:
module = imp.load_source( 'file1', '.\parsers\file1.py')
methodToCall = getattr( module, 'filemethod' )
methodToCall( data )

rawDescription: python and dynamic imports of sub directories

description: Python and dynamic imports of sub directories


code:
whitespace = dict.fromkeys((9, 10, 13, 32))  # tab, space, newline and carriage return
data = binascii.unhexlify(args.data.translate(whitespace))

rawDescription: Escaped string of bytes to bytestring

description: Escaped string of bytes to bytestring


code:
import itertools, re
from multiprocessing import Process, Manager

def parse(queue, d, m):
    while True:
       line = queue.get()
       if line is None:
           return # we are done with this thread
       key, tweet = line.split('\t')
       data = d.get(key)
       e = r'(@\w+)'
       if data:
          mentions = re.findall(e, tweet)
          for mention in mentions:
              if mention in data:
                  if mention not in m:
                     m[mention] = 1
                  else:
                     m[mention] += 1

if __name__ == '__main__':
     workers = 2
     manager = Manager()

     d = manager.dict()
     d2 = manager.dict()
     d = {'100022441': ['@frankgaffney', '@DavidBartonWB']}

     queue = manager.Queue(workers)

     worker_pool = []
     for i in range(workers):
         p = Process(target=parse, args=(queue, d, d2))
         p.start()
         worker_pool.append(p)

     # Fill the queue with data for the workers
     with open(r'tweets2.txt') as f:
         iters = itertools.chain(f, (None,)*workers)
         for line in iters:
             queue.put(line)

     for p in worker_pool:
         p.join()

     for i,data in d.iteritems():
       print('For ID: {}'.format(i))
       for key in data:
          print(' {} - {}'.format(key, d2[key]))

rawDescription: Python multiprocessing: Reading a file and updating a dictionary


code: var1, var2, var3, var4 = l[:4]

rawDescription: What's the simplest way to assign list members to different variables?


code:
newlist =[]
adds = ['', ',', '.', '?', '!', ':']
for item in oldlist:
    for add in adds:
        newlist.append(item+add)

rawDescription: Extend every single string in a list with punctuation


code:
def bracketed_find(s, start, end, startat=0):
    startloc=s.find(start, startat)
    if startloc==-1:
    	return
    endloc=s.find(end, startloc+len(start))
    if endloc == -1:
    	yield s[startloc+len(start):]
    	return
    else:
    	yield s[startloc+len(start):endloc]

    for found in bracketed_find(s, start, end, endloc+len(end)):
    	yield found

rawDescription: Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc


code:
l = []
for inner_list in my_list:
  for item in inner_list:
    if item == 'two':
      l.append(item)

rawDescription: How to find all occurrences of an element in a list?

description: Find all occurrences of an element in a list


code:
import re
a = "data23/45 data"
[int(x) for x in re.split('[^\d]+', a) if x]

rawDescription: I want to get numeric data from string. How to do that in python?


code:
from collections import Counter
Counter("11234458881")

rawDescription: In Python how can I check how many times a digit appears in an input?


code:
def pretty(d, indent=10, result=""):
    for key, value in d.iteritems():
        result += " " * indent + str(key)
        if isinstance(value, dict):
            result = pretty(value, indent + 2, result + "\n")
        else:
            result += ": " + str(value) + "\n"
    return result

env.filters['pretty'] = pretty

rawDescription: jinja 2 nested dictionaries to yaml

description: Jinja 2 nested dictionaries to yaml


code:
from contextlib import contextmanager

class MyClass(object):
    def __init__(self):
        self.level = 0
    def inclev(self):
        self.level += 1
    def declev(self):
        self.level -= 1

    @contextmanager
    def Nest(self):
        self.inclev()
        try:
            yield
        finally:
            self.declev()

rawDescription: Context manager inside a class instance

description: Context manager inside a class instance


code:
import numpy as np
import numba as nb

def f_big(A, k, std_A, std_k, mean_A=10, mean_k=0.2, hh=100):
    return ( 1 / (std_A * std_k * 2 * np.pi) ) * A * (hh/50) ** k * np.exp( -1*(k - mean_k)**2 / (2 * std_k **2 ) - (A - mean_A)**2 / (2 * std_A**2))

def func():
    outer_sum = 0
    dk = 0.01 #0.000001
    for k in np.arange(dk, 0.4, dk):
        inner_sum = 0
        for A in np.arange(dk, 20, dk):
            inner_sum += dk * f_big(A, k, 1e-5, 1e-5)
        outer_sum += inner_sum * dk

    return outer_sum

@nb.jit(nopython=True)
def f_big_nb(A, k, std_A, std_k, mean_A=10, mean_k=0.2, hh=100):
    return ( 1 / (std_A * std_k * 2 * np.pi) ) * A * (hh/50) ** k * np.exp( -1*(k - mean_k)**2 / (2 * std_k **2 ) - (A - mean_A)**2 / (2 * std_A**2))

@nb.jit(nopython=True)
def func_nb():
    outer_sum = 0
    dk = 0.01 #0.000001
    X = np.arange(dk, 0.4, dk)
    Y = np.arange(dk, 20, dk)
    for i in xrange(X.shape[0]):
        k = X[i] # faster to do lookup than iterate over an array directly
        inner_sum = 0
        for j in xrange(Y.shape[0]):
            A = Y[j]
            inner_sum += dk * f_big_nb(A, k, 1e-5, 1e-5)
        outer_sum += inner_sum * dk

    return outer_sum

rawDescription: Use numba to speed up for loop

description: Use numba to speed up for loop


code:
from twisted.internet.protocol import ClientCreator

ClientCreator(reactor, YourProtocol, reactor).connectTCP(...)

rawDescription: What is the preferred way to pass the reactor to a protocol in Twisted?


rawDescription: Hierarchical Tags in Google App Engine ndb


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label

class AppLayout(BoxLayout):
    def __init__(self, **kwargs):
        super(AppLayout, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.padding = [10, 10, 10, 10]
        self.text_bar = TextInput(hint_text='Write Something',
                                  multiline=False,
                                  padding=[5, 5, 5, 5],
                                  font_size=20,
                                  size_hint=(0.8, 1))
        self.button = Button(text="Do Something",
                                    size_hint=(0.2, 1))

        self._text_bar_box = BoxLayout(pos_hint={'top': 1},
                                       size_hint=(1, 0.04),
                                       orientation='horizontal')
        self._text_bar_box.add_widget(self.text_bar)
        self._text_bar_box.add_widget(self.button)
        self.add_widget(self._text_bar_box)

        self.label = Label(text="Your text will be displayed here", font_size=20)
        self._big_box = BoxLayout(padding=[10, 10, 10, 10],
                                  size_hint=(1, 0.65))
        self._big_box.add_widget(self.label)
        self.add_widget(self._big_box)

class AppController:
    def __init__(self, app_layout= AppLayout):
        self.app_layout = app_layout
        self.app_layout.button.bind(on_press=self.get_string)

    def get_string(self, *args):
        self.app_layout.label.text = self.app_layout.text_bar.text

class MainApp(App):

    def build(self):
        app_layout = AppLayout()
        self._controller = AppController(app_layout)
        return app_layout

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

rawDescription: Separate layout and controller in kivy gui


code:
from matplotlib.ticker import FuncFormatter

fig, ax2 = plt.subplots(1, 1)

im = rand(400, 400)
ax2.imshow(im, interpolation='none', origin='bottom')

nbins = 5
scale_factor = .5
form_fun = lambda x, i, scale_factor=scale_factor: '{:.3f}'.format(scale_factor * x)
ax2.get_xaxis().set_major_formatter(FuncFormatter(form_fun))
ax2.get_yaxis().set_major_formatter(FuncFormatter(form_fun))
ax2.get_xaxis().get_major_locator().set_params(nbins=nbins)
ax2.get_yaxis().get_major_locator().set_params(nbins=nbins)

rawDescription: Fits image input to a range in plot - Python


code:
results = [x for x in results if x%newnumber!=0]
results.append(newnumber)

rawDescription: deconstructing word solution

description: Deconstructing word solution


code:
def filter_duplicates(items):
  """A generator that ignores subsequent entires that are duplicates

  >>> items = [0, 1, 1, 2, 3, 3, 3, 4, 1]
  >>> list(filter_duplicates(items))
  [0, 1, 2, 3, 4, 1]

  """
  prev = None
  for item in items:
    if item != prev:
        yield item
        prev = item

rawDescription: Python, efficient way to operate on pair of coordinates


code: filter(lambda d: d['name'], ToD)

rawDescription: How should I remove all dicts from a list that have None as one of their values?


code:
def product(*iterables, **kwargs):
    if len(iterables) == 0:
        yield ()
    else:
        iterables = iterables * kwargs.get('repeat', 1)
        it = iterables[0]
        for item in it() if callable(it) else iter(it):
            for items in product(*iterables[1:]):
                yield (item, ) + items

rawDescription: Cartesian product of large iterators (itertools)


code: df.ix[:,'Col2':] # to select Col2, Col3, ...

rawDescription: How to select n-1 column in a dataframe

description: Select n-1 column in a dataframe


code:
def __call__(self, event):
    self.event = event
    xdata, ydata = event.artist._offsets[:,0], event.artist._offsets[:,1]
    #self.x, self.y = xdata[event.ind], ydata[event.ind]
    self.x, self.y = event.mouseevent.xdata, event.mouseevent.ydata
    if self.x is not None:
        city = clim['Name'][event.ind[0]]
        if city == self.annotation.get_text() and self.annotation.get_visible():
            # You can click the visible annotation to remove it
            self.annotation.set_visible(False)
            event.canvas.draw()
            return
        self.annotation.xy = self.x, self.y
        self.annotation.set_text(city)
        self.annotation.set_visible(True)
        event.canvas.draw()

rawDescription: Pop up annotations on matplotlib within wxPython


code:
from selenium import webdriver

dr = webdriver.PhantomJS()

dr.get("www.foo.bar/baz")

dr.find_element_by_xpath("//a[@href='javascript:showContent()']").click()

rawDescription: BeautifulSoup: scrape HTML only accessible after clicking "Accept" in the same URL


code: text_new = [p.sub(r"<tag>\1</tag>", word) for word in text]

rawDescription: How to find words from list of words in another list

description: Find words from list of words in another list


code:
import matplotlib.pyplot as plt

# make the pie circular by setting the aspect ratio to 1
plt.figure(figsize=plt.figaspect(1))
values = [3, 12, 5, 8]
labels = ['a', 'b', 'c', 'd']

def make_autopct(values):
    def my_autopct(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        return '{p:.2f}%  ({v:d})'.format(p=pct,v=val)
    return my_autopct

plt.pie(values, labels=labels, autopct=make_autopct(values))
plt.show()

rawDescription: How do I use matplotlib autopct?

description: Use matplotlib autopct


code:
with open(afinn_filename, 'rb') as infile:
    reader = csv.reader(infile, delimiter='\t')
    afinn = {key.decode('utf8'): int(score) for key, score in reader}

rawDescription: python re.compile and split with ÆØÅ charcters

description: Python re.compile and split with ÆØÅ charcters


rawDescription: Iterate through triple nested tuple Python 3.4


code:
fruits.pop('apple')
print( fruits )

rawDescription: How do I generate a list for each list item

description: Generate a list for each list item


code:
rng = rng.take(rng.indexer_between_time('09:30','16:00'))
rng

rawDescription: Pandas: Generate Sequential Timestamp with Jump


code:
#create the full structure:  output_rows
primofile = csv.reader(open(file, 'rb'), delimiter=";", quotechar='|')
output_rows = []
for row in primofile:
    output_rows.append([row[2], row[15]])

rawDescription: CSV files and Python

description: CSV files and Python


code: Location = [0, 2, 4]

rawDescription: Append index of items in one list to another in Python 2.7


code:
for i in range(ord('a'), ord('z') + 1):
    text.bind('<Control-Key-'+chr(i)+'>',  key)

rawDescription: tkinter shortcuts impossible to enable

description: Tkinter shortcuts impossible to enable


code:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def wait_for_element(self, elm, by = 'id', timeout=10):
    wait = WebDriverWait(self.driver, timeout)
    wait.until(EC.presence_of_element_located((By.XPATH, elm)))
    return self.driver.find_element_by_xpath(elm)
    wait_for_element(self,
                     "//span[@data-input-id='id_branch-autocomplete']/span[@data-value='1']",
                     "xpath").click()

rawDescription: Django - Selecting Autocomplete-Light choices with Selenium


code:
def my_handler(self, old, new):
    if old is self.my_text_edit:
        print('focus out')
    elif new is self.my_text_edit:
        print('focus in')

rawDescription: How can I intercept when a widget loses its focus

description: Intercept when a widget loses its focus


code:
def comb(S):
    if not '?' in S:
        yield S
    else:
        for i in comb(S.replace('?','0',1)):
            yield i
        for i in comb(S.replace('?','1',1)):
            yield i
for s in comb('abc?def?'):
    print(s)
for s in comb('0?1?'):
    print(s)
S = '0?1??011'
for s in comb(S):
    print(s)

rawDescription: Replace a character with multiple characters using Python


rawDescription: How to counter at even numbers only

description: Counter at even numbers only


code: domains = [matching['domain'] for matching in matchings if matching['id'] == the_id]

rawDescription: What's the most efficient way to access sibling dictionary value in a Python dict?


code:
from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')
setup(
  options = {
    'py2exe' : {
        'compressed': 1,
        'optimize': 2,
        'bundle_files': 3, #Options 1 & 2 do not work on a 64bit system
        'dist_dir': 'dist',  # Put .exe in dist/
        'xref': False,
        'skip_archive': False,
        'ascii': False,
        }
        },
  zipfile=None,
  console = ['thisProject.py'],
)

rawDescription: 15 Python scripts into one executable?

description: 15 Python scripts into one executable


code:
title = 'cats'
substrings = {title[a:a+k] for k in range(1,1+len(title))
             for a in range(1+len(title)-k)}

rawDescription: Split string into all possible search strings


code:
import urllib2
import urllib
import random

CAproxies = [{"http":"199.201.122.175:3128", "https":"199.201.122.175:3128"},{"http":"192.99.3.129:3128", "https":"192.99.3.129:3128"},{"http":"192.99.246.101:8118", "https":"192.99.246.101:8118"},{"http":"205.205.129.130:443", "https":"205.205.129.130:443"} ]

proxies = urllib2.ProxyHandler(random.choice(CAproxies))

url = 'https://store.playstation.com/#!/en-ca/movies/the-house/cid=UV0130-NPVA92773_CN-0000000000236063'

request = urllib2.Request(url)
request.add_header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0")
request.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

opener = urllib2.build_opener(proxies)
urllib2.install_opener(opener)
r = urllib2.urlopen(request, timeout=15)
html = r.read()

rawDescription: Request from different Country IP

description: Request from different Country IP


code:
def get_string(self, **kwargs):

    """Return string representation of table in current state.
       ...
    """

rawDescription: How do I save table from prettytable >

description: Save table from prettytable >


code:
np.linspace(-5, 5, 10)
np.linspace(-5, 5, 10, endpoint=False)
np.arange(-5, 5, 1.)

rawDescription: Subtracting values to contour map axis python


code:
L = []
for i in range(3,6):
    L = L + [np.array(range(1,i))]

rawDescription: how to stack numpy array in a list

description: Stack numpy array in a list


code: df

rawDescription: writing to CSV in python

description: Writing to CSV in python


code:
class MyClass(object):
    def __init__(self, authenticate=None, authorize=None):
        if authenticate is None:
            authenticate = default_authenticate
        if authorize is None:
            authorize = default_authorize
        self.authenticate = authenticate
        self.authorize = authorize
    def request(self, user, password, action):
        self.authenticate(user, password)
        self.authorize(user, action)
        self._do_request(action)

...
helper = AuthService(...)
# Pass bound methods to helper.authenticate and helper.authorize to MyClass.
inst = MyClass(authenticate=helper.authenticate, authorize=helper.authorize)
inst.request(...)

rawDescription: How to do dependency injection python-way?

description: Do dependency injection python-way


code:
from symbolic import *
x = Symbol('x')
x+x

rawDescription: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?


code:
from tweepy.utils import import_simplejson
json = import_simplejson()

rawDescription: Extracting only tweets of a particular # hastag


code:
from collections import defaultdict
catalog = defaultdict(int)
for line in input_file:
    catalog[line] += 1

rawDescription: Using conditionals with variable strings in python


rawDescription: how to keep the precision when convert string to double value

description: Keep the precision when convert string to double value


code:
for i in xrange(len(yourList)-1, -1, -1):
    item = yourList[i]
    ...

rawDescription: Best method for changing a list while iterating over it


code:
s1 = xray.DataArray(np.random.randn(3,256,256), dims=['voltage', 'x', 'y'])
s2 = xray.DataArray(np.random.randn(3,256,256), dims=['voltage', 'x', 'y'])
ds = xray.Dataset({'SNMOS': s1, 'SPMOS': s2})
ds

rawDescription: Best data structure to use in python to store a 3 dimensional cube of named data


code:
if args.option1 and not args.option2:
    parser.error('some error')

rawDescription: argparse with different modes

description: Argparse with different modes


code:
(lambda x: x and x - 1)(('abcd'.find('b') + 1) or None)
(lambda x: x and x - 1)(('abcd'.find('_') + 1) or None)

rawDescription: Expression evaluating to None when substr is not found


rawDescription: How to extract the attributes of a function of an instance passed as a function?

description: Extract the attributes of a function of an instance passed as a function


code:
np.tensordot(a,a,(1,1))
np.diagonal(np.rollaxis(np.tensordot(a,a,(1,1)),1),0,2).T  # with cleanup

rawDescription: Black voodoo of NumPy Einsum

description: Black voodoo of NumPy Einsum


code: rais = [i for i,d in enumerate(Player_list) if d['LastName'].startswith("Rai")]

rawDescription: python list of dict find value starts with

description: Python list of dict find value starts with


code:
import pandas as pd
data = pd.DataFrame({'date':[2000, 2001, 2002, 2003], 'type':['A', 'B', 'A', 'C']})
data['date'] = data['date'].astype('int64')

rawDescription: Changing the dtype for specific columns in a pandas dataframe


code:
"http://www.ivona.com/voicetest.php?rtr=1&t2r=%(the_text)s..&v2r=dXNfc2FsbGk.&lang=us" % dict(
    the_text=base64.b64encode("Hello, world!"),
    the_voice=base64.b64encode("us_salli"),
    )

rawDescription: Download a file from a site (partly written in Javascript) using Python


code:
box1 = gtk.HBox()
label1 = gtk.Label("Label 1")
box1.pack_start(label1)

box2 = gtk.HBox()
label2 = gtk.Label("Label 2")
box2.pack_start(label2)

box3 = gtk.HBox()
label3 = gtk.Label("Label 3")
box3.pack_start(label3)

box.pack_start(box1)
box.pack_start(box2)
box.pack_start(box3)

rawDescription: In-place substitution of PyGTK widgets

description: In-place substitution of PyGTK widgets


code:
a,b,c,d,e,f,g,h,j,i,p
a,e,f,g,h,d,e,g,z,g,z
z,z,z,c,x,s,e,f,d,s,f
q,e,r,s,f,t,y,y,u,i,f
e,p,l,l,k,k,z,z,q,e,r
o,i,i,j,l,s,w,e,r,q,g
w,e,r,f,g,s,v,h,d,b,z
t,r,y,e,u,i,o,p,d,f,j

rawDescription: python: How to compare values in a list by row?

description: Python: How to compare values in a list by row


code:
import autopep8
import imp

try:
    import dodgymodule
except TabError as e:
    with open(e.filename, 'r') as f:
        new_module_contents = autopep8.fix_code(f.read())
        dodgymodule = imp.new_module('dodgymodule')
        exec(new_module_contents, dodgymodule.__dict__)

dodgymodule.somefunc()

rawDescription: how to make python ignore the -tt option

description: Make python ignore the -tt option


code:
from collections import defaultdict
class missingdict(defaultdict):
    def __missing__(self, key):
        return self.default_factory()

d = missingdict(list)
d['foo']
d

rawDescription: Python defaultdict that does not insert missing values


rawDescription: Complex dataframe plotting with Pandas / Matplotlib


code:
def curry_function(function, first, second):
    return lambda third: function(first, second, third)

f = curry_function(f, "dummy1", "dummy2")

rawDescription: How to pass an integer series as argument to a python function?

description: Pass an integer series as argument to a python function


code:
class A(base):
    def calc(self, x, a=a):
        self.last_result = a(x)
        return self.last_result

rawDescription: Python dynamically generate dependencies between class instances


code:
def removePunctuation(text):
    return re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', text.lower())

rawDescription: Remove special character and apostrophe and unwanted space in string using re.sub function in python


code:
import subprocess

subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)

rawDescription: How can I execute shell command with a | pipe in it

description: Execute shell command with a | pipe in it


rawDescription: replacing a string in a text file

description: Replacing a string in a text file


code:
import numpy as np
height, width = 20,20

# Make an array with 4 bands of uint8 integers
image = np.zeros((height, width, 4), dtype=np.uint8)

# Filling a single band (red)
b,g,r,a = image.T
r.fill(255)

# Fill the image with yellow and leave alpha alone
image[...,:3] = (255, 255, 0)

# Then when we want to view it as a single, 32-bit band:
image32bit = image.reshape(-1).view(np.uint32).reshape(height, width)
# (Note that this is a view. In other words,  we could change "b" above
#  and it would change "image32bit")

rawDescription: Plotting directly to movie with numpy and mencoder


code:
m = MyClass('World')
m.member
m.member = 'Hello Planet Earth!'
m.member
m._member

rawDescription: Python class members confusion

description: Python class members confusion


code:
table = pd.pivot_table(apps, index=['app_name', 'date'],
                       columns=['is_match'],
                       values = 'rewards_count')
table['total'] = table[False] + table[True]
table['percent_false']  = table[False] / table.total * 100
table['percent_true']  = table[True] / table.total * 100

rawDescription: Pandas Column Calculations in PivotTable


code:
def textOf(soup):
    return u''.join(soup.findAll(text=True))

rawDescription: BeautifulSoup - easy way to to obtain HTML-free contents


code: format(x, 'x')

rawDescription: python change str to hex, NOT CONVERTING

description: Python change str to hex, NOT CONVERTING


rawDescription: Integrate histogram in python?

description: Integrate histogram in python


rawDescription: How can I iterate and apply a function over a single level of a DataFrame with MultiIndex?

description: Iterate and apply a function over a single level of a DataFrame with MultiIndex


code:
second
fifth
fourth
third
first

rawDescription: How do I loop a set of strings in reverse in Python?

description: Loop a set of strings in reverse in Python


rawDescription: How to join multiple params dynamically for django Q object

description: Join multiple params dynamically for django Q object


code:
syntax = self.view.settings().get("syntax")
syntax.endswith("Perl.tmLanguage") or syntax.endswith("Perl.sublime-syntax")

rawDescription: Get file syntax selection in sublime text 3 plugin


code:
for i in range(len(name)):
    print(name[i].ljust(20,' '),sport[i].ljust(20,' '),age[i].ljust(20,' '))

rawDescription: How do I display tuples in columns? [Python]

description: Display tuples in columns? [Python]


code:
header_list = ['First Name: ', 'Last Name: ', 'Phone: ', 'City: ', 'State: ', 'Zip: ']
client_list = ['Joe', 'Somebody', '911']

for head, entry in zip(header_list, client_list):
    print(head, entry)

rawDescription: How to loop through a list inside of a loop

description: Loop through a list inside of a loop


code:
var = 1
var2 = var
var = 2

rawDescription: python: imported module is in a different context

description: Python: imported module is in a different context


code:
class Email(models.Model):
    """
    Model to store all the outgoing emails.
    """
    when = models.DateTimeField(
        null=False, auto_now_add=True
    )
    to = models.EmailField(
        null=False, blank=False,
    )
    subject = models.CharField(
         null=False, max_length=128,
    )
    body = models.TextField(
        null=False, max_length=1024,
    )
    ok = models.BooleanField(
        null=False, default=True,
    )

rawDescription: How can I log all outgoing email in Django?

description: Log all outgoing email in Django


rawDescription: Python: how to compare not operator with 'not' string?


code: patch_collection = mpl.collections.PatchCollection(patches,cmap=matplotlib.cm.jet, norm=matplotlib.colors.LogNorm(), lw=0)

rawDescription: Log Scale Matplotlib PatchCollection Colors


code:
@classmethod
def says(cls, *arg, **kw):
    return cls.to_past_tense(cls, super().says)(*arg, **kw)

rawDescription: Override the value of a static variable while using decorator


code: import tkinter.filedialog as fdialog

rawDescription: filedialog, tkinter and opening files

description: Filedialog, tkinter and opening files


code:
def select_elements(seq, perc):
    """Select a defined percentage of the elements of seq."""
    return seq[::int(100.0/perc)]

rawDescription: How should a certain percentage of evenly-distributed elements of a Python list be extracted?


code: k = np.arange(1, N+1)

rawDescription: Filling a numpy array using an arbitrary function


code:
def pict_test(audio):
    try:
        x = audio.pictures
        if x:
            return True
    except Exception:
        pass
    if 'covr' in audio or 'APIC:' in audio:
        return True
    return False

rawDescription: mutagen: how to detect and embed album art in mp3, flac and mp4

description: Mutagen: how to detect and embed album art in mp3, flac and mp4


code:
import numpy as np
a = np.arange(100).reshape((-1,10))
a

rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code:
import pkgutil
import processors

if __name__ == '__main__':
    modules = []
    for loader, name, is_pkg in pkgutil.walk_packages(processors.__path__):
        modules.append(loader.find_module(name).load_module(name))

    # Later in the code when processing is required:
    for module in modules:
        module.process()

rawDescription: Importing all files in a directory as modules, and calling a class method


code:
INDICES = (np.random.rand(COUNT,4)*COUNT).astype(int)
SPLIT = POINT_CLOUD[INDICES.T]
SPLIT.shape

rawDescription: Split a large numpy array into separate arrays with a list of grouped indices


code:
import datetime
today = datetime.date.today()
filename = 'ex{:02}{:02}{:02}.log'.format(today.year%100, today.month, today.day)
filename

rawDescription: open file named with two digit year-Python

description: Open file named with two digit year-Python


code:
def PRINT_ITEM(f, item):
    if f.softspace:
        f.write(' ')
    f.write(str(item))
    f.softspace = True

def PRINT_NEWLINE(f):
    f.write('\n')
    f.softspace = False

rawDescription: Why there is space in the code example in python threading


code:
arrays = [['Amount', 'Amount', 'Amount', 'Amount', 'dwy', 'dwy', 'dwy', 'dwy', 'bmd', 'bmd', 'bmd', 'bmd'],
          ['EUR', 'GBP', 'JPY', 'USD', 'EUR', 'GBP', 'JPY', 'USD', 'EUR', 'GBP', 'JPY', 'USD']]

tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=['Portfolio', 'Currency'])

data = [100, 200, 300, 400, -0.5, 0.5, 0, 0.8, 3.8, 3, 0, 3]

df = pd.DataFrame(data).T
df.columns = index
df.index = ['2016-05-13']

rawDescription: How can I rearrange a DataFrame with Pandas?

description: Rearrange a DataFrame with Pandas


code: x[(x.start >= some_start) & (x.end <= some_end)]

rawDescription: conditionly selecting a portion of a dataframe rows

description: Conditionly selecting a portion of a dataframe rows


code:
for command in 'F+F-F++FF':
   map[command]()

rawDescription: Assigning turtle commands to variables and recalling them on python


code:
from itertools import groupby
def speaker_times(a):
    result = []
    for item in groupby(a, lambda x:x[2]):  # Group by speaker name
        values = list(item[1])              # Convert iterator to list
        result.append((min(values)[0], max(values)[1], item[0]))
    return result

rawDescription: Find intervals given a list of tuples

description: Find intervals given a list of tuples


code: reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"

rawDescription: Python change an array's value from array index


code:
from glob import iglob
import os

files = []
ext = "py"
for dirpath, dirnames, file in os.walk(path):
    match = next(iglob(os.path.join(dirpath, "2*")),"")
    if match:
        files.extend(iglob(os.path.join(match,"*.{}".format(ext))))
print(files)

rawDescription: Recursively expand and search pattern of specific subdirectories


code:
import subprocess
subprocess.call(['open', '-a', 'TextEdit', file])

rawDescription: How do I open a text file in TextEdit from Python on Mac?

description: Open a text file in TextEdit from Python on Mac


code:
from hashlib import md5
from werkzeug import check_password_hash, generate_password_hash
from CodernityDB.database_thread_safe import ThreadSafeDatabase
from CodernityDB.database import RecordNotFound

#indexTypes

from CodernityDB.hash_index import HashIndex
from CodernityDB.tree_index import TreeBasedIndex

class UserIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = '16s'
        super(UserIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        if data['t'] == 'user':
            username = data['username']
            return md5(username).digest(), {'user_id': data['user_id'], 'email': data['email']}

    def make_key(self, key):
        return md5(key).digest()

class UserIDIndex(HashIndex):

    def __init__(self, *args, **kwargs):
        kwargs['key_format'] = 'I'
        super(UserIDIndex, self).__init__(*args, **kwargs)

    def make_key_value(self, data):
        if data['t'] == 'user':
            user_id = data['user_id']
            return user_id, {'username': data['username'], 'email': data['email']}

    def make_key(self, key):
        return key

#Functions
def register(username_input,email_input,password_input):
    """Registers the user."""

    try:
        cdb.get('user', username_input, with_storage=False)
    except RecordNotFound:
        cdb.insert(dict(
                    t='user',
                    user_id=cdb.count(cdb.all, 'user') + 1,  # do not use in production!
                    username=username_input,
                    email=email_input,
                    pw_hash=generate_password_hash(password_input)))
        print('You were successfully registered')
    else:
        print('The username is already taken')

# configuration
DATABASE = 'testDB'
SECRET_KEY = 'development key'
cdb = ThreadSafeDatabase(DATABASE)

#main
def main():
    if cdb.exists():
        cdb.open()
        cdb.reindex()
    else:
        #from database_indexes import UserIndex, MessageAllIndex, MessageUserIndex, FollowerRel1Index, FollowerRel2Index, UserIDIndex, FollowerIndex
        cdb.create()
        cdb.add_index(UserIndex(cdb.path, 'user'))
        cdb.add_index(UserIDIndex(cdb.path, 'user_id'))

    #test insert
    username_input="none"
    print("type 'n' to end database population")
    while username_input != "n":
        username_input = raw_input("new username: ")
        email_input = raw_input("new email: ")
        password_input = raw_input("new password: ")
        register(username_input,email_input,password_input)

#Run Main
if __name__ == '__main__':
    main()

rawDescription: codernitydb index with string value

description: Codernitydb index with string value


rawDescription: How to convert numpy datetime64 into datetime

description: Convert numpy datetime64 into datetime


code:
file = [file for file in zipfilelist.namelist() if file.split('/')[-1] == target]
if file:
    tmp = archive.read(file[0])
    with NamedTemporaryFile(delete=False) as f:
        f.write(tmp)
        return f.name

rawDescription: Traversing ZIP Files

description: Traversing ZIP Files


code:
lis=[1,2,3]
x=lis
x is lis  #both point to the same object
x=lis[:]  #create a shallow copy
x is lis

rawDescription: How to reinitialize list in loop iteration?

description: Reinitialize list in loop iteration


code: element.style.display = '';

rawDescription: How to hide a row of table (or a list item) and update the datastore without reloading the page?

description: Hide a row of table (or a list item) and update the datastore without reloading the page


code:
e.elementB[3].value = 'abc\x00def'
e.elementB[3].value
e.elementB[3].raw

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code:
def weighted_choice_bisect(items):
    added_weights = []
    last_sum = 0

    for item, weight in items:
        last_sum += weight
        added_weights.append(last_sum)

    return items[bisect.bisect(added_weights, random.random() * last_sum)][0]

rawDescription: Probability distribution in Python

description: Probability distribution in Python


rawDescription: Calculate during merge using pandas

description: Calculate during merge using pandas


code:
mat = []

def test_append():
    for i in range(10):
        #mat += [i]
        mat.append(i)

def test_iadd2(mat):
    for i in range(10):
        mat += [i]

test_append()
print(mat)
test_iadd2(mat)
print(mat)

rawDescription: Why is list.append(x) more efficient than list += l[x]?


code:
from SendKeys import SendKeys

SendKeys(r"""
    {LWIN}
    {PAUSE .25}
    r
    C:\Path\To\tsfoil2.exe{ENTER}
    {PAUSE 1}
    I:\{ENTER}
    {PAUSE 1}
    test{ENTER}
    {PAUSE 1}
    SC20610.inp{ENTER}
    {PAUSE 1}
    {ENTER}
""")

rawDescription: How to handle an executable requiring interactive responses?

description: Handle an executable requiring interactive responses


code:
from string import digits
allowed = set(digits).union('/-')
all(c in allowed for c in '2015-07-01')
all(c in allowed for c in '2015-Jul-01')

rawDescription: How to check if a string contains only [numbers OR special characters] in python

description: Check if a string contains only [numbers OR special characters] in python


code:
class B(object):
    def __init__(self, creator):
        self._creator = creator   # or do something else with it

rawDescription: How to reference creator object in Python?

description: Reference creator object in Python


code:
from random import randint

def getNum1To4(runs):
    occurences = {n+1:0 for n in range(4)}
    for i in range(runs):
        options = [n for n in occurences if occurences[n] < runs / 4]
        choice = options[randint(0, len(options) - 1)]
        occurences[choice] += 1
        yield choice

rawDescription: How do I generate a sequence of integer numbers in a uniform distribution?

description: Generate a sequence of integer numbers in a uniform distribution


rawDescription: Table join using the Django ORM

description: Table join using the Django ORM


code:
a=np.array([0,1,1,1,1,10,10,10,10,0])
scipy.integrate.simps(a)
scipy.integrate.simps(a[:5])
scipy.integrate.simps(a[5:])

rawDescription: Using scipy to perform discrete integration of the sample


code:
import datetime

date1, time1 = '2012-09-08', '12:23:33'
date2, time2 = '2012-09-08', '12:23:33'

dt1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
dt2 = datetime.datetime.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")

print (dt1 - dt2).total_seconds()

rawDescription: what's the fastest way of converting a string time stamp into epoch time with python?

description: What's the fastest way of converting a string time stamp into epoch time with python


rawDescription: Extracting last character from a string in python?


code:
def trunc_GBL(p, x, threshold):
    loc=p[0]
    scale=p[1]
    x1=x[x<threshold]
    nx2=len(x[x>=threshold])
    L1=(-np.log((gumbel_pdf(x1, loc, scale)/scale))).sum()
    L2=(-np.log(1-gumbel_cdf(threshold, loc, scale)))*nx2
    #print x1, nx2, L1, L2
    return L1+L2

rawDescription: How to find parameters of gumbel's distribution using scipy.optimize

description: Find parameters of gumbel's distribution using scipy.optimize


code: [frac.split('/')[0] for frac in c.split(',')]

rawDescription: What's wrong with this nested list comprehension?


code:
def func_uses_mean_and_std(mean=None, std=None, **kwargs):
    ...

features = instance.extractFeatures()
result = func_uses_mean_and_std(**features)

rawDescription: Organize values of nested tuples in a single tuple


code:
limit_msec = 40000    # user-defined value in milliseconds
limit_timedelta = timedelta( milliseconds=limit_msec )

rawDescription: time delta parameter in python script

description: Time delta parameter in python script


rawDescription: How to update from json a Mongoengine DynamicDocument

description: Update from json a Mongoengine DynamicDocument


code:
import lxml

text = """

    This tag includes 'some_text'

A h2 tag

"""

doc = lxml.etree.fromstring(text, parser=lxml.etree.HTMLParser())
doc.xpath("//*[contains(text(),'some_text')]/following-sibling::*")
# [<Element h2 at 102eee100>]

doc = lxml.html.fromstring(text)
doc.xpath("//*[contains(text(),'some_text')]/following-sibling::*")
# [<Element h2 at 102f6f188>]

rawDescription: How to get siblings when using contains(text(), ) in xpath

description: Get siblings when using contains(text(), ) in xpath


code:
class System(object):
    type_ = "Base system"
    def __init__(self, sitenum, devicenum, IP):
        self._sitenum = sitenum
        self._devicenum = devicenum
        self._IP = IP
        # the leading underscores are a flag to future coders that these are
        # "private" variables. Nothing stopping someone from using it anyway,
        # because System()._IP is still that attribute, but it makes it clear
        # that they're not supposed to be used that way.
    @staticmethod
    def ping_system(IP):
        subprocess.call(["ping",IP], shell=True) # OH GOD SECURITY FLAW HERE
        # group this with Systems because maybe that's how I want it? It's an
        # aesthetic choice. Note that this pings ANY system and requires an
        # argument of an IP address!
    @classmethod
    def type_of_system(cls):
        return cls.type_
        # imagine I had a bunch of objects that inherited from System, each w/
        # a different type_, but they all inherit this....
    @property
    def description(self):
        return "Site {}, Device {} @ {}".format(self._sitenum,
                                                self._devicenum,
                                                self._IP)
    @description.setter
    def description(self, *args):
        if len(args) == 3:
            self._sitenum, self._devicenum, self._IP = args
        elif len(args) == 1 and len(args[0]) == 3:
            self._sitenum, self._devicenum, self._IP = args[0]
        else:
            raise ValueError("Redefine description as Sitenum, Devicenum, IP")

rawDescription: python classes getters and setters static method and class method

description: Python classes getters and setters static method and class method


code:
import wx
import wx.grid as gridlib

########################################################################
class MyForm(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, parent=None, title="A Simple Grid")
        panel = wx.Panel(self)

        myGrid = gridlib.Grid(panel)
        myGrid.CreateGrid(12, 8)
        myGrid.SetColLabelValue(0, "ID")
        myGrid.SetColLabelValue(1, "Name")
        myGrid.SetColLabelValue(2, "Lastname")
        myGrid.SetColLabelValue(3, "01-Jan-13")
        # etc. etc.

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(myGrid, 1, wx.EXPAND)
        panel.SetSizer(sizer)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm().Show()
    app.MainLoop()

rawDescription: How to set wxpython Grid top headers?

description: Set wxpython Grid top headers


code:
import clr
clr.AddReference("ClassLibrary1")
from ClassLibrary1 import Class1

Class1.MyMethod(1234, "test")

rawDescription: IronPython - emit warning from C#

description: IronPython - emit warning from C#


code: dfm = pd.read_csv('/path/to/map.csv', delim_whitespace=True, index_col=[0,1])

rawDescription: python pandas - map using 2 columns as reference

description: Python pandas - map using 2 columns as reference


code: re.findall(r"\w+", "CHROMOSOME_IV ncRNA gene 5723085 5723105 . - . ID=Gene:WBGene00045518 CHROMOSOME_IV ncRNA ncRNA 5723085 5723105 . - . Parent=Gene:WBGene00045518")

rawDescription: python beginner - faster way to find and replace in large file?

description: Python beginner - faster way to find and replace in large file


code:
def defer_huge_operation(w):
    ...
    yield x
    ...
    ...
    ...
    yield y

op = defer_huge_operation(w)
x = next(op)
...
...
y = next(op)

rawDescription: Python: How to condition the execution of a part of a function on the return values


code:
Title: song1
Artist: artist1
Directory: dir1

Title: song2
Artist: artist2
Directory: dir2

Title: song3
Artist: artist3
Directory: dir3

rawDescription: How to print out __str__ for each instance of a class in a loop

description: Print out __str__ for each instance of a class in a loop


code: {{ django_version }}

rawDescription: Django template tag to display Django version


code: Memoized.__cache[self.key] = {args : value}

rawDescription: What can be done to speed up this memoization decorator?


code:
from z3c.form import field
from plone.app.z3cform.layout import wrap_form
from collective.documentviewer.views import GlobalSettingsForm
class CustomGlobalSettingsForm(GlobalSettingsForm):
    fields = field.Fields(IEnhancedDocumentViewerSchema)
CustomGlobalSettingsFormView = wrap_form(CustomGlobalSettingsForm)

rawDescription: Plone - Override Zope Schema fields

description: Plone - Override Zope Schema fields


rawDescription: Is there way to use dictionary in python to print 2 outputs: one as string of whole token and one as number


rawDescription: Maintaining session in an Eventlet page scraper?


code:
def has_id_en(elem):
    return elem.get('id', '').startswith('en')

def segment(sequence, is_head):
  current = []
  for x in sequence:
      if is_head(x):
          if current:
              yield current
              current = []
      current.append(x)
  if current:
      yield current

text_list = [' '.join(e.text for e in bunch)
             for bunch in segment(line_list, has_id_en)]

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


code:
temp = integer // base
value = integer - temp * base
integer = temp

rawDescription: Divmod alternative method

description: Divmod alternative method


code: ['1', 'Flat 5, Park Street']

rawDescription: Remove unwanted commas from CSV using Python


code: re.match(r, t, flags=re.U).group()

rawDescription: Regex for file encoded with CP1252

description: Regex for file encoded with CP1252


code:
#instead of my_frame.Close() (or my_frame.Destroy())
my_frame.Hide()

rawDescription: wxPython: How the radio buttons can remember my choice when I close the frame

description: WxPython: How the radio buttons can remember my choice when I close the frame


code:
@log_begin_end
def myfunc(x,y,z):
    pass  # or do whatever you want

rawDescription: How to simplify python logging code

description: Simplify python logging code


code:
listOfLines = ['hi there', 'how are you']
for word in words(listOfLines):
    print(word)

rawDescription: How to split a text file to its words in python?

description: Split a text file to its words in python


code:
class Expr(object):

    def __init__(self, op, left, right):
        self.op = op
        self.left = left
        self.right = right

    def __call__(self, current):
        l = self._replace_current(self.left, current)
        r = self._replace_current(self.right, current)
        return self._do_operation(l, r)

    def _replace_current(self, val, current):
        if val == 'current':
            return current
        elif isinstance(val, Expr):  # recurse
            return val(current)
        else:
            return val

    def _do_operation(self, l, r):
        if self.op == '+':
            return l + r
        elif self.op == '*':
            return l * r
        elif self.op == '-':
            return l - r

    def __add__(self, other):
        return self._left_op('+', other)

    def __radd__(self, other):
        return self._right_op('+', other)

    def __mul__(self, other):
        return self._left_op('*', other)

    def __rmul__(self, other):
        return self._right_op('*', other)

    def __sub__(self, other):
        return self._left_op('-', other)

    def __rsub__(self, other):
        return self._right_op('-', other)

    def _left_op(self, op, other):
        if isinstance(other, Current):
            return Expr(op=op, left=self, right='current')
        else:
            return Expr(op=op, left=self, right=other)

    def _right_op(self, op, other):
        if isinstance(other, Current):
            return Expr(op=op, left='current', right=self)
        else:
            return Expr(op=op, left=other, right=self)

class Current(Expr):

    def __init__(self):
        super(Current, self).__init__(None, None, None)

    def __call__(self, current):
        return current

    def _left_op(self, op, other):
        return Expr(op=op, left='current', right=other)

    def _right_op(self, op, other):
        return Expr(op=op, left=other, right='current')

current = Current()

class YourObj(object):

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __call__(self, **kw):
        for key, val in kw.iteritems():
            # You should probably make sure it is actually an attribute of YourObj
            if isinstance(val, Expr):
                current = self.a
                new_val = val(current)
                setattr(self, key, new_val)
            else:
                setattr(self, key, val)

rawDescription: Is it possible to create a variable as a placeholder for 'current' value of a class in python?


code:
s = global_list[1]
x = T.scalar(dtype=theano.config.floatX)
g = theano.function([x], [s], updates=[(s, T.inc_subtensor(s[0, 0], x))])

rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


code:
seta = set(tuple(item) for item in lista)
setb = set(tuple(item) for item in listb)
listc = list(setb.intersection(seta))

rawDescription: coordinating comparisons with lists inside lists lists

description: Coordinating comparisons with lists inside lists lists


code:
def compare(s, t):
    return Counter(s) == Counter(t)

rawDescription: How to efficiently compare two unordered lists (not sets) in Python?

description: Efficiently compare two unordered lists (not sets) in Python


rawDescription: getting a grammar to read more than one keyword in the text

description: Getting a grammar to read more than one keyword in the text


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.toolbar = tk.Frame(self)
        self.toolbar.pack(side="top", fill="x")
        do_button = tk.Button(self.toolbar, text="do it", command=self.do_it)
        undo_button = tk.Button(self.toolbar, text="UNdo it", command=self.undo_it)
        do_button.pack(side="left")
        undo_button.pack(side="left")

        self.text = tk.Text(self, wrap="word", undo=True)
        self.text.pack(fill="both", expand=True)
        with open(__file__, "r") as f:
            self.text.insert("1.0", f.read())

    def do_it(self):
        self.text.edit_separator()
        count = int(self.text.index('end-1c').split('.')[0])
        for i in range(1, count):
            self.text.insert('%d.end' % i, '<br>')
            text = self.text.get("1.0", "end-1c")

    def undo_it(self):
        self.text.edit_undo()

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Python 3.4 Tkinter - How can I just delete a string anywhere in a text widget?


code:
markup = '\nI linked to example.com\n'
soup = BeautifulSoup(markup)
soup.get_text()

rawDescription: Python, remove all html tags from string


code:
for key_value_pair in key_value_pairs:
    key = key_value_pair[0]
    value = key_value_pair[1]

rawDescription: Ask user for key:value pair in Python

description: Ask user for key:value pair in Python


code: A_db_model.all().filter('valueA IN', ['aaa', 'bbb'])

rawDescription: Google app engine or query (python)

description: Google app engine or query (python)


code:
main.py
import wsgiref.handlers

from google.appengine.ext import webapp
from myapp.views import *

application = webapp.WSGIApplication([
  ('/', IndexHandler),
  ('/foo', FooHandler)
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

rawDescription: Project structure for Google App Engine

description: Project structure for Google App Engine


code:
rows = page.xpath('//div[@class="urtwo"]/p//strong')
for element in rows:
    label = element.text.strip()
    value = element.xpath("following-sibling::text()")[0].strip()

    print(label, value)

rawDescription: How to parse a htmlpage with lxml with <br /> screwing up?

description: Parse a htmlpage with lxml with <br /> screwing up


code:
def removeBlankRows(grid):
    return [list(row) for row in grid if any(x is not None for x in row)]

rawDescription: Remove row or column from 2D list if all values (in that row or column) are None


code:
def getCardValue(inputVal): #custom key func that calculates zero as a 10
    num = int(inputVal[:-1])
    if num == 0:
        return 10
    return num

trumpCard = '2D'
tricks = ('9D', '9S', '3S', '0D')
potentialWinners = [x for x in tricks if x[-1] == trumpCard[-1]] #remove cards that don't have same suit as trumpCard
print(max(potentialWinners, key=getCardValue)) #get max card value while calculating zero as 10

rawDescription: Sorting Cards played in each trick according to a certain set of rules


code:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
     return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

rawDescription: How to refer a certain place in a line in Python

description: Refer a certain place in a line in Python


code:
gamma(101)
float(fac(100))

rawDescription: conversion float to long in python

description: Conversion float to long in python


code:
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
       tk.Tk.__init__(self, *args, **kwargs)
       self.frame = tk.Frame(self)
       self.frame.pack(side="top", fill="both", expand=True)
       self.label = tk.Label(self, text="Hello, world")
       button1 = tk.Button(self, text="Click to hide label",
                           command=self.hide_label)
       button2 = tk.Button(self, text="Click to show label",
                           command=self.show_label)
       self.label.pack(in_=self.frame)
       button1.pack(in_=self.frame)
       button2.pack(in_=self.frame)

    def show_label(self, event=None):
        self.label.lift(self.frame)

    def hide_label(self, event=None):
        self.label.lower(self.frame)

def main():
    app = SampleApp()
    app.mainloop()
    return 0

if __name__ == '__main__':
    main()

rawDescription: Lift and raise a Canvas over a Canvas in tkinter


rawDescription: Difference between two time items

description: Difference between two time items


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.loader.processor import TakeFirst
from scrapy.contrib.loader import XPathItemLoader
from scrapy.selector import HtmlXPathSelector

from scrapy.item import Item, Field

class PlayGroundItem(Item):
    title = Field()
    url = Field()
    download_url = Field()

class PlayGroundLoader(XPathItemLoader):
    default_output_processor = TakeFirst()

class PlayGroundSpider(CrawlSpider):
    name = "playground_spider"
    allowed_domains = ["www.playground.ru"]
    start_urls = ["http://www.playground.ru/files/stalker_clear_sky/"]
    rules = (
        Rule(SgmlLinkExtractor(allow=('/files/s_t_a_l_k_e_r_chistoe_nebo')), follow=True, callback='parse_item'),
    )

    def parse_item(self, response):
        hxs = HtmlXPathSelector(response)
        l = PlayGroundLoader(PlayGroundItem(), hxs)
        l.add_value('url', response.url)
        l.add_xpath('title', "//div[@class='downloads-container clearfix']/h1/text()")
        l.add_xpath('download_url', "//div[@class='files-download-holder']/div/a/@href")

        return l.load_item()

rawDescription: Scrapy does not write data to a file

description: Scrapy does not write data to a file


code:
my_list = [1, 2, 3]
dict.fromkeys(my_list)

rawDescription: Is there a better way to convert a list to a dictionary in Python with keys but no values?


code:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

rawDescription: Can I create a sort of cache in DB using django?

description: Create a sort of cache in DB using django


rawDescription: Select a specific column in a DF and a random column (python3, pandas)


code:
from haystack import indexes

class MyIndexClass(indexes.SearchIndex, indexes.Indexable):
    field_1 = indexes.CharField(document=True, use_template=True)
    field_2 = indexes.CharField(model_attr='field_of_MyModelClass_class')
    field_3 = indexes.CharField(model_attr='field_of_MyModelClass_class')

def get_model(self):
    return MyModelClass

rawDescription: Django: Use MySQL and ElasticSearch in single application


rawDescription: Python - append VS extend efficiency

description: Python - append VS extend efficiency


code:
layout = QtGui.QHBoxLayout(self)
Right = QtGui.QVBoxLayout(self)
Left = QtGui.QVBoxLayout(self)

rawDescription: Change my Qdialog to QMainWindow

description: Change my Qdialog to QMainWindow


code:
class Event(db.Model):

    __tablename__ = "event"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    jobs = db.relationship('Job', backref='job_event')

class Job(db.Model):

    __tablename__ = "job"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    event_id = db.Column(db.Integer, db.ForeignKey('event.id'))
    apscheduler_job_id = db.Column(db.TEXT, db.ForeignKey('apscheduler_jobs.id'))

class APSchedulerJobsTable(db.Model):
    # TODO: This feels bad man
    __tablename__ = "apscheduler_jobs"

    id = db.Column(db.TEXT, primary_key=True, autoincrement=True)
    next_run_time = db.Column(db.REAL)
    job_state = db.Column(db.TEXT)
    job = db.relationship('Job', backref='job_event')

rawDescription: How to relate APScheduler JobStore with SQLAlchemy Models (foreign key) - Python Flask

description: Relate APScheduler JobStore with SQLAlchemy Models (foreign key) - Python Flask


code:
class CompanyForm(forms.ModelForm):
    s_address = forms.CharField(label='Address', max_length=500, required=False)

    def __init__(self, *args, **kwargs):
        super(CompanyForm, self).__init__(*args, **kwargs)
        self.fields['s_address'].initial = self.instance.address.address1

    def save(self, commit=True):
        model = super(CompanyForm, self).save(commit=False)
        saddr = self.cleaned_data['s_address']
        if saddr:
            if model.address:
                model.address.address1 = saddr
                model.address.save()
            else:
                model.address = Address.objects.create(address1=saddr)
                # or you can try to look for appropriate address in Address table first
                # try:
                #     model.address = Address.objects.get(address1=saddr)
                # except Address.DoesNotExist:
                #     model.address = Address.objects.create(address1=saddr)

        if commit:
            model.save()

        return model

    class Meta:
        exclude = ('address',) # exclude form own address field

rawDescription: How to make a modelform editable foreign key field in a django template?

description: Make a modelform editable foreign key field in a django template


code:
class RequestsProxy(object):
    def __init__(self):
        self.special_sauce_decorator = special_sauce_indeed()
        self._requests = __import__("requests")

    def __getattr__(self, attrname):
        val = getattr(self._requests, attrname)
        if callable(val):
            return self.special_sauce_decorator(val)
        return val

rawDescription: Automatically execute code in front of module methods


code: result = IT.izip(keys, values)

rawDescription: create a list of dictionaries with randomised elements from two lists - python

description: Create a list of dictionaries with randomised elements from two lists - python


rawDescription: Writing Python lists to columns in csv

description: Writing Python lists to columns in csv


code:
full_links = ["www.google.es", "www.myblog.com.hghg$hfgh%hgh.113124534"]

pattern = "hghg"
full_links = [(x[:x.find(pattern)+len(pattern)] + str(number) + x[x.find(pattern)+len(pattern):]) if pattern in x else x for x in full_links]

rawDescription: Insert a character into a url

description: Insert a character into a url


code:
import pygame, itertools

def fade_into(c1, c2, n):
    """ Give the next color to draw \n"""
    "Args: c1,c2 => colors, n => int"
    dif = [(c1[i]-c2[i])/float(n) for i in range(3)] # calculate the per-frame difference
    return [c1[i]-dif[i] for i in range(3)] # subtract that difference

RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)

FADE_SPEED = 80 # no of frames for shifting

colors = (RED, BLACK, BLUE) # to allow you to iterate over the colors

SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)

# to cycle through the colors
cycle = itertools.cycle(colors)

## needed for fading
c_color = cycle.next() # RED    current_color
n_color = cycle.next() # BLACK  next_color
frames = FADE_SPEED
## --------------

clock = pygame.time.Clock() # regulate fps

while True:
    # handling events
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # close window event
            pygame.quit()

    c_color = fade_into(c_color, n_color, frames) # get next color

    pygame.draw.circle(screen,map(int,c_color),(500,500),200)
    pygame.display.flip()

    frames -= 1
    if frames == 0: # translation complete
        frames = FADE_SPEED
        n_color = cycle.next() # get next color

    clock.tick(40) # run at maximum of 40 frames per second

rawDescription: Basic Pygame Graphics

description: Basic Pygame Graphics


code: numpy.tile(2, 25)

rawDescription: how to create an array of specified dimension of specific type initialized with same value in python?

description: Create an array of specified dimension of specific type initialized with same value in python


code:
subtag2 = etree.Element("subtag2", subattrib2="2")
subtext = etree.SubElement(subtag2, "subtext")
subtext.text = "text2"
tag.insert(1, subtag2)   # Add subtag2 as the second child (index 1) of the root element

rawDescription: lxml: insert tag at a given position

description: Lxml: insert tag at a given position


code:
import numpy as np
from bokeh.plotting import *

N = 100

x = np.linspace(0.1, 5, N)

output_file("logscatter.html", title="log axis scatter example")

figure(tools="pan,wheel_zoom,box_zoom,reset,previewsave",
       y_axis_type="log", y_range=[0.1, 10**2], title="log axis scatter example")

scatter(x, np.sqrt(x), line_width=2, line_color="yellow", legend="y=sqrt(x)")

show()

rawDescription: Log scale using Bokeh's scatter function


rawDescription: Is it possible to use Angular with the Jinja2 template engine?


code:
df = df.sort_values(by='births', ascending=False)
df.groupby(['year', 'sex'], as_index=False).first()

rawDescription: group by values across two columns and filter in Pandas

description: Group by values across two columns and filter in Pandas


code:
class X(object):
  @classmethod
  def clame(cls): pass
  @staticmethod
  def stame(): pass
  def meth(self): pass
  def __init__(self):
    self.lam = lambda: None
    self.val = 23

x = X()
dir(x)

rawDescription: list of methods for python shell?

description: List of methods for python shell


code:
a = 'bad'

def bad_fn():
    a = 'good'
bad_fn()
print('bad_fn() is'+a)

def good_fn():
    global a
    a = 'good'
good_fn()
print('good_fn() is'+a)

rawDescription: Python is not recognizing my variables, but instead replacing them with zero


code:
def system_execute(self, command, path, out_file):
    params_list = command.split(' ')
    file_path = os.path.join(path, out_file)
    f = open(file_path, "w")
    subprocess.call(params_list, stdout=f)
    f.close()

rawDescription: Python subprocess.Popen and asynchronous output


code:
import pandas as pd
import os
import csv
import io

caminho = r'C:\Users\u5en\Documents\SAP\Testes\\'
arquivo = os.path.join(caminho, "ExpComp_01.txt")
arquivo_csv = os.path.splitext(arquivo)[0] + '.csv'

def desmembra(linha, limites):
    # This functions receives each delimiter's index and cuts around it
    return [linha[limites[i]+1:limites[i+1]].strip()
            for i in range(len(limites[:-1]))]

def pre_processa(arquivo, enc):
    # Translates SAP output into an iterator of lists of strings
    with io.open(arquivo, "r", encoding=enc) as entrada:
        for line in entrada:
            # Find heading
            if line[0] == "|":
                delimitadores = [x for x, v in enumerate(line) if v == '|']
                if line[-2] != "|":
                    delimitadores.append(None)
                cabecalho_teste = line[:50]
                yield desmembra(line, delimitadores)
                break
        for line in entrada:
            if line[0] == "|" and line[:50] != cabecalho_teste:
                yield desmembra(line, delimitadores)

def post_process(dados):
    dados['LEADTIME'] = dados['LEADTIME'].astype('int16')
    for col in ('SEND_TIME', 'LOAD_TIME', 'PRICE'):
        dados[col] = dados[col].str.replace(r'.', '')
    for col in ('SEND_TIME', 'LOAD_TIME', 'APPR_TIME'):
        dados[col] = pd.to_datetime(dados[col], format="%Y%m%d%H%M%S")
    return dados

enc = 'mbcs'
saida = pre_processa(arquivo, enc)
header = next(saida)
dados = pd.DataFrame(saida, columns=header)
dados = post_process(dados)
print(dados)

rawDescription: Pre-process data file before pandas read_csv


code:
f = open('nul', 'w')
sys.stdout = f

rawDescription: Redirecting stdout to "nothing" in python


code:
def fitfunc(M,p1,p2):
    N = p1+( (M)*p2 )
    return N

rawDescription: Confidence regions of 1sigma for a 2D plot


code:
def bogo_bubble(blist):
    cmpcount, swapcount = 0, 0
    n = 0
    while n < len(blist) - 1:
        cmpcount += 1
        if blist[n] > blist[n + 1]:
            swapcount += 1
            blist[n], blist[n+1] = blist[n+1], blist[n]
            n = 0
        else:
            n = n + 1
    return blist, cmpcount, swapcount

rawDescription: Is this most efficient to bubble sort a list in python?


code:
class D(object):
    def __init__(self, i):
        pass
class A(D):
    def __init__(self, i):
        super(A,self).__init__(i)
        self.i = i
class B(D):
    def __init__(self, j):
        super(B,self).__init__(j)
        self.j = j

class C(A, B):
    def __init__(self):
        super(C, self).__init__(4)
c = C()
print(c.i,c.j)
# (4, 4)

rawDescription: How can I call a particular base class method in Python?

description: Call a particular base class method in Python


rawDescription: How to randomize the order of elements of a list while making sure no consecutive values are equal?

description: Randomize the order of elements of a list while making sure no consecutive values are equal


code:
class A(object):
    def __init__(self):
        self.df2 = pd.DataFrame({'df2': range(5)})
        self.sr2 = pd.Series(range(5))
        self.x = 4
        self.y = 'abc'
        self.z = []

def get_attributes_of_type(cls, types):
    return [i for _, i in cls.__dict__.iteritems() if isinstance(i, types)]

rawDescription: Most efficient way in Python to check if object attributes are assigned DataFrames?


rawDescription: Print different results in Python a dictionary


code: df = pd.read_csv(path_to_edge_list, sep='\s+', header=None, names=['Node1','Node2','Weight'])

rawDescription: networkx - read edgelist in chunks (pandas)

description: Networkx - read edgelist in chunks (pandas)


code:
game_code = 'GameCode'
pass_yds = 'PASS'
rush_yds = 'RUSH'

output_list = []
for row in combineddff.itertuples():
    if row[0] == game_code:
        if row[2] is not None: pass_yds = row[2]
        if row[1] is not None: rush_yds = row[1]
    else:
        output = (game_code, pass_yds, rush_yds)
        output_list.append(output)

# Flush the last group
output = (game_code, pass_yds, rush_yds)
output_list.append(output)

rawDescription: Merging values in different columns into one in python list


code:
d = {}

text = ['time', 'after', 'time']

for w in text:
    if w:                         # If we have the empty string. w[0] Does not Exist (DNE)
        if w[0] in d:             # Check to see if we have first character in dictionary.
            d[w[0]] = d[w[0]] + 1 # Use the first character as key to dictionary.
        else:                     # If character has not been found start counting.
            d[w[0]] = 1           # Use the first character as key to dictionary.

rawDescription: Using Dictionaries to Count First Letter in a String - Python


code: required_options = [options.monitor, options.service, ...]

rawDescription: Optparse and a lot of if not

description: Optparse and a lot of if not


code:
df["total"] = df[columns].mean(
                 axis=1,      # columns mean
                 skipna=True  # skip nan values
                 )

rawDescription: Calculating mean of each row, ignoring 0 values in python


code:
import sys

with open(sys.argv[1], 'r') as in_f:
    for line in in_f:
        line = line.strip()
        if len(line) > 55:
            line = "{0}... <Read More>".format(line[:40].rsplit(" ", 1)[0].rstrip())
        sys.stdout.write("{0}\n".format(line))

rawDescription: Parsing/Printing depending on char length in Python; only 98% on CodeEval


rawDescription: grep output not same as "re.findall()" output in python3

description: Grep output not same as "re.findall()" output in python3


code: {{ year_est|labeled:"Year Established: " }}

rawDescription: Django Template Headings

description: Django Template Headings


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

class Particle(object):
    def __init__(self, value = 0, weight = 0):
        self.value = value
        self.weight = weight
lst = []
for x in range(0,10):
    lst.append(Particle(value=np.random.random_integers(10), weight = 1))

values = [x.value for x in lst]

plt.plot(values, 'ro')
plt.show()

rawDescription: Plotting python object attribute and objects are stored in list


code:
def mousePressEvent(self, event):
    if self.contains(event.pos()):
        self.myMethod()

rawDescription: How to detect mouse click on ellipse drawn in pyside?

description: Detect mouse click on ellipse drawn in pyside


code: list += ['four']

rawDescription: Why do copied dictionaries point to the same directory but lists don't?


code:
tag3 = root.xpath('/Root/Child[3]')[0]
tag3.attrib['name']

rawDescription: How to get total count in root.iter() in ElementTree

description: Get total count in root.iter() in ElementTree


code: np.allclose (a, idct2(dct2(a)))

rawDescription: In scipy why doesn't idct(dct(a)) equal to a?


code: code_list = [(int(code), data) for (code, data) in json_obj.items()]

rawDescription: Split dictionary by keys in Python

description: Split dictionary by keys in Python


code:
for i in range(26):
    print ((i + 13) % 26),

rawDescription: Rot13 and the use of the modulo

description: Rot13 and the use of the modulo


code:
import re
import codecs

with codecs.open("input.txt", "r", "utf-8") as infile:
    inp = infile.read()

pat = re.compile(r"(@.*\*)")
mylist = pat.findall(inp)

with codecs.open("output.txt", "w", "utf-8") as outfile:
     outfile.write("\n".join(mylist))

rawDescription: Python: Problems with latin characters in output


code:
MAGICSTRING = '1234'
'\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2))
'\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2)) == '\x00\x31\x32\x33\x34\x00\x06'

rawDescription: Python String to Escaped Hex

description: Python String to Escaped Hex


code:
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

rawDescription: Can someone help me understand special methods vs normal methods?


code: stream = filter(None, stream)

rawDescription: Delete tab character from config files

description: Delete tab character from config files


code:
element = driver.find_element_by_xpath("//div[@class='WB_feed_type SW_fun S_line2']") #which is created by js
wbHTML = driver.execute_script("return arguments[0].innerHTML;", element)

rawDescription: Selenium: do javascript actions reflect in driver.page_source?


rawDescription: Celery revoke task before execute using django database


code:
import random

nouns = ["random_noun1","random_noun2","random_noun3"]
adverbs = ["random_adverb1","random_adverb2","random_adverb3"]
verbs = ["random_verb1","random_verb2","random_verb3"]

rawDescription: Trying to output to file as well as printing to screen inside a for loop


code: words = [w for w in text.split(' ') if w]

rawDescription: How to split a long string based on character count

description: Split a long string based on character count


code:
for column in ['Subject', 'Lag', 'T1acc', 'T2acc', 'NumberOfTargets']:
    del grouped[column]

rawDescription: How can I reduce lines in a DataFrame, aggregating identical values in a given column?

description: Reduce lines in a DataFrame, aggregating identical values in a given column


code:
NSMAP = {
  None: 'http://www.w3.org/2000/svg',
'inkscape': 'http://www.inkscape.org/namespaces/inkscape',
}

root = etree.Element('{http://www.w3.org/2000/svg}svg', nsmap=NSMAP)

rawDescription: python lxml inkscape namespace tags

description: Python lxml inkscape namespace tags


rawDescription: find and remove common substring with python

description: Find and remove common substring with python


code:
from twisted.internet import reactor

# ...
def connectionMade(self):
    # ... your code
    # cancel connection in 2 minutes
    reactor.callLater(120, self.transport.loseConnection)

rawDescription: implementing timeout in python twisted

description: Implementing timeout in python twisted


rawDescription: Is there any lib for python that will get me the synonyms of a word?


code:
from functools import reduce
from operator import add
reduce(add, mayorPowers)

rawDescription: Adding Lists Elements to 'Mega List'

description: Adding Lists Elements to 'Mega List'


code:
for state in states:
    if state == bad:
        score += penalty
    else:
        score += bonus

rawDescription: Python Ternary Style: Is this good or bad style?


code:
class A(object):
    instances = []

    def __init__(self, foo):
        self.foo = foo
        A.instances.append(self)

rawDescription: Keep track of instances in python

description: Keep track of instances in python


code:
class GpsInfo(ComplexModel):
    # (...)
    doppler_time = Double(sub_name="DopplerTime")
    # (...)

rawDescription: Python: Joining and writing (XML.etrees) trees stored in a list


code:
import json
with open('data.json', 'w') as fp:
    json.dump(data, fp)

rawDescription: Storing Python dictionaries

description: Storing Python dictionaries


rawDescription: Sort N-D numpy array by column with a smaller N-D array


code:
out2 = fill_nans(dat, method='cubic')
print(out2)

rawDescription: fill/predict unknown values of matrix in python

description: Fill/predict unknown values of matrix in python


code:
class image_with_alpha(object):
    def __init__(self,name=None):
        self.img=None
        self.alpha={}
        if name:
            self.load_image(name)

    def load_image(self,name):
        self.img=pygame.image.load(name)
        self.alpha[255]=self.img
        #self.pre_compute_alpha()

    def pre_compute_alpha(self):
        for alpha in range(0,10):
            self.alpha[alpha]=change_alpha(self.img,alpha)

    def get_img(self,a=255):
        try:
            return self.alpha[a]
        except:
            self.alpha[a]=change_alpha(self.img,a)
        return self.alpha[a]

rawDescription: Pygame, set transparency on an image imported using convert_alpha()


rawDescription: converting strings to numeric

description: Converting strings to numeric


code:
from pyspark.sql.functions import greatest

df.select(greatest("a", "b", "c"))

rawDescription: Comparing columns in Pyspark

description: Comparing columns in Pyspark


code:
def __call__(self, func):
    @wraps(func)
    def inner():
        now = time.time()
        if BAILOUT or now > self.timestamp + self.ttl:
            self.cached_result = func()
            self.timestamp = now
        return self.cached_result
    return inner

rawDescription: Running unit tests in Python with a caching decorator


code:
def save(player, blocks):
    f = shelve.open("save.bin")
    f['player'] = player
    f['blocks'] = blocks
    f.close()

rawDescription: Save a list of objects on exit of pygame game


rawDescription: PyQt4 QStandardItem need setInputMask

description: PyQt4 QStandardItem need setInputMask


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


code: d = datetime.fromtimestamp(1440498131.372625, utc)

rawDescription: fractions of seconds and pytz: do you have a cleaner solution?

description: Fractions of seconds and pytz: do you have a cleaner solution


code:
def year(dates):
    "Return an array of the years given an array of datetime64s"
    return dates.astype('M8[Y]').astype('i8') + 1970

def month(dates):
    "Return an array of the months given an array of datetime64s"
    return dates.astype('M8[M]').astype('i8') % 12 + 1

def day(dates):
    "Return an array of the days of the month given an array of datetime64s"
    return (dates - dates.astype('M8[M]')) / np.timedelta64(1, 'D') + 1

def combine64(years, months=1, days=1, weeks=None, hours=None, minutes=None,
              seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
    years = np.asarray(years) - 1970
    months = np.asarray(months) - 1
    days = np.asarray(days) - 1
    types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
             '<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
    vals = (years, months, days, weeks, hours, minutes, seconds,
            milliseconds, microseconds, nanoseconds)
    return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
               if v is not None)

# break the datetime64 array into constituent parts
years, months, days = [f(dates_np) for f in (year, month, day)]
# recompose the datetime64 array after adding 1 to the years
dates3 = combine64(years+1, months, days)

rawDescription: numpy and pandas timedelta error

description: Numpy and pandas timedelta error


code:
from functools import partial

for i, blog in enumerate(blogs):
    self.blog_menu_ids.append(blog[0])
    self.menu_blogs.add_command(label=blog[1],
                                command=partial(self.load_blog, i))

rawDescription: How to effectively turn a variable into a hardcoded value

description: Effectively turn a variable into a hardcoded value


rawDescription: editing plot - python

description: Editing plot - python


code:
import numpy as np
def map_array_to_index(uniq_arr):
    return np.vectorize(dict(map(reversed, enumerate(uniq_arr))).__getitem__)

def recreate(arr, *coord_arrays):
    if len(coord_arrays) != arr.shape[1] - 1:
      coord_arrays = map(np.unique, arr.T[0:-1])
    lookups = map(map_array_to_index, coord_arrays)
    new_array = np.nan * np.ones(map(len, coord_arrays))
    new_array[tuple(l(c) for c, l in zip(arr.T[0:-1], lookups))] = arr[:, -1]
    new_grids = np.meshgrid(*coord_arrays, indexing='ij')
    return new_array, new_grids

rawDescription: Correspondence between a "ij" meshgrid and a long meshgrid


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

from scrapy.spiders import Spider
from scrapy.http import Request

from scraper_app.items import NSERCGrant

class NSERC_Spider(Spider):

    name = 'NSERCSpider'
    allowed_domains = ["http://www.nserc-crsng.gc.ca"]
    # Maximum page id to use.
    max_id = 5

    def start_requests(self):
        for i in range(1, self.max_id):
            yield Request("http://www.nserc-crsng.gc.ca/ase-oro/Details-Detailles_eng.asp?id=%d" % i,
                          callback=self.parse_grant)

    def parse_grant(self, response):

        print("Being called")

        item = NSERCGrant()

        # Row one
        item['Competition_Year'] = response.xpath('//tr[1]//td[2]//text()').extract()
        item['Fiscal_Year'] = response.xpath('//tr[1]//td[4]//text()').extract()

        # Row two
        item['Project_Lead_Name'] = response.xpath('//tr[2]//td[2]//text()').extract()
        item['Institution'] = response.xpath('//tr[2]//td[4]//text()').extract()

        # Row three
        item['Department'] = response.xpath('//tr[3]//td[2]//text()').extract()
        item['Province'] = response.xpath('//tr[3]//td[4]//text()').extract()

        # Row four
        item['Award_Amount'] = response.xpath('//tr[4]//td[2]//text()').extract()
        item['Installment'] = response.xpath('//tr[4]//td[4]//text()').extract()

        # Row five
        item['Program'] = response.xpath('//tr[5]//td[2]//text()').extract()
        item['Selection_Committee'] = response.xpath('//tr[5]//td[4]//text()').extract()

        # Row six
        item['Research_Subject'] = response.xpath('//tr[6]//td[2]//text()').extract()
        item['Area_of_Application'] = response.xpath('//tr[6]//td[4]//text()').extract()

        # Row seven
        item['Co_Researchers'] = response.xpath("//tr[7]//td[2]//text()").extract()
        item['Partners'] = response.xpath('//tr[7]//td[4]//text()').extract()

        # Award Summary
        item['Award_Summary'] = response.xpath('//p//text()').extract()

        yield item

rawDescription: Added iterating over page id in Scrapy, responses in parse method no longer run


code:
def dothis():
  return 1

rawDescription: Reload self-made module

description: Reload self-made module


code:
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
[wnl.lemmatize(i) for i in "the woman's going home".split()]
[wnl.lemmatize(i) for i in "the women's home is in London".split()]

rawDescription: What should be the outcome of stemming a word with apostrophe?


code:
def print_file(x):
    with open('/home/me/data/db/test.blast', 'r') as h:
        return h.read()

rawDescription: Retain formatting

description: Retain formatting


code:
from django import forms

class SearchForm(forms.Form):
    search_src = forms.CharField(max_length=20, required=False)
    search_dest = forms.CharField(max_length=20, required=False)

rawDescription: How to filter objects of an object_list of a generic view in Django

description: Filter objects of an object_list of a generic view in Django


code:
cards = []
for x in range(10):
   for y in range(10):
      cards.append(Card((x*10,y*10)))
while not finished:
    for card in cards:
        card.draw(screen)
        card.update()
#somewhere in the event loop:
    card.flip()

rawDescription: Short animation class in Pygame?

description: Short animation class in Pygame


code:
class Node(object):
    def __init__(self, word, *children):
            self.word = word
            self.children = children
    def is_leaf(self):
            return not self.children

tree = Node('I', Node('have', Node('a', Node('dog'), Node('shotgun'))), Node("don't", Node('like', Node('Elvis'))))
#tree is now your example tree
list(yield_sentences(tree))

rawDescription: Retrieving branches from a nested dictionary


code:
class Monster(object):
    def __init__(self, traits):
        self._traits = traits

    def __getattr__(self, name):
        if name in self._traits:
            return self._traits[name]
        raise AttributeError(name)

rawDescription: Python properties as instance attributes


code: D = np.choose(C,ii).reshape(A.shape)

rawDescription: Numpy Lookup (Map, or Point)

description: Numpy Lookup (Map, or Point)


rawDescription: Hiding inaccessible links in Jinja2 templates


code:
import os
import pathlib

matches = list(map(str, pathlib.Path(os.path.expanduser('~/x/y')).rglob('*')))

rawDescription: equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure?

description: Equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure


code:
data = "ACCCGATTT"
step = 2
chunk = 4
for i in range(0, len(data) - step, step):
    print(data[i:i+chunk])

rawDescription: How to extract short sequence using window with specific step size?

description: Extract short sequence using window with specific step size


rawDescription: python for loop increasing or decreasing

description: Python for loop increasing or decreasing


code: map(lambda x: b[x],a)

rawDescription: Replace a list item with the value of the item stored in dictionary in python


code: map(lambda x: x or 'NULL', l)

rawDescription: Best strategy for dealing with incomplete lines of data from a file


code:
extracted = tldextract.extract('http://www.google.com')
"{}.{}".format(extracted.domain, extracted.suffix)

rawDescription: Python urlparse -- extract domain name without subdomain


code:
from collections import Counter
from string import ascii_letters

def count():
    c = Counter()
    with open("xxx.txt","r") as file:
        for line in file:
            c.update(line)

    return sum(v for k, v in c.items() if k in ascii_letters)

rawDescription: acount total number of letter ONLY alphabet

description: Acount total number of letter ONLY alphabet


code:
X=np.empty((len(instances),), dtype = np.object)
print(X.shape)
# (2,)

rawDescription: storing record arrays in object arrays

description: Storing record arrays in object arrays


code:
somewidget.setCursor(QtCore.Qt.BusyCursor)
# retrieve network resource ...
somewidget.unsetCursor()

rawDescription: Make a progress bar for an ongoing request in Python


code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf'
prop = font_manager.FontProperties(fname=path)
mpl.rcParams['font.family'] = prop.get_name()
fig, ax = plt.subplots()
ax.set_title('Text in a cool font', size=40)
plt.show()

rawDescription: How to load .ttf file in matplotlib using mpl.rcParams?

description: Load .ttf file in matplotlib using mpl.rcParams


rawDescription: numpy create 3D array from indexed list

description: Numpy create 3D array from indexed list


rawDescription: Most efficient way to find mode in numpy array


code:
print(longest_substr("owadcbjkl"))
# -> adcb

rawDescription: Find the longest substring with contiguous characters, where the string may be jumbled


code:
month = 'January'
month.lower
month.lower == 'January'
month.lower == 'january'
month.lower() == 'january'

rawDescription: Why doesn't if, elif or else work with .lower() in Python?


code:
df1 = pd.DataFrame([[1, 'foo'], [np.nan, 'bar'], [4, 'meh'], [np.nan, 'eurgh']], columns = ['A', 'B'])
df2 = pd.DataFrame([[np.nan, 'bar'], [4, 'meh']], columns = ['A', 'B'])
cols = ['A', 'B']
df2['dummy'] = df2[cols].isnull().any(1)  # rows with NaNs in cols will be True
merged = df1.merge(df2[cols + ['dummy']], how='left')
merged

rawDescription: Set differences on columns between dataframes


code:
from heapq import nlargest
tags = [ ("python", 30), ("ruby", 25), ("c++", 50), ("lisp", 20) ]
nlargest(2, tags, key=lambda e:e[1]) # Gives [ ("c++", 50), ("python", 30) ]

rawDescription: how to efficiently get the k bigger elements of a list in python

description: Efficiently get the k bigger elements of a list in python


code:
import pandas as pd
import numpy as np
np.random.seed(0)

base = np.array(["2013-01-01 00:00:00"], "datetime64[ns]")

a = (np.random.rand(30)*1000000*1000).astype(np.int64)*1000000
t1 = base + a
t1.sort()

b = (np.random.rand(10)*1000000*1000).astype(np.int64)*1000000
t2 = base + b
t2.sort()

rawDescription: pandas.merge: match the nearest time stamp >= the series of timestamps

description: Pandas.merge: match the nearest time stamp >= the series of timestamps


rawDescription: How can I print the decimal representation of a unicode string?

description: Print the decimal representation of a unicode string


code:
class BeeForm(forms.ModelForm):
    check = forms.BooleanField(label="check", required=False)
    class Meta:
        model = Bee

class BeeInline(admin.TabularInline):
    form = BeeForm
    model = Bee

class HiveAdmin(admin.ModelAdmin):
    inlines = (BeeInline,)
    def save_formset(self, request, form, formset, change):
        for bee_form in formset:
            if bee_form.cleaned_data.get('check') == True:
                form.instance.marker = True
                form.instance.save()
        super(HiveAdmin, self).save_formset(request, form, formset, change)

admin.site.register(Hive, HiveAdmin)

rawDescription: Extending Django Admin tabular.html custom checkbox action


code:
def closest(self,*points):
    def keyFunc(x):
        return float(x-self)
    return min(points,key=keyFunc)

rawDescription: What does this lambda function do?

description: What does this lambda function do


code:
with open(in_file) as f:
     lines = reversed(f.readlines()) # start from end of file
     for line in lines:
         if "AC:AC LP" in line: # if AC:AC LP is in the line
             print( next(lines).rsplit(":",1)[-1]) # go to  next line, split, get ip and break the loop
             break

rawDescription: python search a text file for a string and add the value to a variable

description: Python search a text file for a string and add the value to a variable


code: array = sortedlistwithkey.SortedListWithKey(key=lambda x: (-x[-1], -x[-2]))

rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


code:
images, anims = [], []

for f in files:
    if f.lower() in IMAGE_TYPES:
        images.append(f)
    else:
        anims.append(f)

rawDescription: Python: split a list based on a condition?


code:
def max_in_list(list):
    max = 0
    for i in range(len(list)-1):
        if list[i] > list [i+1] and list [i] > max:
            max = list[i]
        elif list[i+1] > max:
            max = list [i+1]
    return max

rawDescription: Assigning return value of a function to a variable in Python


code:
class MyClass(SuperClass):

    def __init__(self, super_arg, my_arg):
        super().__init__(super_arg)
            # ^ don't need these
                       # ^ still need these
        self.my_arg = my_arg

rawDescription: How to handle python inheritance properly

description: Handle python inheritance properly


code:
class CourseListView(AuthView):
    def get(self, request, format=None):
        """
        Returns a JSON response with a listing of course objects
        """
        courses = Course.objects.order_by('name').all()
        paginator = CustomCoursePaginator()
        result_page = paginator.paginate_queryset(courses, request)
        serializer = CourseSerializer(result_page, many=True)
        return paginator.get_paginated_response(serializer.data)

rawDescription: Django Rest Framework 3.1 breaks pagination.PaginationSerializer


code:
from . import db
...

rawDescription: Python clean imports for models - SQL Alchemy


code:
buttonParameters = {
    "button1": "button1.png",
    "button2": "button2.png",
    "button3": "button3.png",
    "button4": "button4.png",
    "button5": "button5.png",
}

buttonParameters['button1'] #=> "button1.png"

rawDescription: accessing values from a list in python

description: Accessing values from a list in python


code:
words = sentence.split()
counts = {}
for word in words:
    if word not in counts:
        counts[word] = 0
    counts[word] += 1

rawDescription: Python Duplicate words

description: Python Duplicate words


code: myColourList = ["blue" for i in range(len(volumes))]

rawDescription: How to colour maixum and minimun of each bar in bar graph in python?

description: Colour maixum and minimun of each bar in bar graph in python


code: contains_all = set(two).issubset(one)

rawDescription: Python dictionnary items() method cost inside iterable


code: days, remaindays = divmod(min,1440)

rawDescription: Zero out a value

description: Zero out a value


code:
year = int(item['year'].split('-')[0])
month = int(item['month'].split('-')[1])

rawDescription: Count choices in django

description: Count choices in django


code:
import multiprocessing as mp
import tables as pt

num_arrays = 100
num_processes = mp.cpu_count()
num_simulations = 1000

def Simulation(ii):
    result = []
    result.append(('createGroup', ('/', 'A%s' % ii)))
    for i in range(num_arrays):
        result.append(('createArray', ('/A%s' % ii, 'B%s' % i, [ii, i])))
    return result

def handle_output(result):
    hdf = pt.openFile('simulation.h5', mode='a')
    for args in result:
        method, args = args
        getattr(hdf, method)(*args)
    hdf.close()

if __name__ == '__main__':
    # clear the file
    hdf = pt.openFile('simulation.h5', mode='w')
    hdf.close()
    pool = mp.Pool(num_processes)
    for i in range(num_simulations):
        pool.apply_async(Simulation, (i, ), callback=handle_output)
    pool.close()
    pool.join()

rawDescription: Write data to hdf file using multiprocessing


rawDescription: RegEx- How to make a blank space between a non-alphabetic char and an alphabetic char in a string


rawDescription: splitting an array into two smaller arrays in python

description: Splitting an array into two smaller arrays in python


rawDescription: pandas re-indexing with missing dates

description: Pandas re-indexing with missing dates


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

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


code:
for k, v in sorted(d_max.items(), key=lambda x: x[1], reverse=True):
    print('{} : {}'.format(k,v))

rawDescription: Sorting a dictionary by highest value of nested list


code:
class Board(object):
    def __init__(self, matrix, whitepos=None):
        self.matrix = matrix
        self.whitepos = whitepos
        if not whitepos:
            for y in xrange(3):
                for x in xrange(3):
                    if board[y][x] == 0:
                        self.whitepos = (x, y)
    def __eq__(self, o):
        # Note that comparing whitepos is not strictly necessary; but I left
        # it in as a safety measure in case the board state gets corrupted.
        # If speed becomes an issue, take it out.
        return (self.matrix, self.whitepos) == (o.matrix, o.whitepos)

class Node(object):
    def __init__(self, board, parent):
        self.state = board
        self.parent = parent
        if not parent:
            self.g = 0
        else:
            self.g = parent.g + 1
        self.h = heuristic(board)

    def test_goal(self):
        return is_final_state(self.state)

    def expand(self):
        children = []
        b = self.state
        x, y = get_whitepos(b)
        if x > 0:
            children.append(Node(move(b, x, y, -1, 0), self))
        if x < 2:
            children.append(Node(move(b, x, y, +1, 0), self))
        if y > 0:
            children.append(Node(move(b, x, y, 0, -1), self))
        if y < 2:
            children.append(Node(move(b, x, y, 0, +1), self))
        return children

    def __eq__(self, o):
        # Note that you don't have to compare parents, since your goal
        # is to eliminate ANY nodes with the same position.
        return self.state == o.state

class Solution(object):
    def __init__(self, node, mem_needed, steps):
        self.node = node
        self.mem_needed = mem_needed
        self.iterations = steps

    def inc(self, other):
        self.node = other.node
        self.mem_needed = max(self.mem_needed, other.mem_needed)
        self.iterations += other.iterations

#...

print_solution("bl", bl_search(board))
# I commented out all but the first search to avoid cluttering up the output.

rawDescription: 8 tile solver with repeated nodes - Python


rawDescription: fit multiple gaussians to the data in python

description: Fit multiple gaussians to the data in python


code:
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np

def main():
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='polar')
    x = np.radians(np.arange(0, 360, 10))
    y = np.random.random(x.size)
    z = np.random.random(y.size)
    cmap = plt.get_cmap('cool')
    coll = colored_bar(x, y, z, ax=ax, width=np.radians(10), cmap=cmap)
    fig.colorbar(coll)
    ax.set_yticks([0.5, 1.0])
    plt.show()

def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    width = itertools.cycle(np.atleast_1d(width))
    bottom = itertools.cycle(np.atleast_1d(bottom))
    rects = []
    for x, y, h, w in zip(left, bottom, height, width):
        rects.append(Rectangle((x,y), w, h))
    coll = PatchCollection(rects, array=z, **kwargs)
    ax.add_collection(coll)
    ax.autoscale()
    return coll

if __name__ == '__main__':
    main()

rawDescription: How would one add a colorbar to this example?


code:
fs = gridfs.GridFS(db)
gridout = fs.get_last_version("testimage")

rawDescription: How to retrieve file's with grid fs

description: Retrieve file's with grid fs


code:
set_sim(['Player3', 'Player1'], 2)
set_sim(['Player1', 'Player2'], 3)
set_sim(['Player2', 'Player3'], 3)
get_sim(['Player3','Player2'])
similarities

rawDescription: How to make array of array of dictionaries in python

description: Make array of array of dictionaries in python


code:
psimaps_comp = [np.sum(featureParams*features[k], axis=1, keepdims=True) + transitiveParams for k in xrange(len(features)-1)]
psimaps_comp[-1] += np.sum(featureParams*features[-1], axis=1)

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

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


rawDescription: Python - unpack struct into multiple tuples


code:
import numpy
import pandas
from matplotlib import pyplot
import seaborn
seaborn.set(style="ticks")

# Data
df = pandas.DataFrame(numpy.random.rand(10,4), columns=list('ABCD'))
df['E'] = [1, 2, 3, 1, 1, 4, 3, 2, 3, 1]

rawDescription: Python Side-by-side box plots on same figure


code:
a = range(5)
b = range(3)
c = range(2)
b.append(a)
b
c.extend(a)
c

rawDescription: Python: take the content of a list and append it to another list


code:
indexed_sums = {}
for o in xbs:
    if (o.W, o.X, o.Y) not in indexed_sums:
        indexed_sums[(o.W, o.X, o.Y)] = 0
    indexed_sums[(o.W, o.X, o.Y)] += o.Z

rawDescription: Summing Attribute in a list of Python Objects