rawDescription: Python 2.7: get the size of a file just from its handle (and not its path)


code:
X3
Y3

rawDescription: Inserting values from table into different table with python or awk


rawDescription: Python: return list of sequentially occuring common items from lists and also a list of uncommon ones


code:
key1: val1-words
key2: val2-words
key3: val3-words

rawDescription: Regex: How to match sequence of key-value pairs at end of string


code:
from collections import OrderedDict
OrderedDict(sorted(dict_of_lists.items())).values()

rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code:
from django.views.decorators.http import require_POST

@require_POST
def vnc(request):
    ip = request.POST.get('ip', None)
    response = HttpResponse(ip, content_type='application/octet-stream')
    # If you don't want the file to be downloaded immediately, then remove next line
    response['Content-Disposition'] = 'attachment; filename="ip.vnc"'
    return response

rawDescription: Setup POST HTTP Request to create variable .vnc file


rawDescription: how to generate random num with conditions

description: Generate random num with conditions


code:
def s(n):
    tsum = 0
    root = int(n**0.5)  # floor of the square root of n, at least for small enough n
    i = 1
    while i < root + 1:
        if n % i == 0:
            tsum += i + n/i
        i += 1
    # check whether n is a square, if it is, we have added root twice
    if root*root == n:
        tsum -= root
    return tsum

rawDescription: How would I go about improving/making this run faster?


code: csv2 = set(int(n) for n in csv2)

rawDescription: Converting set of string values to numeric values


code:
from flask import Flask, flash, redirect, render_template, \
     request, url_for

app = Flask(__name__)
app.secret_key = 'some_secret'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
                request.form['password'] != 'secret':
            error = 'Invalid credentials'
        else:
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

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

rawDescription: how tp pass some string from one url to another using redirect in flask

description: How tp pass some string from one url to another using redirect in flask


code:
for Z in Zs:
    Ws=Z.xpath('W')
    assert(len(Ws)==2)  #<--- Change to 9
    a_vals=('42','256')
    for W,a_val in zip(Ws,a_vals):
        abc=W.xpath('descendant::text()')
        assert(abc[0] == a_val)
        result.append([' '.join(abc)])
print(result)
# [['42 b c'], ['256 b c'], ['42 b c'], ['256 b c']]

rawDescription: Switching from amara to lxml in Python

description: Switching from amara to lxml in Python


code:
import collections
import itertools

x=[['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']]
y=[['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']]

result=collections.defaultdict(list)
for item in itertools.chain(x,y):
    result[item[0]].append(item)
result=[list(itertools.chain.from_iterable(value)) for value in result.values()]
print(result)

rawDescription: Merging Two Outer Lists Based on Iterated Inner List Value


rawDescription: Python Append to a list returns none

description: Python Append to a list returns none


code:
import os
from distutils.extension import Extension

dirname = os.path.dirname(__file__)

def make_ext(modname, pyxfilename):
    return Extension(
        name=modname,
        sources=[pyxfilename, "cobject.cpp"],
        language="c++",
        include_dirs=[dirname]
    )

rawDescription: Using data in python code from cpp using cython


code: [line.strip().split() for line in z if not line.startswith(('a', 'b'))]

rawDescription: Python - ignore lines in a file

description: Python - ignore lines in a file


code:
a = numpy.random.random(10)
ind = numpy.indices(a.shape)
numpy.rec.fromarrays([ind[0], a])

rawDescription: how to speed up enumerate for numpy array / how to enumerate over numpy array efficiently?

description: Speed up enumerate for numpy array / how to enumerate over numpy array efficiently


code:
df.index.name = 't'
df

rawDescription: Python Pandas: Convert nested dictionary to dataframe


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
driver.close()

rawDescription: What is the proper way I can invoke firefox from a python3 program?


code:
johns = []
for s in L1:
    # NOTE: not the most robust parsing method.
    v = [x.strip() for x in s.split(",")]
    data = {
        "gender": v[-1],
        "last_name": v[0],
        "first_name": v[1],
    }

    # build keyword args for datetime.date()
    v = v[2:-1] # remove parsed data
    kwargs = { "year": int(v.pop(0)), "month": 1, "day":1 }
    try:
        kwargs["month"] = int(v.pop(0))
        kwargs["day"] = int(v.pop(0))
    except:
        pass

    data["date"] = date(**kwargs)
    johns.append(data)

rawDescription: Finding the amount of time difference between dates in python


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


code:
with open('example') as f:
    lists = [[], []]
    i = 0
    for line in f:
        lists[i].append(line.strip())
        i ^= 1

print(lists[0])  # ['Item 1', 'Item 3', 'Item 5']
print(lists[1])  # ['Item 2', 'Item 4']

rawDescription: Append every other line from a text file? (Python)


code:
class Etudiant(object):
    def __init__(self, numero):
        self.numero = numero
        self._cours = []
    def addCours(self, cours):
        self._cours.append(cours)
    def cours(self, cours):
        return cours in self._cours
    def __repr__(self):
        return '{}: {}'.format(self.numero, self._cours)

rawDescription: Output a dict in python

description: Output a dict in python


code:
def increment_digits(string):
    return ''.join([x if not x.isdigit() else str((int(x) + 1) % 10) for x in string])

rawDescription: Python: add 1 to each digit that is an integer


code:
if type(x) is str:
    return True

rawDescription: Python Control Flow

description: Python Control Flow


code:
e = ["2311","1441","31","233122"]
r = ["asasa2311","dadewr1441","app"]
[eelem for eelem in e if any(r if eelem in relem else False for relem in r)]

rawDescription: Cross Matching in python

description: Cross Matching in python


code:
re.findall(r"""
   '          #apostrophe before the string Mortein
   (          #start capture
   Mortein.*? #the string Moretein plus everything until...
   )          #end capture
   '          #...another apostrophe
   .*         #zero or more characters
   \$         #the literal dollar sign
   (          #start capture
   .*?        #zero or more characters until...
   )          #end capture
   '          #an apostrophe""", s, re.X)

rawDescription: How does re.match().groups() work?

description: How does re.match().groups() work


code: df['date_threshold'] += timewindow

rawDescription: Dropping rows fast from a multi-indexed data frame conditional on the level 1 index


code:
for w in myfile:
    for n in words:
        if n not in stop_words:
            filtered_sentence.append(' '+n)

rawDescription: How to read a CSV file line by line and store it to new CSV file on new row every time?

description: Read a CSV file line by line and store it to new CSV file on new row every time


code:
username = User.query.filter_by(id=post.id).first().name
email = User.query.filter_by(id=post.id).first().email

rawDescription: Referencing values using foreign key on flask sql-alchemy


rawDescription: Numpy fancy indexing in multiple dimensions


code:
class HashStorage(object):
    def __init__(self, fname_fmt):
        self.fname_fmt = fname_fmt
        self.hashfile = {}

    def thefile(self, hash):
        hashlen = len(hash)
        try:
            return self.hashfile[hashlen]
        except KeyError:
            newfile = open(self.fname_fmt.format(hashlen), 'w')
            self.hashfile[hashlen] = newfile
            return newfile

    def write(self, hash):
        self.thefile(hash).write(hash + '\n')

    def __del__(self):
        for f in self.hashfiles.itervalues():
            f.close()
        del self.hashfiles

store = HashStorage('c:/HashFiles/hashes{}.txt')

with open('c:/HashFiles/Part1.txt') as inf:
    for line in inf:
        data = line.split(',')
        hash = data[4]
        store.write(hash)

rawDescription: parsing/extracting data from a text file. Unable to make it work

description: Parsing/extracting data from a text file. Unable to make it work


code:
result2.append((
    fncts[fnct[0]][4],
    object,
    id,
    map(lambda x: fncts[x][1], fnct)
))

rawDescription: Strange super () return behaviour when using a temp variable to store the super return value


code:
import moviepy.editor as mp
messages = ["Dog", "Cat", "Duck", "Wolf"]
clips = [ mp.TextClip(txt, fontsize=170, color='green', size=(500,300))
            .set_duration(1)
          for txt in  messages]
concat_clip = mp.concatenate_videoclips(clips)
concat_clip.write_videofile("texts.mp4")

rawDescription: How to concatenate videos in moviepy?

description: Concatenate videos in moviepy


code: MyClassFormSet = inlineformset_factory(User, MyClass, form=MyForm, can_delete=False, extra=5)

rawDescription: Define CSS style in Django model field

description: Define CSS style in Django model field


code:
def sumFirstSix(self):
    """
    sums the first six moments and returns the sum of the values
    """
    l=('Ettor','Tvåor','Treor','Fyror','Femmor','Sexor')
    sum=0
    for item in l:
        sum+=self.moment[item]
    return sum

rawDescription: How to sum some of the values for dicts in a list?

description: Sum some of the values for dicts in a list


code:
t('S.O.S.')
t('Stack Overflow')

rawDescription: How to improve efficiency in loops?

description: Improve efficiency in loops


code:
p = MySubProcess(any_args_here)
p.start()
p.join()

rawDescription: Python3 from Thread class to Process

description: Python3 from Thread class to Process


rawDescription: I have a piece of code that only works for numbers greater than 1000. Any explanation why?


code:
xdata = data[:,0]
ydata = data[:,1]

z = np.polyfit(xdata, ydata, 5)
f = np.poly1d(z)

rawDescription: OpenCV: fit the detected edges

description: OpenCV: fit the detected edges


code:
import random
pin_length = 6
random_pin = ''.join(random.choice(alphabet) for i in xrange(0, pin_length))

rawDescription: How Do I Get Unique IDs Efficiently in Python?


code:
df_pos = df[df.events == 1]
df_neg = df[df.events == 0]

rawDescription: Ploting matrix in matplotlib, while taking indexed data for positive and negative values, returns wrong plot axis or data


rawDescription: Can the value of both the current and next item be accessed in a Python list comprehension?


code:
# No arguments
@logged
def some_function(x):
    pass

# One or more arguments
@logged(1, 2, 3)
def some_function(x):
    pass

# One or more keyword arguments
@logged(key=1, another_key=2)
def some_function(x):
    pass

# A mix of the two
@logged(1, 2, key=3)
def some_function(x):
    pass

rawDescription: Python decorator optional argument

description: Python decorator optional argument


code: def func(data, options): _func(data, **options)

rawDescription: Python convenient passing of dictionary arguments to function


code:
my_dict={i:j for i,*j in [l[i:i+4] for i in range(0,len(l),4)]}
my_dict

rawDescription: Python 3.4: List to Dictionary

description: Python 3.4: List to Dictionary


code:
example_string = "Test"
example_list = list(example_string)

rawDescription: Python: More efficient way to break down string and append it to a list


code: vct

rawDescription: NumPy - Image (matrix) thresholding using an intensity value matrix.


rawDescription: Python: sharing a list between threads

description: Python: sharing a list between threads


code: numpy.loadtxt('data.txt', dtype=[ ('time', np.uint64), ('pos', [('x', np.float), ('y', np.float)]) ])

rawDescription: NumPy: using loadtxt or genfromtxt to read a ragged structure


code:
inclusion(A, B)
inclusion(A, C)
inclusion(A, D)

rawDescription: Finding a partial or complete inclusion of a set of points in convex hull of other set of points in 2D in python


code: [(a, b, c.replace(",", "")) for a, b, c in List]

rawDescription: Convert string to int in a list by removing floating (Python)


code: lines[1] = str(round(strength, 2)) + "\n"

rawDescription: Python: How to 'write' on the second line of a text file ignoring the first line


code:
def __lt__(self, other):
    return self.intAttribute < other.intAttribute

