code:
def solve(d):

    x_min, y_min = map(min, zip(*d))
    x_max, y_max = map(max, zip(*d))

    arr = [[0]*(x_max-x_min+1) for _ in xrange(y_max-y_min+1)]

    for i, y in enumerate(xrange(y_min, y_max+1)):
        for j, x in enumerate(xrange(x_min, x_max+1)):
            arr[i][j] = d.get((x, y), 0)
    return arr[::-1]

rawDescription: Dictionary of points and values to array


code:
lis = [['welcome','a1'],['welcome','a1'],['hello','a2'],['hello','a3']]
s = set()
for item in lis:
    tup = tuple(item)  #covert to tuple
    s.add(tup)
s

rawDescription: How to count elements in a list of lists of strings

description: Count elements in a list of lists of strings


code:
with open(filename) as f:
     lines = f.read().replace("None","")
with open(filename,"w") as f1:
     f1.write(lines)

rawDescription: Removing lines from a csv with Python also adds an extra line


code:
from itertools import zip_longest, starmap

def map2x(func, *iterables):
    zipped = zip_longest(*iterables)
    if func is None:
        return zipped
    return starmap(func, zipped)

rawDescription: How do I get Python2.x `map` functionality in Python3.x?

description: Get Python2.x `map` functionality in Python3.x


code: waves = [(frequency, amplitude) for _ in range(wave_count)]

rawDescription: Python 3.2: Can I multiply a tuple in a list without concatenating the individual tuples into one tuple?


code:
lst = [(int(key), value['std']) for key, value in sd_dict.items()]
lst.sort(key=lambda x: (x[1], x[0]))
lst

rawDescription: Sorting nested python dictionary by label


code:
clean_compare = [i[13:-1] for i in compare]
clean_compare
name
{i:i in clean_compare for i in name} #for Python 2.7+

rawDescription: Searching lists and comparing with another not exact list


code: print(*(str(col) + '\t' + (len(item)*'{}').format(*(i.ljust(25) for i in item)) for col,*item in mylist), sep='\n')

rawDescription: Pretty print Python Lists

description: Pretty print Python Lists


rawDescription: How do I return a web page's table cell value without ID, using column and row names (not index)

description: Return a web page's table cell value without ID, using column and row names (not index)


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.app import App
from kivy.lang import Builder

from functools import partial

class TestApp(App):
    def build(self):
        return Button(on_press=partial(self.popup_display, "title", "bar "*80))

    def popup_display(self, title, message, widget):
        btnclose = Button(text='Close me', size_hint_y=None, height=50)
        l = Label(text=message)
        l.bind(size=lambda s, w: s.setter('text_size')(s, w))

        content = BoxLayout(orientation='vertical')
        content.add_widget(l)
        content.add_widget(btnclose)
        popup = Popup(content=content, title=title, size_hint=(None, None), size=(300, 300), auto_dismiss=False)
        btnclose.bind(on_release=popup.dismiss)

        popup.open()

if __name__ == '__main__':
    TestApp().run()

rawDescription: Kivy : Relative size of text displaying in a popup


code:
diction1 = {'john': [10, 20], 'mary': [12,], 'chris': [10, 20]}

# Contains names as keys and average as values.
averages_dct = {}

for name in diction1:
    student_average = sum(diction1[name]) / len(diction1[name])

    # Store the value:
    averages_dct.update({name: student_average})

# Dict containing averages as keys and names as values
# (inserting averages first)
reversed_dct = {averages_dct[k]: [] for k in averages_dct}

# (matching names)
for average in reversed_dct:
    for name in averages_dct:
        if average == averages_dct[name]:

            # Adds name of student if he has this average
            reversed_dct[average].append(name)

# Prints the results from highest to lowest.
for av in sorted(reversed_dct, reverse=True):
    print('average: %s, students: %s' % (av, reversed_dct[av]))

rawDescription: I need to know how to sort my dictionary on python by aveage scores with students with multi-ple scores?


rawDescription: How to get node name without namespace if it exists?

description: Get node name without namespace if it exists


code:
# Get the rows in the table, then get the second column's value for
# each row
terms = [row['c'][2]['v'] for row in result_object['table']['rows']]

rawDescription: Extracting data from a URL result with special formating


code:
with open("test.txt",'r+') as w_file:
    w_file.write(str(0.8) + "\n" + str(0.2))
    w_file.flush()
    subprocess.call(["cat","test.txt"]) #Here I want to call my routine

rawDescription: Write file input for subprocess

description: Write file input for subprocess


code:
def a():
  return 1

a.command_name = 'get_one'

rawDescription: Most Pythonic way to provide function metadata at compile time?


rawDescription: What is the most efficient way to move/rename a node in NetworkX?


rawDescription: Python sort and merge with dense list of sublisted lists


code:
def test_pip_python_packages_installed_twice(self):
    # http://stackoverflow.com/a/23941861/633961
    pkg_name_to_locations=defaultdict(set)
    for dist in pkg_resources.working_set:
        for pkg_name in dist._get_metadata('top_level.txt'):
            for location in sys.path:
                try:
                    importutils.does_module_exist_at_given_path(pkg_name, [location])
                except ImportError:
                    continue
                if location.startswith('/usr'):
                    # ignore packages from "root" level.
                    continue
                pkg_name_to_locations[pkg_name].add(location)

    errors=dict()
    for pkg_name, locations in sorted(pkg_name_to_locations.items()):
        if pkg_name in ['_markerlib', 'pkg_resources', 'site', 'easy_install', 'setuptools', 'pip']:
            continue
        if len(locations)==1:
            continue
        errors[pkg_name]=locations
    self.assertFalse(errors,
                     'Some modules are installed twice:\n%s' % '\n'.join(['%s: %s' % (key, value) for key, value in sorted(errors.items())]))

rawDescription: pip installs package twice

description: Pip installs package twice


code:
base_dir = 'C:/INTERMITTENT/MARCH/'
nc_fnames = ['20080305.faieb3p4e.nc', '20080306.faieb3p4e.nc']

# beams
ibeams = [0, 0]

# Change directory
os.chdir(base_dir)
for i, fname in enumerate(nc_fnames):
    # Open file
    fd = nc.Dataset(fname, 'r')

    # Read variables
    beam = fd.variables['beam'][:]
    rng = fd.variables['range'][:]
    tim = fd.variables['time'][:]
    pwr = fd.variables['pwr'][:]
    nfft = fd.variables['nfft'][0]
    pn = fd.variables['pnoise'][:]

    # Close netCDF file
    fd.close()

    # Specify beam
    ibeam = ibeams[i]

    # Time convertion
    tim = tim/3600.0

    #Plot
    p_plot = pwr[ibeam]
    for it in range(len(tim)):
            p_plot[it] = p_plot[it] - pn[ibeam][it] - 10.*np.log10(nfft)
    p_plot = p_plot.transpose()

    #Plot colorbar
    fig.colorbar(p_plot, ax=axs[i])

# Set X and Y axis lower/uppser limit
set_xy = range(4)
set_xy[0] = 18.0 # x min
set_xy[1] = 30.0 # x max
set_xy[2] = 90.0 # y min
set_xy[3] = 170.0 # y max
pl.axis(set_xy)

# Set labels
pl.xlabel('time (hours)')
pl.ylabel('range (km)')

pl.show()

rawDescription: make loop of many file with python

description: Make loop of many file with python


code: objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])

rawDescription: Building up a string using a list of values


code:
import random
answers = ['Without a doubt!', 'Hmmm, not so sure', 'By the winds, set sail now!', 'Oh no, no NO NO!!']
print(random.choice(answers))
print(random.choice(answers))

rawDescription: Selecting One String from data list in Python


code:
#at the top of your script:
from copy import deepcopy

#meanwhile, several lines down...
for item in raw:
  if not cardinals.has_key(item[1]):#wdir e.g. 'W'
    cardinals[item[1]] = deepcopy(bands)
for item in cardinals.keys():
  if not cardinal_count.has_key(item):
    cardinal_count[item] = deepcopy(counts) #

rawDescription: Strange counting behaviour when sorting list of tuples into dictionary


code: r, g, b = [int(x*100/255) for x in triple1]

rawDescription: Python: How to convert a rgb or hex value to single color values


code:
import foo
foo.foo()

rawDescription: AutoKey Python - How do I create a global function library


code:
df = {'android_id': 'ds cgethcvwrzvbjezrzve',
      'app': 'hndbfhjdfhf bnmhjknuihklmmkbghjbtfgjnkluilnkkfbnjtkjzn',
      'app_ver': '10.0.1_0',
      'at': '2016-02-02 23:59:47',
      'birth_date': 1447896843,
      'browser': 'Android 4',
      'carrier': 'Comcast Cable',
      'city_name': 'Jacksonville',
      'country': 'us',
      'custom': {'Action': 'Click',
      'Campaign ID': '167713',
      'Creative ID': '113961',
      'Creative Type': 'Alert',
      'Schema Version - Client': '3',
      'Schema Version - Server': '1'},
      'customer_ids': {'customer_id': '1234587612545464525441540341414'},
      'data_conn': 'android_network_type_3',
      'device_new': False,
        }

sub_df1 = df.pop('custom')
sub_df2 = df.pop('customer_ids')

df.update(sub_df1)
df.update(sub_df2)

# you can define a function to do this
def un_nest(df):
    sub_df1 = df.pop('custom')
    sub_df2 = df.pop('customer_ids')

    df.update(sub_df1)
    df.update(sub_df2)
    return df

rawDescription: How to Access nested dictionary keys to make a Pandas DataFrame


code:
df1 = df1.reindex_axis(sorted(df.columns), axis=1)
df2 = df2.reindex_axis(sorted(df.columns), axis=1)

rawDescription: Compare columns of 2 different Data frames


code:
import cffi
ffi = cffi.FFI()
ffi.cdef('typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;')
typeof_strategy = ffi.typeof('strategy')
typeof_strategy.relements
typeof_strategy.relements['SEARCH']

rawDescription: Fetching a C variable value in an enum using its name (a Python string) in Python


code: personalposts = db.GqlQuery("select * from PersonalPost where user_id =:1 order by created desc limit 30",user_id)

rawDescription: pass a string variable into a gql query

description: Pass a string variable into a gql query


code:
bins = [[i*bin_width, (i+1)*bin_width, 0] for i in range(num_bins)]
for data_point in data_points:
    bin_number = data_point // bin_width
    bins[bin_number][2] += 1

rawDescription: How to count how many data points fall in a bin

description: Count how many data points fall in a bin


code:
from myapp.models import Message, Like

@register.inclusion_tag('user_stats.html')
def user_stats(user):
    return {'user': user,
            'messages': Message.objects.filter(user=user).count(),
            'likes': Like.objects.filter(user=user).count()}

rawDescription: How to create inclusion_tag Django?

description: Create inclusion_tag Django


rawDescription: Basic Python loop question - problem reading a list from a text file


code:
df = pd.read_csv('yourfile.txt',header=None)
df.columns = ['paths']
# pandas string method extract takes a regex
df['paths'].str.extract('(\d{4})(\d{2})')

rawDescription: Use Regex to extract file path and save it in python


code:
from flask import session
from functools import wraps

def random_string(length):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length))

def validate_token(f):
    @wraps(f)
    def wrapper(existing_token, *args, **kwargs):
        if session['token'] != existing_token:
            # Logic on failure. Do you present a 404, do you bounce them back to your main page, do you do something else?
            # It is IMPORTANT that you determine and implement this logic
            # otherwise the decorator simply changes the token (and behaves the same way as the else block).
            session['token'] = random_string(20)
        else:
            session['token'] = random_string(20)
        return f(*args, **kwargs)
    return wrapper

rawDescription: How to limit one session from any browser for a username in flask?

description: Limit one session from any browser for a username in flask


