code: numpy.random.pareto(a, size=None)

rawDescription: How to generate random numbers in specyfic range using pareto distribution in Python

description: Generate random numbers in specyfic range using pareto distribution in Python


rawDescription: take only text from a certain line of multi-line Python String

description: Take only text from a certain line of multi-line Python String


code: sum(len(i) for i in ar1)

rawDescription: Using 'for loop' to sum nested list values and return (total of sum)


rawDescription: Asterisk art in python

description: Asterisk art in python


code:
help('if')
help('def')

rawDescription: Python: Function Documentation

description: Python: Function Documentation


code:
from collections import defaultdict
from itertools import groupby
from pprint import pprint
from trueskill import Rating, rate

results = [(1, 'alice', 2),
           (1, 'bob', 1),
           (1, 'eve', 3),
           (2, 'alice', 1),
           (2, 'eve', 1),
           (3, 'bob', 1),
           (3, 'carol', 2),
           (3, 'alice', 3),
           (3, 'ted', 4),
           (3, 'eve', 5)]
ratings = defaultdict(Rating)

for game_id, result in groupby(results, lambda x: x[0]):
    result = list(result)
    rating_groups = [(ratings[name],) for game_id, name, rank in result]
    ranks = [rank for game_id, name, rank in result]
    transformed_groups = rate(rating_groups, ranks=ranks)
    for x, (game_id, name, rank) in enumerate(result):
        ratings[name], = transformed_groups[x]

pprint(dict(ratings))

rawDescription: Python Trueskill - Using Dictionaries

description: Python Trueskill - Using Dictionaries


code:
class Test1(object):
    def __init__(self):
        pass
    def a(self):
        print("Running a of Test1")
        test_instance2 = Test2(self)
    def z(self):
        print("Running z of Test1")

class Test2:
    def __init__(self, a):
        self.b(a)
    def b(self, a):
        print('Running b of Test2')
        a.z()

rawDescription: Call method in a class which called the current class


code: ",".join(["{%s}" % e for e in myList])

rawDescription: Mapping and joining a python list

description: Mapping and joining a python list


code: RDD.takeOrdered(5, key = lambda x: x[0])

rawDescription: takeOrdered descending Pyspark

description: TakeOrdered descending Pyspark


code: [k for k,v in G.out_degree().iteritems() if v > 0]

rawDescription: How to list specific node/edge in networkx?

description: List specific node/edge in networkx


code:
# select the last two rows and the last 3 columns
print(df.loc[2:4, ['Oct', 'Nov', 'Dec']])
#    Oct  Nov  Dec
# 2    6    0    2
# 3    1    3    5

# sum over them
print(df.loc[2:4, ['Oct', 'Nov', 'Dec']].sum())
# Oct    7
# Nov    3
# Dec    7
# dtype: int64

# alternatively, use df.iloc[2:4, 1:] to select by column index rather than name

rawDescription: how to sum over certain row of a data frame in Python

description: Sum over certain row of a data frame in Python


code:
line_segments.set_array(x)
line_segments.set_cmap(cm.coolwarm)  #this is the new line
ax.add_collection(line_segments)

rawDescription: Graphic with color gradient in python

description: Graphic with color gradient in python


code:
import SendKeys
SendKeys.SendKeys("""
    {LWIN}
    {PAUSE .25}
    r
    Notepad.exe{ENTER}
    {PAUSE 1}
    Hello{SPACE}World!
    {PAUSE 1}
    %{F4}
    n
""")

rawDescription: How can I paste some string to the active window in Python?

description: Paste some string to the active window in Python


code: data="{'username': 'jackripper@example.com', 'password': 'crm114'}",

rawDescription: Bad Request when posting JSON to Flask endpoint in unit test


code:
import logging

logging.getLogger("requests").setLevel(logging.WARNING)

rawDescription: How do I disable log messages from the Requests library?

description: Disable log messages from the Requests library


code:
def main():

    ships = []
    for n in range(4):
        ship = Ship(raw_input("What would you like to name this ship?"))
        ship.fuel = int(raw_input("How much fuel does this ship have?"))
        ships.append(ship)

    for ship in ships:
        ship.status()

main()
raw_input("Press enter to exit.")

rawDescription: Spaceship objects

description: Spaceship objects


code: output = input[index.astype(np.bool)]

rawDescription: Get a subarray from a numpy array based on index


rawDescription: Can't return the list I want

description: Can't return the list I want


code:
class A(object):
    def __init__(self, data, x):
        self.data = data
        self.x = x

    def make_new(self, myslice):
        return self.__class__(self.data[myslice], self.x)

    def f(self, myslice):
        return self.make_new(myslice)

class B(A):
    def __init__(self, data, x, y):
        self.data = data
        self.x = x
        self.y = y

    def make_new(self, myslice):
        return self.__class__(self.data[myslice], self.x, self.y)

rawDescription: Inheritance and Slicing, making it the child type


code:
vc /= float(vc.sum())
assert vc.sum() == 1

rawDescription: How to create a bar chart/histogram with bar per discrete value?

description: Create a bar chart/histogram with bar per discrete value


code:
def ask(month):
    print(input("How much snow fell during the month of %s" % month))
ask("January")
ask("February")
ask("March")

rawDescription: Implementation of functions

description: Implementation of functions


rawDescription: Python - How to count the number of occurrences in a list


code:
a.ndim
b.ndim

rawDescription: numpy: 1D array with various shape

description: Numpy: 1D array with various shape


code:
import re
regex = re.compile(".*?\((.*?)\)")
result = re.findall(regex, mystring)

rawDescription: Remove text between () and [] in python

description: Remove text between () and [] in python


code:
def convert_currency(rates, value, src_curr, dest_curr):
    return value / rates[src_curr] * rates[dest_curr]

rawDescription: Curency Rate Conversion Wrong Base Currency


rawDescription: Get DataFrame selection's row posititions


rawDescription: Django IntegerField with Choice Options (how to create 0-10 integer options)


code: groups

rawDescription: Python way of getting max of list containing integers and floats


rawDescription: Use Python to extract Branch Lengths from Newick Format


code:
class ConfigurationSerializer(serializers.ModelSerializer):
    parameters = ParameterSerializer(many=True, source='parameter_set')

rawDescription: How to serializer/deserialize Django models

description: Serializer/deserialize Django models


code:
class MyRx(object):
    @classmethod
    def search(cls, p):
        return 'test' in p or '.git' in p

rawDescription: Regex for matching either of two subdirectories any number of directories deep?


code:
b_e_arg = robobrowser.forms.fields.Input('\<input name="__EVENTARGUMENT" value="" \/\>')

b_e_target = robobrowser.forms.fields.Input('\<input name="__EVENTTARGET" value="PhoneListsControl$MasterDataControl$masterList$_ctl0$SelectButton" \/\>')

In [30]: form_find_b.add_field(b_e_target)
In [31]: form_find_b.add_field(b_e_arg)

rawDescription: Python - Requests/RoboBrowser - ASPX POST JavaScript


code:
newd = {}

for key, values in d.iteritems():

     p[key]['newcol'] = values

     # Add new keys and dataframe to a new dictionary
     newd[key] = p[key]

rawDescription: Python - Add a column to each dataframe of a Pandas Panel


code:
from nltk.tokenize.punkt import PunktSentenceTokenizer

def truncate_paragraph(text, maxnchars,
                       tokenize=PunktSentenceTokenizer().span_tokenize):
    """Truncate the text to at most maxnchars number of characters.

    The result contains only full sentences unless maxnchars is less
    than the first sentence length.
    """
    sentence_boundaries = tokenize(text)
    last = None
    for start_unused, end in sentence_boundaries:
        if end > maxnchars:
            break
        last = end
    return text[:last] if last is not None else text[:maxnchars]

rawDescription: Function to return sentences under a given character count


code:
def update_weights(weights, fields, to_increase, to_decrease):
  weights[to_increase,:] += fields
  weights[to_decrease,:] -= fields
  return weights

rawDescription: Python optimisations in this code?

description: Python optimisations in this code


code:
from time import sleep
from multiprocessing import Pool
from random import randint
class Gen:
    def __init__(self, limit):
        self.__l = limit
        self.__t = []
        self.__v = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.__v += 1
        if self.__v +1 >= self.__l:
            raise StopIteration
        print("NEXT:{}".format(self.__v))
        sleep(0.01)
        w = 0
        self.__t.append(self.__v)
        return self.__t[:]

r = Gen(1000)

rawDescription: Python returns string instead of list during iterate


code:
class BaseProductFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_type='icontains')
    cost = django_filters.NumberFilter(lookup_type='lt')

class FoodProductFilter(BaseProductFilter):
    farmer = django_filters.CharFilter(lookup_type='icontains')

    class Meta:
        model = FoodProduct
        fields = ['name', 'cost', 'farmer']

class ClothingProductFilter(BaseProductFilter):
    # size lookup_type will be 'exact'
    class Meta:
        model = ClothingProduct
        fields = ['name', 'cost', 'size']

rawDescription: Using filters with model inheritance

description: Using filters with model inheritance


rawDescription: How do you delete a node in networkx?

description: Delete a node in networkx


code:
import numpy as np
import pandas as pd

city = ['Lubbock.txt','Erie.txt']

for filename in city:
    data = pd.read_table(filename, sep='\s+', usecols=(6,7,8,9), parse_dates=[0])
    data[['precip', 'tmax', 'tmin']] /= 10.0

    years = pd.DatetimeIndex(data['date']).year
    avg = data.groupby(years)['precip', 'tmax', 'tmin'].mean()
    print(avg)

rawDescription: Averaging Parts of An Array In Python

description: Averaging Parts of An Array In Python


code:
for button in buttons:
    if region.contains(button):
        continue # that will skip the buttons inside your region
    else:
        button.click() # that will click on the buttons outside your region

rawDescription: How do I click on an image outside the defined region?

description: Click on an image outside the defined region


code:
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

rawDescription: Add an object to a python list

description: Add an object to a python list


code:
letter = ["a", "b", "c"]
word = raw_input('Enter a word:')
first = word[0]
first in letter

rawDescription: Checking if a value is equal to any value in an array


code:
POST /demo
{
    "mappings": {
        "doc": {
            "properties": {
                "title": {
                    "type": "string",
                    "fields": {
                        "simple": {
                            "type": "string",
                            "analyzer": "simple"
                        }
                    }
                }
            }
        }
    }
}

rawDescription: Elasticsearch - Not require an exact match


rawDescription: How do I get rid of dotted line on x axis of Pandas/Matplotlib bar plot?

description: Get rid of dotted line on x axis of Pandas/Matplotlib bar plot


code:
def lstrip(value, chars=None):
    if chars is None:
        chars=' \t\n'
    while value and value[0] in chars:
        value = value[1:]
    return value

rawDescription: Equivalent of str.lstrip(char) in jython < 2.1


code:
string = "header1 header2 header3 header4 header5
 10 15 20 27 to/path/foo.c
 7 67 10 22 to/path/boo.c"