rawDescription: How to make heapq evaluate the heap off of a specific attribute?

description: Make heapq evaluate the heap off of a specific attribute


code: new_list = [d[key] for key in string_list]

rawDescription: Given two lists in python one with strings and one with objects, how do you map them?


rawDescription: Why aren't my old boxes disappearing?

description: Why aren't my old boxes disappearing


code: from PIL import Image

rawDescription: Scipy.misc.imread flatten argument -- converting to grey scale


code:
rawList = [[[u'Hot Dogs', u'hotdog'], [u'Food Stands', u'foodstands']], [[u'Scandinavian',       u'scandinavian'], [u'Breakfast & Brunch', u'breakfast_brunch'], [u'Coffee & Tea', u'coffee']],    [[u'Burgers', u'burgers']]]
finalList = []

for l in rawList:
    finalList.append([i[0] for i in l])

rawDescription: Python Remove 2nd item from List within List


rawDescription: The most effective way to random flip every image in a numpy array


code:
def func(word, lst):
  items = sorted((dist(word, w), w) for w in lst)
  # Print items here for debugging.
  if not items:
    raise ValueError('List of words is empty.')
  return items[0][1]

rawDescription: How to return the most similar word from a list of words?

description: Return the most similar word from a list of words


code:
@app.route('/questions/<int:num>')
def questions(num):
    # This part disallows the user from jumping a future question
    # without first answering all the questions that lead up to it
    # i.e a user cannot go from question 1 to question 8 without
    # first answering questions 2 - 7 but once they've answered
    # question 8 they can jump back to question 2 and then jump to
    # question 9
    highest_num_seen = session.get('highest_num_seen', 1)
    if num > highest_num_seen:
        num = highest_num_seen

    question = db.load_question(num) # Load your question from db

    # update highest_num_seen if and only if it is the next question
    # from what the user last answered
    if num == highest_num_seen + 1:
        session['highest_num_seen'] = num

    render_template('blahblah')

rawDescription: Revert back to previous flask session variables when going back a page


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

07/02/13
|
02:15

Text Start: This text changes each time, 5-4