rawDescription: How do you get a decimal in python?

description: Get a decimal in python


code:
vector_a = [int(a.strip()) for a in vector_a]
vector_b = [int(a.strip()) for a in vector_b]

rawDescription: Append input to list as integers

description: Append input to list as integers


code:
sp = subprocess.Popen(['python', 'script.py'])
print('PID is ' + str(sp.pid))

rawDescription: getting ProcessId within Python code

description: Getting ProcessId within Python code


code:
@pytest.fixture(scope="class")
def oneTimeSetUp(request, browser):
    print("Running one time setUp")
    if browser == 'firefox':
        driver = webdriver.Firefox()
        driver.maximize_window()
        driver.implicitly_wait(3)
        print("Running tests on FF")
    else:
        driver = webdriver.Chrome()
        print("Running tests on chrome")

    if request.cls is not None:
        request.cls.driver = driver

rawDescription: pytest -> How to use fixture return value in test method under a class

description: Pytest -> How to use fixture return value in test method under a class


code:
import uuid

from sqlalchemy.event import listen

from mypackage.models import Base

def generate_license(mapper, connect, target):
    target.generate_license()

class User(Base):
    __tablename__ = "users"
    id = Column(String(36))
    license = Column(String(256))

    def generate_license(self):
        if not self.license:
            self.license = str(uuid.uuid4())
        return self.license

listen(User, 'before_insert', generate_license)

rawDescription: Hooking into sqlalchemy models

description: Hooking into sqlalchemy models