rows = string.split("
")
data = map(lambda r: r.split(" "), rows)
html_rows = map(lambda r: "" + "	".join(r) + "	", data)
html_table = "

" + "

".join(html_rows) + "

"

rawDescription: Python: String to HTML5 table without external modules


code: re.findall("(?:ABC)+\d+", s)

rawDescription: Regular Expression: Include Text After (...) Group


code:
flatten('a + b', mapping)
flatten('d PLUS c', mapping)

rawDescription: Flatten expression algorithm

description: Flatten expression algorithm


rawDescription: Display a .txt file in alphabetical order in python


code: u'this is a {} {}'.format(u'привет', u'мир')

rawDescription: How to build a utf8 string in python

description: Build a utf8 string in python


code: sublists = list(out.values())

rawDescription: python : generate sublists depending on the elements values

description: Python : generate sublists depending on the elements values


code:
import mosquitto
import time

client=mosquitto.Mosquitto("read-file")
client.connect("broker.mqttdashboard.com", 1883)

while client.loop() == 0:
    f = open("/home/ioana/date_sensor", "rb")
    data = f.read()
    client.publish("ioana/test", data)
    f.close()
    time.sleep(60)

rawDescription: Mqtt : Publish the last line from a file that is periodically updated


code: from OpenGL import *

rawDescription: NameError when running pyOpenGL

description: NameError when running pyOpenGL


code:
import pygame
from pygame import *
from particle import Emitter, smoke_machine
WIN_WIDTH = 1120 - 320
WIN_HEIGHT = 960 - 320
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 0
FLAGS = 0
CAMERA_SLACK = 30

levels = {0: {'level': [
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                         E  ",
                    "                            PPPPPPPPPPPPPPPP",
                    "                            PPPPPPPPPPPPPPPP",
                    "                            PPPPPPPPPPPPPPPP",
                    "               PPPPP        PPPPPPPPPPPPPPPP",
                    "                            PPPPPPPPPPPPPPPP",
                    "                            PPPP           P",
                    "                            PPPP           P",
                    "                            PPPP     PPPPPPP",
                    "                      PPPPPPPPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "       PPPP                 PPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "PPPPP                       PPPP     PPPPPPP",
                    "PPP                         PPPP     PPPPPPP",
                    "PPP                         PPPP     PPPPPPP",
                    "PPP                         PPPP     PPPPPPP",
                    "PPP         PPPPP           PPPP     PPPPPPP",
                    "PPP                                     PPPP",
                    "PPP                                     PPPP",
                    "PPP                                     PPPP",
                    "PPP                       PPPPPPPPPPPPPPPPPP",
                    "PPP                       PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP    S      PPPPPPPPPPPPPPPPPP",],
             'enemies': [(9, 38)]},
             1: {'level': [
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                            ",
                    "                                         E  ",
                    "                            PPPPPPPPPPPPPPPP",
                    "                            PPPPPPPPPPPPPPPP",
                    "                            PPPPPPPPPPPPPPPP",
                    "               PPPPP        PPPPPPPPPPPPPPPP",
                    "                            PPPPPPPPPPPPPPPP",
                    "                            PPPP           P",
                    "                            PPPP           P",
                    "                            PPPP     PPPPPPP",
                    "                      PPPPPPPPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "       PPPP                 PPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "                            PPPP     PPPPPPP",
                    "PPPPP                       PPPP     PPPPPPP",
                    "PPP                  PPPPPPPPPPP     PPPPPPP",
                    "PPP                         PPPP     PPPPPPP",
                    "PPP                         PPPP     PPPPPPP",
                    "PPP             PPPPPPPP    PPPP     PPPPPPP",
                    "PPP                                     PPPP",
                    "PPP                                     PPPP",
                    "PPP          PPPPP                      PPPP",
                    "PPP          P            PPPPPPPPPPPPPPPPPP",
                    "PPP          P    PPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",
                    "PPPPPPPPPPPPPPP           PPPPPPPPPPPPPPPPPP",],
             'enemies': [(9, 38), (18, 38), (15, 15)]}}

...

class GameScene(Scene):
    def __init__(self, levelno):
        super(GameScene, self).__init__()
        self.bg = Surface((32,32))
        self.bg.convert()
        self.bg.fill(Color("#0094FF"))
        up = left = right = False
        self.entities = pygame.sprite.Group()
        self.player = Player(5, 40)
        self.player.scene = self
        self.platforms = []

        self.levelno = levelno

        levelinfo = levels[levelno]
        self.enemies = [Enemy(*pos) for pos in levelinfo['enemies']]

        level = levelinfo['level']
        total_level_width = len(level[0]) * 32
        total_level_height = len(level) * 32

        self.emitter = []

        # build the level
        x = 0
        y = 0
        for row in level:
            for col in row:
                if col == "P":
                    p = Platform(x, y)
                    self.platforms.append(p)
                    self.entities.add(p)
                if col == "E":
                    e = ExitBlock(x, y)
                    self.platforms.append(e)
                    self.entities.add(e)
                if col == "S":
                    e = Emitter((x, total_level_height))
                    e.add_factory(smoke_machine())
                    self.emitter.append(e)
                x += 32
            y += 32
            x = 0

        self.camera = Camera(complex_camera, total_level_width, total_level_height)
        self.entities.add(self.player)
        for e in self.enemies:
            self.entities.add(e)

    def render(self, screen):
        for y in range(20):
            for x in range(25):
                screen.blit(self.bg, (x * 32, y * 32))

        for e in self.emitter:
            e.draw(screen, self.camera.apply)

        for e in self.entities:
            screen.blit(e.image, self.camera.apply(e))

    def update(self):
        for e in self.emitter:
            e.update()

        pressed = pygame.key.get_pressed()
        up, left, right = [pressed[key] for key in (K_UP, K_LEFT, K_RIGHT)]
        self.player.update(up, left, right, self.platforms)

        for e in self.enemies:
            e.update(self.platforms)

        self.camera.update(self.player)

    def exit(self):
        if self.levelno+1 in levels:
            self.manager.go_to(GameScene(self.levelno+1))
        else:
            self.manager.go_to(CustomScene("You win!"))

    def die(self):
        self.manager.go_to(CustomScene("You lose!"))

    def handle_events(self, events):
        for e in events:
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                self.manager.go_to(TitleScene())

...

if __name__ == "__main__":
    main()

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
class Example(object):
    pass

myobject = Example()
myobject.a = "value"

rawDescription: How to create a object of variables, and return it, in Python?

description: Create a object of variables, and return it, in Python


code: x= all((a, b, c, d, e, f))

rawDescription: Check at once the boolean values from a set of variables


rawDescription: Pandas Multiple Conditions Function based on Column


rawDescription: Why does this return False

description: Why does this return False


code: obj = obj or myotherobj

rawDescription: How can i omit the redundant words in python condition loop

description: Omit the redundant words in python condition loop


code:
from itertools import islice

line_number = int(input('Enter the line number: '))
with open('yourfile') as fin:
    print(next(islice(fin, line_number - 1, line_number), ''), end='')

rawDescription: Python program prints an extra empty line when reading a text file


code:
from tkinter import *

wd = Tk()
wd.config(height=500, width=500)
can = Canvas(wd, bg = 'red', height=100, width=100)
can.place(x=200, y=200, anchor=NW)

rawDescription: How to center Tkinter wiget?

description: Center Tkinter wiget


code:
query( models.Object )\
.filter(
     sqlalchemy.func.upper( models.Object.fieldname )\
     .in_( (sqlalchemy.func.upper(foo) , sqlalchemy.func.upper(bar), ) )
)\
.all()

rawDescription: SQLAlchemy case insensitive IN based search query?


code:
import string
string.ascii_letters

rawDescription: Python: How to import ascii characters

description: Python: How to import ascii characters


code: for c in compositions("foobar",3): print(c)

rawDescription: Create possible combinations of specific size


code: [np.outer(xx,yy) for xx,yy in izip(x,y)]

rawDescription: Is there a more vectorized way to perform numpy.outer along an axis?


rawDescription: Save email attachment (python3, pop3_ssl, gmail)


code:
if stmt:
    do_a()
if not stmt:    # same effect as 'else:'
    do_b()

rawDescription: Slicing strings of a sentence with a scale


code: [list(map(lambda x: float(re.sub(r'(\.\d{4}).*', r'\1', x)),i.split(','))) for i in line]

rawDescription: making list of float from list and sub list ,also that list callable in another object

description: Making list of float from list and sub list ,also that list callable in another object


code:
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'
d.items()
d.items()[0]
d.items()[1]

rawDescription: Accessing Items In a ordereddict

description: Accessing Items In a ordereddict


code:
s = "DFDAXDJSDSJDAFGCJASDJASAGXCJAD"
s.split('A')
[ 'A%s' % s for s in  s.split('A') ]

rawDescription: Python regex char pattern group

description: Python regex char pattern group


rawDescription: Count repeating events in pandas timeseries


code:
import matplotlib.ticker
import matplotlib
import re

# create a definition for the short hyphen
matplotlib.rcParams["text.latex.preamble"].append(r'\mathchardef\mhyphen="2D')

class MyLogFormatter(matplotlib.ticker.LogFormatterMathtext):
    def __call__(self, x, pos=None):
        # call the original LogFormatter
        rv = matplotlib.ticker.LogFormatterMathtext.__call__(self, x, pos)

        # check if we really use TeX
        if matplotlib.rcParams["text.usetex"]:
            # if we have the string ^{- there is a negative exponent
            # where the minus sign is replaced by the short hyphen
            rv = re.sub(r'\^\{-', r'^{\mhyphen', rv)

        return rv

rawDescription: Matplotlib log-scale tick labels, minus sign too long in latex font


code:
...
ax.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
    matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()

rawDescription: How to format axis number format to thousands with a comma in matplotlib

description: Format axis number format to thousands with a comma in matplotlib


code:
# file: literal_eval.py

import ast

def literal_eval(value):
    return ast.literal_eval(value)

from django import template
register = template.Library()
register.filter('literal_eval', literal_eval)

rawDescription: is there any template tag in django to make ast.literal_eval?

description: Is there any template tag in django to make ast.literal_eval


code:
def build_sentence(info):
    addMe = " is a benefit of functions!"
    return info + addMe

rawDescription: My function doesn't return an entire sentence


code:
with open('dummy.pkl', 'wb') as f:
  dill.dump(dummy_class_1, f)
  dill.dump(dummy_class_2, f)

rawDescription: Serializing functions/classes in python

description: Serializing functions/classes in python


code:
cursor.execute('SELECT id FROM TABLE WHERE condition LIMIT 1')
result_id, = cursor.fetchone()

rawDescription: The ,= operator

description: The ,= operator


code:
dt_name = "Data Table" # name of the data table

dt = Document.Data.Tables[dt_name]

Document.Data.Tables.Remove(dt)

rawDescription: Spotfire IronPython script: Delete a data-table


code:
import b

b.foo('foo')

# monkey-patch
import __builtin__
__builtin__.str = unicode

b.foo('foo')

# Results:
#foo <type 'str'>
#foo <type 'unicode'>

rawDescription: Monkey Patching in python: When we need it?


rawDescription: Egg and basket game in python

description: Egg and basket game in python


rawDescription: Formatting multiple datetimes into a string


code:
# suppose your list is this
lis1 = [1,2,3,4,5,6,7,8]
filter(lambda x: x&1 == 0, lis1)
# output -- [2,4,6,8]

rawDescription: I want to make a script that recognises even numbers


code:
from flask_sqlalchemy import models_committed

def notify_subscribers(app, changes):
    new_posts = [target for target, op in changes if isinstance(target, Post) and op in ('insert', 'update')]
    # notify about the new and updated posts

models_committed.connect(notify_subscribers, app)

rawDescription: Run function after a certain type of model is committed


code:
from contextlib import contextmanager

filetypes = [('.gz', gzip.GzipFile, (IOError, MaybeSomeGzipExceptions)),
             ('.x', xCompressLib.xCompressFile, (IOError, MaybeSomeXCompressExceptions))]

@contextmanager
def open_compressed(fn):
    f = None
    try:
        for ext, cls, exs in filetypes:
            try:
                f = cls(fn + ext)
            except exs:
                pass
            else:
                break
        yield f
    finally:
        if f is not None:
            f.close()

with open_compressed(fn) as f:
    result = "some default value" if f is None else process(f)

rawDescription: Several `with`s in `try`s

description: Several `with`s in `try`s


code:
from leapyear import new_leap
new_leap(2008, 2032)

rawDescription: Leap-year program in Python

description: Leap-year program in Python


code:
import ast
fd2['a']=df2['a'].apply(lambda x: ast.literal_eval(x))
type(df2['a'][1])

rawDescription: list to string in df.to-csv()

description: List to string in df.to-csv()


code:
def split_tags(self):
    return [urlify(tag) for tag in self.tags.split(', ')]

rawDescription: Django trying to split and urlify tags in models, but code isn't working


code: list(itertools.product(*[range(1, j+1) for j in c]))

rawDescription: PYTHON - Output every possible outcome from a set of multiple choices?


code:
fig = plt.figure()
ax = fig.add_subplot(111)

rawDescription: Why do many examples use "fig, ax = plt.subplots()" in Matplotlib/pyplot/python


code:
# test string
s = "0 380 -222 0 382 -218 45 428 174"
# splitting based on the spaces
l = s.split()

rawDescription: How to split a line of txt file into 3 values per line

description: Split a line of txt file into 3 values per line


code: logger.debug("try to get queued task from queue %s", self.taskInfos)

rawDescription: deadlock because of blocking Queue.get() method

description: Deadlock because of blocking Queue.get() method


code:
import sys
import time                    # Import time module
print("hi",end = "")           # End on the same line and not on next line
sys.stdout.flush()
time.sleep(2)
print("\rthere")               # Use \r (return) to clear the
                               # line for new words

rawDescription: How do i overwrite the previous line?

description: Overwrite the previous line


code: (df["binary"] == 0).cumsum()

rawDescription: python pandas - creating a column which keeps a running count of consecutive values

description: Python pandas - creating a column which keeps a running count of consecutive values


code:
""" myfabfile.py """

from fabric.api import task as origtask
from decorator import FunctionMaker

def decorator_apply(dec, func):
    return FunctionMaker.create(
        func, 'return decorated(%(signature)s)',
        dict(decorated=dec(func)), __wrapped__=func)

def task(func):
    return decorator_apply(origtask, func)

@task
def setup_development(remote='origin', branch='development'):
    """Setup your development environment.

    * Checkout development branch & pull updates from remote
    * Install required python packages
    * Symlink development settings
    * Sync and migrate database
    * Build HTML Documentation and open in web browser

    :param remote: Name of remote git repository.
    :param branch: Name of your development branch.
    """
    pass

rawDescription: Using sphinx autodoc for a fabfile

description: Using sphinx autodoc for a fabfile


code:
import time
# some code
time.sleep(30) # delays for 30 seconds

rawDescription: Python Selenium continually check for phrase in page source


code:
df_grouped = df.groupby('business')
function_dict = {'business' : take_single, 'zip_code' : take_single, 'profit' : sum}
df_grouped.agg(function_dict)

rawDescription: How to summarise data over several years into one dataframe

description: Summarise data over several years into one dataframe


code:
a
a.split(':')
a.split(':')[1].split(',')
new_dictionary = dict({a.split(':')[0]:map(int,a.split(':')[1].split(','))})
new_dictionary

rawDescription: Convert value of dictionary as a list?

description: Convert value of dictionary as a list


code:
def processing(obj):
      #do something
      pass

rawDescription: list_display with a function, how to pass arguments?

description: List_display with a function, how to pass arguments


code:
import pymongo
from pymongo import MongoClient
connection = MongoClient()
connection.database_names()

rawDescription: How do I use pymongo to connect to an existing document collection/db?

description: Use pymongo to connect to an existing document collection/db


code:
import logging

# set up logging config here

from logging import *

rawDescription: "Unused import warning" and pylint

description: "Unused import warning" and pylint


code: from __future__ import unicode_literals

rawDescription: Split the hash-tags from a tweet and then store them and the remaining string in a CSV


code: axes.xaxis.grid(False, which='minor')

rawDescription: No minor grid lines on the x-axis only

description: No minor grid lines on the x-axis only


code:
for i, (dir, file) in enumerate(zip(directories, files)):
    print(i, os.path.join(dir, file))

rawDescription: Python loops with multiple lists?

description: Python loops with multiple lists


code: [ t for t in target if new_names.intersection(t.lower().split()) ]

rawDescription: What's a more efficient way of looping with regex?


code:
soup.find_all("a", text="price")  # text equals to 'price' exactly
soup.find_all("a", text=lambda text: text and "price" in text)  # 'price' is inside the text

rawDescription: Navigation with BeautifulSoup

description: Navigation with BeautifulSoup


code:
TextAutoComplete = completefactory(TextCtrl)
PriceAutoComplete = completefactory(PriceCtrl)

rawDescription: How to change baseclass

description: Change baseclass


code:
quot, _ = divide(x, y)  # assign one to _, which means ignore by convention
rem = divide(x, y)[1]  # select one by index

rawDescription: How to get a single output from a function with multiple outputs?

description: Get a single output from a function with multiple outputs


code: lst.sort(key=lambda x: (-x[2],x[0])) #relying on tuples

rawDescription: sorting a graph by its edge weight. python

description: Sorting a graph by its edge weight. python


code: qs = list(archive, next)

rawDescription: Django QuerySet: filter by date, then select one more


code:
class MyGlobals(object):
    pass
g = MyGlobals()

rawDescription: Change storage of globals in python

description: Change storage of globals in python


code:
import subprocess

command = "ll"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

output = process.communicate()

print(output[0].decode())    # Required if using Python 3

rawDescription: Python3 Run Alias Bash Commands

description: Python3 Run Alias Bash Commands


code:
import logging
import sys
import time
import threading

from cpppo.server.enip import poll
from cpppo.server.enip.get_attribute import proxy_simple as device
params                  = [('@1/1/1','INT'),('@1/1/7','SSTRING')]

# If you have an A-B PowerFlex, try:
# from cpppo.server.enip.ab import powerflex_750_series as device
# parms                 = [ "Motor Velocity", "Output Current" ]

hostname                = '10.0.1.2'
values                  = {} # { <parameter>: <value>, ... }
poller                  = threading.Thread(
    target=poll.poll, args=(device,), kwargs={
        'address':      (hostname, 44818),
        'cycle':        1.0,
        'timeout':      0.5,
        'process':      lambda par,val: values.update( { par: val } ),
        'params':       params,
    })
poller.daemon           = True
poller.start()

# Monitor the values dict (updated in another Thread)
while True:
    while values:
        logging.warning( "%16s == %r", *values.popitem() )
    time.sleep( .1 )

rawDescription: Read/write values using Ethernet/IP

description: Read/write values using Ethernet/IP


code:
a = ThingList(range(3))
a.append("three")
a
a[0].id

rawDescription: Can you easily create a list-like object in python that uses something like a descriptor for it's items?

description: Easily create a list-like object in python that uses something like a descriptor for it's items


code:
result = []
# from len(rows)-2 to 0, decrementing by one each time
for i in range(len(rows)-2,-1,-1):
       # from 0 to i
    for j in range(i+1):
       result.append((i, j))

rawDescription: Embedded for loops in python

description: Embedded for loops in python


rawDescription: Apply group specific function to groups in Pandas


code:
#!/usr/bin/env python
try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json, jmespath

jsonData = """{
  "products" : {
    "DQ578CGN99KG6ECF" : {
      "sku" : "DQ578CGN99KG6ECF",
      "productFamily" : "Compute",
      "attributes" : {
        "location" : "US East (N. Virginia)",
        "instanceType" : "hs1.8xlarge",
        "tenancy" : "Shared",
        "operatingSystem" : "Windows",
        "licenseModel" : "License Included",
        "preInstalledSw" : "NA"
      }
    },
    "G2N9F3PVUVK8ZTGP" : {
      "sku" : "G2N9F3PVUVK8ZTGP",
      "productFamily" : "Instance",
      "attributes" : {
        "location" : "Asia Pacific (Seoul)",
        "instanceType" : "i2.xlarge",
        "tenancy" : "Host",
        "operatingSystem" : "Windows",
        "licenseModel" : "License Included",
        "preInstalledSw" : "SQL Server Enterprise"
      }
    },
    "FBZZ2TKXWWY5HZRX" : {
      "sku" : "FBZZ2TKXWWY5HZRX",
      "productFamily" : "Compute",
      "attributes" : {
        "location" : "Asia Pacific (Seoul)",
        "instanceType" : "i2.4xlarge",
        "tenancy" : "Dedicated",
        "operatingSystem" : "SUSE",
        "licenseModel" : "No License required",
        "preInstalledSw" : "NA"
      }
    }
  }
}"""

priceJson = json.loads(jsonData)

query = "products.*.{sku: sku, location: attributes.location, instanceType: attributes.instanceType, tenancy: attributes.tenancy, operatingSystem: attributes.operatingSystem, licenseModel: attributes.licenseModel, preInstalledSw: attributes.preInstalledSw}"
output_dict = jmespath.search(query, priceJson)

query2 = "[?operatingSystem=='Windows' && tenancy=='Shared']"
output_dict = jmespath.search(query2, output_dict)

print(output_dict)

rawDescription: Complex JMESPath filter on a large JSON file


code: out = b.copy(); out[test] = a[test]

rawDescription: Numpy: vectorizing two-branch test (ternary-operator like)


code: results

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


rawDescription: efficient algorithm for list edits

description: Efficient algorithm for list edits


code:
def fk_processed (fk):
    filename = fk.__name__ + '_output.json'
    def new_fk (*args):
        store = {}
        if (os.path.exists(filename)):
            store = json.load (open(filename))
        cstore = store
        i = 0
        while i < len(args) and str(args[i]) in cstore:
            cstore = cstore[str(args[i])]
            i += 1
        if i != len(args):
            while i < len(args) - 1:
                cstore[str(args[i])] = {}
                cstore = cstore[str(args[i])]
                i += 1
            # print('compute')
            cstore[str(args[i])] = fk (*args)
            cstore = cstore[str(args[i])]
            json.dump (store, open(filename, 'w'))
        return cstore
    return new_fk

rawDescription: Design for application able to calculate a function or load the result from a file


rawDescription: Using Py_BuildValue() to create a list of tuples in C


code:
def UseOpenpyxl(file_name):
    wb = openpyxl.load_workbook(file_name, read_only=True)
    sheet = wb.active
    rows = sheet.rows
    first_row = [float(cell.value) for cell in next(rows)]
    data = []
    for row in rows:
        record = {}
        for key, cell in zip(first_row, row):
            if cell.data_type == 's':
                record[key] = cell.value.strip()
            else:
                record[key] = float(cell.value)
        data.append(record)
    return data

rawDescription: Reading Excel file is magnitudes slower using openpyxl compared to xlrd


code: map(" ".join, zip(first_names, second_names, third_names))

rawDescription: combining and looping through lists python

description: Combining and looping through lists python


code: print(unicodedata.normalize("NFD","è")[0]) # Prints "e".

rawDescription: Rules from accented letters to ascii ones


rawDescription: python html strip of hyperlinked text only

description: Python html strip of hyperlinked text only


code:
for row in grid[::-1]:
    print (label[i]," ".join(row))
    i+=1

rawDescription: Is it possible to create a 2D array where the row index is in a reverse order?


code:
class Dummy(models.Model):
    mylist = ListField()

    def insert_to_mylist(self, index, value):
        self.mylist.insert(index, value)
        #self.save()
    def remove_from_mylist(self, value):
        self.mylist.remove(value)
        #self.save()

rawDescription: Django ListField with add and remove

description: Django ListField with add and remove


code:
months = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"]

offset = 5
step = 2
for index, element in enumerate(months[offset::step]):

    # recalculate original index
    index = offset + index*step

    # actually repetition of the month is trivial,
    # but I put it just to show that the index is right
    print(index, element, months[index])

rawDescription: How to enumerate over selected elements from an iterable keeping original indices?

description: Enumerate over selected elements from an iterable keeping original indices


code:
for i in container:
    print(i)

rawDescription: How can I allow users to reference variables and other data structures via input?

description: Allow users to reference variables and other data structures via input


code:
class JsonToDict():
    def __call__(self, string):
        return json.loads(string)

rawDescription: Python: Parse multiple datatypes using argparse


code:
sums = {}
for tr in credit_transactions:
    try:
        sums[tr.category] += tr.amount  # not first in this category
    except KeyError:
        sums[tr.category] = tr.amount  # first in this category

rawDescription: Generating python dictionary only stores last value from iterable


code:
from __future__ import division
from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.transforms import Affine2D
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist import angle_helper
from mpl_toolkits.axisartist.grid_finder import MaxNLocator, DictFormatter
from mpl_toolkits.axisartist.floating_axes import GridHelperCurveLinear, FloatingSubplot

def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.25),
                      thlabel='theta', rlabel='r', ticklabels=True, theta_offset=0, rlabels = None):
    '''Return polar axes that adhere to desired theta (in deg) and r limits. steps for theta
and r are really just hints for the locators.'''
    th0, th1 = thlim # deg
    r0, r1 = rlim
    thstep, rstep = step

    tr_rotate = Affine2D().translate(theta_offset, 0)
    # scale degrees to radians:
    tr_scale = Affine2D().scale(np.pi/180., 1.)
    #pa = axes(polar="true") # Create a polar axis
    pa = PolarAxes
    tr = tr_rotate + tr_scale + pa.PolarTransform()
    theta_grid_locator = angle_helper.LocatorDMS((th1-th0)//thstep)
    r_grid_locator = MaxNLocator((r1-r0)//rstep)
    theta_tick_formatter = angle_helper.FormatterDMS()
    if rlabels:
        rlabels = DictFormatter(rlabels)

    grid_helper = GridHelperCurveLinear(tr,
                                        extremes=(th0, th1, r0, r1),
                                        grid_locator1=theta_grid_locator,
                                        grid_locator2=r_grid_locator,
                                        tick_formatter1=theta_tick_formatter,
                                        tick_formatter2=rlabels)

    a = FloatingSubplot(f, 111, grid_helper=grid_helper)
    f.add_subplot(a)
    # adjust x axis (theta):
    print(a)
    a.axis["bottom"].set_visible(False)
    a.axis["top"].set_axis_direction("bottom") # tick direction
    a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel))
    a.axis["top"].major_ticklabels.set_axis_direction("top")
    a.axis["top"].label.set_axis_direction("top")
    a.axis["top"].major_ticklabels.set_pad(10)

    # adjust y axis (r):
    a.axis["left"].set_axis_direction("bottom") # tick direction
    a.axis["right"].set_axis_direction("top") # tick direction
    a.axis["left"].toggle(ticklabels=True, label=bool(rlabel))
    # add labels:
    a.axis["top"].label.set_text(thlabel)
    a.axis["left"].label.set_text(rlabel)
    # create a parasite axes whose transData is theta, r:
    auxa = a.get_aux_axes(tr)
    print(auxa)
    # make aux_ax to have a clip path as in a?:
    auxa.patch = a.patch
    # this has a side effect that the patch is drawn twice, and possibly over some other
    # artists. So, we decrease the zorder a bit to prevent this:
    a.patch.zorder = -2

    # add sector lines for both dimensions:
    thticks = grid_helper.grid_info['lon_info'][0]
    rticks = grid_helper.grid_info['lat_info'][0]
    print(grid_helper.grid_info['lat_info'])
    for th in thticks[1:-1]: # all but the first and last
        auxa.plot([th, th], [r0, r1], ':', c='grey', zorder=-1, lw=0.5)
    for ri, r in enumerate(rticks):
        # plot first r line as axes border in solid black only if it  isn't at r=0
        if ri == 0 and r != 0:
            ls, lw, color = 'solid', 1, 'black'
        else:
            ls, lw, color = 'dashed', 0.5, 'grey'
        # From http://stackoverflow.com/a/19828753/2020363
        auxa.add_artist(plt.Circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=False,
                    transform=auxa.transData._b, zorder=-1))

    return auxa