''')
import re
soup.find_all(text=re.compile('^\s*Text Start:.*'))

rawDescription: Scraping webpage sentences beginning with certain word


code:
import collections

def get(infilepath, name, n):
    d = collections.deque(maxlen=n)
    with open(infilepath) as infile:
        line = infile.readline()
        lines = 1
        while line:
            word = line.strip()
            if word == name:
                print("From up:")
                for item in d:
                    print(item)
                print(word)
                break
            d.append(word)
            line = infile.readline()
            lines += 1
        print("From Down:")

        if n-lines > 0:
            n -= lines
            d = collections.deque(maxlen=n)
            while word:
                d.append(word)
                word = infile.readline().strip()
                if not word:
                    break
            for word in d:
                print(word)

rawDescription: Python Copy specified lines from text file


code:
(key, val) = line.split(': ')
d[key] = val.rstrip('\n')

rawDescription: Python - Reading text file into dict

description: Python - Reading text file into dict


code: p.parse_args('--sizes 1,3 4,6'.split())

rawDescription: How to create argument of type "list of pairs" with argparse?

description: Create argument of type "list of pairs" with argparse


code:
code_lookup = ('PL', 'DE', 'FR')
return lookup.index('PL')

rawDescription: Convert enum to int in python

description: Convert enum to int in python


code:
data_file = open('/var/log/secure', 'r')

variables = RequestContext(request, {
        'data_file': data_file,
        'var2': 'test'
})
return render_to_response('logfiles.html', variables)

rawDescription: How to keep data formatted after reading from log files in django/python

description: Keep data formatted after reading from log files in django/python


rawDescription: Return copies of dictionary modified

description: Return copies of dictionary modified


code:
s = "python is pretty fun to use"
map(len, s.split())       # assuming Python 2.x
list(map(len, s.split())) # assuming Python 3.x

rawDescription: How to get the length of words in a sentence?

description: Get the length of words in a sentence


code: a is e

rawDescription: Three tiers of equality comparison in Python


code:
import os

with open(os.devnull, 'rb') as DEVNULL:
    output = qx(cmd, stdin=DEVNULL) # use subprocess.DEVNULL on Python 3.3+

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


rawDescription: Is there a multi-dimensional version of arange/linspace in numpy?


code:
class MyClass(object):

    def __init__(self, name, *args, **kwargs):
        self.name = name

rawDescription: Ensure uniqueness of instance attribute in python


code:
kwargs = {'bar': 1, 'qux': 23}

foo(**kwargs)

rawDescription: Is there a way in flask to get each object in the request.json and save each attribute on the model?


code: l = len(Quest)

rawDescription: Python v3 to store a len value and hold in a variable


code:
for i in range(len(node)):
     options [i] = names[:]

rawDescription: Python: Updating a list of values in a dictionary


code:
import collections
projects = collections.defaultdict(list)
contexts = collections.defaultdict(list)
for line in todo_list.splitlines():
    for item in re.findall(r'[+]\D\w+', line):
        projects[item].append(line)
    for item in re.findall(r'[@][A-Z]\w+', line):
        contexts[item].append(line)

rawDescription: Get text surrounding regex match with python


code: sorted(array, key=lambda x:x[:24])

rawDescription: sort lines in text file, but only use the first N characters

description: Sort lines in text file, but only use the first N characters


code:
class AssetModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = AssetModel

    # Fields org and name of AssetModel will be inlcuded by default

class DataitemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dataitem

    mod = AssetModelSerializer()
        # This is the Dataitem.mod field
        # which is a FK to AssetModel,
        # Now it'll be serilized using the AssetModelSerializer
        # and include the org and name fields of AssetModelSerializer

rawDescription: Writable nested serializer in django-rest-framework?


code: func("some", "values", "in", "a", "list")

rawDescription: Passing a list of parameters into a Python function


code:
def my_view(request):
    # View code here...
    return render_to_response(request, 'myapp/index.html', {"foo": "bar"},
                 context_instance=RequestContext(request)
                 )

rawDescription: How to insert data to a template after render ? (django)

description: Insert data to a template after render ? (django)


code: np.savetxt('output_file_name', data)

rawDescription: Replace a value based on specific criteria


code:
repr(1)
repr(1).rjust(3)

rawDescription: Can someone explain how to use the repr function to format the output?


code:
def algo_by_name(name):
    return {'algo0': algo0, 'algo1': algo1, }[name]

rawDescription: Processing a simple workflow in Python

description: Processing a simple workflow in Python


code:
from django import template
register = template.Library()

@register.simple_tag
def dictKeyLookup(the_dict, key):
   # Try to fetch from the dict, and if it's not found return an empty string.
   return the_dict.get(key, '')

rawDescription: How do I access dictionary keys that contain hyphens from within a Django template?

description: Access dictionary keys that contain hyphens from within a Django template


code:
size = asksize() #store the data on to variable called size
#then just call your check move
checkmove(x)

rawDescription: How to reuse user's raw input in other function

description: Reuse user's raw input in other function


code:
import math

def roundTo32(x, base=32):
    return int(base * math.ceil(float(x) / base))

rawDescription: How to round up to 32 using the math module (Python 3,)

description: Round up to 32 using the math module (Python 3,)


code:
import requests
from bs4 import BeautifulSoup

resp = requests.get('https://www.digitalocean.com')
soup = BeautifulSoup(resp.text)
digits = [tag.getText() for tag in soup.find_all(class_="count")]
count = int(''.join(digits))

rawDescription: Is there an easy way to script a comparison of a web page over time?


rawDescription: Group by multiple keys and summarize/average values of a list of dictionaries


rawDescription: Setting ndarray values with the flat iterator


code:
x
repeat_on = np.array([2, 0, 1, 0, 3])
x.repeat(repeat_on, axis=0)

rawDescription: Make a new array selectively copying, with varying multiplicity, rows of old array in numpy


code:
for line in infile:
    words = line.split() # splits long string into array of single words

rawDescription: Python sad/happy face machine learning (Get rid of text)


code: tagger.tag(['select', 'the', 'files'])

rawDescription: custom tagging with nltk

description: Custom tagging with nltk


code:
a, b = 10, 20
a, b
b, a = a, b
a, b
a, b = a*b, a/b
a, b

rawDescription: Is sequence unpacking atomic?

description: Is sequence unpacking atomic


rawDescription: Numpy - assign column data types (dtype) to existing array


code:
class MyBackend(object):
    def authenticate(self, username=None, password=None):

        # Check if username i.e. UUID exists
        try:
            my_uuid = MyUUIDModel.objects.get(uuid=username)
        except MyUUIDModel.DoesNotExist:
            return None
        return my_uuid

rawDescription: How to Create A User Model Only Including Username in Django?


code:
namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
                 OrderedDict=OrderedDict, _property=property, _tuple=tuple,
                 namedtupleBase=namedtupleBase)

rawDescription: Serializing namedtuples via PyYAML

description: Serializing namedtuples via PyYAML


code:
class InvoiceForm(Form):
    # define all your fields, I put some dummy fields here
    field1 = CharField()
    field2 = TextField()
    # etc
    tax = ModelChoiceField(queryset=Tax.objects.all())

rawDescription: How to customize a ModelForm with ChoiceField for a Model FloatField attribute Django

description: Customize a ModelForm with ChoiceField for a Model FloatField attribute Django


code: result

rawDescription: Returning groups of correlated columns in pandas data frame


rawDescription: Iterate over list of values dictionary

description: Iterate over list of values dictionary


code:
from django.contrib import admin

from models import MyModel
from forms import MyModelForm

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
admin.site.register(MyModel, MyModelAdmin)

rawDescription: How include a filefield in a django admin model form that is not in the model


code:
def make_tree(path):
    tree = dict(name=os.path.basename(path), children=[])
    try: lst = os.listdir(path)
    except OSError:
        pass #ignore errors
    else:
        for name in lst:
            fn = os.path.join(path, name)
            if os.path.isdir(fn):
                tree['children'].append(make_tree(fn))
            else:
                tree['children'].append(dict(name=name))
    return tree

rawDescription: How to generate an html directory list using Python

description: Generate an html directory list using Python


code:
mystr = r'a\t\tb'  # Escape sequences are ignored
print(mystr)
print(mystr.replace('\t', ' '))  # This replaces tab characters
print(mystr.replace(r'\t', ' '))  # This replaces the string '\t'

rawDescription: How to treat \t as a regular string in python

description: Treat \t as a regular string in python


code: df['country'] = map(get_country, df['season'])

rawDescription: Find key from value for Pandas Series

description: Find key from value for Pandas Series


code:
class Bird:
    ...

rawDescription: get the name of the class and wrap it in an if statement

description: Get the name of the class and wrap it in an if statement


code:
import re
pattern = re.compile('^api/student/(?P<pk>.*)/(?P<pk2>.*)/$')
pattern.match('api/student/1//').groups()
pattern.match('api/student//1/').groups()

rawDescription: Django urls with empty values

description: Django urls with empty values


code: alphaFadeLayer.blit( self.fadeLayer )

rawDescription: python: Keep entry in dict synced to the original?

description: Python: Keep entry in dict synced to the original


rawDescription: Python return without " ' "

description: Python return without " ' "


code:
from celery import current_app as celery_app, registry as celery_registry

celery_imports = celery_app.conf.get('CELERY_IMPORTS')
if celery_imports:
    for module in celery_imports:
        __import__(module)

task = celery_registry.tasks.get(args.task)
if task:
    result = task.apply_async(task_args, task_kwargs)

rawDescription: Celery and routing

description: Celery and routing


code: owner = ForeignKey(User)

rawDescription: Django Model Design. Want users to have "Collections" of other model instances


code: s.groupby(level=[0, 1]).value_counts()  # equiv .apply(pd.value_counts)

rawDescription: Pivoting a table with hierarchical index


code:
self.m_panel74.SetSizer( sizer )
self.m_panel74.Layout()
sizer.Fit( self.m_panel74 )

rawDescription: Access a specific sizer from wxFormBuilder in Python


code:
import random
f = open('deck.txt', 'w') # op
l = [i for i in range(1,111)] # list from 1 to 110
random.shuffle(l) # shuffle that list
for i in l:
    f.write(str(i))
    f.write('\n')

rawDescription: Card Game Python, Saving a shuffled deck


rawDescription: How to retrieve a value from an executed string?

description: Retrieve a value from an executed string


code: [['odd' if i & 1 else 'even' for i in sub] for sub in l]

rawDescription: Mapping Odd/Even to nested lists

description: Mapping Odd/Even to nested lists


code: all(predicate(e) for e in iterable)

rawDescription: Python version of C++ all_of

description: Python version of C++ all_of


code:
cur = conn.cursor()
cur.executemany("""INSERT INTO bar(first_name,last_name) VALUES (%(first_name)s, %(last_name)s)""", namedict)

rawDescription: How do I get a scrapy item (or a dict / named tuple) into a postgres stored procudure (function) performing an insert using psycopg2

description: Get a scrapy item (or a dict / named tuple) into a postgres stored procudure (function) performing an insert using psycopg2


code:
from django.db import models

class Feat(models.Model):
    title = models.CharField(max_length=150)
    image = models.ImageField(upload_to='path/')
    youtube_link = models.URLField()
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Feat"
        verbose_name_plural = "Feats"

    def __str__(self):
        return self.title

rawDescription: Loops in django 1.8 views

description: Loops in django 1.8 views


rawDescription: What's the pythonic way to add a certain character after every X elements of a list?


rawDescription: numpy array slicing with arbitrary dimension

description: Numpy array slicing with arbitrary dimension


rawDescription: Having trouble with the same origin policy


code:
{'InboundShipmentHeader.AreCasesRequired': 'somevalue',
 'InboundShipmentHeader.DestinationFulfillmentCenterId': 'somevalue',
 'InboundShipmentHeader.LabelPrepPreference': 'somevalue',
 'InboundShipmentHeader.ShipFromAddress.Name': 'Foo',
 'InboundShipmentHeader.ShipmentName': 'somevalue',
 'InboundShipmentHeader.ShipmentStatus': 'somevalue'}

rawDescription: Most efficient way to add prefix to Python dictionary keys


code:
def mykey(row):
    return (row['mrn'], row['specimen_id'], row['lab_num'])

rawDescription: Rewind the file pointer to the beginning of the previous line


code:
import urllib
import lxml.html

# pageReady = u'content.decode()'   <----------- Remove/comment out this line.
page = urllib.urlopen('http://pogoda.yandex.ru/moscow/')
pageReady = page.read()   # <-------------------------------
xmldata = lxml.html.document_fromstring(pageReady)
temperature = xmldata.xpath('//div[@class="b-thermometer__now"]/text()')
clouds = xmldata.xpath('//div[@class="b-info-item b-info-item_type_fact-big"]/text()')
page.close()

print('%s, %s'%(temperature[0], clouds[0]))

rawDescription: Python Parsing data from site using lxml


code: import random

rawDescription: recursive function in class in python

description: Recursive function in class in python


code:
from tkinter import *

root = Tk()

menubar = Menu(root)

helpmenu = Menu(menubar)
nested_menu1 = Menu(helpmenu)
nested_menu1.add_command(label='Stuff 1')
nested_menu1.add_command(label='Stuff 2')

nested_menu2 = Menu(helpmenu)
nested_menu2.add_command(label='Stuff 3')
nested_menu2.add_command(label='Stuff 4')

menu2_nested = Menu(nested_menu2)
menu2_nested.add_command(label='Stuff 5')
nested_menu2.add_cascade(label='Nestception', menu=menu2_nested)

helpmenu.add_cascade(label='1.0 Nested', menu=nested_menu1)
helpmenu.add_cascade(label='2.0 Nested', menu=nested_menu2)

menubar.add_cascade(label="Nested Menus", menu=helpmenu)

root.config(menu=menubar)
root.mainloop()

rawDescription: Adding a menu inside of a menubutton? Python


rawDescription: How to vectorize multiple levels of recursion?

description: Vectorize multiple levels of recursion


code:
def coords_maker(num_x, num_y):

    num_x += 1
    num_y += 1
    coords = [[0]*num_x for x in range(num_y)]
    return coords

rawDescription: python3 string to variable

description: Python3 string to variable


code: x = f(sin(x + y))

rawDescription: How to step through Python expression evaluation process?

description: Step through Python expression evaluation process


code: sum = reduce(lambda x, y: x + y, L)

rawDescription: Python programming functional vs. imperative code


code: ax.scatter(x, y, z, c=colors)

rawDescription: Elegant way to match a string to a random color matplotlib


code:
from tkinter import *

window = Tk()

ia_answers= "trolol\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)

input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)

ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)

user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify =   RIGHT,

bg="white")
user_text.pack(fill=X)

ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = NW, justify = LEFT, bg="white")
ia_text.pack(fill=X)

user_texts = []
ia_texts = []
user_says_list = []
ia_says_list = []
def Enter_pressed(event):
    """Took the current string in the Entry field."""
    input_get = input_field.get()
    input_user.set("")
    user_says1 = StringVar()
    user_says1.set(input_get + "\n")
    user_text1 = Label(ia_frame, textvariable=user_says1, anchor = NE, justify =   RIGHT,

bg="white")
    user_text1.pack(fill=X)
    user_texts.append(user_text1)
    user_says_list.append(user_says1)
    ia_says1 = StringVar()
    ia_says1.set(ia_answers)
    ia_text1 = Label(ia_frame, textvariable=ia_says1, anchor = NW, justify = LEFT,

bg="white")
    ia_text1.pack(fill=X)
    ia_texts.append(ia_text1)
    ia_says_list.append(ia_says1)

input_field.bind("<Return>", Enter_pressed)
window.mainloop()

rawDescription: Discussion with tkinter

description: Discussion with tkinter


code: x[::-1]  # returns a new tuple

rawDescription: How to reverse tuples in Python?

description: Reverse tuples in Python


code:
import itertools

columns = [
    ['1', '2', '3'],
    ['a', 'b', 'c'],
    ['!', '@', '#']
    ]

result = ['-'.join(thing) for thing in itertools.product(*columns)]

rawDescription: Ordered Column Constrained Permutations Python


rawDescription: Python - Uniquely determining which text file an element originated from


code:
x(["bash", "-c", '''shopt -s nullglob
dirs=(*/)
pwd
cd -- "${dirs[RANDOM%${#dirs[@]}]}"
pwd'''])

rawDescription: How to execute bash from within a python file?

description: Execute bash from within a python file


code: keywords = pd.read_csv('keywords.list', sep='\t', skiprows=60,nrows=75436) #Here 75436 is 75496 - 60

rawDescription: Python Pandas reads_csv skip first x and last y rows


code:
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

rawDescription: Does enumerate() produce a generator object?


rawDescription: Access the index of a pandas series

description: Access the index of a pandas series


code:
averaged.ix[0]
(values[0] + values[6] + values[12] + values[18]) / 4.

rawDescription: Timeseries average with python

description: Timeseries average with python


code:
a = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
b = {1, 4}
result = [elem for elem in a if elem in b]

rawDescription: A subset of a list with elements available in another list


code:
s = 'слово'
with open('data.txt','wb') as f:
    f.write(s.encode('unicode_escape'))
    f.write(b'\n')  # add a line feed

rawDescription: More efficient way to make unicode escape codes


code:
class Bar(Foo):
    bar = Foo.bar   # an unbound method from the Foo class!
Bar.bar
Bar.bar.im_class
Bar().bar()  # it'll work like any other method

rawDescription: Not sure what the Python documentation says about user-defined method objects here


code:
for i in range(4):
    l = []

    for row in matrix:
        l.append(row[i])

    yield l

rawDescription: How to read aloud Python List Comprehensions?

description: Read aloud Python List Comprehensions


code:
def price():
    priceList = [1,2,3,4,5,6,7,8,9,10]
    print ("Price of Item Sold:")
    for i in range (10):
        priceList[i] = random.uniform(1.0,1000.0)
        print("${:7.2f}".format(priceList[i]))
    print("\n")
    return priceList

rawDescription: If/Else Statement and Lists Within Functions - Python 3.x


code: step = delta.max / len(colors)

rawDescription: Setting a colour scale in ipython

description: Setting a colour scale in ipython


code:
vals = {k: set(val) for k, val in dict1.items()}
unioned = set()
srt = sorted(dict1.keys())
srt2 = srt[:]
for key in srt:
    for k in srt2:
        if k == key:
            continue
        if vals[k].intersection(dict1[key]) and key not in unioned:
            unioned.add(k)
            dict1[key] = list(vals[k].union(dict1[key]))
            srt2.remove(k)

for k in unioned:
    del dict1[k]

rawDescription: How to combine values composed of lists with common items in a dictionary using Python?

description: Combine values composed of lists with common items in a dictionary using Python


rawDescription: How to convert ticks to datetime in Python?

description: Convert ticks to datetime in Python


code:
set_of_strings = {'abc', 'def', 'xyz'}
value = {'pr': 0, 'wt': 0}
dict(zip(set_of_strings, [value]*len(set_of_strings)))

rawDescription: GIven a set of strings, create a dictionary of dictionaries using them as keys to entries with default values


code:
# Convert the Aug-10 style strings
pd.to_datetime(date, format='%b-%y', coerce=True)
# Convert the 9/1/13 style strings
pd.to_datetime(date, format='%m/%d/%y', coerce=True)

rawDescription: Reformat a column containing dates in Pandas


code:
closest = argsmallest_n(dists, 100)
tu = np.triu_indices(1000, 1)
pairs = np.column_stack((np.take(tu[0], closest),
                         np.take(tu[1], closest))) + 1

rawDescription: extract the N closest pairs from a numpy distance array

description: Extract the N closest pairs from a numpy distance array


code:
def recAnswer(memo, current, y, z, count):
    # dict key is the tuple of arguments
    key = (current, y, z, count)

    # Have we been here before? If so, return memoized answer
    if key in memo:
        return memo[key]

    if count == z and current == y:
        return 1

    count += 1
    if count > z:
        return 0

    total = 0
    for i in dict.get(current):
        total += recAnswer(memo, i, y, z, count)

    # Store answer for later use
    memo[key] = total

    return total

rawDescription: Permutation of phone numbers starting at button x, ending at button y, and z numbers long


code: myhostbecomevariables(*hosts)

rawDescription: How do you create multiple variables from raw input in python?

description: Create multiple variables from raw input in python


code: samples = [do_sampling() for _ in xrange(n_samples)]

rawDescription: More Compact List Comprehension Where Iteration Variable is Unused


code:
yy = [list('abc') for _ in range(3)]
yy[0][0]='A'
yy

rawDescription: Regarding python list with reference

description: Regarding python list with reference


code: np.where(a == 1)

rawDescription: How to find the index of a value in 2d array in Python?

description: Find the index of a value in 2d array in Python


code:
while True:
    do_something()
    if some_condition: break

rawDescription: Pythonic way of doing this?

description: Pythonic way of doing this


code:
from pyparsing import *

stringWord = Word(alphas, alphanums)

# only want words not at the end of the string for the leading part
leadingWord = stringWord + ~LineEnd()

leadingPart = originalTextFor(stringWord + ZeroOrMore(leadingWord))

# define parser, with named results, similar to named groups in a regex
parser = leadingPart("first") + Optional(stringWord, default='')("second")

rawDescription: How to parse this string with pyparsing

description: Parse this string with pyparsing


code:
newDict = {'a': 1, 'b': 2, 'c': 3, 'd': True}
stA = frozenset('a')
stB = frozenset('b')
stC = frozenset('c')
stD = frozenset('d')
newDict.keys() & stA
for key in newDict.keys() & stA:
    print(newDict[key])

rawDescription: Retrieving values if keys of the dictionary are in frozensets


code:
import threading
def run_item(f, item):
    result_info = [threading.Event(), None]
    def runit():
        result_info[1] = f(item)
        result_info[0].set()
    threading.Thread(target=runit).start()
    return result_info

rawDescription: Threading in Python for each item in list


code:
for k, v in d.items():
    if v == searchValue:
        print(k)

rawDescription: How to turn a dictionary "inside-out"

description: Turn a dictionary "inside-out"


code: tmp

rawDescription: Pandas: Change dates in dataframe to same date format


code:
def gen_vms():
    tg = tracegen.TraceGenerator()
    trace = tg.gen_trace()
    items = [{
                  'name': 'item %d' % i,
                  'weight': 1,
                  'cpu': t[0],
                  'mem': t[1],
                  'disk': t[2],
                  'net': t[3],
                  'n': 1
             } for i,t in islice(enumerate(trace), 200)]
    return items

rawDescription: How to solve 3D multi bin-packing with OpenOpt

description: Solve 3D multi bin-packing with OpenOpt


code:
src = ColorConvert[Import["http://davemark.com/images/sudoku.jpg"], "Grayscale"];
white = Closing[src, DiskMatrix[5]];
srcAdjusted = Image[ImageData[src]/ImageData[white]]

rawDescription: How to remove convexity defects in a Sudoku square?

description: Remove convexity defects in a Sudoku square


rawDescription: Python socket only accepting local connections


code:
some_var = '123'
message_tmpl = '{{msg}}. Path  {some_var} cannot be extracted'.format(some_var=some_var)
message_tmpl.format(msg='a message')

rawDescription: How to get rid of repeating variable in str.format?

description: Get rid of repeating variable in str.format


code: photos[1] == photo

rawDescription: Check if list contains another list in python


code:
from osgeo import gdal
gdal.UseExceptions()
driver = gdal.GetDriverByName('Terragen')
dst_ds = driver.Create('test.ter', 4,4,1,gdal.GDT_Float32, ['MINUSERPIXELVALUE = 1', 'MAXUSERPIXELVALUE= 4'])
dst_ds = driver.Create('test.ter', 4,4,1,gdal.GDT_Float32, ['MINUSERPIXELVALUE=1', 'MAXUSERPIXELVALUE=4'])
type(dst_ds)

rawDescription: creating elevation/height field gdal numpy python

description: Creating elevation/height field gdal numpy python


code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

file_path = "./3D_surface_and_contour.jpg"
p = 0.05
f = -0.01

def get_data(p):
    x, y, z = axes3d.get_test_data(p)
    z = f * z
    return x, y, z

def plot_3d_contour(p, f):
    nrows = 4
    ncols = 5

    x, y, z = get_data(p)

    x_min, x_max = np.min(x), np.max(x)
    y_min, y_max = np.min(y), np.max(y)
    z_min, z_max = np.min(z), np.max(z)

    fig = plt.figure(figsize=(15, 10))
    for n in range(nrows * ncols):
        i = n % ncols
        j = n / ncols
        k = n + 1
        if j == 0:
            azim = -60 + (i - 2) * 15
            elev = 30
        elif j == 1:
            azim = -60
            elev = 30 + (i - 2) * 5
        elif j == 2:
            azim = 60 + (i - 2) * 10
            elev = 30
        elif j == 3:
            azim = 60
            elev = 30 + (i - 2) * 5
        ax = fig.add_subplot(nrows, ncols, k, projection='3d')
        ax.set_title("azim=" + str(azim) + " elev=" + str(elev))
        ax.tick_params(labelsize=8)
        ax.view_init(azim=azim, elev=elev)
        ax.plot_surface(x, y, z, rstride=10, cstride=10, alpha=0.3)
        ax.contourf(x, y, z, zdir='z', offset=z_min, cmap=cm.coolwarm)
        ax.contourf(x, y, z, zdir='x', offset=x_min, cmap=cm.coolwarm)
        if j == 0 or j == 1:
            ax.contourf(x, y, z, zdir='y', offset=y_max, cmap=cm.coolwarm)
        elif j == 2 or j == 3:
            ax.contourf(x, y, z, zdir='y', offset=y_min, cmap=cm.coolwarm)

        ax.set_xlabel('X')
        ax.set_xlim(x_min, x_max)
        ax.set_ylabel('Y')
        ax.set_ylim(y_min, y_max)
        ax.set_zlabel('Z')
        ax.set_zlim(z_min, z_max)

    plt.savefig(file_path, dpi=80)
    plt.close()

plot_3d_contour(p, f)

rawDescription: 3D plot with Matplotlib

description: 3D plot with Matplotlib


rawDescription: How to set significant figures in pyplot annotation

description: Set significant figures in pyplot annotation


code:
import operator as op
import functools
functools.reduce(op.mul, (sum(x) for x in zip(*list_)))

rawDescription: Working with nested lists in Python

description: Working with nested lists in Python


code:
DOWNLOADER_MIDDLEWARES = {
    'scrapy.contrib.downloadermiddleware.retry.RetryMiddleware': None,
    'middlewares.MyRetryMiddleware': 500,
}

rawDescription: Scrapy RetryMiddleWare send signal to spider


code:
def extract_date(s):
    return datetime.strptime(s.split("_")[0], "%Y%m%d%H%M%S")

def starts_with_date(s):
    try:
        extract_date(s)
        return True
    except Exception:
        return False

rawDescription: python deleting older files that match an unknown pattern (tricky)

description: Python deleting older files that match an unknown pattern (tricky)


code:
class TrackedFile(file):
    def __init__(self, filename, mode):
        self.size = 0
        super(TrackedFile, self).__init__(filename, mode)
    def write(self, s):
        self.size += len(s)
        super(TrackedFile, self).write(s)

rawDescription: How do I determine an open file's size in Python?

description: Determine an open file's size in Python


code:
import fileinput
import re
import sys

...
for line in fileinput.FileInput(myfile, inplace=1):
    matchObj = re.match( r'(.*)../Config/(.*).cfg(.*)', line, re.M|re.I)
    if matchObj:
      line = line.replace("Config","AnotherConfig")
    sys.stdout.write(line)

rawDescription: Find text with regular expression and replace in file


code:
ids = [2, 3]
query = "SELECT b, c, d FROM x WHERE a IN ({0}) AND b > 5 ORDER BY c".format(','.join('?' for i in ids))
query
conn.execute(query, ids).fetchall()

rawDescription: How to write this query?

description: Write this query


rawDescription: Lxml equivalent for BeautifulSoup find()


code:
def __init__(self, lst=None, intg=0):
     if lst is None:
         lst = []
     # ...

rawDescription: Python list should be empty on class instance initialisation, but it's not. Why?


code: a = [[1 - (i > 0 < j) for i in range(n)] for j in range(n)]

rawDescription: Filling in a symmetric 2D array

description: Filling in a symmetric 2D array


code: pd.concat([A, B], axis=1)

rawDescription: Reindexing dataframes and joining columns


rawDescription: to_excel on desktop regardless of the user

description: To_excel on desktop regardless of the user


code:
from openpyxl import Workbook
def writeToExcel(rows, filename):
    wb = Workbook()
    ws = wb.active
    for row in rows:
        ws.append(row)

    ws.save(filename)

import csv

rows = []
with open("readfile.csv", "r") as r:
    reader = csv.reader(r, lineterminator = "\n")

    for row in reader:
        if "SPTU" in row: #"SPTU" Has to be the entire value of the column. Please comment if you want to see if one of the columns CONTAINS "SPTU
            rows.append(row)

writeToExcel(rows, "insert_name_of_file_here.xlsx")

rawDescription: Copy Specific Rows and Columns from a .csv into .xlsx


code: price_1, price_2 = df['Price'].iloc[idx-1:idx+1]

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


code:
import lxml.html as LH

root = LH.fromstring('Telefon: +421 902 808 344')

for span in root.xpath('//span[@class="date" and contains(text(), "Telefon:")]'):
    print(span.text_content())
    # Telefon: +421 902 808 344

rawDescription: Beautifulsoup can't find tag by text

description: Beautifulsoup can't find tag by text


rawDescription: Optimal extraction of columns from numpy matrix


code:
LOGGER = logging.getLogger('your.module.file.name')
LOGGER.setLevel(_level)
LOGGER.info('foo')

rawDescription: Change level of python fileConfig logger


code: final_set = list(set(similar_assets) or set(exact_assets))

rawDescription: Iterate through two lists simultaneously and remove from one if exists in the other


code: [(char, [i for i,c in enumerate(a) if c==char]) for char in b]

rawDescription: Get the index of a list from another list in python


code: 'A string with   some    space,\ttabs and \n\n newlines'.split()

rawDescription: optimizing python code for performance

description: Optimizing python code for performance


rawDescription: Decimal approximation to expression (square root)


code:
data = { "query": [ { "code": "Region", "selection": { "filter": "vs:RegionRiket99", "values": [ "00" ] } }, { "code": "Hustyp", "selection": { "filter": "item", "values": [ "FLERBO", "SMÅHUS" ] } }, { "code": "Tid", "selection": { "filter": "item", "values": [ "2012" ] } } ], "response": { "format": "csv" } }
data = json.dumps(data)

rawDescription: JSON query in a post request from Python and save result as csv file


code:
node["key3b"]=0
pprint(t)

rawDescription: how to traverse this tree?

description: Traverse this tree


rawDescription: Dictionary that counts occurrences of its items


rawDescription: Unicode extraction

description: Unicode extraction


code: df.columns[(df < 0).any()].tolist()

rawDescription: Get list of column names for columns that contain negative values


code:
from tkinter import Tk,Button

class Application(Tk):

    def say_hi(self):
        print('Hello world?!')

    def close_app(self):
        self.destroy()

    def create_Widgets(self):
        self.quitButton = Button(self, width=12, text='Quit', bg='tan',
                    command=self.close_app)
        self.quitButton.grid(row=0, column=0, padx=8, pady=8)

        self.helloButton = Button(self, width=12, text='Hello',
                    command=self.say_hi)
        self.helloButton.grid(row=0, column=1, padx=8, pady=8)

    def __init__(self):
        Tk.__init__(self)
        self.title('Hello world!')
        self.create_Widgets()

app = Application()
app.mainloop()

rawDescription: Tkinter - RuntimeError: maximum recursion depth exceeded


rawDescription: Numpy 3D array transposed when indexed in single step vs two steps


code:
def obsfucate_letters(letters):
    for i in range(len(letters)):
        letters[i] = obfuscate_function(letters[i])

    return letters

rawDescription: Return original value, python

description: Return original value, python


code: sorted(dictionary.items(), key=lambda t: t[::-1])

rawDescription: Sorting dictionary keys by value, then those with the same value alphabetically


code:
def is_past(dt_string):
    return datetime.strptime(dt_string, '%b %d, %Y %I:%M %p') < datetime.now()

rawDescription: datetime comparison with string?

description: Datetime comparison with string


code:
class Word:
    def __init__(self,word):
        self.word = word
        self.occ = 1

rawDescription: Counting word occurances in txt file, returning dictionary and converting dict to list with the help of classes


code:
x = 1
y = 2
foo(x, y)

rawDescription: Do you change variables AFTER you run a function in python?


code:
# baaz.py
class Baaz: pass

rawDescription: python modify __metaclass__ for whole program

description: Python modify __metaclass__ for whole program


code: table = [bin(i).count('1') for i in xrange(1<<16)]

rawDescription: Numpy: check whether a bit is set to 1 or 0 in an array?


code:
from unittest import TestCase
from unittest.mock import patch
import mock_print_module

class MyTestCase(TestCase):
    @patch("mock_print_module.print",autospec=True)
    def test_something(self,mock_print):
        mock_print_module.print_something()
        mock_print.assert_called_with("print something")

rawDescription: Mocking print but allow using it in tests


rawDescription: How to copy unique keys and values from another dictionary in Python

description: Copy unique keys and values from another dictionary in Python


code:
def erase(string, positions):
    return "".join([y for x,y in enumerate(string) if x not in positions])

rawDescription: How to erase letters at any position in a string in python?

description: Erase letters at any position in a string in python


code:
class ExampleTestCase(unittest.TestCase):
    def test_example(self):
        """If this fails, it may not be your fault.
        Try hacking the integer cache. Evil laugh."""
        self.assertEqual(3, 4)

rawDescription: Get the docstring of the test methods from a result of unit testing


code:
def parse(self, response):
     ...
     item['category'] = next(category for category in settings.CATEGORIES if category in response.url)
     ...

rawDescription: Separate output file for every url given in start_urls list of spider in scrapy


rawDescription: Matplotlib wont join data points when the x axis isn't equally spaced


rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


code:
fig = plt.figure()
ax1 = fig.add_subplot(221)   #top left
ax2 = fig.add_subplot(222)   #top right
ax3 = fig.add_subplot(223)   #bottom left
ax4 = fig.add_subplot(224)   #bottom right

rawDescription: How to aggregate plots into figure with subplots

description: Aggregate plots into figure with subplots


code: [Counter({u"''": 1, u'``': 1, u'said': 1, u'took': 1, u'primary': 1, u'evidence': 1, u'produced': 1, u'investigation': 1, u'place': 1, u'election': 1, u'irregularities': 1, u'recent': 1}), Counter({u'the': 6, u'election': 2, u'presentments': 1, u'``': 1, u'said': 1, u'jury': 1, u'conducted': 1, u"''": 1, u'deserves': 1, u'charge': 1, u'over-all': 1, u'praise': 1, u'manner': 1, u'term-end': 1, u'thanks': 1})]

rawDescription: How to vectorize bigrams with the hashing-trick in scikit-learn?

description: Vectorize bigrams with the hashing-trick in scikit-learn


code:
class TimeLineList(generics.ListAPIView):
    serializer_class = TimeLineSerializer

    def get_queryset(self):
        return list(itertools.chain(Tweet.objects.all(), Article.objects.all()))

rawDescription: Return results from multiple models with Django REST Framework


code: self.fig = plt.figure()

rawDescription: Matplotlib animation inside your own PyQt4 GUI


code:
class Node(object):

  def __init__(self, payload):
    self.payload = payload
    self.left = self.right = 0

    # this concludes the "how to represent" asked in the question.  Once you
    # represent a BST tree like this, you can of course add a variety of
    # methods to modify it, "walk" over it, and so forth, such as:

  def insert(self, othernode):
    "Insert Node `othernode` under Node `self`."
    if self.payload <= othernode.payload:
      if self.left: self.left.insert(othernode)
      else: self.left = othernode
    else:
      if self.right: self.right.insert(othernode)
      else: self.right = othernode

  def inorderwalk(self):
    "Yield this Node and all under it in increasing-payload order."
    if self.left:
      for x in self.left.inorderwalk(): yield x
    yield self
    if self.right:
      for x in self.right.inorderwalk(): yield x

  def sillywalk(self):
    "Tiny, silly subset of `inorderwalk` functionality as requested."
    if self.left:
      self.left.sillywalk()
    print(self.payload)
    if self.right:
      self.right.sillywalk()

rawDescription: represent binary search trees in python

description: Represent binary search trees in python


code:
path
'.'

file_name
'test.txt'

rawDescription: most efficient way to substring path and file out of a string

description: Most efficient way to substring path and file out of a string


rawDescription: Elegant way of reducing list by averaging?


code:
def extract(s):
    return s.partition("(")[2].rpartition(")")[0]
print(extract('datediff(varchar(30),timestamp(3),timestamp(3))'))
print(extract('reverse(text)'))
print(extract('checkcluster(int,int,int,int,int)'))
print(extract('declaredown(int)'))

rawDescription: String splitting python

description: String splitting python


code:
def addcolumn(table, column):
    tr = transpose([table, column])
    return [(x if x else []) + (list(y) if y else []) for x, y in tr]

rawDescription: How can I append whole columns to a table (list of lists) in python?

description: Append whole columns to a table (list of lists) in python


code: object_dict = {x.id: x for x in object_list}

rawDescription: reduce python list of objects to dict object.id -> object

description: Reduce python list of objects to dict object.id -> object


code:
import json
import requests
import pprint
url = 'http://httpbin.org/post'
data = {"data" : "24.3"}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=data_json, headers=headers)
pprint.pprint(response.json())
pprint.pprint(response.json()['json'])

rawDescription: REST post using Python-Request

description: REST post using Python-Request


rawDescription: Best practice to reduce memory usage when splitting array


rawDescription: Assign value to an individual cell in a two dimensional python array


code:
class ExampleApp(QtGui.QMainWindow, masimo.Ui_MainWindow):
    def __init__(self, event, parent=None):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.dataWasReadEvent = event

        self.checkThreadTimer = QtCore.QTimer(self)
        self.checkThreadTimer.setInterval(500) #.5 seconds

        self.checkThreadTimer.timeout.connect(self.readListValues)

    def readListValues(self):
        if self.dataWasReadEvent.is_set():
            #Read your events from the list and update your fields

            self.dataWasReadEvent.clear() #Clear the event set flag so that nothing happens the next time the timer times out

rawDescription: Have textbox update every 5 seconds PyQt


code:
from threading import Timer

class Watchdog:
    def __init__(self, timeout, userHandler=None):  # timeout in seconds
        self.timeout = timeout
        self.handler = userHandler if userHandler is not None else self.defaultHandler
        self.timer = Timer(self.timeout, self.handler)

    def reset(self):
        self.timer.cancel()
        self.timer = Timer(self.timeout, self.handler)

    def stop(self):
        self.timer.cancel()

    def defaultHandler(self):
        raise self

rawDescription: How to implement a watchdog timer in Python?

description: Implement a watchdog timer in Python


code: foo in (8, 9)

rawDescription: In python, is 'foo == (8 or 9)' or 'foo == 8 or foo == 9' more correct?


rawDescription: numpy 2d array operation, keeping certain positions

description: Numpy 2d array operation, keeping certain positions


code:
#!/bin/python -B
from auth import *
print('Username:', USR)
print('Password:', PWD)

rawDescription: Python 3 Include Custom File with Variables


code: s = "#big and #big, #big. #small, #big-red, #big-red-car and #big"

rawDescription: python: Replace/substitute all whole-word match in a string

description: Python: Replace/substitute all whole-word match in a string


rawDescription: Python: Combine two lists, overwriting the final few lines of the first list


code:
from django import forms
from django.forms.fields import DEFAULT_DATE_INPUT_FORMATS
from django.db import models

class EuDateFormField(forms.DateField):
    def __init__(self, *args, **kwargs):
        kwargs.update({'input_formats': ("%d.%m.%Y",)+DEFAULT_DATE_INPUT_FORMATS})
        super(EuDateFormField, self).__init__(*args, **kwargs)

class EuDateField(models.DateField):
    def formfield(self, **kwargs):
        kwargs.update({'form_class': EuDateFormField})
        return super(EuDateField, self).formfield(**kwargs)

rawDescription: European date input in Django Admin

description: European date input in Django Admin


rawDescription: converting a list of integers into range in python

description: Converting a list of integers into range in python


code:
app = webapp2.WSGIApplication([('/', MainHandler), # or whatever it's called
                               (r'/static/(.+)', StaticFileHandler), # add this
                               # other routes
                              ])

rawDescription: cannot access webserver resources using virtualenv and webapp2

description: Cannot access webserver resources using virtualenv and webapp2


rawDescription: Set value for particular cell in pandas DataFrame


code:
import math

test=r"dir(math)"

eval(test)

rawDescription: Python: How to generate the code on the fly?


code: Button (root, text="+", command=lambda:add_line(N)).grid(row=N, column=2, padx=3)

rawDescription: Tkinter: How to dynamically change layout


code:
def super_munger(_lst):
    return [float_cast(item) for item in _lst]

rawDescription: Casting a list of strings into float if possible. - python


code:
import pickle
import sys
pickle.dumps(sys.modules[__name__])

rawDescription: multiprocess initializer and pickling

description: Multiprocess initializer and pickling


rawDescription: Applying complex function to several timeseries


rawDescription: Scraping web content using xpath won't work


rawDescription: How to scroll a tkinter canvas to an absolute position?

description: Scroll a tkinter canvas to an absolute position


code: {'Curving': 10, 'Keep Away': 5, 'Dodgeball': 15}

rawDescription: How can I add variables into a dictionary with a loop?

description: Add variables into a dictionary with a loop


code: open("student.txt", "a")

rawDescription: Register username and password

description: Register username and password


rawDescription: Calculate difference between two datetimes if both present in pandas DataFrame


rawDescription: Convert tree nodes to coordinates of endpoints of edges


rawDescription: find all files indirectory and sub-directories and provide the path from directory

description: Find all files indirectory and sub-directories and provide the path from directory


code: [list(j) for i in range(len(foobar)+1) for j in combinations(foobar,i) if minval <= sum(f.bar for f in j) <= maxval ]

rawDescription: Generating all possible subsets of a given QuerySet in Django


rawDescription: insert binary(16) with executemany

description: Insert binary(16) with executemany


code: start(Ktest)

rawDescription: Multiple arguments in parameter in def_name() and function's name as variable


code:
sample = SampleClass.from_string("10 permit ip")
sample.valid
sample.protocol
sample2 = SampleClass.from_string("foo bar")
sample2.valid

rawDescription: In Practice, Should all the objects of a class be made to have same number of attributes?


code: something = Something.get(id=1)

rawDescription: Django - Model field define unicode

description: Django - Model field define unicode


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

rawDescription: python: for short_list in long_list

description: Python: for short_list in long_list


code:
import requests
import json

message = "if i can\'t let it go out of my mind"

split_message = message.split()

def decrementList(words):
    for w in [words] + [words[:-x] for x in range(1,len(words))]:
        url = 'http://ws.spotify.com/search/1/track.json?q='
        request = requests.get(url + "%20".join(w))

        json_dict = json.loads(request.content)
        num_results = json_dict['info']['num_results']
        if num_results > 0:
            num_removed = len(words) - len(w)
            return num_removed, json_dict

num_words_removed, json_dict = decrementList(split_message)

rawDescription: How to decrement a list index in a loop

description: Decrement a list index in a loop


code:
contours, hierarchy = cv2.findContours(current, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    area = cv2.contourArea(contour)
    if area < 256:
        cv2.drawContours( current, [contour], 0, [0,0,0], -1 )

rawDescription: Image processing issues with blood vessels


code:
for h in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    for b in range(1, int(size) + 1):
        num = [h, b]

rawDescription: Bombs Away Battleships

description: Bombs Away Battleships


rawDescription: Determining the First Digit

description: Determining the First Digit


code: df

rawDescription: change column values in CSV using python

description: Change column values in CSV using python


code:
import re
m = re.compile(r'^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[A-Za-z\d]{10,}$')
m.match('43543fooR')
m.match('43543fooRy')
m.match('foobar7678A')
m.match('foobar76(')
m.match('fokhjf7645464644sresrtf')
m.match('fokhjf764546M4644sresrtf')

rawDescription: Match password with Python regex

description: Match password with Python regex


code:
def combos():
    letters = 'ABCDEF'
    numbers = '1234567890'
    argument_combos = stars_and_bars(numbers, letters)
    for args in argument_combos:
        yield from itertools.product(*args)

rawDescription: How can i create a permutation with a limit on specific characters efficently?

description: Create a permutation with a limit on specific characters efficently


code:
levels = [('Location', 'L_'),
          ('Station', 'S_'),
          ('Category', 'C_')]

rawDescription: pandas df into nested json

description: Pandas df into nested json


code: new_list = list(old_list)

rawDescription: How to clone or copy a list in Python?

description: Clone or copy a list in Python


code:
list_of_cards = [listCards.GetCard(i) for i in range(len(listCards))]
self.Add(*list_of_cards)

rawDescription: Two functions same name python

description: Two functions same name python


code:
class HoldingsAnalyser:
    # static method sample. Call it like this: "HoldingsAnalyser.run(..)"
    @staticmethod
    def run(holding_list):
        # do your model generation here or whatever you need
        return True # or whatever you need to return

    # instance method sample. Create an instance first and then call the method:
    # analyser = HoldingsAnalyser()
    # analyser.run(...)
    def run(self, holding_list):
        # do your model generation here or whatever you need
        return True # or whatever you need to return

rawDescription: Where does business logic in a model method go in Django Rest Framework?


code: foo.__globals__ = {}

rawDescription: Is func_globals mutable?

description: Is func_globals mutable


code: group(["foo", "bar", "blub", "blah", "bonk"], len)

rawDescription: Gather elements from list into lists of lists of equal elements?


code: distance = numpy.linalg.norm(atom1.coord - v)

rawDescription: Biopython PDB: calculate distance between an atom and a point


code: points[i]

rawDescription: Get point associated with Voronoi region (scipy.spatial.Voronoi)


code:
import time
import cherrypy
import threading
from cherrypy.process import plugins

UPDATE_INTERVAL = 0.5
REQUEST_DELAY = 0.1
UPDATE_DELAY = 0.1
THREAD_POOL_SIZE = 20

next_data = 1

def processData():
    """Backround task works for half hour three times a day,
        and when finishes it publish it in the engine buffer."""
    global next_data
    cherrypy.engine.publish("doChangeData", next_data)
    next_data += 1

class DataPublisher(object):

    def __init__(self):
        self._data = next_data
        self._data_readable = threading.Event()
        cherrypy.engine.subscribe('doChangeData', self.changeData)

    @property
    def data(self):
        if self._data_readable.is_set():
            return self._data
        else:
            self._data_readable.wait()
            return self.data

    @data.setter
    def data(self, value):
        self._data_readable.clear()
        time.sleep(UPDATE_DELAY)
        self._data = value
        self._data_readable.set()

    def changeData(self, newData):
        cherrypy.engine.log("Changing data, buffering should start!")
        self.data = newData
        cherrypy.engine.log("Continue serving buffered and new requests.")

    @cherrypy.expose
    def index(self):
        result = "I get " + str(self.data)
        cherrypy.engine.log(result)
        time.sleep(REQUEST_DELAY)
        return result

if __name__ == '__main__':
    conf = {
        'global': {
            'server.thread_pool': THREAD_POOL_SIZE,
            'server.socket_host': '127.0.0.1',
            'server.socket_port': 8080,
        }
    }
    cherrypy.config.update(conf)
    plugins.BackgroundTask(UPDATE_INTERVAL, processData).start()
    cherrypy.quickstart(DataPublisher())

rawDescription: CherryPy: how to stop and buffer incoming request while data is updated


code:
# file 1: test_me.py
import unittest

class TestMe(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

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

rawDescription: Run unittests from a different file

description: Run unittests from a different file


code:
files = []
for (dirpath, dirnames, filenames) in walk(path):
    files.extend(filenames)
    files = list(map(lambda x: x.strip(".txt"), files))
    print(files)

rawDescription: Why is python not stripping?

description: Why is python not stripping


code: simplified_list = [element[0] for element in my_array_of_arrays]

rawDescription: I have single-element arrays. How do I change them into the elements themselves?


code: 'This is a first guid: c5842b59-795d-452f-b0cd-ba5c7369dde7 and this is a second one: 8c20f372-8044-4b82-bbbd-0e667fb14ed3'

rawDescription: Call GUID function more than once in print formatting in python


code:
import numpy as np

indices = np.random.randint(0, 100, (1000, 1000))
weights = np.random.rand(1000, 1000)

def orig(indices, weights):
    x, y = [], []
    row_matrix = np.fromfunction(lambda i, j: i, weights.shape)
    col_matrix = np.fromfunction(lambda i, j: j, weights.shape)
    num_regions = indices.max()+1
    for ind in range(num_regions):
        mask = (indices == ind)
        xSum = sum(weights[mask] * row_matrix[mask])
        ySum = sum(weights[mask] * col_matrix[mask])
        dSum = sum(weights[mask])

        x.append(xSum / dSum)
        y.append(ySum / dSum)
    return x, y

def alt(indices, weights):
    indices = indices.ravel()
    h, w = weights.shape
    row_matrix, col_matrix = np.ogrid[:h, :w]
    dSum = np.bincount(indices, weights=weights.ravel())
    xSum = np.bincount(indices, weights=(weights*row_matrix).ravel())
    ySum = np.bincount(indices, weights=(weights*col_matrix).ravel())
    return xSum/dSum, ySum/dSum

expected_x, expected_y = orig(indices, weights)
result_x, result_y = alt(indices, weights)

# check that the result is the same
assert np.allclose(expected_x, result_x)
assert np.allclose(expected_y, result_y)

rawDescription: Efficient region weighted sum using numpy


rawDescription: Python: Picking a certain element from an array


code:
def index():
    take = 10

    if not request.vars.page:
        page = 1
    else:
       page = int(request.vars.page)
    skip = 0;
    if (page == 1):skip = 0
    else:skip = ((page - 1) * take)

    total  = db(db.table_name.id>0).count()
    paging = pagination(total ,  page ,  take ,  1 ,'default' , 'index' , '')
    data = db(db.table_name.id>0).select(db.table_name.field1, db.table_name.field2 , limitby=(skip,take*page))
    return dict(data = data , paging=paging , b_url = base_url())

rawDescription: how to make custom paging in web2py depend on bootstrap?

description: Make custom paging in web2py depend on bootstrap


code:
A[np.arange(A.shape[0]), y]
A[np.arange(A.shape[0]), y] = -99
A

rawDescription: How to extract elements from a matrix using a vector of indices using numpy?

description: Extract elements from a matrix using a vector of indices using numpy


code:
from PIL import Image, ImageDraw
im = Image.new('RGBA', (400, 400), (0, 255, 0, 0))
draw = ImageDraw.Draw(im)
draw.line((100,200, 150,300), fill=128)
im.show()

rawDescription: drawing a line on an image with PIL

description: Drawing a line on an image with PIL


rawDescription: Extracting elements inside and between brackets


code:
def send(data):
    context = zmq.Context()
    socket = context.socket(zmq.PUB)
    socket.connect("tcp://localhost:5000")
    while data:
        time.sleep(1)
        socket.send('Sender: %i' % data)
        data -= 1
    socket.close()

rawDescription: communication with 0mq

description: Communication with 0mq


code: query = YourModel.objects.filter(last_updated__gte = last_api_call_time)

rawDescription: Implementing autocomplete in android based on django model


rawDescription: selecting records in a python structure based on a related structure

description: Selecting records in a python structure based on a related structure


code:
from django.utils.feedgenerator import Rss201rev2Feed
class CustomFeedGenerator(Rss201rev2Feed):
    def add_item_elements(self, handler, item):
        super(CustomFeedGenerator, self).add_item_elements(handler, item)
        handler.addQuickElement(u"featured", item['featured'])

rawDescription: Django RSS add attribute into item

description: Django RSS add attribute into item


code:
class Game(models.Model):

    def __init__(self):
        self.moves = Moves()

class Moves():

    def __init__(self):
        self.moves = []

rawDescription: (For all instances of) Django model field 'moves', it maps to the same Move class instance


code:
from Tkinter import *

gui = Tk()

#create variables to store check state
checked1 = IntVar()
checked2 = IntVar()
#create values for the two boxes
cb1 = 5
cb2 = 10

#create a callback for our button
def callback():
    print(checked1.get()*cb1+checked2.get()*cb2)

c1 = Checkbutton(gui, text='b1', variable=checked1)
c2 = Checkbutton(gui, text='b2', variable=checked2)
b1 = Button(gui, text="ADD", command=callback)

c1.pack()
c2.pack()
b1.pack()

gui.mainloop()

rawDescription: How to create a GUI to add two numbers from different two checkboxes?

description: Create a GUI to add two numbers from different two checkboxes


code:
from django.forms import ModelForm
from myapp.models import Article
class ArticleForm(ModelForm):
    class Meta:
        model = Article
form = ArticleForm()

rawDescription: Display django admin form only

description: Display django admin form only


code:
def findLine(lines, text):
    for i, line in enumerate(lines):
        if text in line:
            return i
    return None

with open("./log.txt") as f:
    lines = f.readlines()

    startIndex = findLine(lines, "Cell's that didn't call in")
    endIndex   = findLine(lines, "Cell's that didn't clear in the past 2 days")

    extractedLines = [line for i,line in enumerate(f) if i>startIndex and i<endIndex]

rawDescription: How to return all rows between 2 sections in a string in python 3.X?

description: Return all rows between 2 sections in a string in python 3.X


rawDescription: Summarize a list of dictionaries based on common key values


code:
niter = 10000

prog = ProgressReporter(niter)

for i in range(niter):
    doSomeWork()
    prog.update()
prog.finish()

rawDescription: How to add progressbar in python

description: Add progressbar in python


code:
sums = {}
for entry in myList:
    key = entry[0], entry[-1]
    if key not in sums:
        sums[key] = entry[:]
        sums[key][1] = set([entry[1]])
    else:
        sums[key][3:-1] = [s + elem for s, elem in zip(sums[key][3:-1], entry[3:-1])]
        sums[key][1].add(entry[1])

newList = [e[:1] + [':'.join(e[1])] + e[2:] for e in sums.values()]

rawDescription: Python 2.7 List of Lists Manipulation

description: Python 2.7 List of Lists Manipulation


rawDescription: Finding adjacent cells in a wraparound matrix


code:
current_events = Event.objects.filter(from_date__lte=now, to_date__gte=now)
postponed_events = Event.objects.exclude(from_date__lte=now, to_date__gte=now).filter(logs__from_date__lte=now, logs__to_date__gte=now)
all_events = current_events + postponed_events

rawDescription: How to get events which can be postponed for a given date from a table with change log and a table for event in Django?

description: Get events which can be postponed for a given date from a table with change log and a table for event in Django


code:
import pprint

modules = [
    {'moduletitle': 'Parent Module 1', 'position': '1'},
    {'moduletitle': 'Parent Module 2', 'position': '2'},
    {'moduletitle': 'Parent Module 3', 'position': '3'},
]

submodules = [
    {'moduletitle': 'sub module 11', 'position': '1'},
    {'moduletitle': 'sub module 22', 'position': '2'},
    {'moduletitle': 'sub module 1', 'position': '1'},
    {'moduletitle': 'sub module 2', 'position': '3'},
]

subtotal = [2, 2, 0]

subcontent = [
    {'content': 'Dj.docx', 'position': '10', 'contenttype': 'Pdf/Doc', 'coursemoduleid': 55341, 'contenttitle': 'test content'},
]

contenttotal = [0, 0, 1, 0]

###

#first, nest the "subcontent" items in the "submodule" items
subcontent_iter = iter(subcontent)
for sub, num_content_items in zip(submodules, contenttotal):
    tmp = []
    for i in range(num_content_items):
        tmp.append(next(subcontent_iter))
    sub['content'] = tmp

#then, nest the "submodule" items under the "module" items
submodule_iter = iter(submodules)
for (module, num_submodules) in zip(modules, subtotal):
    tmp = []
    for i in range(num_submodules):
        tmp.append(next(submodule_iter))
    module['submodules'] = tmp

pprint.pprint(modules)

rawDescription: Python code not working similar in Jinja Template


code:
numberList  = list(string_dict.values())
numz = []
placeholder = 0

numz = list(map(int, numberList))

placeholder = sum(numz)
print (placeholder)

rawDescription: Calculating the value of integers in list


rawDescription: how to iterate through consecutive lines of a csv file

description: Iterate through consecutive lines of a csv file


code:
from spyne.util.wsgi_wrapper import WsgiMounter

app1 = Application([SomeService], tns=tns,
        in_protocol=Soap11(), out_protocol=Soap11())
app2 = Application([SomeOtherService], tns=tns,
        in_protocol=Soap11(), out_protocol=Soap11())
wsgi_app = WsgiMounter({
    'app1': app1,
    'app2': app2,
})

rawDescription: Deploy multiple web services, i.e. multiple wsdl files, in python


rawDescription: Interactive matplotlib under windows

description: Interactive matplotlib under windows


code:
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame([[1,2,3],[7,0,3],[1,2,2]],columns=['col1','col2','col3'])

df.plot()

plt.savefig('myfile.pdf')

rawDescription: how to export to pdf a graph based on a pandas dataframe?

description: Export to pdf a graph based on a pandas dataframe


code: crc32 = '%08x' % binascii.crc32(open(filename, 'rb').read())

rawDescription: Different values for linux crc32 vs python binascii


code:
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')
def convert(name):
    s1 = first_cap_re.sub(r'\1_\2', name)
    return all_cap_re.sub(r'\1_\2', s1).lower()

rawDescription: Elegant Python function to convert CamelCase to snake_case?


code:
# main.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
    return 'Hi'

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

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

rawDescription: Python response to JavaScript

description: Python response to JavaScript


code:
shared_username = ['[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>, <User: awesome>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]', '[<User: mr--adhikari>]']
[[y.lstrip('[<User: ').rstrip('>]') for y in x.split(', ')] for x in shared_username]

rawDescription: How to convert this list in a given format?

description: Convert this list in a given format


code:
ram
sita
geeta

rawDescription: Print length of strings from each line of stdin in python


code:
mycount('a*b*c','abc')
mycount('a*k','akka')
mycount('b*o','bboo')
mycount('b*o','bb123oo')
mycount('b*o','ffbfbfffofoff')

rawDescription: Count overlapping regex matches once again


code: print(employee)

rawDescription: How do I take the users input and if it equals 1 it would be day and a 2 would be night?

description: Take the users input and if it equals 1 it would be day and a 2 would be night


code:
def distribute_overrun(groups,overrun,part):
    i = 0
    while overrun < 0:
      group = list(groups[i])
      group[part] -= 1
      groups[i] = tuple(group)
      overrun += 1
      i += 1

rawDescription: Maintaining a ratio when splitting up data in python function


code:
np.sum(a)
np.sum(6.0)

rawDescription: Sum up over np.array or np.float

description: Sum up over np.array or np.float


code:
words_to_insert = ['foo', 'foobar']
queries_expecting_true = words_to_insert
queries_expecting_false = "fo foe foob food foobare".split()

rawDescription: How can I improve my Trie implementation in terms of initialization?

description: Improve my Trie implementation in terms of initialization


code: vec += centroid

rawDescription: plotting the eigenvector of covariance matrix using matplotlib and np.linalg

description: Plotting the eigenvector of covariance matrix using matplotlib and np.linalg


rawDescription: Search string with re module in html page


code:
class A(models.Model):
   def get_B(self):
       try:
          return self.b
       except:
          return None

class B(models.Model):
   ref_a = models.OneToOneField(related_name='ref_b', null=True)

rawDescription: Check if a OneToOne relation exists in Django


code:
class someclass:
    @staticmethod
    @cachedAttributes(doctyperegex = re.compile(r'<!DOCTYPE.*?>\s*', re.S|re.U),
              htmlregex = re.compile(r'<html.*?>\s*', re.S|re.U),
              metaregex = re.compile(r'<meta(.*?)>', re.S|re.U))
    def method(*args):
        # compile regex operation
        # compile regex operation
        # compile regex operation

        # compute and return something
        ...
        pass

rawDescription: Python write decorator for static method


rawDescription: Divide one column in array by another numpy


code:
if parameter in f:
    newWord = input('Second parameter to replace with: ')
    newString = f.replace(parameter, newWord)
else:
    print('%s not found.' % parameter)

rawDescription: How to exchange parameter in list in file by new input

description: Exchange parameter in list in file by new input


rawDescription: Perform Numpy operation on matrix of user-defined type items


rawDescription: pulling key by place from dictionary using pandas

description: Pulling key by place from dictionary using pandas


rawDescription: read a table according to a certain number of characters

description: Read a table according to a certain number of characters


code:
('Difensori dei diritti umani', 'Human rights defenders')
('libertà di espressione', 'freedom of expression')
('Difensori dei diritti umani', 'freedom of expression')
('libertà di espressione', 'Human rights defenders')

rawDescription: Creation of bigrams in python

description: Creation of bigrams in python


code:
class MutableDict(Mutable, dict):

    @classmethod
    def coerce(cls, key, value):
        if not isinstance(value, MutableDict):
            if isinstance(value, dict):
                return MutableDict(value)
            return Mutable.coerce(key, value)
        else:
            return value

    def __delitem(self, key):
        dict.__delitem__(self, key)
        self.changed()

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        self.changed()

    def __getstate__(self):
        return dict(self)

    def __setstate__(self, state):
        self.update(self)

rawDescription: How to implement mutable PickleTypes that automatically update on change

description: Implement mutable PickleTypes that automatically update on change


code:
BLOCK_SIZE = 500
while not_done:
   dbCursor.begin()
   for junk in irange(BLOCK_SIZE):
       dbCursor.execute("EXECUTE cms_lib_insert(...)")
       cms_lib_id = dbCursor.fetchone()[0]     # you're using this below.
       dbCursor.executemany("EXECUTE metadata_insert(...)")
       dbCursor.executemany("EXECUTE library_insert(...)")
   dbCursor.commit()

rawDescription: Python with postgres using named variables and bulk inserts


code:
def sfmat(data):
    n = len(data)
    out = np.empty((n, n-1))
    out[0, :] = data[:n-1]
    for i in xrange(1, n):
        out[i, :n-i] = data[i:]
        out[i, n-i:] = 0
    return out

rawDescription: Efficient Cython for large matrix creation/manipulation


code: alter_sql = 'ALTER TABLE `%s` ADD COLUMN `%s` TEXT'

rawDescription: Escaping MySQL reserved words with Python dbapi


code:
def near_callback(space, arbiter, *args, **kwargs):
    body_i = arbiter.shapes[0].body
    body_j = arbiter.shapes[1].body

    # calculate the forces force_i and force_j with your formula
    ...

    body_i.apply_force(force_i)
    body_j.apply_force(force_j)

rawDescription: Simulating a simple physics related scenario


code:
my_dict= {"0" : {"1","2","3"},"1":{"2"},"2":{"3"}}
from collections import defaultdict
from collections import defaultdict
result = defaultdict(set)
for key,value in my_dict.items():
    result[key].update(value)
    for elem in value:
        result[elem].add(key)
pprint.pprint(result)

rawDescription: Match keys to values in dictionary in python


code:
vals = df.values.reshape(-1)
new_index = pd.date_range(start=df.index[0], periods=24*len(df), freq='H')
pd.Series(vals, new_index)

rawDescription: too long dataframe apply row functions

description: Too long dataframe apply row functions


code:
for line in BigList:
   savefile.write(line + "\r\n")

rawDescription: python: save list to a file with performance in mind

description: Python: save list to a file with performance in mind


code:
#!/usr/bin/env python3

import time
import datetime as dt

last_time = dt.datetime.today().timestamp()
diffs = []
while(True):
    time.sleep(0.1)

    # Add new time diff to list
    new_time = dt.datetime.today().timestamp()
    diffs.append(new_time - last_time)
    last_time = new_time

    # Clip the list
    if len(diffs) > 10:
        diffs = diffs[-10:]

    print(len(diffs) / sum(diffs))

rawDescription: How to print iterations per second?

description: Print iterations per second


code:
s = 'abc\u3020def'
print(s)
s.encode(encoding='gbk')
s.encode(encoding='gbk', errors='replace')
s.encode(encoding='gbk', errors='replace').decode()
print(s.encode(encoding='gbk', errors='replace').decode())

rawDescription: How to print unsupported unicode characters on Windows cmd as e.g. "?" instead of raising exception?

description: Print unsupported unicode characters on Windows cmd as e.g. "?" instead of raising exception


code:
import chardet

for msg in src:
    msg=unicode(msg, chardet.detect(msg)['encoding']).encode('ascii', 'ignore')
    dest.add(msg)

rawDescription: Python mailbox encoding errors

description: Python mailbox encoding errors


code:
third_level = re.compile('\n(\d+\.\d+\.\d+[^\n]*)')
pages = re.compile(r'[\n\f](\d+)\n.*?(?=[\n\f](\d+)\n)', flags = re.DOTALL | re.MULTILINE)

third_levels = list()

for page in pages.finditer(s, content_end):
    page_no = page.group(1)
    for item in third_level.finditer(page.group()):
        third_levels.append('{}\t{}'.format(item.group(1), page_no))

rawDescription: Extract section names and starting pages from a text file


rawDescription: Replace space character between two numbers


code:
data = {
'ComponentA': {'key1':'value1', 'key2':'value2', 'key3':'value3'},
'ComponentB': {'key4':'value4'},
'ComponentC': {'key5':'value5', 'key6':'value6'},
}

rawDescription: How to associate elements in a set with multiple dict entries

description: Associate elements in a set with multiple dict entries


code:
talker.py
import time
import sys

DELAY = int(sys.argv[1])
ii = 1
while 1:
    sys.stdout.write("Talking every %i seconds, blabbed %i times\n" % (DELAY, ii))
    sys.stdout.flush()
    ii += 1
    time.sleep(DELAY)

rawDescription: How to constantly send STDOUT to my python TCP server?

description: Constantly send STDOUT to my python TCP server


rawDescription: How would I extract this with Python regular expressions?


rawDescription: Caesar cypher in Python

description: Caesar cypher in Python


code:
import foobar

foobar.part1()
py_part2()

rawDescription: how to share a lib between process and called script subprocess using SWIG?

description: Share a lib between process and called script subprocess using SWIG


code:
int_or_none = option(int)
int_or_none(None)
int_or_none(12)

rawDescription: Python idiom for applying a function only when value is not None


code: lst_of_arrays = [ np.zeros(1) for _ in range(N) ]

rawDescription: numpy multiple ndarray creation at once

description: Numpy multiple ndarray creation at once


code:
ADMIN = 1
AUTHORIZATION_STATUS = 11
BLPSERVICE_STATUS = 9
PARTIAL_RESPONSE = 6
PUBLISHING_DATA = 13
REQUEST_STATUS = 4
RESOLUTION_STATUS = 12
RESPONSE = 5
SESSION_STATUS = 2
SUBSCRIPTION_DATA = 8
SUBSCRIPTION_STATUS = 3
TIMEOUT = 10
TOKEN_STATUS = 15
TOPIC_STATUS = 14
UNKNOWN = -1
fields = ['BID']
tickers = ['AUD Curncy']
interval = '' #'interval=5.0'

rawDescription: Asynchronous data through Bloomberg's new data API (COM v3) with Python?


rawDescription: "Balancing" a list of symbols

description: "Balancing" a list of symbols


code:
import numpy as np
from scipy.sparse import coo_matrix

xs = np.array([1, 2, 3, 3, 2])
ys = np.array([2, 3, 1, 1, 1])
A = coo_matrix((np.ones((5,)), (xs, ys)))

rawDescription: Is Scipy's sign() not guaranteed working?


code:
import numpy as np
images_and_labels_array = np.array([[...], ...],  # [[1,12,34,24,53,...,102],
                                                  #  [12,112,43,24,52,...,98],
                                                  #  ...]
                                   dtype=np.uint8)

images_and_labels_array.tofile("/tmp/images.bin")

rawDescription: Attach a queue to a numpy array in tensorflow for data fetch instead of files?


code: dict((s, v) for (o, s), v in mydict.iteritems() if o is co1)

rawDescription: Compact Way To Shear Dictionary With Tuple For Key in Python


rawDescription: Python: How to find greater than N rows with non zero cells in greater than M common columns


code:
import pytz
def to_utc(dt):
    try:
        return dt.astimezone(pytz.utc)
    except ValueError:
        return pytz.utc.localize(dt)

rawDescription: Convert a list of sample dates into GMT

description: Convert a list of sample dates into GMT


code:
import Tkinter as tk

class Window():

    def __init__(self, root):

        self.frame = tk.Frame(root)
        self.frame.pack()

        self.i = 0
        self.labelVar = tk.StringVar()
        self.labelVar.set("This is the first text: %d" %self.i)

        self.label = tk.Label(self.frame, text = self.labelVar.get(), textvariable = self.labelVar)
        self.label.pack(side = tk.LEFT)

        self.button = tk.Button(self.frame, text = "Update", command = self.updateLabel)
        self.button.pack(side = tk.RIGHT)

    def updateLabel(self):

        self.i += 1
        self.labelVar.set("This is new text: %d" %self.i)

root = tk.Tk()
window = Window(root)
root.mainloop()

rawDescription: Label keeps on appearing

description: Label keeps on appearing


code:
e1 = Employee(name="Foo", hired_by=Shop.objects.get(name="First Shop"))
e2 = Employee(name="Bar", hired_by=Shop.objects.get(name="First Shop"))
e3 = Employee(name="John", hired_by=Shop.objects.get(name="Second Shop"))
e4 = Employee(name="Carl", hired_by=Shop.objects.get(name="Second Shop"))
e1.save()
e2.save()
e3.save()
e4.save()
Employee.objects.all()

rawDescription: How do I create this object with the models I have set up?

description: Create this object with the models I have set up


rawDescription: Shallow copy: why is list changing but not a string?


code: result.append(big_nums[i] + str( text_one))

rawDescription: why is my code not writing to a new text file

description: Why is my code not writing to a new text file


code:
def run_test(data, method=choose_best1):
    bests = {}
    for key, dict_list in data.items():
        best = method(dict_list)
        bests[key] = best
    return bests

rawDescription: Max value in Dictionary of List of Dictionaries in Python


code: A = [x for x in A if len(x[1]) == 2]

rawDescription: How to remove a list within list based on len in python?

description: Remove a list within list based on len in python


code:
import csv
from operator import itemgetter

with open(outputfile, 'wb') as outf:
    writer = None  # will be set to a csv.DictWriter later

    for key, item in sorted(data.items(), key=itemgetter(0)):
        row = {}
        nested_name, nested_items = '', {}
        for k, v in item.items():
            if not isinstance(v, dict):
                row[k] = v
            else:
                assert not nested_items, 'Only one nested structure is supported'
                nested_name, nested_items = k, v

        if writer is None:
            # build fields for each first key of each nested item first
            fields = sorted(row)

            # sorted keys of first item in key sorted order
            nested_keys = sorted(sorted(nested_items.items(), key=itemgetter(0))[0][1])
            fields.extend('__'.join((nested_name, k)) for k in nested_keys)

            writer = csv.DictWriter(outf, fields)
            writer.writeheader()

        for nkey, nitem in sorted(nested_items.items(), key=itemgetter(0)):
            row.update(('__'.join((nested_name, k)), v) for k, v in nitem.items())
            writer.writerow(row)

rawDescription: Parsing nested JSON and writing it to CSV


code:
p = ArgumentParser()
p.add_argument("-m", "--mac", action="store_const", const="mac_address")
p.add_argument("addresses", nargs="*")

args = p.parse_args()

if args.mac is not None and len(args.addresses) > 1:
    p.error("Only one argument allowed in conjunction with --mac")

rawDescription: N sys.argv[1:] args with optional args XOR 1 argparse arg, with 1 optional arg?


code:
import requests
from time import time, sleep

url = 'http://www.worldofdraft.com/ajax/user.php'
gameurl = 'http://www.worldofdraft.com/ajax/entry.php'
GPL = ['5332', '5594', '5444', '5488', '5547', '5371', '5383', '5061', '5456', '5451', '5550']
BPL = ['5388', '5596', '5481', '5587', '5585', '5514', '5099', '5249', '5566', '5501', '5357']
GID = id
UDID = '0'
ACT = 'draft'
ACT2 = 'save_draft'
SIGN = '18852c5f48a94bf3ee58057ff5c016af'
USERNAME1 = 'email@randommail.com'
USERNAME2 = 'email2@randommail.com'
PASSWORD = 'supersecretpass'
LOGIN = 'login'

last_request = time()
def get(c, url):
    global last_request
    if time()-last_request < 2:
        sleep(2-(time()-last_request))
    ret = c.get(url)
    last_request = time()
    return ret

def post(c, url, data):
    global last_request
    if time()-last_request < 2:
        sleep(2-(time()-last_request))
    ret = c.post(url, data = login_data)
    last_request = time()
    return ret

def vissok(id):
    global url, gameurl, GPL, GID, UDID, ACT, ACT2, SIGN, USERNAME1, PASSWORD, LOGIN
    with requests.Session() as c:
        get(c, url)
        login_data = dict(action = LOGIN, login = USERNAME1, password = PASSWORD)
        post(c, url, data = login_data)

        get(c, gameurl)
        for index in range(0, len(GPL)-1):
            game_data = dict(player_id = GPL[index], action = ACT, id = GID)
            post(c, gameurl, data = game_data)

        game_data_save = dict( action = ACT2, id = GID, user_draft_id = UDID, sign = SIGN)
        post(c, gameurl, data = game_data_save)

def simplebot(id):
    global url, gameurl, BPL, GID, UDID, ACT, ACT2, SIGN, USERNAME2, PASSWORD, LOGIN
    with requests.Session() as c:

        get(c, url)
        login_data = dict(action = LOGIN, login = USERNAME2, password = PASSWORD)
        post(c, url, data = login_data)

        get(c, gameurl)
        for index in range(0, len(BPL)-1):
            game_data = dict(player_id = BPL[index], action = ACT, id = GID)
            post(c, gameurl, data = game_data)

        game_data_save = dict( action = ACT2, id = GID, user_draft_id = UDID, sign = SIGN)
        post(c, gameurl, data = game_data_save)

i = 184
while i < 189:
    simplebot(i)
    vissok(i)
    i += 1
    sleep(30) # Not sure why you want to wait 30 seconds here, but i kept it.

rawDescription: Connection aborted requests error

description: Connection aborted requests error


rawDescription: Python 2.7 - Adding unicode strings to list


rawDescription: Very specific sorting in Python

description: Very specific sorting in Python


code:
class PermissionList(...):
    ...
    @classmethod
    def is_on_whitelist(email):
        return PermissionList.objects.filter(email=email, permission=True).count() > 0

    @classmethod
    def is_on_blacklist(email):
        return PermissionList.objects.filter(email=email, permission=False).count() > 0

    @classmethod
    def has_permission(email):
        if PermissionList.is_on_whitelist(email):
            return True
        if PermissionList.is_on_blacklist(email):
            return False
        return None

rawDescription: email whitelist/blacklist in python/django

description: Email whitelist/blacklist in python/django


code:
class Player(object):
    # has self.hand

    def __str__(self):
        return "Player's Cards %s (Total %d)" % (
            ",".join(str(card) for card in self.hand),
                     self.__sum_of_hand()
        )

rawDescription: Python - __str__ returning elements of a list


code:
def __matrix_fib__(n):
    if n == 1:
        return [0, 1]
    else:
        f = __matrix_fib__(n / 2)
        c = f[0] * f[0] + f[1] * f[1]
        d = f[1] * (f[1] + 2 * f[0])
        if n % 2 == 0:
            return [c, d]
        else:
            return [d, c + d]

def fib(n):
    assert (n >= 0)
    if n == 0:
        return n
    else:
        return __matrix_fib__(n)[1]

rawDescription: Dynamically changing the recursion limit for a fibonnacci program python


rawDescription: how to deal in a pythonic way with list of arrays or single array

description: Deal in a pythonic way with list of arrays or single array


code:
args = parse_args()
args.cmd(args)

rawDescription: Call function based on argparse

description: Call function based on argparse


code: syn1 = 2*np.random.random((len(train_sample), 10)) - 1

rawDescription: Neuro Network on MNIST--Result is not expected


code:
sample = [dict(event=d.pop("event"), id=min(d), name=min(d.values())) for d in sample]
pd.DataFrame(sample)

rawDescription: Convert a list of dictionaries with varying keys to a dataframe


code:
def add_items(tree, items):
    if items[0] not in tree:
        branch = {}
        tree[items[0]] = branch
    else:
        branch = tree[items[0]]
    if len(items) > 1:
        add_items(branch, items[1:])

tree = {}
with open('commands.txt') as f:
    for line in f:
        items = line.strip().split()
        add_items(tree, items)

from pprint import pprint
pprint(tree)

rawDescription: Text file with repeated elements to JSON


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

rawDescription: Removing a char from String in Python

description: Removing a char from String in Python


code:
class Test():

    static_attr1 = 2

    def __init__(self):
        pass

    @staticmethod
    def static_method(v):
        Test.static_attr1 = v

rawDescription: Java-like static class & method in Python


rawDescription: copy.copy vs copy.deepcopy performance on tuples

description: Copy.copy vs copy.deepcopy performance on tuples