code:
def sort_nicely(l):
    """
    Sort the given list in the way that humans expect. Returns a new list.
    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(l, key=alphanum_key)
newlist = sort_nicely(mylist)
print(*newlist, sep='\n')

rawDescription: How to sort files in linux by number?

description: Sort files in linux by number


rawDescription: How to use a conditional statement based on DataFrame boolean value in pandas

description: Use a conditional statement based on DataFrame boolean value in pandas


code:
foo
bar
asdijaiojsd
asdiaooiasd

rawDescription: Reading two strings from file

description: Reading two strings from file


code:
x=np.linspace(1e10,1e12,num=10)
y=np.linspace(1e5,1e7,num=5)
z = x[:,None]**2 + y[None,:]**2
z.shape

rawDescription: Reshaping numpy array without using two for loops


code:
if __name__ == '__main__':
    inst = sys.argv[1] # will be 'inst1', 'inst13', etc.
    inst_number = inst[5:] # so '1', '13', etc.
    inst_name = 'instance' + inst_number
    instance = globals()[inst_name]
    instance.execute()

rawDescription: Writing a Python script to execute with a console command


code:
@route('/')
def index():
    refresh()
    # print the value of AAPL here, to confirm that it's updated
    return template('index', **my_dict)

rawDescription: How can I refresh data from yahoo finance API every time webpage is viewed in Python?

description: Refresh data from yahoo finance API every time webpage is viewed in Python


code:
def newFrame(self, event):
    self.new_window = wx.Frame(self, title='frame2', size=(500, 500), pos=(800,0))
    sz = wx.BoxSizer()
    sz.SetMinSize((500,500)) #force minimum size
    self.scroll = wx.ScrolledWindow(self.new_window, -1)
    sz.Add(self.scroll,1,wx.EXPAND)
    self.scroll.SetScrollbars(1, 1, 1600, 1400)
    self.new_window.SetSizer(sz)
    self.new_window.Layout()
    self.new_window.Fit()
    self.new_window.Show()

rawDescription: creating a wxpython scrolled window (frame) by an event

description: Creating a wxpython scrolled window (frame) by an event


rawDescription: What's the equivalent of PHP's "$my_array[]" in Python?


rawDescription: How to fields to the User model

description: Fields to the User model


code:
a = ["string2" , "string4"]
b = ["string1" , "string2" , "string3" , "string4" , "string5"]
c = [b.index(i) for i in a]
c

rawDescription: Check if items in list a are found in list b and return list c with matching indexes of list b in Python


code:
import itertools

num = [1, 2, 3, 4, 5,6,7,8,9,10]
combinations = itertools.combinations(num, 3)
matching = [c for c in combinations if reduce(lambda x, y: x * y, c, 1) == 60]

print(matching)

rawDescription: Finding all possible combination on python


code:
b = B()
b.bar() # prints 'Foo'

rawDescription: Python calling method in class

description: Python calling method in class


code:
dt.year
dt.month
dt.day

rawDescription: Number Trouble with Regex in Python

description: Number Trouble with Regex in Python


rawDescription: Python beautiful soup how to get deep nested elements


rawDescription: Pass data Python to PHP via JSON

description: Pass data Python to PHP via JSON


code:
lemmas_in_words  = set(i for i in wn.words())
len(lemmas_in_wordnet)
len(lemmas_in_words)

rawDescription: How can I print the entire contents of Wordnet (preferably with NLTK)?

description: Print the entire contents of Wordnet (preferably with NLTK)


code:
@asyncio.coroutine
def hello_world(loop):
    print('Hello')
    yield from asyncio.sleep(5, loop=loop)
    print('World')
    loop.stop()

rawDescription: Execute coroutine from `call_soon` callback function


rawDescription: list(set) for nested lists?

description: List(set) for nested lists


rawDescription: Find a value within nested json dictionary in python


code:
def to_python(self, value):
    # logic and unpickling, then right before your return:
    if hasattr(self, 'model_instance'): # avoid AttributeError if list, dict, etc.
        value.model_instance = self.model_instance
    return value

rawDescription: Django Pickle Field Access to its model instance on load


code:
import numpy as np
diff = np.array(array[n-1:]) -  np.array(average[:-n+2])

rawDescription: Function which is similar to numpy's diff


code:
class Item(db.Model):
    page = db.ReferenceProperty(Page, required=True)
    name = db.StringProperty(required=True)

    def put(self):
        if not self.page.has_items:
            self.page.has_items = True
            self.page.put()
        return db.put(self)

rawDescription: Google app engine python problem

description: Google app engine python problem


rawDescription: How to access all list elements from last to first in python list

description: Access all list elements from last to first in python list


code:
def drop(list, slice):
    return list[slice:]

rawDescription: User Defined Slice function in python script


code: records = list(chunkRecords(records))

rawDescription: chunking list by delimiter in Python

description: Chunking list by delimiter in Python


code:
{'Anna T': {'Average': '2',
            'Excellent': '0',
            'Poor': '0',
            'Terrible': '0',
            'Very good': '2'},
 'Arlyss T': {'Average': '0',
              'Excellent': '6',
              'Poor': '0',
              'Terrible': '0',
              'Very good': '1'},
 'Bf B': {'Average': '1',
          'Excellent': '22',
          'Poor': '0',
          'Terrible': '0',
          'Very good': '17'},
 'Charmingnl': {'Average': '15',
                'Excellent': '109',
                'Poor': '4',
                'Terrible': '4',
                'Very good': '45'},
 'Jackie M': {'Average': '2',
              'Excellent': '10',
              'Poor': '0',
              'Terrible': '0',
              'Very good': '4'},
 'Jonathan K': {'Average': '69',
                'Excellent': '90',
                'Poor': '6',
                'Terrible': '0',
                'Very good': '154'},
 'Sapphire-Ed': {'Average': '8',
                 'Excellent': '47',
                 'Poor': '2',
                 'Terrible': '0',
                 'Very good': '49'},
 'TundraJayco': {'Average': '14',
                 'Excellent': '59',
                 'Poor': '0',
                 'Terrible': '1',
                 'Very good': '49'},
 'Versrii': {'Average': '2',
             'Excellent': '8',
             'Poor': '0',
             'Terrible': '0',
             'Very good': '10'},
 'tripavisor83': {'Average': '12',
                  'Excellent': '9',
                  'Poor': '1',
                  'Terrible': '0',
                  'Very good': '20'}}

rawDescription: Scraping information from hoverbox

description: Scraping information from hoverbox


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=5, ncols=5)
plt.setp(axes.flat, xticks=[], yticks=[], zorder=0)

ax = axes[0,0]
ax.annotate('Testing this out and seeing what happens', xy=(0.5, 0.5),
            xytext=(1.1, .5), textcoords='axes fraction', zorder=100)

plt.show()

rawDescription: How to prevent a matplotlib annotation being clipped by other axes

description: Prevent a matplotlib annotation being clipped by other axes


code:
class PublishView(UpdateView):

    model = Blog

    def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk', None)
        Blog.objects.filter(pk=pk).update(publish_date=datetime.datetime.now())
        return HttpResponseRedirect("/blogs/" + pk)

rawDescription: Django permissions mixin on CBV, how to apply on 'publish blog' method


code:
df = pd.DataFrame({'A':range(5), 'B':range(10,20,2)})
df
mask = (df['A'].shift(1) + df['B'].shift(2) > 12)
mask
df[mask]

rawDescription: Fastest way to iterate through a pandas dataframe?


code:
def setWorkDays(dayNameList):
    while self.count > 0: #continue loop until all 5 work days have been filled or the loop breaks at the end
        for day in dayNameList: #iterate over days, adding days to work days if they are not free days, AL days, preferred days, or free Saturdays
            if day in self.freeDays or day in self.alDays or (day == 'Saturday' and self.satOff is True):
                continue
            elif day in self.programDays:
                yield day
            elif self.preferredDay is not None and day in self.preferredDay:
                continue
            else:
                yield day
        if self.preferredDay not in self.workDays: #if iteration completes, 5 work days have not been filled, and the preferred day has not been added, add the preferred day
            yield day

workDays = [setWorkDays(dayNameList) for _ in range(5)]

rawDescription: When Does a While Loop Break

description: When Does a While Loop Break


code:
import operator as op
sorted(lst, key=op.itemgetter(1))

rawDescription: How to sort an itertools grouper array in python

description: Sort an itertools grouper array in python


code:
import datetime as DT
date_data = ['12,Dec,2014, 02,15,28,31,37,04,06', '9,Dec,2014, 01,03,31,42,46,04,11']

for line in date_data:
    part = line.split(', ', 1)
    date = DT.datetime.strptime(part[0], '%d,%b,%Y').date()
    numbers = map(int, part[1].split(','))
    print(date, numbers)

rawDescription: convert str(time) to date format with other data included

description: Convert str(time) to date format with other data included


code: np.argwhere((arr == [0, 4]).all(axis=2))

rawDescription: Find 2d array inside a 3d array

description: Find 2d array inside a 3d array


rawDescription: Retrieving each element of multiple arrays in python


code:
Example
list_address = ["key1", "key1.2", "key1.2.1", "key1.2.1.1", "value"]
dict_nested = {
    "key1": {
                "key1.1": {
                            "...": "...",
                },
                "key1.2": {
                            "key1.2.1": "change_this",
                },
            },

    "key2": {
                "...": "..."
            },
}

set_value(dict_nested, list_address[:-2], *list_address[-2:])
assert reduce(dict.get, list_address[:-1], dict_nested) == list_address[-1]

rawDescription: Python: Change values in dict of nested dicts using items in a list


code:
class _max:
    def __lt__(self, other): return False
    def __gt__(self, other): return True

class _min:
    def __lt__(self, other): return True
    def __gt__(self, other): return False

MAX, MIN = _max(), _min()

print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")])))
# [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>]

rawDescription: Python: Usable Max and Min values

description: Python: Usable Max and Min values


code:
parser.add_argument('--include','-i', default=[], nargs='*', action="append")
parser.add_argument('--exclude','-e', default=[], nargs='*', action="append")
parser.add_argument('include', nargs='*', action="append")

rawDescription: Handling string with delimiters in argparse


code:
import sys

inputFile = open(sys.argv[2],"r")
outputFile = open(sys.argv[3], "w")
leadingRemoved=int(sys.argv[1])

#strips extra whitespace from each line in file then splits by ","
lines = [x.strip().split(",") for x in inputFile.readlines()]
#zips all but the first x number of elements in the first and third row
zipped = zip(lines[0][leadingRemoved:],lines[2][leadingRemoved:])
for tuples in zipped:
    #writes the question/ number pair to a file.
    outputFile.write(",".join(tuples))

inputFile.close()
outputFile.close()

#input from command line: python questions.py leadingRemoved pathToInput pathToOutput

rawDescription: How to extract specific data from a downloaded csv file and transpose into a new csv file?

description: Extract specific data from a downloaded csv file and transpose into a new csv file


code:
from pygments.styles import get_all_styles
list(get_all_styles())

rawDescription: IPython nbconvert to latex - syntax colouring


code:
def count (*args):
    l = len(args[0])
    end = {}
    for lst in args:
        y = 0
        for x in lst:

            end.setdefault(x, l*[0])
            end[x][y] += 1
            y += 1
    return end

rawDescription: Python dict count

description: Python dict count


code:
for url in re.findall(r'"(http[^"]+).*360p"', elt.text):
    print(url)

rawDescription: using python lxml+xpath to get videos from a page, get a list but can't print out the result?

description: Using python lxml+xpath to get videos from a page, get a list but can't print out the result


rawDescription: What are the upper and lower bound for Chinese char in UTF-8?


code:
import json
dict_str = """{"a":[1,2,3], "b":[4,5]}
              {"z":[-1,-2], "x":-3}"""
#strip the whitespace away while making list from the lines in dict_str
dict_list = [d.strip() for d in dict_str.splitlines()]

dict_list
['{"a":[1,2,3], "b":[4,5]}', '{"z":[-1,-2], "x":-3}']
j = [json.loads(i) for i in dict_list]
j
[{u'a': [1, 2, 3], u'b': [4, 5]}, {u'x': -3, u'z': [-1, -2]}]

rawDescription: How to convert a string with multiple dictionaries, so json.load can parse it?

description: Convert a string with multiple dictionaries, so json.load can parse it


code:
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'pubdate','user')

class MyPosts(Post):
    class Meta:
        proxy = True

class MyPostAdmin(PostAdmin):
    def queryset(self, request):
        return self.model.objects.filter(user = request.user)

admin.site.register(Post, PostAdmin)
admin.site.register(MyPost, MyPostAdmin)

rawDescription: Multiple ModelAdmins/views for same model in Django admin


code: [' Saturday, June 20, 2015', ' Friday, June 19, 2015', ' Thursday, June 18, 2015', ' Wednesday, June 17, 2015', ' Tuesday, June 16, 2015', ' Monday, June 15, 2015', ' Sunday, June 14, 2015']

rawDescription: Problems with turning a timedelta calculation into " %A, %B %d, %Y"


code: items = [x + step for x in items]

rawDescription: Iterate over a list indexes

description: Iterate over a list indexes


code:
x = [dte for dte in d if dte <= cutoff]
y = [[],[]]
for k in x:
    y[0].append(d[k]["start qty"])
    y[1].append(d[k]["end qty"])

rawDescription: transforming nested dictionaries into various lists

description: Transforming nested dictionaries into various lists


code:
import numpy as np

a = np.ravel(your_list_of_lists)

np.setdiff1d(np.arange(21000), a)

rawDescription: Python: Find indices which are *not* contained in a list of lists


rawDescription: Parsing an equation with custom functions in python


code: df

rawDescription: Summing values in a group of a groupby object?


code:
b.__class__.__str__ =  lambda self: "In b"
print(str(a))
print(str(b))

rawDescription: Making len() work with instance methods

description: Making len() work with instance methods


rawDescription: Python regex get with zero or more occurences within the pattern


code:
def titlecase(s):
    return re.sub(re.compile(r"[\w]+('[\w]+)?", flags=re.UNICODE),
                  lambda mo: mo.group(0)[0].upper() +
                             mo.group(0)[1:].lower(),
                  s)

rawDescription: How can I use str.title with another language?

description: Use str.title with another language


code:
class MyFile():
    def __enter__(self):
        return self

    def __init__(self, path):
        ''' store the path, but don't actually open the file '''
        self.path = path
        self.file_object = None

    def write(self, s):
        ''' you open the file here, just before writing '''
        if not self.file_object:
            self.file_object = open(self.path, 'w')
        self.file_object.write(self, s)

    def close(self):
        ''' close the file '''
        if self.file_object:
            self.file_object.close()

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.close()

rawDescription: Delete log file if it is empty after being closed


code:
def _validate_item(item):
    if item <= 0:
        raise ValueError("item should be positive.")

rawDescription: Unit testing a method called during initialization?


code:
df = pd.DataFrame({
  'dep': np.random.choice(list('ABC'), 20),
  'manager_id': np.random.randint(0, 10, 20),
  'salary': np.random.randint(5000, 5006, 20)
})

rawDescription: Pandas: top N rows, top N rows per group, equivalent for ROW_NUMBER OVER(PARTITION BY ... ORDER BY ...)


code:
class Product(models.Model):
    name = models.CharField()

class ProductImage(models.Model):
    product = models.ForeignKey(Product)
    image = models.ImageField()

class ProductWeight(models.Model):
    product = models.ForeignKey(Product)
    weight = models.DecimalField()

class ProductURL(models.Model):
    product = models.ForeignKey(Product)
    url = models.URLField()

class ProductFile(models.Model):
    product = models.ForeignKey(Product)
    file = models.FileField()

rawDescription: How do you implement multiple data types for an object in Django?

description: Implement multiple data types for an object in Django


code:
from ctypes import windll, byref
from ctypes.wintypes import SMALL_RECT

STDOUT = -12

hdl = windll.kernel32.GetStdHandle(STDOUT)
rect = wintypes.SMALL_RECT(0, 50, 50, 80) # (left, top, right, bottom)
windll.kernel32.SetConsoleWindowInfo(hdl, True, byref(rect))

rawDescription: How to control the size of the Windows shell window from within a python script?

description: Control the size of the Windows shell window from within a python script


code:
class SjsuSpider(CrawlSpider):

    name = 'sjsu'
    allowed_domains = ['sjsu.edu']
    start_urls = ['http://cs.sjsu.edu/']
    # allow=() is used to match all links
    rules = [Rule(SgmlLinkExtractor(allow=()), callback='parse_item')]

    def parse_item(self, response):
        x = HtmlXPathSelector(response)

        filename = "sjsupages"
        # open a file to append binary data
        open(filename, 'ab').write(response.body)

rawDescription: scrapy crawling just 1 level of a web-site

description: Scrapy crawling just 1 level of a web-site


rawDescription: User selects file names and writes the file names to a text file [Python]


code:
from unidecode import unidecode
unidecode(phrase)

rawDescription: Problems with encoding while parsing website (html) and getting strings


code:
def purify(numbers):
    numbers_buf = numbers
    should_be = numbers[:]
    for ind, item in enumerate(numbers):
        print("{} should be at {}, is at {}".format(item,should_be.index(item),ind))
        if item % 2:
            numbers_buf.remove(item)
    return numbers_buf
print(purify([4,5,4,7,3,1]))

rawDescription: Python remove element in for loop

description: Python remove element in for loop


code:
my_string = "Here come the braces : {a{b}c}d{e}f"
additional_content = " : {}"
additional_content = additional_content.format(42)
my_string += additional_content
my_string

rawDescription: Python Alternative to Old String Formatting


code: pd.concat([df1, df2, df3], axis=1, keys=['df1', 'df2', 'df3'])

rawDescription: Append Level to Column Index in python pandas


rawDescription: What is an alternative to sorted() in this situation? Or can this be managed?


rawDescription: How to replace commas with tabs in TSV File

description: Replace commas with tabs in TSV File


code: sum(prices[k]*stock[k] for k in prices)

rawDescription: Multiplying and then summing values from two dictionaries


code:
from functools import singledispatch

@singledispatch
def bar(x):
    pass

@bar.register(RDD)
def _(arg):
    return "RDD"

@bar.register(DataFrame)
def _(arg):
    return "DataFrame"

bar(sc.parallelize([]))
## 'RDD'

bar(sc.parallelize([("foo", 1)]).toDF())
## 'DataFrame'

rawDescription: Check Type: How to check if something is a RDD or a dataframe?


code:
def can_afford(path, cards):
    """
    Return True if `path` can be followed using `cards`, False if not.
    `cards` might be updated, so pass a copy if you don't want that to
    happen.
    """
    grays = []
    for segment in path:
        c, w = segment.color, segment.weight
        if c == 'Gray':
            grays.append(w)
        elif cards.get(c, 0) >= w:
            cards[c] -= w
        else:
            return False
    return packing(tuple(cards.values()), tuple(grays)) is not None

rawDescription: "Ticket to Ride" board game logic for gray routes


code:
import tkinter
from tkinter.filedialog import askopenfile

f = askopenfile(filetypes=[("Text files","*.txt")])

import_list = []

txt = f.read()

import_list.append(txt)
# import_list[-1] now contains txt

# ... any other operations on f.

f.close()

rawDescription: How to read a randomly imported text file and store it in a list

description: Read a randomly imported text file and store it in a list


code:
import Image
import ImageFont
import ImageDraw

font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
text = "copyright"
size = font.getsize(text)
img = Image.new('RGBA', size=size, color=(0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fill=(209, 239, 8), font=font)
img.save('label.jpg')

rawDescription: A watermark inside a rectangle which filled the certain color


code:
def split_subsequences(iterable, length=2, overlap=0):
    it = iter(iterable)
    results = list(itertools.islice(it, length))
    while len(results) == length:
        yield results
        results = results[length - overlap:]
        results.extend(itertools.islice(it, length - overlap))
    if results:
        yield results

rawDescription: Python Equivalent to Ruby's #each_cons?

description: Python Equivalent to Ruby's #each_cons


code:
from pysqlite2 import dbapi2 as sqlite
conn = sqlite.connect(...)
conn.row_factory = dict_factory

rawDescription: Sqlite and Python -- return a dictionary using fetchone()?


code:
def map_intenum(data):
    if isinstance(data, IntEnum):
        return {'__class__': o.__class__.__name__,
                '__value__': (o.value,)}
    if isinstance(data, dict):
        return {k: map_intenum(v) for k, v in data.iteritems()}
    if isinstance(data, (list, tuple)):
        return [map_intenum(v) for v in data]
    return data

rawDescription: How do I serialize IntEnum from enum34 to json in python?

description: Serialize IntEnum from enum34 to json in python


code:
c = sum((Counter(set(x)) for x in docDict.itervalues()), Counter())
{k: {k1:c[k1] for k1 in set(v)} for k, v in docDict.iteritems()}

rawDescription: How to count the documents which contain a specific word?

description: Count the documents which contain a specific word


code:
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
    captcha_login = CaptchaField()

rawDescription: Django Tastypie Captcha

description: Django Tastypie Captcha


rawDescription: Merge several tuples in python list

description: Merge several tuples in python list


rawDescription: Select dataframe rows between two dates

description: Select dataframe rows between two dates


rawDescription: Python working with objects

description: Python working with objects


rawDescription: Pandas - bucketing events close to each other


code:
import dis
dis.dis(lambda: print_arg(**{'key': 'value'}))

rawDescription: Mutability of the **kwargs argument in Python


code:
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z,rstride=1, cstride=1, cmap=cm.jet)
plt.show()

rawDescription: 2 dimensional interpolation problem

description: 2 dimensional interpolation problem


code: shutil.copy(srcfile, dstdir)

rawDescription: Python - Copying only new files into another directory


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

def centeredDistanceMatrix(n):
    # make sure n is odd
    x,y = np.meshgrid(range(n),range(n))
    return np.sqrt((x-(n/2)+1)**2+(y-(n/2)+1)**2)

def function(d):
    return np.log(d) # or any function you might have

d = centeredDistanceMatrix(101)
f = function(d)
plt.plot(np.arange(51),function(np.arange(51)))
plt.show()
plt.imshow(f.T,origin='lower',interpolation='nearest')
plt.show()

rawDescription: Converting 1D radial profil to 2D image

description: Converting 1D radial profil to 2D image


code:
import numpy as np

kern = np.hanning(50)   # a Hanning window with width 50
kern /= kern.sum()      # normalize the kernel weights to sum to 1

hanning = ndimage.convolve1d(img, kern, 1)

rawDescription: Smoothing a 2D array along only one axis


code:
from Taco import Taco
from Spaghetti import Spaghetti

rawDescription: Modularizing peewee

description: Modularizing peewee


code:
a = 'The quick brown fox.'
b = 'The quick brown fox jumped over the lazy dog.'
import difflib
s = difflib.SequenceMatcher(None, a, b)
s.find_longest_match(0,len(a),0,len(b))

rawDescription: What is a simple fuzzy string matching algorithm in Python?


code: ps1 = 'something else '

rawDescription: Python import and module scoping (specifically sys.ps1)


code:
from collections import defaultdict, Counter

totals = defaultdict(Counter)

for item in data:
    cat = item.pop('cat')
    totals[cat] += Counter(item)

rawDescription: python dictionary with two running totals

description: Python dictionary with two running totals


code:
import re
from itertools import product

my_list = ['ab', 'cde']
keywords = ['ab', 'cd', 'de']

indices = {}
pats = [re.compile(i) for i in keywords]

for i, pat in product(my_list, pats):
    indices.setdefault(i, [])
    for m in re.finditer(pat, i):
        indices[i].append((m.start(), m.end()))

print(indices)

rawDescription: Nesting lists in for loop in python

description: Nesting lists in for loop in python


code: alldeciles = len({x // 10 for x in l}) == 5

rawDescription: How to check if a group of numbers are represented from each decile?

description: Check if a group of numbers are represented from each decile


code:
import numpy as np
n = len(Tm)
t = np.empty(n)

t[0] = 0  # or whatever the initial condition is
t[1:] = Tm[1:] + (t[0:n-1] - Tm[1:])**(-tau[1:])

rawDescription: Is a "for" loop necessary if elements of the a numpy vector are dependant upon the previous element?


code: a = [mynamedtuple(*el) for el in a]

rawDescription: Named tuples in a list

description: Named tuples in a list


code:
def merge(lst, ngroups):
    return [' '.join(lst[start::ngroups]) for start in xrange(ngroups)]

rawDescription: Concatenating Arbitrary number of items of a string in Python


code:
import csv
csv.register_dialect('csvrd', delimiter='\t', quoting=csv.QUOTE_NONE)
data = '''\
c11\tc21\tc31
c21\tc22\tc32
'''
reader = csv.reader(data.splitlines(True), 'csvrd')
a0, a1, a2 = zip(*reader)
a0
a1
a2

rawDescription: Python - CSV Reader List Comprehension

description: Python - CSV Reader List Comprehension


rawDescription: Pivoting SQLite table, setwise like SQL should be


code:
mask = (graph_array[:, :2]==[r,c]).all(axis=1)
graph_array[mask,3] = d

rawDescription: Speed up operations on a for loop with `coo` matrix and a numpy array in python


code:
textEdit = QtGui.QTextEdit()
scrollArea = QtGui.QScrollArea(MainWindow)
scrollArea.setWidget(textEdit)

rawDescription: Adding Content to pyqt4 scroll area

description: Adding Content to pyqt4 scroll area


code: soup.find_all('div', class_="crBlock ")

rawDescription: Using BeautifulSoup to select div blocks within HTML


code:
img = Image.new("L", (3, 3))
data = [0, 255, 0, 255, 0, 255, 0, 255, 0]
img.putdata(data)
img.save("checkerboard.png")

rawDescription: Python: how do you create an array with information about each pixel from an image?


code:
view.py
from . import forms

def my_view(request):

    preset_form = forms.PresetListForm()

    return render_to_response('services.html', {
        'array': json.dumps(data, cls=SpecialEncoder),
        'preset_form': preset_form,
    })

rawDescription: HTML tags for choicefield in Django

description: HTML tags for choicefield in Django


code:
def get_queryset(self):
    # You are sending GET params here, not POST
    form = InputForm(self.request.GET)
    if form.is_valid():
        company = form.cleaned_data['company']
        region = form.cleaned_data['region']

        queryset=Result.objects.filter(region=region)
        return queryset
    return Result.objects.all()

rawDescription: django- why after redirecting, the form display "None"

description: Django- why after redirecting, the form display "None"


code: print('Current construct number is: #' + row[0] + ' on row ' + str(counter) + ', which is a Gibson assembly')

rawDescription: Processing a sub-list of variable size within a larger list


rawDescription: Python: How to convert a rgb or hex value to single color values


code:
text = incoming_bytes.decode("shift_jis")
# ... do stuff ...
outgoing_bytes = text.encode("shift_jis")

rawDescription: How to detect double-byte numbers

description: Detect double-byte numbers


code: list(xrange(1, 6, 2))

rawDescription: list of random integers without zero Python

description: List of random integers without zero Python


code:
from pylab import *
from scipy.spatial import ConvexHull

def hit(U,hull):
    eq=hull.equations.T
    V,b=eq[:-1],eq[-1]
    alpha=-b/dot(V,U)
    return np.min(alpha[alpha>0])*U

rawDescription: Intersection of nD line with convex hull in Python


code:
import xml.etree.ElementTree as ET

def getUnparsedContent(element):
    return ''.join(ET.tostring(e) for e in element)

xmlstring = """<myTag1 myAttrib="value">
  <myTag2>