if __name__ == '__main__':
    f1 = plt.figure(facecolor='white')
    r_locs = [0, .25, .5, .75, 1]
    r_labels = ['5', '10', '15', '20', '25']
    r_ticks = {loc : label for loc, label in zip(r_locs, r_labels)}
    a1 = fractional_polar_axes(f1, thlim=(-90, 90),step=(10, 0.2),
        theta_offset=90, rlabels = r_ticks)
    # example spiral plot:
    thstep = 10
    th = np.arange(-90, 90+thstep, thstep) # deg
    rstep = 1/(len(th)-1)
    r = np.arange(0, 1+rstep, rstep)
    a1.plot(th, r, 'b')
plt.show()

rawDescription: How to change ticklabels within figure created with axisartist

description: Change ticklabels within figure created with axisartist


code:
procs = [mp.Process(target=popen_wrapper, args=(inqueue, outqueue))
         for i in range(max_parallel)]

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

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


code:
from datetime import datetime
dt = datetime.fromtimestamp( data['date'] )

rawDescription: Trouble parsing API JSON output with python using 'requests'


code: eval("text" + str(1))

rawDescription: Cycling through a group of variables with similar names


code:
with open (path,'r') as p:
    data = list(csv.DictReader(p))
    FIELDS = ["name", "timeZone_label"]
    for i in FIELDS:
        for row in data:
            print (row[i])

rawDescription: nested loop in python is not looping more than once

description: Nested loop in python is not looping more than once


code:
Abroad = A[:,np.newaxis,:]  # prepared for broadcasting
C = np.sum((Abroad - B)**2/(Abroad + B), axis=-1)/2.

rawDescription: Optimizing histogram distance metric for two matrices in python


rawDescription: Python3 - default keyword for default values for type?


code:
from multiprocessing import Process, Queue
output = Queue()

class TSProcess(Process):
    def __init__ (self, param):
        Process.__init__(self)
        self.param = param
    def run(self):
        result = TS(self.param)
        output.put(result)

processes = []
with open("dataset.txt") as dataset:
       k = int(dataset.readline().split()[0])
       for i in xrange(k):
           aux = map(int, dataset.readline().split())
           current = TSProcess(aux)
           processes.append(current)
           current.start()

       for p in processes:
           p.join()
       # process result with output.get()

rawDescription: Complete a multithreading parallelize process with k threads


rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


code:
def binomial_choice(L, p):
    iterator = iter(L)
    try:
        while True:
            to_skip = numpy.random.geometric(p) - 1
            yield next(itertools.islice(iterator, to_skip, None))
    except StopIteration:
        return

rawDescription: Given iterable, select each element independently with probability p


code: help(print)

rawDescription: "print x," equivalent in Python3

description: "print x," equivalent in Python3


code:
#### #0 -- function attributes
def fun1(x):
    return x + fun1.c

fun1.c = 1;  y = fun2(fun1, x0);   print(y)   # --> 2
fun1.c = 2;  y = fun2(fun1, x0);   print(y)   # --> 3

#### #1 -- closure
def fun1(c):
    def wrapper(x):
        return x + c
    return wrapper

y = fun2(fun1(c=1), x0);   print(y)   # --> 2
y = fun2(fun1(c=2), x0);   print(y)   # --> 3

#### #2 -- functools.partial object
from functools import partial

def fun1(x, c):
    return x + c

y = fun2(partial(fun1, c=1), x0);   print(y)   # --> 2
y = fun2(partial(fun1, c=2), x0);   print(y)   # --> 3

#### #3 -- function object (functor)
class Fun1(object):
    def __init__(self, c):
        self.c = c
    def __call__(self, x):
        return x + self.c

y = fun2(Fun1(c=1), x0);   print(y)   # --> 2
y = fun2(Fun1(c=2), x0);   print(y)   # --> 3

#### #4 -- function decorator
def fun1(x, c):
    return x + c

def decorate(c):
    def wrapper(f):
        def wrapped(x):
            return f(x, c)
        return wrapped
    return wrapper

y = fun2(decorate(c=1)(fun1), x0);   print(y)   # --> 2
y = fun2(decorate(c=2)(fun1), x0);   print(y)   # --> 3

rawDescription: How to pass additional parameters (besides of arguments) to a function in Python

description: Pass additional parameters (besides of arguments) to a function in Python


code:
from selenium import webdriver
import base
import unittest

class LoginPage(base.Login):

    def test_logn(self):
        elt = self.driver.find_element_by_name('q')
        elt.send_keys('python')
        elt.submit()
        for result in self.driver.find_elements_by_class_name('g'):
            print(result.text)
            print('-' * 80)