My what a lovely day.

  </myTag2>
</myTag1>"""

root = ET.fromstring(xmlstring)
print(getUnparsedContent(root[0]))

rawDescription: In Python, Parsing Custom XML Tags Without Parsing HTML


code:
tupleOfTuples = ((1, 2), (3, 4), (5,))
[element for tupl in tupleOfTuples for element in tupl]

rawDescription: How do I convert a tuple of tuples to a one-dimensional list using list comprehension?

description: Convert a tuple of tuples to a one-dimensional list using list comprehension


code:
def poisci_pare(text):
    sents = text.split('.')
    answer = [sent.split() for sent in sents if sent]
    return answer

rawDescription: Python how to split a string inside a list


code: latin1 = 'abcdé'.decode('latin1')  # provided `é` is stored in the source as a E9 byte.

rawDescription: Specifying unicode literal's encoding on a per-literal basis


code:
class A:
    def __init__(self, name):
        self.name = name
    def foo(self):
        print(self.name)

a = A('One')
a.foo
a.foo.__self__
a.foo.__func__
A.__dict__['foo']
A.__dict__['foo'].__get__(a, A)
A.__dict__['foo'].__get__(a, A)()

rawDescription: Does Python really create all bound method for every new instance?


code:
boomBangs = lambda xs: ("BOOM!" if x < 10 else "BANG!" for x in xs if odd(x))

def boomBang(xs):
  return ("BOOM!" if x < 10 else "BANG!" for x in xs if odd(x))

rawDescription: Partially applied List Comprehension

description: Partially applied List Comprehension


code:
combinations_dict = {}
for comb in combinations_dict_list:
    if not combinations_dict.get(comb['color'], {}):
        combinations_dict[comb['color']] = {}
    if not combinations_dict[comb['color']].get(comb['size'], {}):
        combinations_dict[comb['color']][comb['size']] = {}
    combinations_dict[comb['color']][comb['size']] = comb['color__count']

colors = combinations_dict.keys()
sizes = combinations_dict[colors[0]].keys()

rawDescription: Django object query for counting different combinations of column counts


code:
not_on_flickr = []
for file_on_drive in files_on_drive:
    if file_on_drive in flickr_photos:
        continue
    else:
        not_on_flickr.append(file_on_drive)
print(not_on_flickr)

rawDescription: Python compare differences in XML.Etree and file and folder names in directory listings


code:
fig1 = plt.figure()
ax = fig1.add_subplot(111)
ax.plot(new_series,your_pandas_dataframe)

rawDescription: pandas, matplotlib, use dataframe index as axis tick labels

description: Pandas, matplotlib, use dataframe index as axis tick labels


code:
def palindrome(word):
    if len(word) > 1:
        return word == word[::-1]
    return word.isalpha()

rawDescription: Python Palindrome Help: Count palindromes in a sentence


code:
import matplotlib.pyplot as plt

fig = plt.figure()

for idx in xrange(9):
    ax = fig.add_subplot(3, 3, idx+1) # this line adds sub-axes
    ...
    ax.imshow(patch) # this line creates the image using the pre-defined sub axes

fig.savefig('test.png')

rawDescription: python subplot for loop

description: Python subplot for loop


code:
grouped = df.groupby('one')
grouped.apply(lambda x: x.index[0])

rawDescription: How do I get the first timestamp (index) of a group when applying groupby to a python pandas dataframe?

description: Get the first timestamp (index) of a group when applying groupby to a python pandas dataframe


code:
all_samples = df.sample(50)
samples = [all_samples.iloc[5*i:5*i+5] for i in range(10)]

rawDescription: Pandas create random samples without duplicates


rawDescription: How to open external programs in Python

description: Open external programs in Python


code:
import numpy as np
d1 = np.array([[1, 2, 3], [4, 5, 6]])
d2 = np.array([[7, 8, 9], [1, 2, 3]])
d3 = np.array([d1, d2])

dnew = np.array([[6, 5, 4], [3, 2, 1]])
d3 = np.array([dnew] + [d3[a, ...] for a in range(d3.shape[0])])

# Add to the end of the array
dlast = np.array([[6, 5, 4], [3, 2, 1]])
d3 = np.array([d3[a, ...] for a in range(d3.shape[0])] + [dlast])

rawDescription: combine 2-d array to existing 3-d array

description: Combine 2-d array to existing 3-d array


code:
Problem #1: Check if a data row is longer than the header row:
for i in csv[1:]:
    if len(i) > len(csv[0]):
        print("found a data row that is longer then the header row.")

rawDescription: Python- Check in the CSV file the Header value and data value is equal


code:
def and_(op1, op2):
    return op1 and op2

def or_(op1, op2):
    return op1 or op2

rawDescription: Python function for boolean "and" operator?


code: [x for i, x in enumerate(unculledlist) if (i % 6) % 2 == 0 if (i % 5) % 2 == 0]

rawDescription: Remove items from list by using python list comprehensions


rawDescription: Linking two related lists of different lengths in python


rawDescription: count number of formats in a python string

description: Count number of formats in a python string


code:
def choose_acct():
    while True:
        get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
        if get == "Adap1":
            return Adap1
        elif get == "Adap2":
            return Adap2
        elif get == "Adap3":
            return Adap3
        elif get == "Adap4":
            return Adap4

rawDescription: How to change a global variable in python?

description: Change a global variable in python


code:
def test_iter_user_repos(self):
    self.response('repo', _iter=True)
    self.get('https://api.github.com/users/sigmavirus24/repos')
    self.conf.update(params={'type': 'all', 'direction': 'desc'})

    next(self.g.iter_user_repos('sigmavirus24', 'all', direction='desc'))
    self.mock_assertions()

    self.conf.update(params={"sort": "created"})
    self.get('https://api.github.com/users/sigmavirus24/repos')

    assert isinstance(next(self.g.iter_user_repos('sigmavirus24', sort="created")),
                      github3.repos.Repository)
    self.mock_assertions()

rawDescription: How can I find all public repos in github that a user contributes to?

description: Find all public repos in github that a user contributes to


code:
class MainWindow(QWidget): # or QMainWindow
    ...

    def closeEvent(self, event):
        # do stuff
        if can_exit:
            event.accept() # let the window close
        else:
            event.ignore()

rawDescription: PySide / PyQt detect if user trying to close window


code:
x = int(input("Geef de X as op >> "))
y = int(input("Geef de Y as op >> "))

rawDescription: Python click bot TypeError: an integer is required #CookieClickerV2


code:
a
b
a - b[:,None]

rawDescription: Subracting all elements of array A from all elements of B?


code:
class DemoTest(unittest.TestCase):

    D1 = {'a': 1, 'b': 2, 'c': [1, 2]}
    D2 = {'a': 1, 'b': 2, 'c': [1]}

    def test_useful(self):
        self.assertDictEqual(self.D1, self.D2)

    def test_not_so_useful(self):
        assert self.D1 == self.D2

rawDescription: Why assertDictEqual is needed if dicts can be compared by `==`?


code:
before = [67,45,2,13,1,998]

after = sorted(before) # creates a completely  new list

print(after)

rawDescription: Why is object.sort() passing None to variable?


code:
from collections import Counter
counter = Counter(x)
counter.get(1)

rawDescription: Count the number of occurrences of an item in a list without list.count


code:
import re
' '.join([set([set(re.split(r'\s{2,}',i)).pop() for i in column]).pop() for column in zip(*splitted_lines)])

rawDescription: Python - Merging two strings that overlap


rawDescription: Creating a 2d mesh in python

description: Creating a 2d mesh in python


code:
import bunch_methods as bm
Bunch_Class = type('Bunch_Class', (), bm.__dict__)
bunch_object = Bunch_Class()
bunch_object.__class__
bunch_object.one(1)
bunch_object.two(1)

rawDescription: Progammatically turn module/set of functions into a Python class


code:
text= "I say what I mean. I mean what I say. i do."
sentences = text.lower().split('.')
dic = {}
i = -1
for sen in sentences:
    i += 1
    for word in sen.split():
        if word not in dic:
            dic[word] = [i]
        elif dic[word][-1] != i:     # this prevents duplicate entries
            dic[word].append(i)

dic

rawDescription: word/pair list using dictionaries and strings

description: Word/pair list using dictionaries and strings


rawDescription: Pythonic way to create a list with X amount of empty sub-lists


code:
names = ['ALICE', 'BOB', 'ME']
sum(i * sum(ord(ch) - ord('A') + 1 for ch in name) for i, name in enumerate(names, 1))

rawDescription: Python for loop with two related variables


code:
from celery import task

@task(name='my_task')
def my_task():
     ...

rawDescription: Call Django celery task by name

description: Call Django celery task by name


rawDescription: What is the most efficient method to assign an X and Y header for a list of the following nature?


code:
class CustomFilter(logging.Filter):
    def __init__(self, state):
        self.state = state

    def filter(self, record):
        if self.state == 1:
            return record.levelno in [logging.INFO, logging.ERROR,
                                      logging.CRITICAL]
        elif self.state == 2:
            return record.levelno in [logging.INFO, logging.DEBUG,
                                      logging.ERROR, logging.CRITICAL]
        elif self.state > 2:
            return record.levelno in [logging.INFO, logging.DEBUG,
                                      logging.ERROR, logging.CRITICAL,
                                      logging.WARNING]
        else:
            return False

h1 = logging.StreamHandler(sys.stdout)
logger = logging.getLogger("my.logger")
logger.setLevel(logging.DEBUG)
print("No logging:")
f1 = CustomFilter(0)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
print ("Level 1:")
h1.removeFilter(f1)
f1 = CustomFilter(1)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
print("Level 2:")
h1.removeFilter(f1)
logger.removeHandler(h1)
f1 = CustomFilter(2)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")
print("Level 3:")
h1.removeFilter(f1)
logger.removeHandler(h1)
f1 = CustomFilter(3)
h1.addFilter(f1)
logger.addHandler(h1)
logger.info("info")
logger.debug("debug")
logger.error("error")
logger.warning("warning")
logger.critical("critical")

rawDescription: How to tweak the logging level behaviour?

description: Tweak the logging level behaviour


rawDescription: "Easy" Access to Facebook Profile Photo via Graph API


code: wordcounts = nltk.ConditionalFreqDist((w.lower(), t) for w, t in brown.tagged_words())

rawDescription: Python NLTK - Making a 'Dictionary' from a Corpus and Saving the Number Tags


code: itertools.product(*[(0, 1)] * n)

rawDescription: Get a list of all possible binary tuples with length n


code:
grouper = (v!=v.shift()).cumsum()
grouper

rawDescription: Pandas cumulative sum on column with condition


code: df['total'] = df[['drinking', 'drugs', 'both']].sum(axis=1)

rawDescription: pandas: append new column of row subtotals

description: Pandas: append new column of row subtotals


code: master = {}

rawDescription: Using Nested Dictionaries in Python -- combining two datasets with a common 'key' and different other variables


code:
hr, sec = divmod(sec, 3600)
min, sec = divmod(sec, 60)
offstr = '{:+03d}{:02d}'.format(hr, min)

rawDescription: Time issues in Python

description: Time issues in Python


code:
xfmt = mdates.DateFormatter('%b %d')
ax.xaxis.set_major_formatter(xfmt)

rawDescription: How do I display dates when plotting in matplotlib.pyplot?

description: Display dates when plotting in matplotlib.pyplot


code: scrabble_table = scrabble_table.replace(' ', '')

rawDescription: Pandas: transform a DataFrame by splitting each value into multiple values


rawDescription: Numpy loadtxt single line into multidim-array


rawDescription: How to change value in dataframe

description: Change value in dataframe


code:
def mydecorator(f,cls):
    #f is the method being modified, cls is its class (in this case, Datum)
    def func_wrapper(*args,**kwargs):
        #*args and **kwargs are all the arguments that were passed to f
        newvalue = f(*args,**kwargs)
        #newvalue now contains the output float would normally produce
        ##Now get cls instance provided as part of args (we need one
        ##if we're going to reattach instance information later):
        try:
            self = args[0]
            ##Now check to make sure new value is an instance of some numerical
            ##type, but NOT a bool or a cls type (which might lead to recursion)
            ##Including ints so things like modulo and round will work right
            if (isinstance(newvalue,float) or isinstance(newvalue,int)) and not isinstance(newvalue,bool) and type(newvalue) != cls:
                ##If newvalue is a float or int, now we make a new cls instance using the
                ##newvalue for value and using the previous self instance information (arg[0])
                ##for the other fields
                return cls(newvalue,self.dtype,self.source,self.index1,self.index2)
        #IndexError raised if no args provided, AttributeError raised of self isn't a cls instance
        except (IndexError, AttributeError):
            pass
        ##If newvalue isn't numerical, or we don't have a self, just return what
        ##float would normally return
        return newvalue
    #the function has now been modified and we return the modified version
    #to be used instead of the original version, f
    return func_wrapper

rawDescription: How to set up a class with all the methods of and functions like a built in such as float, but holds onto extra data?

description: Set up a class with all the methods of and functions like a built in such as float, but holds onto extra data


rawDescription: python - sort mongodb by the value of one key

description: Python - sort mongodb by the value of one key


rawDescription: Numpy Vector (N,1) dimension -> (N,) dimension conversion


rawDescription: Reading the CSV file and extract the desired amount of data using python


code:
a.uint /= 2
a.bin
list(a.findall('0b1011'))
a *= 2     # concatenation
a.bin
a.replace('0b00001', '0xe')
a.bin

rawDescription: Patterns in Binary Fractions with Python


code: tree

rawDescription: Navigate trough lxml categories

description: Navigate trough lxml categories


code:
offset = 2
aString = raw_input("digit a letter: ")
aString
chr(ord(aString)+offset)

rawDescription: Returning the value of an index in a python list based on other values


code:
user_flags = {'is_registered':True, 'has_paid':False, 'has_phone':True}
not any(not value for value in user_flags.values())
user_flags = {'is_registered':True, 'has_paid':True, 'has_phone':True, 'one_more_flag':True}
not any(not value for value in user_flags.values())

rawDescription: Verify state of boolean variables in a dict


code:
dict1 = {str(i):None for i in range(10000)}
dict2 = {}
dict2.update(dict1)

rawDescription: Order of traversal in dictionary

description: Order of traversal in dictionary


code:
def save(self):
    heap_copy = tuple(self.heap)
    toll = self.toll
    gevent.spawn(save_heap, heap_copy, toll)

rawDescription: How could a distributed queue-like-thing be implemented on top of a RBDMS or NOSQL datastore or other messaging system (e.g., rabbitmq)?


code:
class Foo(object):
    @autoassign
    def __init__(self,a,b,c=False,*args):
        pass
a=Foo('IBM','/tmp',True, 100, 101)
print(a.args)
# AttributeError: 'Foo' object has no attribute 'args'

rawDescription: What is the best way to do automatic attribute assignment in Python, and is it a good idea?


code: reduce(pd.merge, tmp)

rawDescription: Concatenating/Merging List of Dataframes by Predefined columns


rawDescription: Solving symbolically. Choosing the symbols in the final representation


code:
per_url = {}
for entry in a + b:
    key = entry['url']
    if key not in per_url:
        per_url[key] = entry.copy()
    else:
        per_url[key]['views'] += entry['views']

c = per_url.values()  # use list(per_url.values()) on Python 3

rawDescription: Combine two lists of dicts, adding the values together


code:
import datetime

def get_ldap_date_range_query(dt):
    start_date = dt.replace(hour=0, minute=0, second=0)
    end_date = dt.replace(hour=23, minute=59, second=59)

    return "(&(createTimestamp>=%s)(createTimestamp<=%s))" % (convert_datetime_to_generalized_time(start_date),
                                                              convert_datetime_to_generalized_time(end_date))

print(get_ldap_date_range_query(datetime.datetime.now() - datetime.timedelta(days=1)))

rawDescription: Querying LDAP by date

description: Querying LDAP by date


code: tuples = sorted(zip(name, score_list))

rawDescription: How to sort a list according to another list? Python

description: Sort a list according to another list? Python


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

# If you're not familiar with np.r_, don't worry too much about this. It's just
# a series with points from 0 to 1 spaced at 0.1, and 9 to 10 with the same spacing.
x = np.r_[0:1:0.1, 9:10:0.1]
y = np.sin(x)

fig,(ax,ax2) = plt.subplots(1, 2, sharey=True)

# plot the same data on both axes
ax.plot(x, y, 'bo')
ax2.plot(x, y, 'bo')

# zoom-in / limit the view to different portions of the data
ax.set_xlim(0,1) # most of the data
ax2.set_xlim(9,10) # outliers only

# hide the spines between ax and ax2
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.yaxis.tick_right()

# Make the spacing between the two axes a bit smaller
plt.subplots_adjust(wspace=0.15)

# This looks pretty good, and was fairly painless, but you can get that
# cut-out diagonal lines look with just a bit more work. The important
# thing to know here is that in axes coordinates, which are always
# between 0-1, spine endpoints are at these locations (0,0), (0,1),
# (1,0), and (1,1). Thus, we just need to put the diagonals in the
# appropriate corners of each of our axes, and so long as we use the
# right transform and disable clipping.

d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((1-d,1+d),(-d,+d), **kwargs) # top-left diagonal
ax.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-left diagonal

kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
ax2.plot((-d,d),(-d,+d), **kwargs) # top-right diagonal
ax2.plot((-d,d),(1-d,1+d), **kwargs) # bottom-right diagonal

# What's cool about this is that now if we vary the distance between
# ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),
# the diagonal lines will move accordingly, and stay right at the tips
# of the spines they are 'breaking'

plt.show()

rawDescription: Python/Matplotlib - Is there a way to make a discontinuous axis?


rawDescription: Ansible lineine file with regex is adding new line when it shouldn't


code:
import mymodule
mymodule.__doc__
mymodule.f.__doc__

rawDescription: print(__doc__) in Python 3 script

description: Print(__doc__) in Python 3 script


code:
anchors = response.selector.xpath("//table[@class='style1']//ul//li//a")
for anchor in anchors:
    link = anchor.xpath('@href').extract()[0]
    # go one level back and access text()
    name = anchor.xpath('../text()').extract()

rawDescription: XPath - How to access anchor text and href from the current node in a loop


rawDescription: How to evaluate an expression-tree in sympy?

description: Evaluate an expression-tree in sympy


code:
global_var = 7
#execfile('y.py')   # Python 2.x
with open('y.py') as f:
    exec(f.read())
print(global_var)

rawDescription: Allow a module loaded with imp to access local variables in python


rawDescription: capturing data from clients as hex using twisted Python

description: Capturing data from clients as hex using twisted Python


code:
import json

def create_tests(func_name, file):
    def decorator(cls):
        func = getattr(cls, func_name)
        # Set new funcs to class:
        with open(file, 'r') as fh:
            data = json.loads(fh.read())['data']
            for i, params in enumerate(data):
                def tmp(params=params):  # need for http://stackoverflow.com/q/7546285/1113207
                    def wrapper(self, *args, **kwargs):
                        return func(self, **params)
                    return wrapper
                setattr(cls, func_name + '_' + str(i), tmp())
        # Remove func from class:
        setattr(cls, func_name, None)
        return cls
    return decorator

rawDescription: How to dynamically create parameterized test from the file (json or yaml) in python

description: Dynamically create parameterized test from the file (json or yaml) in python


rawDescription: Extending Django Flatpages to accept template tags


code:
result2=[];
for ob in result:
  if ob.get('name') in list1:
    result2.append(ob)

rawDescription: How to make a query on pymongo cursor object [mongo db]

description: Make a query on pymongo cursor object [mongo db]


code:
G = [ [1,2,3] ]
next(i for i, (x,y) in enumerate(zip(G, G[1:])) if x == y)

rawDescription: Python: Index in a list of lists

description: Python: Index in a list of lists


code:
pd.pivot_table(df, index=['Month'], columns=['ID'],
               values=['Quantity'],aggfunc='sum')

rawDescription: How do I use timestamp dates as an index in a pivot table in python?

description: Use timestamp dates as an index in a pivot table in python


code:
import numpy as np

num_classes = 3
K_val  = np.array([[1,2,3,4,6],
                  [2,4,5,5,7]])

l_val  = np.array([[0,1,2,0,1],
                   [2,0,1,2,0]])

def label_distance(l_val, K_val):
    nrows, ncols = l_val.shape
    shift = (np.arange(nrows)*num_classes)[:, np.newaxis]
    result = (np.bincount((l_val+shift).ravel(), weights=K_val.ravel(),
                          minlength=num_classes*nrows)
              .reshape(nrows, num_classes))
    return result

print(label_distance(l_val, K_val))

rawDescription: Summation by class label without loop in numpy


code:
...
url(r'^(?P<pk>\d+)$', SingleCat.as_view(), name='category_details'),
...

rawDescription: Make that my categories displays each respective content isolatedly


code:
for idx in range(len(li)):
    i = li[idx]
    i = 'foo'

rawDescription: Can't modify list elements in a loop Python


code:
from dns import resolver

res = resolver.Resolver()
res.nameservers = ['8.8.8.8']

answers = res.query('stackexchange.com')

for rdata in answers:
    print (rdata.address)

rawDescription: Socket resolve DNS with specific DNS server


rawDescription: How to group items in an iterable object based on the first character of the item?

description: Group items in an iterable object based on the first character of the item


code:
from collections import OrderedDict
import random
items = OrderedDict((('B', [100, 10]), ('S', [8,80])))
rs = OrderedDict((k, random.gauss(*v)) for k,v in items.items())
rs

rawDescription: Take OrderedDictionary as an argument and apply random.gauss(mean,std)


code:
people = []
for id in persons_database:
    info = persons_database[id]
    people.append(Person(info[0], info[1], info[2]))

rawDescription: Dynamically create instances of a class python


code:
rounded_a[0] == rounded_b[0]
rounded_a[-1] == rounded_b[-1]

rawDescription: Rounding numbers - What's wrong here?

description: Rounding numbers - What's wrong here


code:
import re
re.findall(r"(?=(AAA(?:\w{3})*?CCC))", "AAAAGGCCCC")

rawDescription: Python Regular Expressions: How to repeat a repeat of a pattern?


code:
# Input array
# Verify outputs
np.allclose(arrc1,arrc2)
np.allclose(arrc1,arrc3)

rawDescription: Replace values in numpy 2D array based on pandas dataframe


code: page, resources = ghost.evaluate("document.getElementById('details').click();", expect_loading=True)

rawDescription: Ghost.py - click specific button

description: Ghost.py - click specific button


code:
def rolling_group(val):
    if pd.notnull(val): rolling_group.group +=1 #pd.notnull is signal to switch group
    return rolling_group.group
rolling_group.group = 0 #static variable

rawDescription: Combine rows (under a condition) in a Pandas Dataframe


code:
from channels import Channel
from .soup import ProviderParser, sort_articles_by_date
from .models import Provider
from django.template.loader import render_to_string
from json import dumps

class Content:
    def __init__(self, reply_channel):
        self.reply_channel = reply_channel

    def send(self, json):
        Channel(self.reply_channel).send({'content': dumps(json)})

def ws_message(message):
    providers = Provider.objects.all()
    content = Content(message.reply_channel)

    content.send({'providers_length': len(providers)})

    articles = []
    for provider in providers:

        content.send({'provider': str(provider)})

        parser = ProviderParser(provider)
        articles.extend(parser.parse_articles())

    sort_articles_by_date(articles)
    html = render_to_string('news_providers/article.html', {'articles': articles})

    content.send({'html': html})

rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


code:
def all_gt(nums, n):
    return [i for i in nums if i > n]

rawDescription: Constructing a list from another list in python


rawDescription: Python - Convert tab delimited file into csv in a specific manner


rawDescription: Add two matrices in python

description: Add two matrices in python


rawDescription: Pandas: subset by filtering for a variable level and group it returning a count?


code: parents = {n: [p1, p2] for n, p1, p2 in group}

rawDescription: interating through a list of lists to create a new list

description: Interating through a list of lists to create a new list


code:
class MyTable(QtGui.QTableWidget):

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_V and event.modifiers() == QtCore.Qt.ControlModifier:
            # Check to see if clipboard contains excel data.
            # Manually process clipboard data and insert
            # it into the table starting from the selected tableitem
            ...
            return
        super(MyTable, self).keyPressEvent(event)

rawDescription: PyQt4 table for inserting a table from the clipboard - tableWidget?


code:
import os.path

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

rawDescription: How to indicate the current directory of the script not me?

description: Indicate the current directory of the script not me


code:
from pyspark.ml.feature import Tokenizer
from pyspark.sql.functions import explode

tokenizer = Tokenizer(inputCol="document_text", outputCol="words")

tokenized = (tokenizer.transform(documents_df)
    .select(col("document_id"), explode(col("words")).alias("token")))

like_with_tokenizer = (tokenized
    .join(keywords_df, col("token") == col("keyword"))
    .drop("token"))

like_with_tokenizer.show()

## +-----------+-------+
## |document_id|keyword|
## +-----------+-------+
## |          3|haskell|
## |          1|  spark|
## |          2| erlang|
## +-----------+-------+

rawDescription: How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?


code: from myfile import a_function

rawDescription: Convert Python 3 script to function

description: Convert Python 3 script to function


code: a.foo = new_foo.__get__(a, type(a))

rawDescription: How can i add behaviour to a instance of a class without changing the base class

description: Add behaviour to a instance of a class without changing the base class


rawDescription: Splitting a filename into words and numbers in Python


code:
import urllib2

def image_handler(request):
    url = "http://someurl.com/image.png"
    image_file = urllib2.urlopen(url)
    request.response.body_file = image_file
    request.response.content_type = 'image/png'
    return request.response

rawDescription: How to send request to another server and response the result in pyramid view?

description: Send request to another server and response the result in pyramid view


rawDescription: How to update values for specific keys in dict in Python

description: Update values for specific keys in dict in Python


code:
from itertools import takewhile, izip, tee

data = ...

def criterion(_):
    prev, curr = _
    return prev[0] <= curr[0] and prev[1] >= curr[1]

it1, it2 = tee(iter(data))
print [next(it2)[0]] + [y[0] for x, y in takewhile(criterion, izip(it1, it2))]

rawDescription: Pythonic way to break out of iteration over tuples when one value changes


code:
['PTR1', 'needThis1', 'thisOneAsWell1']
['PTR2', 'needThis2', 'thisOneAsWell2']
['PTRN', 'needThisN', 'thisOneAsWellN']

rawDescription: Retreiving text from Pattern1 to Pattern2 - Python


code:
sep_names = name.split('_')
Name = 'Name='+sep_names[0]
Test = 'Test='+sep_names[2]
Data = 'Date='+sep_names[5]+'/'+sep_names[4]+'/'+sep_names[3]

rawDescription: Readable display of the filename using python


rawDescription: wxPython: how to make taskbar icon respond to left-click

description: WxPython: how to make taskbar icon respond to left-click


code:
from datetime import datetime
time = datetime.now().time()
hour, min, sec, micro = time.hour, time.minute, time.second, time.microsecond

rawDescription: Python program runs for a week, then fails mysteriously


code:
ListA = ['a1','a2','a1','a3','a2','a4','a5','a4']
ListB = ['b1','b2','b1','b3','b2','b4','b5','b4']
cB=collections.Counter(ListB)
cA=x=collections.Counter(ListA)
[i for i in cA if cA[i]>1]
[i for i in cB if cB[i]>1]

rawDescription: List order manipulating in Python

description: List order manipulating in Python


code: list1, list2 = list_of_lists = [list2, [0]*len(list2)]

rawDescription: Swap two lists in python

description: Swap two lists in python


rawDescription: Correct way of unit testing __repr__ with dict


code:
from gi.repository import Gdk as gdk

screen = gdk.Screen.get_default()

css_provider = gtk.CssProvider()
css_provider.load_from_path('/path/to/file.css')

context = gtk.StyleContext()
context.add_provider_for_screen( screen,
                                 css_provider,
                                 gtk.STYLE_PROVIDER_PRIORITY_USER
                                 )

rawDescription: pygtk global label style

description: Pygtk global label style


rawDescription: Python Argparser show parser from instancemethod


code:
class Foo(CommonEqualityMixin):
    __slots__ = ('a', )
    def __init__(self, a):
        self.a = a

Foo(1) == Foo(2)
# False
Foo(1) == Foo(1)
# True

rawDescription: Equality of Python classes using slots

description: Equality of Python classes using slots


code: import numpy as np

rawDescription: Average multiple vectors of points of different lengths in python


rawDescription: How can I get element from XML file with attribute having specific value

description: Get element from XML file with attribute having specific value


code:
A = np.dot((xx-yy),VI)
B = (xx-yy).T
n = A.shape[0]
D = np.empty(n)
for i in range(n):
    D[i] = np.sqrt(np.sum(A[i] * B[:,i]))

rawDescription: Calculate Mahalanobis distance using NumPy only


code:
prof = Profile()

progname = 'myscript.py'
sys.path.insert(0, os.path.dirname(progname))
with open(progname, 'rb') as fp:
    code = compile(fp.read(), progname, 'exec')
globs = {
        '__file__': progname,
        '__name__': '__main__',
        '__package__': None,
        '__cached__': None,
        }
modules = sys.modules.copy()
prof.runctx(code, globs, None)
newmodes = [modname for modname in sys.modules if modname not in modules]
for modname in newmodes:
    del sys.modules[modname]
prof.create_stats()
print(len(prof.stats))

rawDescription: Why is number of function calls different on second time?


code:
from ctypes import *

class object_t(Structure):
    _fields_ = [
        ('a', c_uint8),
        ('b', c_uint8),
        ('c', c_uint32),
        ('d', POINTER(c_uint8)),
    ]

callback_t = CFUNCTYPE(None, POINTER(object_t))

lib = CDLL('./file.dll')

func1 = lib.func1
func1.argtypes = None
func1.restype  = POINTER(object_t)

func2 = lib.func2
func2.argtypes = [callback_t]
func2.restype   = None

ret = func1()

a = ret.contents.a
b = ret.contents.b
c = ret.contents.c
d = ret.contents.d

def mycallback(obj):
    a = obj.contents.a
    b = obj.contents.b
    c = obj.contents.c
    d = obj.contents.d

func2(callback_t(mycallback))

rawDescription: How to access data from pointer in struct from Python with ctypes?

description: Access data from pointer in struct from Python with ctypes


code:
from collections import deque
from itertools import cycle

try:
    xrange
except NameError: # python3
    xrange = range

def pack(d):
    tup = tuple(d)
    return zip(cycle(tup[0:1]), tup[1:])

def window(seq, n=2):
    it = iter(seq)
    d = deque((next(it, None) for _ in xrange(n)), maxlen=n)
    yield pack(d)
    for e in it:
        d.append(e)
        yield pack(d)

rawDescription: Python nested loop - get next N lines

description: Python nested loop - get next N lines


code:
mismatch("ACG", "ACGTN", 0)
list(mismatch("ACG", "ACGTN", 0))
list(mismatch("ACG", "ACGTN", 1))

rawDescription: introducing mutations in a DNA string in python

description: Introducing mutations in a DNA string in python


rawDescription: Generating list with constraints

description: Generating list with constraints


code:
print("Enter positive, negative or zero to determine the average: ")
# get list of values/numbers from the user
values = [i for i in iter(lambda: int(input("Enter a number (-9999 to end): ")), -9999)]

rawDescription: Implementing a dictionary function to calculate the average of a list


code:
prices = {"apple" : 1.50, "banana" : 3.80, "cranberry" : 9.99}
order = [("apple", 4), ("banana", 1)]
total = sum_prices(order, prices)

rawDescription: How to add a list of tuples (Python)

description: Add a list of tuples (Python)


code:
line = u'ABcdef124__++--()zyxôôô999٤end'
print(''.join(c for c in line if c.isalpha()))

rawDescription: Replace all non-alphabet in a string

description: Replace all non-alphabet in a string


code:
from datetime import date, datetime, time
from babel.dates import format_date, format_datetime, format_time
d = date(2007, 4, 1)
format_date(d, locale='en')
format_date(d, locale='de_DE')

rawDescription: Convert date to natural language in python?


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

xdata, ydata, zdata = np.random.random((3, 10))

cmap = plt.cm.gist_earth
norm = plt.Normalize(zdata.min(), zdata.max())

fig, ax = plt.subplots()
for x, y, z in zip(xdata, ydata, zdata):
    ax.plot([x], [y], marker='o', ms=20, color=cmap(norm(z)))

sm = plt.cm.ScalarMappable(norm, cmap)
sm.set_array(zdata)
fig.colorbar(sm)

plt.show()

rawDescription: Colormap in Matplotlib without using the "scatter" function


code:
class User(db.Model, UserMixin):
    """
    Represents a registered user.

    @TODO Override setter for password so it is always encrypted.
    @TODO Add last_login column
    """

    __tablename__ = 'User'

    def __init__(self, username=None, password=None, email=None):
        self.username = username
        self.email = email
        self.password = encrypt(password)

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, default=u'Anonymous Lifter', info={'label': 'Name'})
    username = db.Column(db.String, nullable=False, info={'label': 'Username'})
    password = db.Column(db.String, nullable=False, info={'label': 'Password'})

rawDescription: How to set form element name?

description: Set form element name


code: model = CUSTOMER_MODELS.get(region)

rawDescription: Django: Get Model Name by a dynamic condition


code:
def int_dammit_else_float(s):
    f = float(s)
    i = int(f)
    return i if i == f else f

rawDescription: How can I convert a string to either int or float with priority on int?

description: Convert a string to either int or float with priority on int


code:
from nltk.tag.stanford import POSTagger
path_to_model= '/home/alvas/stanford-postagger-full-2015-01-30/models/arabic.tagger'
path_to_jar = '/home/alvas/stanford-postagger-full-2015-01-30/stanford-postagger-3.5.1.jar'

artagger = POSTagger(path_to_model, path_to_jar, encoding='utf8')
artagger._SEPARATOR = '/'
tagged_sent = artagger.tag(u"أنا تسلق شجرة")
print(tagged_sent)

rawDescription: Unknown symbol in nltk pos tagging for Arabic


rawDescription: see if list of keys exist in dictionaries of a dictionary in python

description: See if list of keys exist in dictionaries of a dictionary in python


code: newlist = ['{}:{}'.format(l, ','.join([w for w in list2 if w[0] == l])) for l in list1]

rawDescription: Only using items from one list once in nested list comprehension


code:
for index, row in enumerate(csv.DictReader(csvfile)):
    if index >= 100:
        break
    print(row['first_name'], row['last_name'])

rawDescription: Reading first n lines of a CSV into a dictionary


code:
from numpy.random import randint
n = 5000
G = Graph(directed=False)
G.add_vertex(n)
G.add_edge(0, 1)
for i in range(2, n):
    G.add_edge(i, randint(i))

rawDescription: Graph-tool surprisingly slow compared to Networkx


code: subprocess.check_call( ["./test.sh", loop], shell=False)

rawDescription: Passing variable from python script to bash script


code: table = zeros(npoints, dtype=int)

rawDescription: python(numpy) -- create array and how to implement an expression

description: Python(numpy) -- create array and how to implement an expression


code:
import matplotlib.pyplot as plt, numpy as np
...
line2d = plt.plot(xnew,heights_smooth)
xvalues = line2d[0].get_xdata()
yvalues = line2d[0].get_ydata()

rawDescription: How to extract points from a graph?

description: Extract points from a graph


code:
s1 = [('This', 'DT'), ('feature', 'NN'), ('would', 'MD'), ('be', 'VB'), ('nice', 'JJ'), ('to', 'TO'), ('have', 'VB')]
s2 = [('I', 'PRP'), ('am', 'VBP'), ('able', 'JJ'), ('to', 'TO'), ('delete', 'VB'), ('the', 'DT'), ('group', 'NN'), ('functionality', 'NN')]

def would_be(tagged):
   return any(['would', 'be', 'JJ'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][1]] for i in xrange(len(tagged) - 2))

def am_able_to(tagged):
    return any(['am', 'able', 'to', 'VB'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][0], tagged[i+3][1]] for i in xrange(len(tagged) - 3))

sent1 = ' '.join(s[0] for s in s1)
sent2 = ' '.join(s[0] for s in s2)

print("Is '{1}' of type 'would be' + adj? {0}".format(would_be(s1), sent1))
print("Is '{1}' of type 'am able to' + verb? {0}".format(am_able_to(s1), sent1))

print("Is '{1}' of type 'would be' + adj? {0}".format(would_be(s2), sent2))
print("Is '{1}' of type 'am able to' + verb? {0}".format(am_able_to(s2), sent2))

rawDescription: detecting POS tag pattern along with specified words

description: Detecting POS tag pattern along with specified words


code: myarr[myarr[:,0] != 2]

rawDescription: Concise way to get NumPy to return array of proper shape after logical indexing, without doing a reshape?


code:
vprod=np.vectorize(lambda x,y: x**2+y**2)
vprod(x[:,None],y[None,:]).shape

rawDescription: Reshaping numpy array without using two for loops


code:
def on_data(self, data):
    YourThreadSubclass(data).start()

rawDescription: How do I parallelize I/O-bound operations in Python?

description: Parallelize I/O-bound operations in Python


code:
from System.Windows import WindowState as WindowState1
from ESS.MS.Framework.UIG.Mask import WindowState as WindowState2

rawDescription: IronPython import two enums with the same name


code:
alphabet = set(['a', 'b', 'c'])
def T(x, y):
    return (alphabet - set([x, y])).pop()

rawDescription: Natural ternary logic?

description: Natural ternary logic


rawDescription: input to C++ executable python subprocess

description: Input to C++ executable python subprocess


rawDescription: Arabic strings generated by gettext are shown scrambled in Qt UI


code:
from itertools import count

def Generator(level=0, PData={}):
    '''prime generator that can save its internal data
    Refs:  http://stackoverflow.com/a/10733621
           http://stackoverflow.com/a/19391111
           http://stackoverflow.com/a/23258396'''
    # this version works if you don't stop before the first 4 primes
    dat=PData.get(level, 0)

    if not dat:# handling the initial primes
        for p in [2, 3, 5, 7]:
            yield p

        if STOP:return#lowest level has nothing to store so return

        D,c={},9
        ps=Generator(level+1, PData)
        next(ps);p=next(ps)
        psq=p*p

    else:       # past the initial primes, load from previous run
        D,c,p=PData[level]
        psq=p*p # need the squared prime, it was not stored
        g=0     # correction factor
        ps=Generator(level+1,PData)

        #if p<=7, its the lowest level, so skip previous values it gave before.
        while g<p and p<=7:g=next(ps)

    #all primes after initial set
    for i in count(c, 2):

        if STOP:
            Internals[level]=[D,i,p]#store dict, current value and prime
            next(ps)#call the next level down
            #it will hit this if statement and stop before changing its data
            break

        step=D.pop(i, 0)
        if not step:
            if i<psq:
                yield i
                continue
            else:
                step=2*p
                p=next(ps)
                psq=p*p
        i+=step
        while i in D:
            i+=step
        D[i]=step

rawDescription: Pausable prime generator

description: Pausable prime generator


code:
import sys
from collections import deque

class ExitStack(object):
    """Context manager for dynamic management of a stack of exit callbacks

    For example:

        with ExitStack() as stack:
            files = [stack.enter_context(open(fname)) for fname in filenames]
            # All opened files will automatically be closed at the end of
            # the with statement, even if attempts to open files later
            # in the list raise an exception

    """
    def __init__(self):
        self._exit_callbacks = deque()

    def pop_all(self):
        """Preserve the context stack by transferring it to a new instance"""
        new_stack = type(self)()
        new_stack._exit_callbacks = self._exit_callbacks
        self._exit_callbacks = deque()
        return new_stack

    def _push_cm_exit(self, cm, cm_exit):
        """Helper to correctly register callbacks to __exit__ methods"""
        def _exit_wrapper(*exc_details):
            return cm_exit(cm, *exc_details)
        _exit_wrapper.__self__ = cm
        self.push(_exit_wrapper)

    def push(self, exit):
        """Registers a callback with the standard __exit__ method signature

        Can suppress exceptions the same way __exit__ methods can.

        Also accepts any object with an __exit__ method (registering a call
        to the method instead of the object itself)
        """
        # We use an unbound method rather than a bound method to follow
        # the standard lookup behaviour for special methods
        _cb_type = type(exit)
        try:
            exit_method = _cb_type.__exit__
        except AttributeError:
            # Not a context manager, so assume its a callable
            self._exit_callbacks.append(exit)
        else:
            self._push_cm_exit(exit, exit_method)
        return exit # Allow use as a decorator

    def callback(self, callback, *args, **kwds):
        """Registers an arbitrary callback and arguments.

        Cannot suppress exceptions.
        """
        def _exit_wrapper(exc_type, exc, tb):
            callback(*args, **kwds)
        # We changed the signature, so using @wraps is not appropriate, but
        # setting __wrapped__ may still help with introspection
        _exit_wrapper.__wrapped__ = callback
        self.push(_exit_wrapper)
        return callback # Allow use as a decorator

    def enter_context(self, cm):
        """Enters the supplied context manager

        If successful, also pushes its __exit__ method as a callback and
        returns the result of the __enter__ method.
        """
        # We look up the special methods on the type to match the with statement
        _cm_type = type(cm)
        _exit = _cm_type.__exit__
        result = _cm_type.__enter__(cm)
        self._push_cm_exit(cm, _exit)
        return result

    def close(self):
        """Immediately unwind the context stack"""
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, *exc_details):
        # We manipulate the exception state so it behaves as though
        # we were actually nesting multiple with statements
        frame_exc = sys.exc_info()[1]
        def _fix_exception_context(new_exc, old_exc):
            while 1:
                exc_context = new_exc.__context__
                if exc_context in (None, frame_exc):
                    break
                new_exc = exc_context
            new_exc.__context__ = old_exc

        # Callbacks are invoked in LIFO order to match the behaviour of
        # nested context managers
        suppressed_exc = False
        while self._exit_callbacks:
            cb = self._exit_callbacks.pop()
            try:
                if cb(*exc_details):
                    suppressed_exc = True
                    exc_details = (None, None, None)
            except:
                new_exc_details = sys.exc_info()
                # simulate the stack of exceptions by setting the context
                _fix_exception_context(new_exc_details[1], exc_details[1])
                if not self._exit_callbacks:
                    raise
                exc_details = new_exc_details
        return suppressed_exc

rawDescription: Alternative to contextlib.nested with variable number of context managers


rawDescription: Regex to find search term and place result in another data file?


code:
def dict_values(d):
   return (mydict[key] for key in mydict)

def dict_items(d):
   return ((key, mydict[key]) for key in mydict)

for value in dict_values(mydict):
    ...

for value in dict_items(mydict):
    ...

rawDescription: Generators to iterate over a dictionary uniformly in both Python 2 and 3


code:
def locateBraces(inp):
    bracePositions = []
    braceStack = []
    depth = 0
    for i in range(len(inp)):
        if inp[i] == '(':
            braceStack.append(i)
            depth += 1
        if inp[i] == ')':
            bracePositions.append((braceStack.pop(), i))
            depth -= 1
            if depth < 0:
                raise SyntaxError('Too many closing braces.')
    if depth != 0:
        raise SyntaxError('Too many opening braces.')
    return bracePositions

rawDescription: How to return the regex that matches some text?

description: Return the regex that matches some text


code:
@app.before_request
def check_valid_login():
    login_valid = 'user' in session # or whatever you use to check valid login

    if (request.endpoint and
        'static' not in request.endpoint and
        not login_valid and
        not getattr(app.view_functions[request.endpoint], 'is_public', False) ) :
        return render_template('login.html', next=request.endpoint)

rawDescription: Best way to make Flask-Login's login_required the default

description: Make Flask-Login's login_required the default


code:
A: a
B: {C: c, D: d, E: e}

rawDescription: How can I write data in YAML format in a file?

description: Write data in YAML format in a file


code:
import numpy as np
np.log(1.1, 2)

rawDescription: TypeError: return arrays must be of ArrayType for a function that uses only floats


rawDescription: Python getting unique pairs from multiple lists of different lengths


code:
foo = self.foo
factorial = math.factorial
for x in really_big_iterator:
    foo(factorial(x))

rawDescription: Constructing objects in __init__

description: Constructing objects in __init__


code:
app = Flask(__name__)
register_blueprint_and_signals(app, "my_module.my_blueprint")
register_blueprint_and_signals(app, "another.blueprint", ['ANOTHERSIGNAL'])

rawDescription: Catch signals in Flask Blueprint

description: Catch signals in Flask Blueprint


code: text_using_only_iso_8859_2_or_5 = invalid.sub('', unicodetext)

rawDescription: In python replacing characters from multiple char maps


code:
def send_into_ampq():
    while True:
       message = dispatcher.get_workger_msg()

       try:
          connection.send(self.encode(message))
       except:
           connection.kill()

def read_from_ampq():
    while True:
        message = connection.wait()

        dispatcher.put_ampq_msg(self.decode(message))

rawDescription: Can eventlet manage an AMQP connection with messages passing asynchronously both in and out?


code: words = {}

rawDescription: Merge some part of the list together using python


code: '\n'.join([' '.join([s for s in line.split(' ') if s]) for line in ex_str.splitlines() if line.strip()])

rawDescription: Removing odd \n, \t, \r and space combinations from a given string in Python


code:
class MyProtocol(LineReceiver):
    ...
    def getNextLine(self):
        self.defer_given_out = Deferred()

    def lineReceived(self, line):
        self.defer_given_out.callback(line)

    def connectionLost(self):
        self.defer_given_out.errback(StopIteration())

rawDescription: Refactoring for a twisted tcp client from existing blocking code


code:
ss = '''<input type="hidden" name="__FOO" id="__FOO" value="garble" />

<script type="text/javascript">
//<![CDATA[
$(function () {
    // convert to
    var True = true, False = false;

    manatee.start({
        pageIDs: ["16798", "16799", "16800", "16801", "16802"],
        userNames: ["Alice", "Bob", "Carol", "Dave", "Eve"],
        wordCounts: [77,23,64,89,93],
        linkCounts: [2,0,3,1,4],
        pageUrls: ["","/blog/35318264c9a98faf79965c270ac80c5606774df1/data.pdf","/blog/da6645f6e22bf5f75974dc7eed5fcd6160d6b51e/data.pdf","/blog/6f90f101115140727c43cadee0b9e17881403a63/data.pdf","/blog/333584fc2850d1a1f97a0a7bf8c5a12e684856bf/data.pdf","/blog/9a018ecc48a37a9247a6404fd83e085384b445aa/data.pdf"],

        toolbar: {
            id: "ManateeToolbar",
            buttons: [
                {
                    id: "ManateeBrowser",
                    text: "Enter Fullscreen",
                    toggleText: "Escape Fullscreen"
                }
            ]
        }

    });
});
//]]>
</script>

<script type="text/javascript">var blah</script>'''

import re

regx = re.compile('^\t*pageUrls[\t ]*:[\t ]*\[(.*?)\],[\t ]*$',re.MULTILINE)

for mat in regx.finditer(ss):
    urls = tuple(el[1:-1] for el in mat.group(1).split(',') if el[1:-1])
    print( urls )

rawDescription: Read contents of <script> with BeautifulSoup


rawDescription: Parallel and conditional: NoneType object has no attribute '__dict__'


code:
test = 'START_DATE'

df_short = df_policy[['OLD_CON_ID',test,'CONTRACT_ID']]
df_short.rename(columns={'OLD_CON_ID':'PID','CONTRACT_ID':'CID'},

inplace = True)
df_test = df_policy[['CONTRACT_ID','END_DATE']]
df_test.rename(columns={'CONTRACT_ID':'CID','END_DATE': 'PED'}, inplace = True)

df_copy1 = df_short.copy()
df_copy2 = df_short.copy()
df_copy2.rename(columns={'PID':'PPID','CID':'PID'}, inplace = True)

df_merge1 = pd.merge(df_short, df_copy2,
    how='left',
    on=['PID'])

df_merge1['START_DATE_y'].fillna(df_merge1['START_DATE_x'], inplace = True)
df_merge1.rename(columns={'START_DATE_x':'1_EFF','START_DATE_y':'2_EFF'}, inplace=True)

rawDescription: Pandas row analysis for consecutive dates


code: bool(set(int(n) for n in a.split(',')).intersection(int(n) for n in b.split(',')))

rawDescription: comparing numbers in 2 string A and B

description: Comparing numbers in 2 string A and B


code:
[[elm.strip() for elm in row.find_all(text=re.compile(r"\d\d:\d\d"))]
 for row in soup.table.find_all("tr")]

rawDescription: python re.findall pattern for different number of matches

description: Python re.findall pattern for different number of matches


code:
def parse_dt(dt, tm, ap):
    return pd.to_datetime(dt + ' ' + tm + ap, dayfirst=True)

df = pd.read_csv(filename, sep='\s+', skiprows=2, header=None,
                 parse_dates={'ts': [0,1,2] }, date_parser=parse_dt)

rawDescription: How reading data with pandas.read_csv containing time AM/PM format?


code:
first_col = xw.Range(1, 'Named range').column
first_row = xw.Range(1, 'Named range').row
xw.Range(1, (first_col + 1, first_row + 1)).value = 'yes'

rawDescription: How assign value to one cell in named range by using xlwings?


code: table.findAll('td', attrs = {"class":re.compile(r'(^|\s)(a|unavailable-available)($|\s)')})

rawDescription: Regex pattern with subpattern exceptions (Python)


code:
from datetime import datetime, date
from io import StringIO
from algebraixlib.io.csv import import_csv
from algebraixlib.mathobjects import Set, Couplet, Atom
import algebraixlib.algebras.sets as sets
import algebraixlib.algebras.clans as clans
from algebraixlib.algebras.relations import is_functional

rawDescription: Writing complex query using algebraixlib


code:
def NewEntry(column, row):
    variable = StringVar()
    variable_entry = ttk.Entry(mainframe, width=15, textvariable=variable)
    variable_entry.grid(column=column, row=row)
    return variable, variable_entry

rawDescription: creating a new variable using the def command in python

description: Creating a new variable using the def command in python


code:
ax.set_yscale("log", nonposy='clip') #nonposy is required, otherwise the bar disappears.
ax.set_ylim((0.1, 100)) #remember to rest the limit.

rawDescription: More plotting options for pandas.DataFrame.plot(kind="bar")


code:
n_perms = 256**len(var_text)
length = int(log10(n_perms)) + 1

rawDescription: Python: Shorten ugly code?

description: Python: Shorten ugly code


code:
foos = [imp.load_source(fname.split('.py')[0], '%s%s' % (FOOS_DIR, fname))
            for fname in os.listdir(FOOS_DIR)
               if re.match(MOD_REGEX, fname)]

rawDescription: Trouble with imp.load_source: 'module' has no attribute 'foo'


code:
City  :  ['"Urban Recovery"', '"Urban Mop-up Operation"', '"The Oncoming Darkness"', '"Arks Ship Fire Swirl"']
Forest  :  ['"Subdue Fang Banther"', '"With Wind and Rain"']
Caves  :  ['"Cave"', '"Volcanic Guerillas"']
Desert  :  ['"Desert Guerillas"']
Tundra  :  ['']
Skyland  :  ['"Rampaging Malice"', '"Chrome"']
Tunnels  :  ['"Mega Mecha awakening"']
Ruins  :  ['']
Coast  :  ['"Beach Wars!"']
Quarry  :  ['']
Space  :  ['"Profound Darkness\' Kin: Elder"', '"Raging Dark Arms"', '"Approaching Dark Arms"', '"Utterly Profound"', '"Falz"', '"Dark Falz"']
Event  :  ['"Merry Christmas on Ice"', '"Trick or Treat"', '"A Boisterous White Day"', '"Where\'s the Chocolate"']

rawDescription: Split lines according to regex pattern with 1 or more results


code: dev = Dev(work_q, q_lock, count)

rawDescription: Threading and information passing -- how to


code:
v1 = self.V1lineEdit.setText
vR = self.VRlineEdit.setText
v3 = self.V2lineEdit.setText

rawDescription: Setting a variable for lineEdits

description: Setting a variable for lineEdits


code:
with open('myfile.txt') as infile:
    uniquevalues = {row.split(': ')[1] for row in infile}

rawDescription: Printing the different values in a column not the amount of their repeats


code: temp_row = matrix[row_num - 1][:]

rawDescription: Why do changes to a temporary variable representing a row of a matrix, affect the row of the matrix itself?