if __name__ == '__main__':
    unittest.main()

rawDescription: Python webdriver: reusing setUp and tearDown


rawDescription: Using a shared variable in a function

description: Using a shared variable in a function


code:
def tester(*args):
    if (isinstance(args[0], str)):
        return "String"
    elif (isinstance(args[0], list)):
        return"List"
    else:
        return "You dun goofed"

rawDescription: Checking the type of parameter entered into a function


code:
usernames = []
with open("passwdfile") as htpwd:
    for line in htpwd.readlines():
        username, pwd = line.split(":")
        usernames.append(username)

rawDescription: How to access the value of username from htpasswd file using python script

description: Access the value of username from htpasswd file using python script


code:
import pandas
csvdata = pandas.read_csv('test.csv')
textdata = pandas.DataFrame(table, columns=['MATCH2', 'MATCH1', 'TITLE01', 'MATCH3', 'TITLE02', 'Data', 'misc2', 'bla3'])
mergeddata = pandas.merge(csvdata, textdata, how='left', on=['MATCH1', 'MATCH2', 'MATCH3'], sort=False)
mergeddata.to_csv('output.csv', index=False)

rawDescription: Matching three variables from textfile to csv and writing variables to the csv on matched rows


code:
import io
import lxml.etree as ET

content='''\
<Envelope xmlns="http://www.xxx.com/zzz/yyy">
  <Header>
    <Version>1</Version>
  </Header>
  <Body>
    some stuff
  </Body>
</Envelope>
'''
dom = ET.parse(io.BytesIO(content))

rawDescription: lxml etree xmlparser namespace problem

description: Lxml etree xmlparser namespace problem


code:
class WrappedVar(object):
    def __init__(self, val):
        self.value = val

MyVar = WrappedVar(5)
d['MyVar'] = MyVar

# later..
d['MyVar'].value = 10

rawDescription: Use a dictionary to handle variables

description: Use a dictionary to handle variables


code: x = [x.text for x in soup.find_all('option')]

rawDescription: Obtain text from all items in list using BeautifulSoup


code:
def find_non_uk(x):
    return re.match(pattern, x)

rawDescription: How can I explain the function of filter and lambda in a line of code?

description: Explain the function of filter and lambda in a line of code


code:
from itertools import groupby

def group_by_name(filenames):
    '''Puts the filenames in the given iterable into a dictionary where
    the key is the first component of the filename and the value is
    a list of the filenames with that component.'''
    keyfunc = lambda f: f.split('.', 1)[0]
    return dict( (k, list(g)) for k,g in groupby(
               sorted(filenames, key=keyfunc), key=keyfunc
           ) )

rawDescription: Python: finding files with matching extensions or extensions with matching names in a list


code:
import time
# print the resulting document to pdf
os.system('launch -p gowdercv.docx')
# give word about 30 seconds to finish printing the document
time.sleep(30)

rawDescription: python: unable to find files in recently changed directory (OSx)

description: Python: unable to find files in recently changed directory (OSx)


code: df['a'] = df['a'].str.replace('Hi', 'hi')

rawDescription: How to correct typos in pandas dataframe

description: Correct typos in pandas dataframe


code:
for row in rows:
        #printing second & third column(See tuples)
        #sets the variable
        self.labelVariable.set(row[1])
        #sets the variable again to a different value
        self.labelVariable.set(row[2])

rawDescription: How to get a for loop to work with tkinter in python 2.7?

description: Get a for loop to work with tkinter in python 2.7


code:
def untar(tarloc, folder):
    filecount = 0
    tar = tarfile.open(tarloc)
    # ....etc

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Module to untar TAR files')
    parser.add_argument('file', help='File to open')
    parser.add_argument('folder', help='Destination to extract to')
    args = parser.parse_args()
    untar(args.file, args.folder)

rawDescription: How do I easily store a file and folder location with argparse and then use those values

description: Easily store a file and folder location with argparse and then use those values


code:
def producer():
    q = Queue()
    t = Thread(target=consumer(q))
    t.daemon = True
    t.start()
    for item in InfStream:
        q.put(item)
    q.task_done()

rawDescription: How do I continue iterating without having to wait output to finish?

description: Continue iterating without having to wait output to finish


code:
testposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12, 23)

def giveme(s, words=()):
    lista = s.split(' ',22)
    result=[lista[item-1] for item in words]
    return result

rec='Lorem ipsum dolor sit amet consectetur adipiscing elit In vitae neque nec magna tristique ornare Cras faucibus risus eu odio pharetra interdum Nunc dui mi rhoncus ut aliquet'
print(giveme(rec, testposition)[-1])

rawDescription: Python - Conditionally split line

description: Python - Conditionally split line


code:
# untested code, use with care
def require_GET(view_func):
    def wrap(request, *args, **kwargs):
        if request.method != "GET":
            return HttpResponseBadRequest("Expecting GET request")
        return view_func(request, *args, **kwargs)
    wrap.__doc__ = view_func.__doc__
    wrap.__dict__ = view_func.__dict__
    wrap.__name__ = view_func.__name__
    return wrap

rawDescription: Django url validation

description: Django url validation


code:
import pandas as pd
import numpy as np

np.random.seed(1)
idx = pd.date_range("2016-03-01 10:00:00", "2016-03-01 20:00:00", freq="S")
idx = idx[np.random.randint(0, len(idx), 10000)].sort_values()
evt = np.array(["no event", "event"])[(np.random.rand(len(idx)) < 0.0005).astype(int)]
df = pd.DataFrame({"event":evt, "value":np.random.randint(0, 10, len(evt))}, index=idx)

rawDescription: Filtering a panda dataframe based on value and time


code: selection = pymel.core.ls(selection=True, transforms=True)

rawDescription: How to isolate group nodes in maya with python

description: Isolate group nodes in maya with python


rawDescription: Make callers use functools.partial or call a factory function?


rawDescription: How to find urdu words in a string using python

description: Find urdu words in a string using python


code:
for tag in soup.findAll(lambda tag: tag.has_key('id') and
                                    tag['id'] in ['footer', 'content', 'links']):
    tag.extract()

rawDescription: Can I combine two 'findAll' search blocks in beautifulsoup, into one?

description: Combine two 'findAll' search blocks in beautifulsoup, into one


code:
grouped = {}
for entry in List:
    env, account = entry[-2:]
    for server in entry[:-2]:
        key = server, account
        grouped.setdefault(key, []).append(env)

rawDescription: Grouping of list of list for elments of inner list in python


code: output = [function_output() for i in range(50)]

rawDescription: Appending arrays by array names

description: Appending arrays by array names


code: NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin

rawDescription: Convert a number range to another range, maintaining ratio


code:
mbox = mailbox.MailDir('/some/path')
uniq_emails = set(parseaddr(email['from'])[1] for email in mbox)

rawDescription: Determine unique "from" email addresses in Maildir folder


code:
def get_dictionaries(list_obj):
    for item in list_obj:
        if type(item) == list:
            for x in get_dictionaries(item):
                yield x
        elif type(item) == dict:
            yield item
        else:
            raise ValueError("unexpected item type (not a list or a dictionary)")

rawDescription: Extracting all dictionaries from a list of lists and dictionaries?


rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
location / {
 # your normal stuff
}

rawDescription: how to configure nginx to serve specific django url path with another domain

description: Configure nginx to serve specific django url path with another domain


rawDescription: Comparing List and get indices in python


code:
import os,webbrowser
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
                        "Internet Explorer\\IEXPLORE.EXE")
browser = webbrowser.get(iexplore)
browser.open(path_to_file)

rawDescription: Python code to open image in browser?

description: Python code to open image in browser


code:
import operator
def my_all(a_list):
  return reduce(operator.and_, a_list, True)

def my_any(a_list):
  return reduce(operator.or_, a_list, False)

rawDescription: How to apply a logical operator to all elements in a python list

description: Apply a logical operator to all elements in a python list


rawDescription: python argparse extra args

description: Python argparse extra args


code: df.resample('100L', loffset='50L')

rawDescription: How to resample starting from the first element in pandas?

description: Resample starting from the first element in pandas


code:
def mykey(text):
    numtxt, name = text.rsplit('-',1)
    numtxt = int(numtxt.replace('-',''))
    return (numtxt, name)

new_str = sorted(str_array, key = mykey)

rawDescription: python string array sorting

description: Python string array sorting


code:
# get where F == 1000
maskF = dataset.F == 1000
# get the values where F == 1000
rows = dataset[maskF]
# get the values where A12 is in column E
rows = rows[rows.E == "A12"]
#remove the we don't want to see
del rows["E"]
del rows["F"]
#Plot the result
rows.plot(xlim=(0,None), ylim=(-1,2))

rawDescription: plot multiple data series from numpy array

description: Plot multiple data series from numpy array


code:
def save(self, which_save, *args, **kwargs):
    if(which_save == 1):
        do_something()
    elif(which_save == 2):
        do_something_else()
    else:
        raise ValueError

rawDescription: 2 function save() to one model

description: 2 function save() to one model


code:
group = Group.objects.get(name='something')
keyw = MyKeywords.objects.get(name='something_else')
group.keywords.add(keyw)
group.keywords.all()
group.keywords.remove(keyw)

rawDescription: django many to many association

description: Django many to many association


code:
def map_GI(gilist, mapped):
    with open(gilist) as infile:
        read_gi = csv.reader(infile)
        GI_list = {rows[0]:rows[1:] for rows in read_gi} # read GI list into dictionary
    with open(mapping_file) as mapping: # thats the cross reference
        read_mapping = csv.reader(mapping, delimiter='\t')
        for gid, xids in read_mapping:
            for gi_seqid, gi_gids in GI_list:
                GI_list[seqid] = [xids if gi_gid == gid else gi_gid for gi_gid in gi_gids]
    with open("/output.txt", 'wb') as outfile: # save mapped SeqIDs plus XIDs
        looked_up_go = csv.writer(outfile, delimiter='\t')
        for key, val in XID_list.iteritems():
            looked_up_go.writerow([key] + val)

rawDescription: Process large csv file, look up values from another csv, Python


code:
im = np.atleast_3d(im)
H, W, D = im.shape[:3]
h, w = tpl.shape[:2]

rawDescription: Determine if an image exists within a larger image, and if so, find it, using Python


code:
def regressionTest(somearg):
   path = os.path.abspath(os.path.dirname(somearg))

rawDescription: How can i make the attached pyunit python script search for tests in subfolders

description: Make the attached pyunit python script search for tests in subfolders


code: { vsub:k for k, v in d.iteritems() for vsub in v }

rawDescription: find key value based on value field python dictionary

description: Find key value based on value field python dictionary


code:
def square(x):
    return mul(x, x)

rawDescription: Query on local frame and global frame in python Environment


code:
ax.plot(x, y, 'b.-', ...)
ax.lines[-1].set_label('line 1')

rawDescription: How do I set label for an already plotted line in matplotlib?

description: Set label for an already plotted line in matplotlib


rawDescription: Is there a better more readable way to coalese columns in pandas


code:
def getkey(line):
    return line.split()[1]

rawDescription: Iterate through a file multiple times

description: Iterate through a file multiple times


code: command = lambda: window2(root)

rawDescription: window label is not printing : Python

description: Window label is not printing : Python


code:
tag_match = lambda el: (
    getattr(el, 'name', None) in ('tagname1', 'tagname2') and
    el.attrs.get('attributename') == 'something' and
    'classname' in el.attrs.get('class')
)
tags = soup.find(tag_match)

rawDescription: BeautifulSoup order of occurrence of Tags


code:
def find_all_paths(graph, start, path=[]):
    path = path + [start]
    yield path
    if start not in graph:
        return
    for node in graph[start]:
        if node not in path:
            yield from find_all_paths(graph, node, path)

rawDescription: Find all paths without specifing end node?


code:
class MyResource(ModelResource):
    city = fields.CharField(attribute="city")

    class Meta:
        ...

rawDescription: How to load the foreign keys elements in Tastypie

description: Load the foreign keys elements in Tastypie


code:
class InvoiceCreateView(CreateView):
    model = Account
    form_class = AccountForm
    template_name = 'account/templates/create.html'
    success_url = reverse_lazy('account_list')

rawDescription: Django CreateView filter foreingkey

description: Django CreateView filter foreingkey


rawDescription: How can I make my code more readable and DRYer when working with XML namespaces in Python?

description: Make my code more readable and DRYer when working with XML namespaces in Python


rawDescription: Pandas: Remove rows whose date does not follow specified format


rawDescription: How to find all divs who's class starts with a string in BeautifulSoup?

description: Find all divs who's class starts with a string in BeautifulSoup


rawDescription: Recursion Formula for Integer Partitions


rawDescription: deleting rows in linux

description: Deleting rows in linux


code:
import bisect
with open('dictionary') as f:
    dictionary = f.read().split()

    # .sort is slow, so better to sort
    # words on disk! And/or run many searches
    # for one invocation
    dictionary.sort()

def bisect_search(key):
    i = bisect.bisect_left(dictionary, key)
    if i != len(dictionary):
        return dictionary[i].startswith(key)

    return False

rawDescription: Optimized regular expression search in a text corpus in Python


code: lambda a, b: (1 - a) | b

rawDescription: Python operations

description: Python operations


code:
data_from_api = ...
info = json.loads(data_from_api)

rawDescription: Converting "true" (JSON) to Python equivalent "True"


code:
lis = [set((0,1,3)), set((1,3))]
set.intersection(*lis)

rawDescription: get intersection of list of sets

description: Get intersection of list of sets


code: list_of_words = ["words and words\n", "I like words\n", "Me too\n"]

rawDescription: Can using a dictionary on standard letters work in the same or similar way using a text file?


code: arr = np.zeros((dim,dim), dtype = 'bool')

rawDescription: Efficient manipulations of binary matrix in numpy


rawDescription: How to read csv file into Python 2d array?

description: Read csv file into Python 2d array


code:
def fileFilter(f):
    if f in filename_badwords:
        return False
    else:
        return True

rawDescription: How do I match items in one list against items in another list in Python

description: Match items in one list against items in another list in Python


code:
import subprocess
number = raw_input("digit: ")
subprocess.call(('ssh', 'foo{}.bar'.format(number)))

rawDescription: Passing a variable into bash command using python


rawDescription: extract specific text from several metadata files using python

description: Extract specific text from several metadata files using python


code:
source = open('myfile', 'r')
output = open('out','w')
output.write('yes\n'.join(','.join(line.split()) for line in source.read().split('\n')))

rawDescription: Edit and save file

description: Edit and save file


code:
u = urllib.request.urlopen(url)

data_blocks = []
total = 0

while True:
    block = fd.read(1024)
    data_blocks.append(block)
    total += len(block)
    print("Downloaded {} bytes".format(total), end="\r")

    if not len(block):
        break

data = "".join(data_blocks)
u.close()

rawDescription: Python 3: How to create a text progress bar for downloading files?


code:
from pyparsing import *
from datetime import datetime

# for the most part, we suppress punctuation - it's important at parse time
# but just gets in the way afterwards
LBRACE,RBRACE,COLON,DBLQ,LBRACK,RBRACK = map(Suppress, '{}:"[]')
DBLQ2 = DBLQ + DBLQ

# define some scalar value expressions, including parse-time conversion parse actions
realnum = Regex(r'[+-]?\d+\.\d*').setParseAction(lambda t:float(t[0]))
integer = Regex(r'[+-]?\d+').setParseAction(lambda t:int(t[0]))
timestamp = Regex(r'""\d{4}-\d{2}-\d{2}T\d{2}:\d{2}""')
timestamp.setParseAction(lambda t: datetime.strptime(t[0][2:-2],'%Y-%m-%dT%H:%M'))
string_value = QuotedString('""')

# define our base key ':' value expression; use a Forward() placeholder
# for now for value, since these things can be recursive
key = Optional(DBLQ2) + Word(alphas, alphanums+'_') + DBLQ2
value = Forward()
key_value = Group(key + COLON + value)

# objects can be values too - use the Dict class to capture keys as field names
obj = Group(Dict(LBRACE + OneOrMore(key_value) + RBRACE))
objlist = (LBRACK + ZeroOrMore(obj) + RBRACK)

# define expression for previously-declared value, using <<= operator
value <<= timestamp | string_value | realnum | integer | obj | Group(objlist)

# the outermost objects are enclosed in "s, and list of them can be given with '|' delims
quotedObj = DBLQ + obj + DBLQ
obsList = delimitedList(quotedObj, delim='|')

rawDescription: Pandas semi structured JSON data frame to simple Pandas dataframe


code:
@classmethod
def all(cls):
    result = cls.view(db, "support/all", include_docs=True)
    return result.rows

rawDescription: Meaning of the map function in couchdb-pythons ViewField


code: pingchk = pinger(pcName, pingchk)

rawDescription: Passing variable from one funtion to another


rawDescription: How to cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout

description: Cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout


code:
#var is the variable containing @a in vim
len(re.split("\n",var))

rawDescription: Python, VIM: How do i count the lines in a VIM register?


code:
import os
import llist

def match_words_and_files(directory):
    directory = os.path.abspath(directory)
    res = {}
    for file_name in filter(os.path.isfile, os.listdir(directory)):
        file_title = os.path.splitext(file_name)[0]
        with open(os.path.join(directory, file_name)) as inp:
            for line in inp:
                parsed_line = line.rstrip().split()
                for word in parsed_line:
                    res.setdefault(word, llist.LinkedList()).insert_with_lookup(file_title)
    return res

rawDescription: using dictionaries and linked list python

description: Using dictionaries and linked list python


code:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

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

rawDescription: Flask with gevent multicore

description: Flask with gevent multicore


code:
import operator

data = data[0] + sorted(data[1:],key=operator.itemgetter(col_num_to_sort_by))

rawDescription: In Python, how can I store table and sort it based on one column?


rawDescription: Displaying a 32-bit image with NaN values (ImageJ)


rawDescription: Finding all partitions of a set in Java

description: Finding all partitions of a set in Java


code:
from itertools import groupby
for day, times in groupby(dates, lambda x: x.date()):
    first, *mid, last = times
    print(first)
    print(last)

rawDescription: Remove certain dates in list. Python 3.4


code:
def timesTwo(x):
    return x * 2

l = map(timesTwo, l)

rawDescription: How to multiply all integers inside list

description: Multiply all integers inside list


code:
#python_test2.py
import random, time

virus_probabilities= { "CompA" : 0.50, "CompB" : .25, "CompC" : .25, "CompBD" : .125,
                   "CompBE" : .125, "CompCD" : .125, "CompCE" : .125}

def check_probability(computer_name, n_repetitions = 100):
    prob_comp, repetitions = 0, 0
    p_computer = virus_probabilities[computer_name]
    while repetitions < n_repetitions:
     x = random.random()
     if x <= p_computer:
          prob_comp += 1
     repetitions += 1
    print ("{0} % changes of getting virus on {1}".format(round(prob_comp/100.0, 2), computer_name))

for key in virus_probabilities:
     check_probability(key, 1000)

rawDescription: Calculate Conditional Probability Python


code:
actor_ids = list(Actor.objects.filter(follow_set__user=request.user).values_list('id', flat=True))
genre_ids = list(Genre.objects.filter(follow_set__user=request.user).values_list('id', flat=True))
films = Film.objects.filter(Q(actors__in=actor_ids) | Q(genres__in=genre_ids)).distinct()

rawDescription: Find related objects and display relation


rawDescription: How to return a subarray of a multidimensional array in Python?

description: Return a subarray of a multidimensional array in Python


code:
for idx in idx_values:
    df.iloc[idx-3: idx+4]

rawDescription: Slicing based on dates Pandas Dataframe

description: Slicing based on dates Pandas Dataframe


code:
import numpy as np
from pprint import pprint
from main_module import arrayholder

def calc(arrayholder):
    arrayholder.test_array = np.append(arrayholder.test_array, [4])
    pprint(arrayholder.test_array)

calc(arrayholder)
pprint(arrayholder.test_array)

rawDescription: Can't append global NumPy array from other module


code:
from itertools import chain
list(chain.from_iterable(animals))

rawDescription: How do I remove extra parsing characters in a list?

description: Remove extra parsing characters in a list


code:
def depth_first_search(self):
    yield self, 0 # root
    for child in self.get_child_nodes():
        for node, depth in child.depth_first_search():
            if(yield node, depth+1):
                yield None # for .send
                return

rawDescription: Stop generator from within block in Python


code:
input = """1023
10?1023
1023
"""

sum(int(line) if line.isdigit() else 0 for line in input.splitlines())

rawDescription: python pattern matching numbers

description: Python pattern matching numbers


code:
s = u'./Björk/Albums/1990 - Gling-Gló [mp3-231]/01 - Gling-Gló.mp3'
s
s.encode('UTF-8')

rawDescription: mutagen and id3 tags - character encoding confusion

description: Mutagen and id3 tags - character encoding confusion


code:
day_h['new_index'] = day_h.index.map(lambda x: datetime.datetime(x[0], x[1], x[2], x[3]))
day_h.set_index('new_index')

rawDescription: Create Datetime index after groupby

description: Create Datetime index after groupby


code:
import re

r = re.compile("(double|int) ([a-zA-Z_]+)=([0-9\.]+)")

header = """/* comments */
int param_nx=2049; // comment
int param_ny=2049; // comment
double param_dt=0.01; // comment"""

params = {}

for line in header.split("\n"):
    m = r.search(line.strip())
    if m:
        if m.group(1) == "int":
            params[m.group(2)] = int(m.group(3))
        elif m.group(1) == "double":
            params[m.group(2)] = float(m.group(3))
print(params)

rawDescription: How to import efficiently values in Python from a list of global variables in a C header file

description: Import efficiently values in Python from a list of global variables in a C header file


code:
from itertools import groupby

three_or_more = (char for char, group in groupby(input_string)
                 if sum(1 for _ in group) >= 3)

rawDescription: Determine if string has 3 or more duplicate sequential characters in Python


code:
class class1:
    def __init__(self, a, b):
        self.a, self.b = a, b
    @staticmethod
    def func1():
        dosomething

obj1 = class1(somevalue1A, somevalue1B)
obj2 = class1(somevalue2A, somevalue2B)
func2(obj1.a, obj1.b)
func2(obj2.a, obj2.b)
obj1.func1()
obj2.func1()
class1.func1()

rawDescription: Access a Python variable which is inside a function, in another function


rawDescription: Using Python Variables in one Instance

description: Using Python Variables in one Instance


code:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

rawDescription: Deleting rows with Python in a CSV file

description: Deleting rows with Python in a CSV file


code:
import functools
f = functools.partial(interp, x, y)
v = list(map(f, u))

rawDescription: Interploating list using python

description: Interploating list using python


code:
def saveToFile(fileName, data):
    f = open(fileName, "w")
    f.write(data)
    f.close()

myname = input("What's your name? ")
saveToFile("name.txt", myname)

myage = input("How old are you? ")
saveToFile("age.txt", myage)

rawDescription: Save variable a user input

description: Save variable a user input


code:
my_list = list('hello')
my_list
my_list.extend('world')
my_list

rawDescription: What is wrong with this alternative bitwise operator function?


rawDescription: Different Dictionaries sharing the same instance


code:
def myview(request):
    t = request.GET.get('t')
    #rest of the code.

rawDescription: Django URLConf for former forum URL

description: Django URLConf for former forum URL


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

rawDescription: Defining a class in python in python

description: Defining a class in python in python


code:
import os
project_root = "/path/to/your/Project"
dirs = os.listdir(project_root)
for app in dirs:
    app_path = os.path.join(project_root, app)
    locale_path = os.path.join(app_path, "locale")
    if(os.path.exists(locale_path)): #modify this condition for exclusion of specific folders
        os.chdir(app_path)
        os.system("django-admin.py makemessages -a --no-wrap")

rawDescription: Make messages i18n for specific directories or exclude directories


code: li

rawDescription: What does this function do? (Python iterators)


rawDescription: BeautifulSoup: Extract "img alt" content Web Scraping in Python


code:
import itertools

class Counter(object):
    def __init__(self, start, step=1):
        self.count = itertools.count(start, step)

    def next(self):
        return self.count.next()

    def __iter__(self):
        return self

    def __unicode__(self):
        return unicode(self.next())

@register.assignment_tag
def counter_from(start, step=1):
    return Counter(int(start), int(step))

rawDescription: How can i use the forloop counter in django without resetting

description: Use the forloop counter in django without resetting


code:
if any(aboveAdj1 + aboveAdj2):
    perAboveFix = 100 * (sum(aboveAdj1) + sum(aboveAdj2)) / (len(aboveAdj1) + len(aboveAdj2))

rawDescription: Check if list is either empty or only containing zeroes


code:
m = [['1']*3]*2
m[1][2] = '0'   # I might think I changed only *one* cell
m
m[0] is m[1]

rawDescription: Translating from numpy to pure python

description: Translating from numpy to pure python


code:
class Thing:
   def __init__(self, **kwargs):
       self.something = kwargs['something']
       #..

rawDescription: Python 3 object construction: which is the most Pythonic / the accepted way?


code:
import struct
s=s.encode('utf-32-be')
struct.unpack('>{}L'.format(len(s)//4),s)
for i in struct.unpack('>{}L'.format(len(s)//4),s):
    print('U+{:04X}'.format(i))

rawDescription: How to iterate over Unicode characters in Python 3?

description: Iterate over Unicode characters in Python 3


code:
test = list('asdf')
map(function, test)

rawDescription: python, functions running from a list and adding to a list through functions

description: Python, functions running from a list and adding to a list through functions


code:
from string import ascii_lowercase
ascii_lowercase  # Just to demonstrate
lst = ['aaaa', 'aaata', 'aaatt']
[">{}/n{}".format(ascii_lowercase[x], y) for x,y in enumerate(lst)]

rawDescription: Append/Prepend a different character to each item in a list


code:
import xml.etree.cElementTree as etree

for event, elem in etree.iterparse(file, events=('start', 'end')):
    if event == 'start':
       print(elem.tag) # use only tag name and attributes here
    elif event == 'end':
       # elem children elements, elem.text, elem.tail are available
       if elem.text is not None and elem.tail is not None:
          print(repr(elem.tail))

rawDescription: Using Python's xml.etree to find element start and end character offsets


code:
block_list = Block.objects.filter(lesson=int(num))

# For each block, fill the stuff inside of the latest revision:
for block in block_list:
    additional = BlockContent.objects.filter(block=block.id).latest('id')
    block.blockcontent_set.add(additional)
    # The block.blockcontent_set contains multiple BlockContent objects
    for block_content in block.blockcontent_set.all():
        print("check: ", block_content.content)

rawDescription: Calling fields in added set in Django

description: Calling fields in added set in Django


code:
verbs = ["get",
         "put",
         "drop",
         "use",
         "enter",
         "leave",
         "walk",
         "search",
         "attack",
         "defend"]

nouns = ["journal",
         "magnifier",
         "glasses",
         "knife",
         "kite",
         "table",
         "chair",
         "key"]

inventory = ""

user_input = input("What would you like to do?\n")

#checking if there are a set of two instructions
if(len(user_input.split())==2):
    counter = 0
    for token in user_input.split():
        print("1", token)
        print(counter)
        if(counter==0):
            if(token not in verbs):
                print("I did not understand the verb entered.")
                #removing square brackets and single quote marks from the array
                print("Please use:", ", ".join(verbs))
                counter = counter + 1
            elif(token in verbs):
                print("Recognized verb entered.")
                counter = counter + 1
                continue
        if(counter==1):
            if(token not in nouns):
                print("I did not understand the noun entered.")
                print("Please use:", ", ".join(nouns))
                counter = counter + 1
            elif(token in nouns):
                print("Recognized verb entered.")
                counter = counter + 1

rawDescription: Why does my code not find a certain string that is present in an array?


rawDescription: Python - Weighted averaging a list

description: Python - Weighted averaging a list


code:
import re
re.findall('.{6}', ss)

rawDescription: greedy regex split python every nth line

description: Greedy regex split python every nth line


code:
# mod_main/__init__.py
import os

from flask import Blueprint

static_folder = os.path.join(os.pardir, 'static')
mod_main = Blueprint(
    'main', __name__, static_folder=static_folder, static_url_path='/static')

from . import views

rawDescription: send_static_file not picking up from static folder at root in Blueprint

description: Send_static_file not picking up from static folder at root in Blueprint


rawDescription: How can I solve system of linear equations in SymPy?

description: Solve system of linear equations in SymPy


code:
from flask import Flask
app = Flask(__name__)

@app.route('/flask')
def hello_world():
  return 'This comes from Flask ^_^'

rawDescription: using Flask and Tornado together?

description: Using Flask and Tornado together


code: array = temp_SN_map

rawDescription: Remove a value from 1D array

description: Remove a value from 1D array


code:
output = output.replace('\n', '')

result = re.findall(r'Data\s+:\s+(.*)}', output, re.M)[0]

rawDescription: Create python map based on bash output

description: Create python map based on bash output


code:
csvDict = DictReaderInsensitive(open('csv-file.csv', 'rU'))

for lineDict in csvDict:
    print(lineDict[' Column_A']) # or
    print(lineDict['Column_A']) # or
    print(lineDict[' column_a']) # all returns the same

rawDescription: Accessing csv header white space and case insensitive


rawDescription: How does the @property decorator work?

description: How does the @property decorator work


rawDescription: how do I print in python if a list contains only 0s?

description: Print in python if a list contains only 0s


code:
base_url = "http://www.ecb.co.uk/stats/fixtures-results?m={month}&y={year}"

for year in range(2000, 2017):
    for month in range(1, 13):
        requests.get(base_url.format(month=month, year=year))

rawDescription: Scraping URLs using BeautifulSoup

description: Scraping URLs using BeautifulSoup


code:
# build sample data
time = 0
samples = [[0, 1350]]
for i in range(0, 200):
   samples.append([time+30, 1400])
   samples.append([time+60, 1350])
   time += 60

n_samples = len(samples)

# METHOD 1
total_ws = 0.0
total_t=0
for i in range(1, n_samples):
   dt = samples[i][0] - samples[i-1][0]
   average = (samples[i][1] + samples[i-1][1]) / 2
   total_ws += average * dt
   total_t+=dt
print("Total ws: %0.2f" % total_ws)
print("Total w: %0.2f" % (total_ws/total_t))

# METHOD 2
total_ws = 0.0
for i in range(0, n_samples - 1):
   total_ws += (samples[i][1] + samples[i + 1][1]) / 2;
total_ws *= (samples[-1][0] - samples[0][0]) / n_samples;
print("Total ws: %0.2f" % total_ws)
print("Total w: %0.2f" % (total_ws/samples[-1][0]))

# "My" METHOD
total_ws = 0.0
total_t=0
for index in range(len(samples)):
    if index==0:dt=samples[index+1][0]/2.
    elif index==len(samples)-1:dt=(samples[index][0]-samples[index-1][0])/2.
    else:dt=(samples[index+1][0]-samples[index-1][0])/2.
    total_t+=dt
    total_ws+=samples[index][1] * dt
print("Total ws: %0.2f" % total_ws)
print("Total w: %0.2f" % (total_ws/total_t))

rawDescription: Best python method for calculating kw/h from data set


code:
for result in x["results"]:
    print(result["source_link"])

rawDescription: Python - Count JSON elements before extracting data


rawDescription: Using re.split() for two { } in python

description: Using re.split() for two { } in python


code:
p=os.path.abspath(sys.executable)
IM0 = os.path.join('Images\\Im_0.jpg')
IM1 = os.path.join('Images\\Im_1.jpg')
IM2 = os.path.join('Images\\Im_2.jpg')
...

rawDescription: python 3.4 py2exe image.open cannot find the images

description: Python 3.4 py2exe image.open cannot find the images


code:
def fib(n, _memo={0:1, 1:1}):
    if n in _memo:
        return _memo[n]
    else:
        _memo[n] = fib(n-1) + fib(n-2)
        return _memo[n]

rawDescription: Python func_dict used to memoize; other useful tricks?


code:
for i in range(len(cursosArreglo)):
    cursosArreglo[i] = "".join(cursosArreglo[i])

print(", ".join(cursosArreglo))

rawDescription: How can i print a list without the brackets?

description: Print a list without the brackets


rawDescription: python - matplotlib - How to specify the scale for x axis

description: Python - matplotlib - How to specify the scale for x axis


code:
dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType()
dev_sda1.size = 50 # size in Gigabytes
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1

rawDescription: How to launch EC2 instance with Boto, specifying size of EBS?

description: Launch EC2 instance with Boto, specifying size of EBS


code:
from itertools import product
dot = lambda X, Y: sum(x * y for x, y in zip(X, Y))
p = [1, 2, 3, ...] # Whatever fixed value you have for `p`
d = 100 # Fixed d
results = []
for q in product(range(0, d+1), repeat=len(p)):
    if dot(p, q) == d:
        results.append(q)

rawDescription: solve particular symbolic equation in python

description: Solve particular symbolic equation in python


rawDescription: How do I split the lists in python

description: Split the lists in python


code:
p = np.random.permutation(len(a))
p[np.argpartition(a[p], -4)[-4:]]

rawDescription: Get indices of N maximum values in a numpy array, with random tie-breaking


code: os.system('sudo "apt-get install snort-mysql"')

rawDescription: Install a package by launching a new terminal through Python


rawDescription: Fastest way to filter values in np array based on changing threshold


code:
import csv
import os
owner,file =[],[]
with open(filePath,'rb') as f:
    reader = csv.reader(f)
    for line in reader:
        owner.append(line.split('/')[0])
        file.append(os.path.join( *line.split('/')[1:] ))

rawDescription: Separate directories from a column using python


code:
numbers = ['Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'no']
plural = "s"

with open("out.txt","w") as f:
    for i, n in enumerate(numbers[:-1]):
        if i > 8:
            plural = ""
        nxt = numbers[i+1]
        text_one = '{w} green bottle{pl}\nHanging on the wall'.format(w=n, pl=plural)
        if nxt == "One":
            plural = ""
        text_two = "And if one green bottle\nShould accidentally fall\nThere'll be {nxt} green bottle{pl}"\
        .format(nxt=nxt.lower(),pl=plural)
        f.write(text_one+text_two+' hanging on the wall\n\n')

rawDescription: Python 3.x Ten green bottles = fix plurals and capitalization


rawDescription: How can I get all of the django foreignkey objects in one shot?

description: Get all of the django foreignkey objects in one shot


code:
def ScalarMult(A,s):
    As = [[s*i for i in row] for row in A]
    return As

rawDescription: How do nested list comprehensions work in python?


code:
A
thresh = 3
np.where((A < thresh).all(0),-1,(A >= thresh).argmax(0))

rawDescription: Find the lowest non-masked point with numpy efficiently


code: v = map(lambda x:x.test(), lobj)

rawDescription: Iterate python list object and invoke each object's method


rawDescription: Order 2 different querysets by date

description: Order 2 different querysets by date


rawDescription: Python - Get redirected url of links from Google Alerts feeds


code:
rr = r"""
    ^         # begin
    ([^,]+)   # match everything but a comma
    (.+?)     # match everything, until next match occurs
    (\S+)     # non-space characters
    $         # end
"""

rawDescription: regular expression to split

description: Regular expression to split


rawDescription: Combining rows in pandas

description: Combining rows in pandas


rawDescription: Convert from bin to int/char without loosing leading "0"


rawDescription: Pandas multi-index slices for level names


code:
Polynomial([1, -6, 3, 2])
Polynomial([1, -6, 3, -2])
Polynomial([])

rawDescription: Pretty polynomial printing in python

description: Pretty polynomial printing in python


code:
import py_compile
py_compile.compile('/path/to/source/code.py', cfile='/path/to/build/code.pyc')

rawDescription: Compile python code then place it somewhere else


code:
import numpy as np
from scipy.spatial.distance import pdist, squareform

def find_gps_sorted(xy_coord, k0=0):
    """Find iteratively a continuous path from the given points xy_coord,
      starting by the point indexes by k0 """
    N = len(xy_coord)
    distance_matrix = squareform(pdist(xy_coord, metric='euclidean'))
    mask = np.ones(N, dtype='bool')
    sorted_order = np.zeros(N, dtype=np.int)
    indices = np.arange(N)

    i = 0
    k = k0
    while True:
        sorted_order[i] = k
        mask[k] = False

        dist_k = distance_matrix[k][mask]
        indices_k = indices[mask]

        if not len(indices_k):
            break

        # find next unused closest point
        k = indices_k[np.argmin(dist_k)]
        # you could also add some criterion here on the direction between consecutive points etc.
        i += 1
    return sorted_order, xy_coord[sorted_order]

rawDescription: Plot line from GPS points

description: Plot line from GPS points


rawDescription: How to access & modify Django template context variables

description: Access & modify Django template context variables


code:
filename = raw_input('Enter filename to delete: ')
client.exec_command('rm {0}'.format(filename))

rawDescription: File Selection From Remote Machine In Python


code: df = df.loc[~mask]

rawDescription: Drop observations from the data frame in python


rawDescription: Python pandas: accumulate data frame rows by condition


code:
if self._parent is not None and self._id is not None:
    ...

rawDescription: Endpoints Proto Datastore - Path {requirement} variable used for keys randomly breaks


code:
import dis
dis.dis(test)

rawDescription: Python Class Stack Frame Limitations

description: Python Class Stack Frame Limitations


code: ['SOME_KEYWORD:', ['line 1', 'line 2', 'line 3', 'line 4'], 'ANOTHER_KEYWORD:', ['line a', 'line b', 'line c']]

rawDescription: Matching nonempty lines with pyparsing

description: Matching nonempty lines with pyparsing


code:
cl = pd.read_csv('country_list.csv', sep=';', dtype={'country_code':str})
ll = pd.read_csv('phones.csv', skipinitialspace=True, dtype={'phonenumber':str})

lookup = cl['country_code']
lookup.index = cl['country_code']

ll['country_code'] = (
    ll['phonenumber']
    .apply(lambda x: pd.Series([lookup.get(x[:4]), lookup.get(x[:3]),
                                lookup.get(x[:2]), lookup.get(x[:1])]))
    .apply(lambda x: x.get(x.first_valid_index()), axis=1)
)

# remove `how='left'` parameter if you don't need "unmatched" phone-numbers
result = ll.merge(cl, on='country_code', how='left')

rawDescription: Python Pandas compare two dataframes to assign country to phone number


rawDescription: How to convert a date string to different format

description: Convert a date string to different format


code:
from collections import Counter
c = Counter(most_used_words)
msg = "Here is your breakdown of your most used words:\n\nWords | Times Used\n:--:|:--:\n"
msg += '\n'.join('%s|%s' % (k.capitalize(), v) for (k, v) in c.most_common(10))
r.send_message(user, 'Most Used Words', msg)

rawDescription: Organize dictionary by frequency

description: Organize dictionary by frequency


code:
longStr = (r"C:\Users\Public\Documents\year 2013\testfiles"
               r"\testcode\rawstringfiles.txt")
raw_StringFile = open(longStr, 'a')

rawDescription: breaking up long path names

description: Breaking up long path names


code: date1 <= to_date and date2 >= from_date

rawDescription: how to filter given two datefields if they coincide with a from and to date in a model django

description: Filter given two datefields if they coincide with a from and to date in a model django


code:
item_maxes = {}
for item in mylist:
    max_value = item_maxes.setdefault(item[0], None)
    if max_value is None or item[1] > max_value:
        item_maxes[item[0]] = item[1]

rawDescription: Improving efficiency in iterating over list sets in python


code: slicedList = zippedLists[::12]

rawDescription: Loop to Match Parts of List

description: Loop to Match Parts of List


code: pivot_df = df.pivot(index='from', columns='to', values='Amt')

rawDescription: matrix representation of pandas data-frame in python

description: Matrix representation of pandas data-frame in python


code:
import gzip
with gzip.GzipFile("/path/to/some_log_file.gz","w") as output_file:
     output_file.write("Hello GZIP World")

rawDescription: BRO IDS searches

description: BRO IDS searches


code: b = zip(*a)

rawDescription: Re assign a list efficiently

description: Re assign a list efficiently


code:
pos = 0
while True:
    try:
        pos = data.index(replaceText, pos)
    except ValueError:
        break
    data[pos:pos+1] = replaceData
    pos += len(replaceData)

rawDescription: python: how to replace a string in a list of string with a list of strings?

description: Python: how to replace a string in a list of string with a list of strings


code:
import dis
dis.dis(compile('f"X is {x}"', '', 'exec'))
dis.dis(compile('"X is {}".format(x)', '', 'exec'))

rawDescription: Why are Python 3.6 literal formatted strings so slow?


code:
def uinput():
    reader = codecs.getreader(sys.stdin.encoding)(sys.stdin)
    with cbreak():
        while True:
            yield reader.read(1)

rawDescription: Python, "filtered" line editing, read stdin by char with no echo


code:
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC

class wait_for_more_than_n_elements(object):
    def __init__(self, locator, count):
        self.locator = locator
        self.count = count

    def __call__(self, driver):
        try:
            count = len(EC._find_elements(driver, self.locator))
            return count > self.count
        except StaleElementReferenceException:
            return False

rawDescription: Selenium about how to get the new_driver after click the more_button?


rawDescription: Python - Intersectiing strings

description: Python - Intersectiing strings


code: [item for item, mask in zip([1, 2, 3], [1, 0, 1]) if mask]

rawDescription: Python reduce list by mask

description: Python reduce list by mask


code:
for (ex,ey,ew,eh) in eyes:
    cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

rawDescription: OpenCV with Python - Trying to overlay an image over the eyes on a webcam feed


rawDescription: python how to make a simple countdown program

description: Python how to make a simple countdown program


code:
s = pd.Series(["A","B","C"], name="foo")
s
pd.DataFrame(s)

rawDescription: what is the name parameter in Pandas Series?

description: What is the name parameter in Pandas Series


code:
from django.db.models.loading import get_model

level_id = request.POST['level_id']
name = request.POST['name']
model = get_model('app_name', 'Level%s' % level_id) #replace app_name with the app this model resides in.

params = {"level%s_name" % level_id: name}
level_name = model.objects.filter(**params)

rawDescription: How can I change the strings as variables in python django?

description: Change the strings as variables in python django


code: ['orange [1, 2]', 'pear [Weight 4 Mass 1.6] [Weight 4 Mass 2] [Weight 4 Mass 2.5]']

rawDescription: adding arrays inside dictionaries, inside more arrays?

description: Adding arrays inside dictionaries, inside more arrays


rawDescription: Circle and line collision detection in python tkinter


code: x - x.mean(axis=0)

rawDescription: Centering a Numpy array of images

description: Centering a Numpy array of images


code:
import lxml.etree

tree = lxml.etree.parse("leg.xml")
for dog in tree.xpath("//Leg1:Dog",
                      namespaces={"Leg1": "http://what.not"}):
    parent = dog.xpath("..")[0]
    parent.remove(dog)
    parent.text = None
tree.write("leg.out.xml")

rawDescription: Removing child elements in XML using python


code:
[(c.name, c.get_items()) for c in forms[4].controls]
forms[4]['vehicle'] = ['Bike', 'Car']

rawDescription: How do you select choices in a form using Python?

description: Select choices in a form using Python