code: grad = [sp.diff(y, i) for i in vm]

rawDescription: Set derivatives of a function to 0 in Python


rawDescription: Celerybeat schedule executing task multiple times?


rawDescription: Trying to find majority element in a list


code:
import cloudstorage
from google.appengine.api import app_identity

bucketName = app_identity.get_default_gcs_bucket_name()

class MainPage(webapp2.RequestHandler):

    def get(self):

        fileName = "/" + bucketName + "/somedir/somefile.txt"

        try:
            with cloudstorage.open(fileName, "r") as gcsFile:
                tempStorage = gcsFile.read()
                tempStorage += "\n"
        except:
            tempStorage = ""

        with cloudstorage.open(fileName, "w") as gcsFile:
            gcsFile.write(tempStorage + "appended text")

        with cloudstorage.open(fileName, "r") as gcsFile:
            output=  gcsFile.read()
        self.response.out.write(output)

rawDescription: Writing to text file with python running on GAE


code:
from igraph import Graph
g = Graph.Lattice([10, 10], circular=False)
g.get_all_shortest_paths(0)

rawDescription: Path between two nodes

description: Path between two nodes


code:
B = scipy.ndimage.laplace(A)
B = np.abs(B, B) # Preform abs in-place
B /= B  # This will produce a divide by zero warning that you can safely ignore
B *= A

rawDescription: Scipy label erosion

description: Scipy label erosion


code:
class Foo(object):
    handlers = []
    def collect_handler(handlers):
        def wrapper(func):
            handlers.append(func)
            return func
        return wrapper
    collect_handler = collect_handler(handlers)

    def __init__(self):
        pass

    def run(self):
        pass

    @collect_handler
    def foo(self):
        pass

    @collect_handler
    def bar(self):
        pass

foo = Foo()
print(foo.handlers)

rawDescription: Use decorator to collect instance methods?


rawDescription: Combining multiple 1D arrays returned from a function into a 2D array python


code:
def SetupGUI(self):
    with self.container(name='root'):
        with self.container():
            for i in range(0,8):
                self.AddWidget(name='button%i' % i, type='button')
        with self.container():
            for i in range(0,8):
                self.AddWidget(name='slider%i' % i, type='slider')

rawDescription: What's a good way to express hierarchical grouping of widgets in Python?


rawDescription: How to sort a complex nested dictionary to a nested list

description: Sort a complex nested dictionary to a nested list


code:
def arrange(nodes: list, contigious: set) -> list:
    # Make sure that contigious is a set
    contigious = set(contigious)

    # Return if all nodes are in contigious or nodes are empty
    if len(contigious.intersection(nodes)) == len(nodes) or not len(nodes):
        return nodes

    if nodes[0] in contigious and nodes[-1] in contigious:
        # The contigious part is split and present on the beggining and the
        # end of the nodes list
        cut = next(i for i, x in enumerate(nodes) if x not in contigious)
        # I move the nodes from the beggining to the end
        return nodes[cut:] + nodes[:cut]
    else:
        # The contigious part is somewhere in the middle of the nodes list
        # I need to find the end of contigious sequence
        cut = next(i for i, x in enumerate(reversed(nodes)) if x in contigious)
        cut = len(nodes) - cut
        return nodes[cut:] + nodes[:cut]

rawDescription: arrange items respecting order

description: Arrange items respecting order


rawDescription: Parsing XML with xml.etree.ElementTree

description: Parsing XML with xml.etree.ElementTree


rawDescription: pandas split string into columns

description: Pandas split string into columns


code:
t = pandas.tslib.Timestamp.now()
t
t.to_datetime()
t.day
t.month
t.year

rawDescription: Extracting just Month and Year from Pandas Datetime column (Python)


code:
IMAGE_DIR = '/path/to/images'
SOUND_DIR = '/path/to/sounds'

rawDescription: wxPython Button to load multiple images

description: WxPython Button to load multiple images


code:
from werkzeug.utils import import_string

def create_app():
    app = Flask(__name__)
    # ...
    for name in ('users', 'posts'):
        bp = import_string('myapp.{0}.views:{1}'.format(name, name))
        app.register_blueprint(bp, prefix='/{0}'.format(name))
    # ...

rawDescription: Can I keep all Flask blueprints in one file?

description: Keep all Flask blueprints in one file


code:
def getVarFromFile(filename):
  import imp
  with open(filename) as f:
      global cs
      cs = imp.new_module('cs')
      exec(f.read(), cs.__dict__)

rawDescription: python always create a file name "c", why ? (with cs=imp.load_source('cs','',f) function)

description: Python always create a file name "c", why ? (with cs=imp.load_source('cs','',f) function)


code:
u"abc(967208) \n abc2(411600) \n abc3(460273)" # input.text

import csv
import re
with open("out.csv","w") as out:
    wr = csv.writer(out,delimiter="\n")
    r = re.compile("\((\d+)\)")
    wr.writerow(r.findall(input.text))

rawDescription: Remove unicode [u']

description: Remove unicode [u']


rawDescription: How to get the expected result using list comprehension

description: Get the expected result using list comprehension


code:
l = [a.get_attribute("href") for a in dr.find_elements_by_css_selector(hrefs)]
len(l)
print(l)

rawDescription: Python expanding YouTube uploads

description: Python expanding YouTube uploads


code:
import lipgui
import winsound
import threading

menu = lipgui.enterbox("Enter a string:")
if menu == "what's up, lip?":
    t1 = threading.Thread(target=winsound.PlaySound, args=("C:/Interactive Program/LIP Source Files/skyisup.wav", 2))
    t2 = threading.Thread(target=lipgui.msgbox, args=("The sky is up",))

    t1.start()
    t2.start()

rawDescription: How to run 2 different processes at once in Python

description: Run 2 different processes at once in Python


code:
def set_property(driver, name, value):
    xpath = '//span[. = "%s"]/following-sibling::div//input' % name

    elem = driver.find_element_by_xpath(xpath)
    elem.clear()
    elem.send_keys(str(value) + Keys.ENTER)

rawDescription: How to automate webpage span control like slider values by using like driver. findElement_by_xpath () , Ubuntu Linux and chromium Autotest

description: Automate webpage span control like slider values by using like driver. findElement_by_xpath () , Ubuntu Linux and chromium Autotest


code:
class A(object):
    def __init__(self, a):
        self.a = a
        self.b = a-1

class B(list):
    """
    Some customization of this class...
    """
    def __getattr__(self, name):
        return (getattr(item, name) for item in self)

bb = B([A(i) for i in range(10)])
print(list(bb.a))
print(list(bb.b))

rawDescription: Get attribute of all items in container python


code:
import numpy as np

def inNd(a, b, assume_unique=False):
    a = np.asarray(a, order='C')
    b = np.asarray(b, order='C')
    a = a.ravel().view((np.str, a.itemsize * a.shape[1]))
    b = b.ravel().view((np.str, b.itemsize * b.shape[1]))
    return np.in1d(a, b, assume_unique)

tests = [
    (np.array([[1, 2], [2, 3], [1, 3]]),
     np.array([[2, 2], [3, 3], [4, 4]]),
     np.array([False, False, False])),
    (np.array([[1, 2], [2, 2], [1, 3]]),
     np.array([[2, 2], [3, 3], [4, 4]]),
     np.array([True, False, False])),
    (np.array([[1, 2], [3, 4], [5, 6]]),
     np.array([[1, 2], [3, 4], [7, 8]]),
     np.array([True, True, False])),
    (np.array([[1, 2], [5, 6], [3, 4]]),
     np.array([[1, 2], [5, 6], [7, 8]]),
     np.array([True, True, False])),
    (np.array([[-0.5, 2.5, -2, 100, 2], [5, 6, 7, 8, 9], [3, 4, 5, 6, 7]]),
     np.array([[1.0, 2, 3, 4, 5], [5, 6, 7, 8, 9], [-0.5, 2.5, -2, 100, 2]]),
     np.array([False, True, True]))
]

for a, b, answer in tests:
    result = inNd(b, a)
    try:
        assert np.all(answer == result)
    except AssertionError:
        print('''\
a:
{a}
b:
{b}

answer: {answer}
result: {result}'''.format(**locals()))
        raise
else:
    print('Success!')

rawDescription: test for membership in a 2d numpy array

description: Test for membership in a 2d numpy array


code:
#!/usr/bin/env python3
import subprocess
import sys

encoding = 'utf-32'
cmd = r'''$env:PYTHONIOENCODING = "%s"; py -3 -c "print('\u270c')"''' % encoding
data = subprocess.check_output(["powershell", "-C", cmd])
print(sys.stdout.encoding)
print(data)
print(ascii(data.decode(encoding)))

rawDescription: Decode poweshell output possibly containing non-ascii unicode characters into a python string


code:
results = results.decode("ascii") # needed in python 3
results = results.replace("\r","")
ls = results.split("\n")
ls = ls[4:]
ssids = []
x = 0
while x < len(ls):
    if x % 5 == 0:
        ssids.append(ls[x])
    x += 1
print(ssids)

rawDescription: List All Wireless Networks Python for PC


code:
def bandwidth_type(x):
    x = int(x)
    if x < 12:
        raise argparse.ArgumentTypeError("Minimum bandwidth is 12")
    return x

parser.add_argument("-b", "--bandwidth", type=bandwidth_type, help="target bandwidth >= 12")

rawDescription: python argparse integer condition (>=12)

description: Python argparse integer condition (>=12)


code: myValueList = [obj.prop1 for obj in myList]

rawDescription: collecting values from objects in a list

description: Collecting values from objects in a list


code: "Internet(R) explorer"

rawDescription: To search exact word in a file using python


code:
import requests
class RequestsHTTPStream(object):
    def __init__(self, url):
        self.url = url

    def iter_lines(self):
        headers = {'Cache-Control':'no-cache',
                   'Accept': 'text/event-stream',
                   'Accept-Encoding': 'gzip'}
        response = requests.get(self.url, stream=True, headers=headers)
        return response.iter_lines(chunk_size=1)

rawDescription: Efficiently reading lines from compressed, chunked HTTP stream as they arrive


code:
with open('file.txt', 'r') as f:
    next(f)
    for line in f:
        print(line.rstrip('\n'))
        for skip in range(3):
            try:
                next(f)
            except StopIteration:
                break

rawDescription: Use readline() from python to read specific line


rawDescription: Python: Use Regular expression to remove something


code:
class Post(models.Model):
    actualPost = models.CharField(max_length=200)

    def get_link(self):
        if self.actualPost and '@' in self.actualPost:
            return self.actualPost.split('@', 1)[1]
        return None

rawDescription: Django - take users form input and create a link in a certain part of the input?


code:
import re
example = '''
"http://someserver.com/"
"https://anotherserver.com/with/path"
'''
re.findall(r'https?://[^/"]+/', example)

rawDescription: Python regex alternation

description: Python regex alternation


code:
#!/usr/bin/env python
from __future__ import print_function
import sys
from itertools import cycle
from subprocess import Popen, PIPE
from textwrap import dedent

# start child process
p = Popen([sys.executable or 'python', '-u', '-c', dedent("""
        for i in range(10):
            x = int(input('Enter x-dimension: '))
            print(x*x)
        """)], stdin=PIPE, stdout=PIPE, universal_newlines=True, bufsize=1)
for n in cycle([3, 1, 4, 15, 926]): # infinite loop
    while p.poll() is None: # while the subprocess is running
        # send input to the child
        print(n, file=p.stdin)
        # read & parse answer
        data = p.stdout.readline().rpartition(' ')[2]
        if not data: # EOF
            answer = None
            break # exit inner loop
        answer = int(data)
        if answer == 1: # show example when input depends on output
            n += 1
        else: # done with given `n`
            break # exit inner loop
    else: # subprocess ended
        break # exit outer loop
    if answer is not None:
        print("Input %3d Output %6d" % (n, answer))
p.communicate() # close pipes, wait for the child to terminate

rawDescription: How to Achieve Continuous Interactive Dialog with a Subprocess in Python?


rawDescription: return constantly changing variable python

description: Return constantly changing variable python


code:
total_squares = sum(number*number * count for number, count in counter)
mean_of_squares = total_squares / count
variance = mean_of_squares - mean * mean
std_dev = math.sqrt(variance)

rawDescription: Calculate mean on values in python collections.Counter


code:
from locale import *
def test(self):
    setlocale(LC_NUMERIC, 'French_Canada.1252')
    a = atof(self.ui.lineEdit.text())
    b = atof(self.ui.lineEdit_2.text())
    Result = math.pow((a+b),2)
    self.ui.lineEdit_3.setText(str(Result))

rawDescription: How to convert an input number 34,6 to decimal form 34.6 in Python

description: Convert an input number 34,6 to decimal form 34.6 in Python


code:
import oper
oper.add_divide(5,10)

rawDescription: Django: Use external function with django variables


code: test_list = [['Biking', '10'], ['Biking|Gym', '14'], ['Biking|Gym|Hiking', '9'], ['Biking|Gym|Hiking|Running', '27']]

rawDescription: Grouping and totaling a pipe separated list


code: sorted([4, 2, 5, 3, 8], cmp=lambda a, b: 1 if a > b else 0 if a == b else -1)

rawDescription: Why is my list not sorted as expected?

description: Why is my list not sorted as expected


code:
from django.template import Template, Context
t = Template('''
{% load name %} {# Don't forget to load #}
{% get_by_name data_name %}
''')
output = t.render(Context({
    'data1': 'this is data1',
    'data2': 'this is data2',
    'data_name': 'data2',
}))
print(output)

rawDescription: django templates - how to dynamically access variable?

description: Django templates - how to dynamically access variable


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

fig, ax = plt.subplots()
Y, X = np.mgrid[-4:4:100j, -4:4:100j]
U =  -0.5*X - Y
V =  X - Y
ax.streamplot(X, Y, U, V, density=[1, 1])
ax.set(xlim=(-4,4), ylim=(-4,4))
plt.show()

rawDescription: Streamflow plot not matching mgrid

description: Streamflow plot not matching mgrid


code:
x="""<!DOCTYPE html>

<html itemscope itemtype="http://schema.org/QAPage">

<head>
"""

rawDescription: Using python re.compile with beautiful soup to match a string


code:
import pytest

@pytest.mark.parametrize('arg, result', [
 ('arg1', 'result1'),
 ('arg2', 'result2'),
 ('arg3', 'result3'),
 ('argN', 'resultN'),
])
def test_cmd0(arg, result):
    out = subprocess.check_output(['cmd', arg])
    assert out.rstrip() == out

rawDescription: Parametrize set of tests using PyTest

description: Parametrize set of tests using PyTest


code:
label = Label(label="fooo", labelname="FOO Name")
label.save()

position = 0
for word in ('a', 'green', 'car'):
    LabelWord(label=label, word=word, position=position).save()
    position += 1

rawDescription: How to annotate/aggregate each item in a list without for loops (Django)

description: Annotate/aggregate each item in a list without for loops (Django)


code:
def get_expected_rows(user, grade):
    #Here i want to list `grade` to be unpacked.
    return dict(zip(
        ['username', 'email', 'total', 'sub1grade', 'sub2grade', sub3grade, sub4grade],
        [ user.username, user.email ] + grade))

rawDescription: Python unpacking list value in kwargs

description: Python unpacking list value in kwargs


rawDescription: Compare 1st element in list of lists and write number of repeated values


code: OrderedDict((x, c[x]) for x in keys)

rawDescription: numpy - how do I count the occurrence of items in nested lists by index?

description: Numpy - how do I count the occurrence of items in nested lists by index


code: ax.scatter(1, 0, s=100000, facecolors='none')

rawDescription: matplotlib: how to plot concentric circles at a given set of radii

description: Matplotlib: how to plot concentric circles at a given set of radii


code:
def get_rows():
    while True:
        rows = input('Enter the number of rows:  ')
        if 3 <= rows <= 33:
            return rows

def triangle(rows, regular=False, invert=True):

    if invert:
        height = -1 * rows
    else:
        height = 0

    # inner padding for min height (3)
    inner_buffer = [0, 1, 3]
    while len(inner_buffer) <= rows:
        inner_buffer.append(inner_buffer[-1]+2)

    level = 0
    while level <= rows:
        outer_padding = ' '*(rows - abs(height))

        if height == 0:
            print(outer_padding + '*')
        else:
            inner_padding = ' '*( inner_buffer[ abs(height) ] )
            print(outer_padding + '*' + inner_padding + '*')

        height += 1
        level += 1

rawDescription: Draw inverted triangle of asterisk by using nested loops in Python


code:
a = np.random.uniform(50,200,5)
b = np.random.uniform(50,200,3)

rawDescription: Euclidean Distance Between All Points in an 2 Vectors


code:
from collections import Counter
from itertools import chain
import re

c = Counter()

l1,l2 = ['accounting', 'actual cost'], ['yields', 'zero-bond']
vocabulary_dict  = {k:0 for k in chain(l1,l2)}
print(vocabulary_dict)
sample_text = "Accounting experts predict actual costs an increase in yields for zero-bond and yields for junk-bonds.".lower()
splitted = sample_text.split()
c.update(splitted)

for k in vocabulary_dict:
    spl = k.split()
    ln = len(spl)
    if ln > 1:
        check = re.findall(r'\b{0}\b'.format(k),sample_text)
        if check:
            vocabulary_dict[k] += len(check)
    elif k in sample_text.split():
        vocabulary_dict[k] += c[k]
print(vocabulary_dict)

rawDescription: Check text/string for occurence of predefined list elements


code: entry = models.ForeignKey(Entry)

rawDescription: What is the best way to fetch/render one-to-many relationships?


code:
class ThingWithReCalc(object):
    def __init__(self, items):
        self.items = items()

    def position_recalc(self):
        for i in self.items():
            i.position_recalc()

class Control:
    def __init__(self, instances):
        self.machine_instances = instances
        ...

    def get(self, elem = 0, end = None, step = 1):
        return ListWithReCalc(machine_instances[elem : end : step])

rawDescription: Chain over iterable

description: Chain over iterable


rawDescription: How do I change each pixel

description: Change each pixel


code:
#coding:utf8
from __future__ import unicode_literals,print_function
import unicodedata as ud
import re
txtWords = 'carbon copolymers—III\n12- Géotechnique\n'
txtWords = re.sub(r'[^\w\n]',r' ',txtWords.lower(),flags=re.U)
txtWords = ud.normalize('NFKD',txtWords).encode('ascii','ignore').decode()
print(txtWords)

rawDescription: Maintaining the consistency of strings before and after converting to ASCII


code:
import csv

output = []
block = ()
with open('input_file') as in_file:
    csv_reader = csv.reader(in_file)
    for row in csv_reader:
        output.append(tuple(row))

first_element = output[0]
a, b, c, d = output[1:]
block = (first_element[0], a, b, c, d)

rawDescription: Create a Tuple from text file

description: Create a Tuple from text file


rawDescription: Python / PyMongo - How to convert a MongoDB find() query to a PyMongo dictionary


code:
s="(You Gotta) Fight For Your Right (to Party)"

import re
re.findall(r'\(([^()]+)\)',s)

rawDescription: How to correctly parse closing parentheses

description: Correctly parse closing parentheses


rawDescription: Sort dictionary alphabetically when the key is a string (name)


code:
import Queue
q = Queue.Queue()
q.put((1,2))
q.put((2,3))
q.get()
q.put((3,5))
q.get()

rawDescription: Python FIFO 2 Dimensional

description: Python FIFO 2 Dimensional


code:
from collections import defaultdict
from itertools   import izip

d = defaultdict(int)
for n, v in izip(ls1, ls2):
   d[n] += v

rawDescription: Merge two lists into a dictionary and sum over the elements of the second list


code:
def author_name(lines):
    '''Finds the authors name within the docstring'''
    for line in lines:
        name = 'Unknown'
        if line.startswith("Author"):
            line = line.strip('\n')
            line = line.strip('\'')
            author_line = line.split(': ')
            if len(author_line[1]) >=4:
                name = author_line[1]
            return "{0:21}{1}".format("Author", name)  # ends the function, we found an author

    return "{0:21}{1}".format("Author", name)

print(author_name(some_docstring.splitlines()))

rawDescription: Find author of python file from docstring


code:
class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def yourfunc(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1

yourfunc = Foo().yourfunc

rawDescription: Static variable in python?

description: Static variable in python


code: full_arr.view('f8, f8, f8').sort(order=['f0'], axis=0)

rawDescription: Memory efficient sort of massive numpy array in Python


code:
sum(1 if meets_condition(x) else 0 for x in my_list)
# or
sum(1 for x in my_list if meets_condition(x))

rawDescription: What is a good way to do countif in Python


code:
import numpy as np
np.r_[1, 2*np.ones(3), 1]

rawDescription: Translating arrays from MATLAB to numpy

description: Translating arrays from MATLAB to numpy


code:
pattern = re.compile('/app[^\.]*jsf')
#or maybe just
pattern = re.compile('/app.*jsf') #if your filename can have multiple periods in it eg app.app.app.jsf

rawDescription: Read a text file. Search for a text based on pattern and print all the matches in another text file


code:
# pass in explicit encoding if set as a header
encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
content = resp.content
soup = BeautifulSoup(content, from_encoding=encoding)
if soup.original_encoding != 'utf-8':
    meta = soup.select_one('meta[charset], meta[http-equiv="Content-Type"]')
    if meta:
        # replace the meta charset info before re-encoding
        if 'charset' in meta.attrs:
            meta['charset'] = 'utf-8'
        else:
            meta['content'] = 'text/html; charset=utf-8'
    # re-encode to UTF-8
    content = soup.prettify()  # encodes to UTF-8 by default

rawDescription: Requests module encoding provides different encode then HTML encode


code: from operator import div, mul, pow, add, sub

rawDescription: How to do this conditional statement?

description: Do this conditional statement


code:
x = pygame.image.load(filename)
x.get_rect(x, y, width, height)

rawDescription: I can't get my class to work in pygame

description: I can't get my class to work in pygame


code:
if __name__ == '__main__':
    # use first argument is provided.
    override = None
    if len(sys.argv) > 1:
        override = sys.argv[1]
    environment_root = resolve_virtual_environment(override)

rawDescription: Virtual environments and embedding Python


code:
import decorator

def mydecorator(f, *d_args, **d_kwargs):
    if (isinstance(f, classmethod)):
        return classmethod(mydecorator(f.__func__))
    elif (isinstance(f, staticmethod)):
        return staticmethod(mydecorator(f.__func__))
    elif (isinstance(f, property)):
        return property(mydecorator(f.fget))
    else:
        return decorator.decorator(f)

rawDescription: How to retrieve original @classmethod, @staticmethod or @property

description: Retrieve original @classmethod, @staticmethod or @property


code:
example.py
tests.py
lib/__init__.py
lib/event.py

rawDescription: Python unit test mock, get mocked function's input arguments


code:
lis  = [[4,5,6], [1,2], [13,1,1,1], [1000]]
def func(x):
    return len(x)  #comparisons are done based on this value

min(lis, key = func)
min(lis, key = len)

rawDescription: max() function: how to get the item being iterated and pass to key=func()

description: Max() function: how to get the item being iterated and pass to key=func()


code: x = x > 9 and 1 or x

rawDescription: Zero assignement in inline comparison

description: Zero assignement in inline comparison


code:
next(k for k, array in {"Di":Di, "Dj":Dj, "Dk":Dk}.items() if ([5, 5] == array).all(1).any())
#>>> 'Dj'

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


code:
s = """Add: 3rd Floor Khemha House
Drive in Road, Opp Drive in Cinema
Ahmedabad - 380 054
Gujarat
Tel: 91-79-7457611 , 79-7450378
Email: a.mitra1@lse.ac.uk
Website: http://www.aavishkaar.org
Contact: Angha Mitra
Purpose: Economics and Finance, Micro-enterprises
Aim/Objective/Mission: To provide timely financing, management support and professional expertise ..."""

rawDescription: Extract data from a site using python

description: Extract data from a site using python


code:
sentenceDataFrame = sqlContext.createDataFrame([
  (0, "Hi I heard about Spark"),
  (0, "I wish Java could use case classes"),
  (1, "Logistic regression models are neat")
], ["label", "sentence"])

tokenizer = NLTKWordPunctTokenizer(
    inputCol="sentence", outputCol="words",
    stopwords=set(nltk.corpus.stopwords.words('english')))

tokenizer.transform(sentenceDataFrame).show()

rawDescription: Create a custom Transformer in PySpark ML


code:
import inspect
inspect.signature(print)

rawDescription: Getting parameter names for __future__ functions in python


rawDescription: Flatten list of lists vertically in Python


code:
list_11 = [item for items in list_1 for item in items]
list_21 = [item for items in list_2 for item in items]
pprint([str1 + " " + str2 for str1, str2 in product(list_11, list_21)])
pprint([dis.jaccard(str1, str2) for str1, str2 in product(list_11, list_21)])

rawDescription: Problems computing the score of a pairwise list in an iterative way?


code:
def functionA(self):
  self.http=QHttp()
  ...
  self.valueA="valueA"
  self.connect(self.http, SIGNAL("done (bool)"), self.functionB)
  self.get("/myurl.html")

def functionB(self, done, valueA=None):
  if valueA is None:
      valueA = self.valueA
  ...

rawDescription: How can I pass to a slot more than the arguments the signal sends in pyqt4?

description: Pass to a slot more than the arguments the signal sends in pyqt4


code:
def listImportablesFromName(name, allowImport = False):
    try:
        return listImportablesFromSourceFile(pathToSourceFile(name))
    except PathToSourceFileException:
        if not allowImport:
            raise
        return dir(__import__(name))

rawDescription: Check Contents of Python Package without Running it?


code: ax.set_yscale('log', basey=2)

rawDescription: Histogram with base 2 logarithmic y-scale in matplotlib?


code:
from run import app
from eve.methods.post import post_internal

payload = {
    "firstname": "Ray",
    "lastname": "LaMontagne",
    "role": ["contributor"]
}

with app.test_request_context():
    x = post_internal('people', payload)
    print(x)

rawDescription: In Eve, what is the difference between inserting a document into a collection using the http method POST and using the mongo shell?


code: dis_vectors = [l - r for l, r in itertools.combinations(points, 2)]

rawDescription: Pairwise displacement vectors among set of points


code: maxi = max(count_dict[item] for item in count_dict)

rawDescription: Without using Counter(), how to find most common element in a list?


rawDescription: concatenating two multidimensional arrays in numpy

description: Concatenating two multidimensional arrays in numpy


rawDescription: slice in python, is a copy or just a pointer

description: Slice in python, is a copy or just a pointer


code:
class MyObject(object):
    ID = 0
    def __init__(self):
       self.id = MyObject.ID = MyObject.ID + 1

MyObject().id
MyObject().id
MyObject().id
MyObject.ID

rawDescription: One int for every python object

description: One int for every python object


rawDescription: How to catch words that ends with dash and its following word? Regex

description: Catch words that ends with dash and its following word? Regex


code: button[i]  = tk.Button(text="Coil %d is On" %i , width=50, command=lambda i=i: toggle_text(i)).grid(row = i, column = 1), "Off"

rawDescription: How to change text of Tkinter button initilised in a loop

description: Change text of Tkinter button initilised in a loop


code:
with open('Myfile.txt') as f:
    for line in f:
        if not line.startswith(' '):
            variable, description, _ = line.split(None, 2)
            print(variable, description)

rawDescription: Skipping lines and splitting them into columns in python text parser


rawDescription: Python list of combinations of positions


rawDescription: how to extract information in txt file using python

description: Extract information in txt file using python


code:
levels = {
    'INFO': logging.INFO,
    'WARNING': logging.WARNING,
    'ERROR': logging.ERROR,
}
py_loglevel = levels.get(self.loglevel, logging.DEBUG)

rawDescription: Python oneline switch

description: Python oneline switch


code: box[a][b] = box[a][b] or chr(current_char)

rawDescription: single line if statement - Python

description: Single line if statement - Python


code:
sdate = datetime(2015, 10, 1)
ndf['Date'] = pd.to_timedelta(ndf['Date'],unit='d') + sdate

rawDescription: Transforming a Date Column with Pandas

description: Transforming a Date Column with Pandas


rawDescription: Select rows from a DataFrame based on values in a column in pandas


code:
ab=ascontiguousarray(vstack((a,b)).T)
dtype = 'S'+str(2*a.itemsize)
c=ab.view(dtype=dtype)

rawDescription: remove duplicate elements from two numpy arrays

description: Remove duplicate elements from two numpy arrays


rawDescription: How can I delete the dictionary of global variables?

description: Delete the dictionary of global variables


code:
with open('textfile','r') as f:
    for line in f:
        print(''.join(table.get(word.lower(),word)
                      for word in re.findall(r'(\W+|\w+)',line)))

rawDescription: Python: normalizing a text file

description: Python: normalizing a text file


code: A, B, C, D = zip(*L)

rawDescription: Python - slice a list of list

description: Python - slice a list of list


code:
from loadBalancerTest import loadBalancerTest
loadBalancerTest(runJar = False)

rawDescription: Bare words / new keywords in Python

description: Bare words / new keywords in Python


code:
d = dict(item.split("=") for item in result[0].split(","))
d['CN']

rawDescription: Python - How do you remove characters recieved as a list from an ldap query?


code: np.allclose(func1(xy, 2), func3(xy, 2))

rawDescription: How to vectorize the dot product between segments of a trajectory

description: Vectorize the dot product between segments of a trajectory


code:
[client]
skip-secure-auth

rawDescription: How to pass secure_auth to MySQL login via SQLalchemy

description: Pass secure_auth to MySQL login via SQLalchemy


code:
dfg[dfg['id'] > 2]
val = dfg[dfg['id'] <= 2]
val

rawDescription: python grouping similar categorical values

description: Python grouping similar categorical values


code:
os.path.splitext(os.path.basename('.a'))[0] + '.new'
os.path.basename('.a').rsplit('.', 1)[0] + '.new'

rawDescription: Python-Which command is better for changing the file extension?


rawDescription: why this regular expression returns empty

description: Why this regular expression returns empty


rawDescription: Python - How do I split a nested list into further list?


code:
import xmltest
xmltest.testJunk(open("test.xml","w"), "wham < 3!")

rawDescription: simple output of xml from python

description: Simple output of xml from python


code: GroupManage.base_fields['group'].help_text = "New help text"

rawDescription: Override a Django form field from a different app


code:
def merge(a, b):
    results = []
    while True:
        try:
            idx = b.index(a[-1]) + 1  # leftmost occurrence of a[-1] in b
        except ValueError:  # a[-1] not in b
            results.append(a + b)
            break
        if a[-idx:] == b[:idx]:
            results.append(a + b[:idx])
    return min(results, key=len)

rawDescription: Pythonic way to merge two overlapping lists, preserving order


code:
class SprintMatrixWrapper(object):
    def __init__(self, sprint_matrix):
        self.__array_interface__ = sprint_matrix.__array_interface__()

rawDescription: Numpy's __array_interface__ not returning dict


code: ax.plot_date(xv, yv, linestyle='-')

rawDescription: Plot Time values with matplotlib

description: Plot Time values with matplotlib


code: from __future__ import unicode_strings

rawDescription: Python 2.7, Appengine Data Store & Unicode


rawDescription: Parsing Dictionary Into Spreadsheet in Python


code:
def outer(x):
    def inner_reads():
        # Will return outer's 'x'.
        return x
    def inner_writes(y):
        # Will assign to a local 'x', not the outer 'x'
        x = y
    def inner_error(y):
        # Will produce an error: 'x' is local because of the assignment,
        # but we use it before it is assigned to.
        tmp = x
        x = y
        return tmp
    return inner_reads, inner_writes, inner_error

inner_reads, inner_writes, inner_error = outer(5)
inner_reads()
inner_writes(10)
inner_reads()
inner_error(10)

rawDescription: What limitations have closures in Python compared to language X closures?


code:
myString = "link: '/Hidden/SidebySideGreen/dei1=1204970159862'};"
print( myString[7:-3] )

rawDescription: Regular expression for string between two strings?


code:
Post.objects.get_or_create(id=1, name="post1")
Post.objects.get_or_create(id=2, name="post2")
Post.objects.get_or_create(id=3, name="post3")
Post.objects.get_or_create(id=4, name="post4")
Vote.objects.get_or_create(id=1, post_id=2, value=1, type="AW")
Vote.objects.get_or_create(id=2, post_id=2, value=1, type="AW")
Vote.objects.get_or_create(id=3, post_id=2, value=1, type="US")
Vote.objects.get_or_create(id=4, post_id=2, value=1, type="US")
Vote.objects.get_or_create(id=5, post_id=3, value=-1, type="AW")
Vote.objects.get_or_create(id=6, post_id=3, value=-1, type="AW")
Vote.objects.get_or_create(id=7, post_id=4, value=-1, type="AW")

rawDescription: Order by dig-like rating in django

description: Order by dig-like rating in django


code:
import sys
import pickle
import csv

def main(csvfname):
    # get existing country data
    with open('country.dat', 'rb') as inf:
        country = pickle.load(inf)

    # get unique country names from your csv file
    with open(csvfname, 'rb') as inf:
        data = sorted(set(row[0] for row in csv.reader(inf)))

    for c in data:
        if c not in country:
            print('"{}" not found'.format(c))
            sugg = possible_countries(c)
            if sugg:
                print('Suggested replacements:\n  {}'.format('\n  '.join(sugg)))
            else:
                print('(no suggestions)')
            repl = raw_input('Enter replacement value (or <Enter> for none): ').strip()
            if repl:
                country[c] = repl

    # re-save country data
    with open('country.dat', 'wb') as outf:
        pickle.dump(country, outf)

if __name__=="__main__":
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print('Usage: python fix_countries.py csvfname')

rawDescription: Compare CSV files and print results using Python


code:
word = 'Americans'
lemmatized = wnl().lemmatize(word.lower())
if word.istitle():
    word = lemmatized.capitalize()
else:
    word = lemmatized
# word = 'American'

rawDescription: nltk lemmatizer doesn't know what to do with the word Americans

description: Nltk lemmatizer doesn't know what to do with the word Americans


code:
df
other
df.mul(other.reindex(df.index, method='ffill'))

rawDescription: Is it possible to do fill forward with DataFrame.mul() fill_value?


code:
@add_visibility_fields
class IMember(Interface):
    first_name = schema.TextLine(title=u'first name')
    last_name = schema.TextLine(title=u'last name')

IMember.names()

rawDescription: How to dynamically add attributes to an interface

description: Dynamically add attributes to an interface


code:
def leaf_dirs(dirlist):
    """Given a list of directories, find leaf directories"""
    parents = {}
    for path in dirlist:
        parts = path.split('/')
        if parts[0] == '':
            raise ValueError("can't handle rooted directory %s" % path)
        parent = '/'.join(parts[:-1])
        parents[parent] = True
    return [path for path in dirlist if path not in parents]

rawDescription: finding smallest unique element in a list

description: Finding smallest unique element in a list


rawDescription: Keyboard interruptable blocking queue in Python


code: ADMIN_ENABLED = True

rawDescription: How can I disable Django's admin in a deployed project, but keep it for local development?

description: Disable Django's admin in a deployed project, but keep it for local development


code:
B = A[[slice(None) if i != axis else slice(0, n-1) for i in xrange(n)]]
C = A[[slice(None) if i != axis else slice(1, n) for i in xrange(n)]]

rawDescription: Slices along arbitrary axis

description: Slices along arbitrary axis


rawDescription: Accessing / modifying submatrix of sparse scipy matrix


code: commands.getoutput("ls –lR")

rawDescription: Files and directories in Python on linux


code:
data
a = np.array(data).reshape(2, 2, 2, 2)
a
a.mean(axis=(1, 3))

rawDescription: Elements Arrangement For Calculating Mean In Python/NumPy


code:
from matplotlib import pylab
import numpy as np
a = np.array([1,2,3,4,5,6,7,100])
pylab.plot( np.arange(1,len(a)+1)/len(a), a,    # This part is required
            '-', drawstyle='steps' )            # This part is stylistic

rawDescription: Numpy/matplot: How to plot First X% is in range Y%?


rawDescription: Numpy genfromtxt issue with datetime with multiple columns


code:
import random
from scipy.linalg import toeplitz
import numpy as np

def is_invertible_F2(a):
    """
    Determine invertibility by Gaussian elimination
    """
    a = np.array(a, dtype=np.bool_)
    n = a.shape[0]
    for i in range(n):
        pivots = np.where(a[i:,i])[0]
        if len(pivots) == 0:
            return False

        # swap pivot
        piv = i + pivots[0]
        row = a[piv,i:].copy()
        a[piv,i:] = a[i,i:]
        a[i,i:] = row

        # eliminate
        a[i+1:,i:] -= a[i+1:,i,None]*row[None,:]

    return True

n = 10
column = [random.choice([0,1]) for x in xrange(n)]
row = [column[0]]+[random.choice([0,1]) for x in xrange(n-1)]
matrix = toeplitz(column, row)

print(is_invertible_F2(matrix))
print(int(np.round(np.linalg.det(matrix))) % 2)

rawDescription: Test if matrix is invertible over finite field


code:
def some_abstract_decorator(func):
    @another_lower_level_decorator
    @wraps(func)
    def wrapper(*args, **kwargs):
        # ... details omitted
        return func(*args, **kwargs)
    return wrapper

rawDescription: Python - correct order of the application of decorators


code:
class Note(object):
    def __init__(self,name, size):
        self.name = name
        self._size = size

    def _get_size(self, notebook_class=None):
        return self._size

    def _set_size(self, notebook_class=None, size=0):
        self._size = size

class Notebook(object):
    def __new__(cls,*notes):
        notebook = object.__new__(cls)
        for note in notes:
            setattr(notebook.__class__, note.name, property(note._get_size, note._set_size))
        return notebook

rawDescription: Adding properties dynamically using functions created dynamically


code:
from serial.tools import list_ports
list_ports.comports()

rawDescription: How to automatically get port no. of a hardware in python serial communcation?

description: Automatically get port no. of a hardware in python serial communcation


rawDescription: Printing all the attributes in a class

description: Printing all the attributes in a class


code:
for dict in a:
    for key,list in dict.items():
        print('{} : {}'.format(key,list))

rawDescription: iterating through a list of dictionary names

description: Iterating through a list of dictionary names


rawDescription: Python array manipulation

description: Python array manipulation


code:
{u'Accounting & Prof. Studies': [u'Accounting Technician (ATI)',
                                 u'APICS Certificate in Production and Inventory Management (CPIM)',
                                 u'APICS Certified Supply Chain professional (CSCP)',
                                 u'Bachelor of Business (Honours) in Accounting & Finance',
                                 u'Bachelor of Business (Honours) in Accounting & Finance',
                                 u'Bachelor of Business in Accounting & Finance',
                                 u'Bachelor of Business in Accounting & Finance',
                                 u'Foundation Certificate in Personnel Practice (CIPD)',
                                 u'Foundation Diploma in Human Resource Practice (CIPD)',
                                 u'Higher Certificate in Business in Accounting',
                                 u'Higher Certificate in Business in Real Estate (Valuation, Sale and Management)'],
 u'Computing': [u'Bachelor of Science (Honours) in Computing',
                u'Bachelor of Science (Honours) in Computing',
                u'Bachelor of Science (Honours) in IT Management',
                u'Bachelor of Science (Honours) IT Management',
                u'Bachelor of Science in Computing',
                u'Bachelor of Science in Computing',
                u'Bachelor of Science in IT Management',
                u'Certificate in Cloud Computing Applications Development',
                u'Certificate in Cloud Computing Infrastructure Management',
                u'Certificate in Fundamentals of Software Development (Minor Award)',
                u'Certificate in Network Design and Implementation',
                u'Higher Certificate in Science in Information Technology',
                u'Higher Certificate in Science in IT Management',
                u'Higher Diploma in Science in Computing',
                u'M. Sc. in Distributed and Mobile Computing',
                u'M.Sc. in Information Technology Management',
                u'PhD in Information Technology',
                u'Postgraduate Diploma in Distributed and Mobile Computing',
                u'Postgraduate Diploma in Information Technology Management',
                u'Postgraduate Diploma in Science in Info Technology Management Information Technology Management'],
 u'Electronic Engineering': [u'Bachelor Degree in Engineering (Honours) in Electronic Engineering',
                             u'Bachelor of Engineering (Honours) in Electronic Engineering',
                             u'Bachelor of Engineering in Electronic Engineering',
                             u'Bachelor of Engineering In Electronic Engineering',
                             u'Cisco CCNA Routing & Switching',
                             u'Higher Certificate in Engineering in Electronic Engineering',
                             u'Masters of Engineering in Electronic Engineering in Electronic System Design',
                             u'Single Subject Certificate Structured Analogue Design'],
 u'External Services': [u'Access English',
                        u'Pre-Start Academic English',
                        u'Pre-Start Maths'],
 u'Humanities': [u'Bachelor of Arts (Honours) in Creative Digital Media',
                 u'Bachelor of Arts (Honours) in European Studies',
                 u'Bachelor of Arts (Honours) International Hospitality & Tourism Management',
                 u'Bachelor of Arts (Honours) Social Care Practice',
                 u'Bachelor of Arts (Ordinary) International Hospitality and Tourism Management',
                 u'Bachelor of Arts in Culinary Arts',
                 u'Bachelor of Arts in International Hospitality and Tourism Management',
                 u'English as a Foreign Language',
                 u'Higher Cert in Arts in International Hospitality & Tourism Operati in Int Hosp & Tourism Operations',
                 u'Higher Certificate in Arts in Culinary Arts'],
 u'Management': [u'Bachelor of Business (Honours) in Management',
                 u'Bachelor of Business (Honours) in Management',
                 u'Bachelor of Business in Management',
                 u'Bachelor of Science (Honours) in the Management of Innovation and Technology',
                 u'Bachelor of Science in the Management of Innovation and Technology',
                 u'Higher Certificate in Business in Business Administration',
                 u'International Digital Management & Sales',
                 u'TA_BMNGT_D - Bachelor of Business in Management'],
 u'Marketing': [u'Bachelor of Arts (Honours) in Advertising & Marketing Communications',
                u'Bachelor of Arts in Advertising and Marketing Communications',
                u'Bachelor of Business (Honours) in Marketing',
                u'Bachelor of Business (Honours) in Marketing Management',
                u'Bachelor of Business in Marketing',
                u'Bachelor of Business in Marketing',
                u'BSc in Data Analytics with Digital Marketing',
                u'Higher Certificate in Business in Marketing',
                u'Higher Diploma in Business in Marketing'],
 u'Mechanical Engineering': [u'B.Eng(Hons) in Mechanical Engineering',
                             u'Bachelor of Engineering (Honours) in Mechanical Engineering',
                             u'Bachelor of Engineering in Energy and Environmental Engineering',
                             u'Bachelor of Engineering in Mechanical Engineering',
                             u'Bachelor of Science (Honours) in Energy Systems Engineering',
                             u'Bachelor of Science (Hons) in Energy Systems Engineering',
                             u'Certificate in Project Management (IPMA)',
                             u'EIQA Diploma in Quality Management Quality Management',
                             u'Higher Certificate in Engineering in Mechanical Engineering',
                             u'Master of Engineering in Mechanical Engineering'],
 u'Science': [u'Bachelor of Science (Honours) in Bioanalytical Science',
              u'Bachelor of Science (Honours) in Bioanalytical Science',
              u'Bachelor of Science (Honours) in Pharmaceutical Science',
              u'Bachelor of Science (Hons) in Sports Science and Health',
              u'Bachelor of Science (Hons) in Sports Science and Health (1 Year Add-On)',
              u'Bachelor of Science Hons in DNA and Forensic Analysis',
              u'Bachelor of Science in Bio Analysis (1 year add-on Bachelor Degree)',
              u'Bachelor of Science in Bioanalysis or Chemical Analysis',
              u'Bachelor of Science in Chemical Analysis',
              u'Bachelor of Science in DNA and Forensic Analysis',
              u'Bachelor of Science in Pharmaceutical Science',
              u'Bachelor of Science in Pharmaceutical Technology',
              u'Bachelor of Science in Sports Science and Health',
              u'Bachelor of Science in Sterile Services Management',
              u'Certificate in Bioprocessing and Cleanroom Management - Minor Award',
              u'Certificate in Food Science and Technology Minor Award',
              u'Certificate in GMP & Regulatory Affairs (MIN) in GMP & Technology',
              u'Certificate in GMP and Medical Device Manufacture (Minor Award)',
              u'Copy of TA_SSPPM_B - Certificate in Pharmaceutical and Medical Device Manufacturing (Special Purpose Award)v2',
              u'Higher Certificate in Science Contamination Control and Asepsis for the Healthcare Sector',
              u'Higher Certificate in Science in Bio & Pharmaceutical Analysis',
              u'Higher Certificate in Science in GMP and Technology',
              u'Higher Certificate in Science in Process Technologies',
              u'Higher Diploma in Food Science and Technology',
              u'Higher Diploma in Science in Pharmaceutical Manufacturing',
              u'Masters in Pharmaceutical Manufacturing & Process Technology',
              u'PhD in Science in Biology',
              u'PhD in Science in Chemistry']}

rawDescription: Scrape a lightbox overlay using Selenium, Beautiful Soup in Python


rawDescription: Return a list of words on a line but ignore certain whitespace


rawDescription: merge two tuples with same key

description: Merge two tuples with same key


code:
with open('binary_file', 'rb') as input_file:
    byte = input_file.read(1)

rawDescription: File manipulation in binary

description: File manipulation in binary


code: target_el = SubElement(root_node, "Target")

rawDescription: Python and ElementTree: How can I nest elements/subelements in an XML?


code: logger.infoc = lambda msg: logger.info('\033[0;41;97m' + msg + '\033[0m')

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


rawDescription: Storing data in a data frame

description: Storing data in a data frame


code: matching = [sender for sender in snaps if sender['media_type'] == 3]

rawDescription: Filtering results in python, I need one variable but only if based on another


code:
import collections

class ROListSlice(collections.Sequence):

    def __init__(self, alist, start, alen):
        self.alist = alist
        self.start = start
        self.alen = alen

    def __len__(self):
        return self.alen

    def adj(self, i):
        if i<0: i += self.alen
        return i + self.start

    def __getitem__(self, i):
        return self.alist[self.adj(i)]

rawDescription: Can I create a "view" on a Python list?

description: Create a "view" on a Python list


code:
f = open('out.txt', 'w')
print >> f, 'Filename:', filename  # or f.write('...\n')
f.close()

rawDescription: How to redirect 'print' output to a file using python?

description: Redirect 'print' output to a file using python


code:
import numpy
partition = numpy.split

rawDescription: Split a list into parts based on a set of indexes in Python


code:
dis.dis(compile("import foo", "", "exec"))
dis.dis(compile("import foo as bar", "", "exec"))

rawDescription: Where does __import__ get alias names from?


code:
{'conocer': ('conocías', 'conozcas', 'conociéremos', 'conocerán', 'conocían'),
 'NOT FOUND': (),
 'planear': ('planeareis', 'planeáramos', 'planeasteis', 'planearás')}

rawDescription: Combining Keys in Dictionary into tuples in a list


code:
class PerUserModelResource(ModelResource):

  def obj_create(self, bundle, request=None, **kwargs):
    return ModelResource.obj_create(self, bundle, request, user=request.user)

  def apply_authorization_limits(self, request, object_list):
    return object_list.filter(user=request.user)

rawDescription: django and backbone.js questions

description: Django and backbone.js questions


code:
import wpf

from System.Windows import Application, Window
from AboutWindow import *

class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'IronPythonWPF.xaml')

    def MenuItem_Click(self, sender, e):
        form = AboutWindow()
        form.Show()

if __name__ == '__main__':
    Application().Run(MyWindow())

rawDescription: IronPython WPF Load New Window

description: IronPython WPF Load New Window


code:
import numpy as np

def centralise(arr):
    # Find the x and y indexes of the nonzero elements:
    x, y = arr.nonzero()

    # Find the index of the left-most and right-most elements for each row:
    nonzeros = np.bincount(x)
    nonzeros_idx = nonzeros.cumsum()
    left = y[np.r_[0, nonzeros_idx[:-1]]]
    right = y[nonzeros_idx-1]

    # Calculate how much each y has to be shifted
    shift = ((arr.shape[1] - (right-left) - 0.5)//2 - left).astype(int)
    shift = np.repeat(shift, nonzeros)
    new_y = y + shift

    # Create centered_arr
    centered_arr = np.zeros_like(arr)
    centered_arr[x, new_y] = arr[x, y]
    return centered_arr

arr = np.array([[0, 1, 2, 0, 2, 1, 0, 0, 0],
                [2, 1, 1, 0, 0, 0, 0, 0, 0],
                [0, 0, 1, 0, 0, 2, 0, 0, 0]])
print(centralise(arr))

rawDescription: Centralising data in numpy

description: Centralising data in numpy


code:
class Category(models.Model):
    ...

class Article(models.Model):
    category = ForeignKey(Category) # this adds a back ref that
                                    # is by default called `article_set`
                                    # into Category

rawDescription: Get nested/related objects in a Django template


rawDescription: Sorting numpy array according to the sum


rawDescription: efficient way to count the element in a dictionary in Python using a loop

description: Efficient way to count the element in a dictionary in Python using a loop


code:
class TimedTask(asyncio.Task):

    self.cputime = 0.0

    def _step(self, *args, **kwargs):
        start = time.time()
        result = super()._step(*args, **kwargs)
        self.cputime += time.time() - start
        return result

rawDescription: How to measure Python's asyncio code performance?

description: Measure Python's asyncio code performance


code: vals = (helper(k, g) for k, g in grouped)

rawDescription: python pandas applying for loop and groupby function

description: Python pandas applying for loop and groupby function


code: text_box.send_keys(zip_codes[0] + "\n")

rawDescription: Click on buttons with images

description: Click on buttons with images


code:
import numpy.linalg as la
from scipy.spatial import distance as dist

# Manually
def method0(x, y):
    dotprod_mat = np.dot(x,  y.T)
    costheta = dotprod_mat / la.norm(x, axis=1)[:, np.newaxis]
    costheta /= la.norm(y, axis=1)
    return np.arccos(costheta)

# Using einsum
def method1(x, y):
    dotprod_mat = np.einsum('ij,kj->ik', x, y)
    costheta = dotprod_mat / la.norm(x, axis=1)[:, np.newaxis]
    costheta /= la.norm(y, axis=1)
    return np.arccos(costheta)

# Using scipy.spatial.cdist (one-liner)
def method2(x, y):
    costheta = 1 - dist.cdist(x, y, 'cosine')
    return np.arccos(costheta)

# Realize that your arrays `x` and `y` are already normalized, meaning you can
# optimize method1 even more
def method3(x, y):
    costheta = np.einsum('ij,kj->ik', x, y) # Directly gives costheta, since
                                            # ||x|| = ||y|| = 1
    return np.arccos(costheta)

rawDescription: Compute matrix of pairwise angles between two arrays of points


code:
import multiprocessing
import os
import sys

import analysis

parent_dir = os.path.realpath(sys.argv[0])

paths = [os.path.join(folderpath, file)
         for file in os.listdir(folderpath)]

with multiprocessing.Pool(processes=6) as pool:
    results = pool.map(analysis.analyze, paths)

rawDescription: How to pass variables in parent to subprocess in python?

description: Pass variables in parent to subprocess in python


rawDescription: How % works in Python

description: How % works in Python


code:
def sigmoid(x, x0, k, y0=0):
   y = 1 / (1 + np.exp(-k*(x-x0))) + y0
   return y

rawDescription: how to find 50% point after curve fitting using numpy

description: Find 50% point after curve fitting using numpy


code:
class Breakfast(object):
    def __init__(self, eggs, spam):
        self.spam, self.eggs = spam, eggs

class HealthyBreakfast(object):
    def __init__(self, spam):
        super(HealthyBreakfast, self).__init__(0, spam)

rawDescription: Multiple constructors in python, using inheritance


code:
routes = [(r'/', MainHandler), (r'/tail/', TailHandler),
    (r'/signin/', SigninHandler), (r'/signout/', SignoutHandler)]

rawDescription: How to stream the last few lines of a file in Django?

description: Stream the last few lines of a file in Django


rawDescription: Binary search to find last element in sorted list that is less then specific value


code:
def set_some_dict(cls):
    cls.some_dict[cls] = True

@set_some_dict
class Test:
    some_dict = {}

rawDescription: class __init__ (not instance __init__)

description: Class __init__ (not instance __init__)


code:
from django.utils import simplejson
from django.http import HttpResponse

def ajax_tweets(request):
    if request.method == 'GET':
        max_id = int(request.GET['max_id'])
        query = request.GET['query']

        ###
        # Perform API auth requirements
        ###

        tweets = tweepy.Cursor(api.search, q=query, max_id=max_id, count=100).items(100)
        json = simplejson.dumps(tweets)

        return HttpResponse(json, mimetype="application/x-javascript")

rawDescription: How to make Django template render a set of results from views and keep calling view for more results without refreshing page

description: Make Django template render a set of results from views and keep calling view for more results without refreshing page


code:
ret = evenrow(TwoDArray)
if ret % 2 == 0:
    print('Total Value: %d\nEven or Odd: Even' % ret)
else:
    print('Total Value: %d\nEven or Odd: Odd' % ret)

rawDescription: Optimizing code for python, values from a 2d array


code:
def heading():
    result=[] #create a void list
    numbersum=sum(list1) #"calculate the total amount of numbers in the list"
# e.g. if list=[1,1,2] sum(list) return 1+1+2.
    for i in range(len(list1)):
         result.append(((list1[i])/float(numbersum))*360) # calculate portion of the circle ("then divide by 360 to work out portions of a circle")
#in this case if you have a list A=[250,250] the function will return two angle of 180°
    #however you can return portion of the circle in percent e.g. 0.50 is half a circle 1 is the whole circle simply removing "*360" from the code above
    return result

rawDescription: Python add numbers up in loop

description: Python add numbers up in loop


code:
def using_tzset(date_strings, tz):
    os.environ['TZ'] = tz
    time.tzset()
    return np.array(date_strings, dtype='datetime64[ns]')

rawDescription: Quickly parse Python datetime in a non-local timezone, adjusting for daylight savings


code:
def test(self):
    model = self.ui.listView.model()
    for row in range(model.rowCount()):
        item = model.item(row)
        if item.checkState() == QtCore.Qt.Checked:
            print('Row %d is checked' % row)

rawDescription: PYQT4, ListView: How to get selected rows using QStandardItemModel


code:
choices, counts = np.unique(a, return_counts=True)
np.random.choice(choices, 5, p=counts/len(a), replace=False)

rawDescription: Generating random numbers with weighted probabilities in python


code:
timeit.Timer('[f(20) for f in functions]', 'functions = [lambda n: i * n for i in range(100)]').repeat()
timeit.Timer('for f in functions: f(20)', 'functions = [lambda n: i * n for i in range(100)]').repeat()

rawDescription: Efficient way of calling set of functions in Python


code: type(B)

rawDescription: pls help - error message "no attribute 'renderContents'"

description: Pls help - error message "no attribute 'renderContents'"


code:
lst = [1,2]
lst in d.itervalues()

rawDescription: How can I check if a list exist in a dictionary of lists in the same order

description: Check if a list exist in a dictionary of lists in the same order


code:
import seaborn as sns

sns.barplot('Month', 'Score', '_Max', df)

rawDescription: vizualize categorical and numerical values on the same plot

description: Vizualize categorical and numerical values on the same plot


code:
with open("filename", "w") as f:
    for key in dict:
        print >>f, key

rawDescription: writing keys of a dictionary to a text file

description: Writing keys of a dictionary to a text file


rawDescription: Python creating Covariance matrix from List


kind: youtube#channelListResponse

kind: youtube#channel

rawDescription: Search YouTube videos by author

description: Search YouTube videos by author


rawDescription: Regular Expression for whole numbers and integers?


rawDescription: How to preserve the item order in a Python dictionary?

description: Preserve the item order in a Python dictionary


rawDescription: Flattening a list which consist of integer and list


code:
class MinerNotFullAction:
   def __init__(self, entity, image_store):
      self.entity = entity
      self.image_store = image_store

   def miner_to_ore(self, world, ore):
       ...

rawDescription: If a function (that's outside of the class) needs to use a method from a class, how do I call the method?


rawDescription: Django: Filtering query with foreign key not working


code:
if first_check:
  new_name = file_name[first_check.span()[1]:]
  shutil.move(os.path.join(dirpath, file_name),
              os.path.join(dirpath, new_name))
else:
   new_name = file_name[second_check.span()[1]:]
   shutil.move(os.path.join(dirpath, file_name),
               os.path.join(dirpath, new_name))

rawDescription: Cleaner way to move renamed files when walking over directory


code:
{'Ford': ('1909', 'Model T'),
 'Horsey': ('1899', 'Horseless'),
 'Overland': ('1911', 'OctoAuto'),
 'Scripps-Booth': ('1913', 'Bi-Autogo')}
{'Ford': ('1909', 'Model T'),
 'FutureX': ('20xx', None),
 'FutureY': (None, None),
 'Horsey': ('1899', 'Horseless'),
 'Overland': ('1911', 'OctoAuto'),
 'Scripps-Booth': ('1913', 'Bi-Autogo')}

rawDescription: Merging three lists into into one dictionary


rawDescription: Django URL regex complication

description: Django URL regex complication


code:
glEnable(GL_LIGHTING)
for i,l in enumerate(lights):
    l.setup(i)

rawDescription: create opengl lights with class constructor

description: Create opengl lights with class constructor


code:
subprocess.call('ping 127.0.0.1')
subprocess.call('ping 127.0.0.1', stdout=subprocess.PIPE)

rawDescription: How to just call a command and not get its output

description: Just call a command and not get its output


code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 9988))
s.sendall('My parameters that I want to share with the server')
s.close()

rawDescription: How to get a python script to listen for inputs from another script

description: Get a python script to listen for inputs from another script


code:
ls.sort()
[ls[i] for i in range(len(ls))[:-1] if ls[i] != ls[i+1][:len(ls[i])]] + [ls[-1]]

rawDescription: Python: Remove elements from the list which are prefix of other


code:
def factorial_recursive(x):
    def inner(n):
        if n == 0:
            return 1
        return n * factorial_recursive(n - 1)
    return inner(x)

def factorial_iterative(n):
    product = 1
    for i in xrange(1, n+1):
        product *= i
    return product

assert test_recursion(lambda: factorial_recursive(5))
assert not test_recursion(lambda: factorial_iterative(5))
assert not test_recursion(lambda: map(factorial_iterative, range(5)))
assert factorial_iterative(5) == factorial_recursive(5) == 120

rawDescription: Is there a way to check if function is recursive in python?


code: cars = {num: pygame.image.load('Car{}.png'.format(num)) for num in range(1, 3)}

rawDescription: Using a String to Call a Variable in Python 3.3 with Pygame


code:
class MyClass(Object):
    class_attribute = "Foo"

    def __init__(self,*args,**kwargs):
        self.instance_property = "whatever"

rawDescription: Best way to publicize instance attributes

description: Publicize instance attributes


code:
class TodoAdminForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.filter(user__pk=self.instance.user.pk)

@admin.register(Todo)
class TodoAdmin(admin.ModelAdmin):
    form = TodoAdminForm
    ...

rawDescription: Limit choices and validate django's foreign key to related objects (also in REST)


code:
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget, proportion=0, style=wx.ALL, border=5)

rawDescription: How I can set gap in Vertical BoxSizer?

description: How I can set gap in Vertical BoxSizer


code:
@app.route('/', methods=['POST'])
def get_data():
    # Dong something here to prepare for data
    def blog_entries():
        for entry in get_entry():
            yield entry
    return Response(stream_template('blog.html',
                                    data=blog_entries(),
                                    total_entries=get_total_entry(),
                                    gen_time=get_generated_time()))

rawDescription: Flask - How to print different variables on the same page


code:
from collections import defaultdict

newresult = defaultdict(list)

for entry in result:
    job_id = entry.pop('job_id')
    newresult[job_id].append(entry)

rawDescription: How to sort a list of dictionaries in python?

description: Sort a list of dictionaries in python


code:
url(
    r'island_name/choices/$',
    'island_name_choices_for_island_group', {
    }, 'island_name_choices_for_island_group',
),

rawDescription: django dynamic filtered form

description: Django dynamic filtered form


code:
for i in numbers(10):
    if condition:
        break
    else:
        print(i)

rawDescription: How to use For loop to cycle through 1 to 10 again and again until the loop is broken in python

description: Use For loop to cycle through 1 to 10 again and again until the loop is broken in python


code:
from kivy.support import install_twisted_reactor
install_twisted_reactor()

from twisted.internet import defer

Builder.load_string('''
<MyPopup>:
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: text_input
        BoxLayout:
            orientation: 'horizontal'
            Button:
                text: 'OK'
                on_press: root.okfn(text_input.text)
''')

class MyPopup(Popup):
    def show(self, *args):
        d = defer.Deferred()
        self.okfn = d.callback
        self.open(*args)
        return d

@defer.inlineCallbacks
def myfunc():
    # do some stuff here
    val = yield MyPopup().show()
    # do some more stuff here

rawDescription: Pause a python script until an event occurs without hanging/blocking the GUI


code:
from collections import Counter

with open('bandfile.txt') as f:
   counts = Counter(line.split('-')[0].strip() for line in f if line)

for band, count in counts.most_common():
    print("{0}:{1}".format(band, count))

rawDescription: Take certain words and print the frequency of each phrase/word?


code:
import scipy
X = scipy.rand(9,4,1)
Y = X.repeat(4096,2)

rawDescription: numpy: extending arrays along a new axis?

description: Numpy: extending arrays along a new axis


code:
def get_subscription_prices(request):
    return {'subscription_price_free_user': settings.SUBSCRIPTION_PRICE_FREE,
            'subscription_price_03Month_user': settings.SUBSCRIPTION_PRICE_03MONTHS,
            'subscription_price_06Month_user': settings.SUBSCRIPTION_PRICE_06MONTHS,
            'subscription_price_12Month_user': settings.SUBSCRIPTION_PRICE_12MONTHS,
            'subscription_price_default': settings.SUBSCRIPTION_PRICE_DEFAULT}

rawDescription: django context processors - how to return everything from one function?

description: Django context processors - how to return everything from one function


code:
def s(df):
    #resample column Timestamp by 100ms, convert bak to integers
    df['Timestamp'] = df['Timestamp'].astype('timedelta64[ms]')
    df = df.set_index('Timestamp')
    out = df[[]].resample('100ms', how='first')
    out = out.reset_index()
    out['Timestamp'] = (out['Timestamp'] / np.timedelta64(1, 'ms')).astype(int)
    #print out.head(10)

    #search start end
    def search(x):
        mask1 = (df.S_time1<=x['Timestamp']) & (df.End_Time_1>=x['Timestamp'])
        #if at least one True return first value of series
        if mask1.any():
                return df.loc[mask1].Sign_1[0]
        #check second start and end time
        else:
                mask2 = (df.S_time2<=x['Timestamp']) & (df.End_time_2>=x['Timestamp'])
                if mask2.any():
                    #if at least one True return first value
                    return df.loc[mask2].Sign_2[0]
                else:
                    #if all False return NaN
                    return np.nan

    out['Bin_time'] = out.apply(search, axis=1)
    #print out.head(10)

rawDescription: Python pandas resampling

description: Python pandas resampling


code:
import Tkinter as tk

root = tk.Tk()
Button1 = tk.Button(root,text="Button1")
Button2 = tk.Button(root,text="Button2")
Button3 = tk.Button(root,text="Button3")
Label1 = tk.Label(root,text="Label1")
Label2 = tk.Label(root,text="Label2")
Label3 = tk.Label(root,text="Label3")

Button1.grid(row=0,column=0,columnspan=2)
Button2.grid(row=0,column=2)
Button3.grid(row=0,column=4,rowspan=2)
Label1.grid(row=1,column=0)
Label2.grid(row=1,column=1)
Label3.grid(row=1,column=2)

root.mainloop()

rawDescription: Tkinter / Python grid layout with listboxes


code:
import scipy.interpolate as interpolate
newx = np.linspace(minX, maxX, 1000)
newy = interpolate.interp1d(x, y, kind='cubic')(newx)

rawDescription: Downsampling non-uniform 1D signals

description: Downsampling non-uniform 1D signals


code: plot(Height, Weight, type="h")

rawDescription: Python's barchart equivalent in R

description: Python's barchart equivalent in R


code: locals().keys()  # ['allDev']

rawDescription: Python: random function from locals() with defined prefix


code: scores = db.ListProperty(db.Key)

rawDescription: Google App Engine: Implementing a collection of ordered lists


rawDescription: Python can not get links from web page

description: Python can not get links from web page


code:
import socket

results = []

with open('hostnames_list.txt') as f:
    for hostname in f:
        try:
            ip = socket.gethostbyname(hostname.strip())
        except socket.gaierror:
            ip = socket.gethostbyname('.'.join(hostname.strip().split('.')[1:]))
        results.append((ip, hostname.strip()))

for (ip, hostname) in sorted(results, key=lambda item: socket.inet_aton(item[0])):
    print (ip.ljust(30,' ')) + '' + (hostname.ljust(30,' '))

rawDescription: How can I get the list sorted out according to the IP address?

description: Get the list sorted out according to the IP address


rawDescription: Select unique value in many lists in python


code:
attrs = vars(self)
out = dict(attrs[self.LOOKUPDICT[k]]({k: query[k]})
           for k in query.keys() - self.exclusions)

rawDescription: Python dictionary comprehension

description: Python dictionary comprehension


code:
x = np.arange(4)
np.tile(x,(3,1))

rawDescription: Create an array from n copies of subarray in python


code:
config.add_route('plot', '/{project_name}/testruns/{testrun_name}/plots/{plot_name}.png')
config.scan()

@view_config(route_name='plot')
def plot_view(request):
    action = request.GET('action')
    if action == 'edit':
        # do something
        return render_to_response('bunseki:templates/form.pt', {}, request)

    # return the png

rawDescription: using query string in Python Pyramid route configuration

description: Using query string in Python Pyramid route configuration


code:
while j < (N):
    j=j+1
    B=A[1+(10*j)+R][1:k] #Extraction expression.
    C=[float(i) for i in B] #Float conversion.
    D[0].append(C[0]),D[1].append(C[1]),D[2].append(C[2])
    for i in range(4, 12):
        if NC >= i:
            D[i - 1].append(C[i - 1])
    if NC == 12:
        D[11].append(C[11])

rawDescription: Alternative to large "if-else" tree algorithm?


code:
class Person():
    name = 'Victor'
    def say(self, what):
        print(self.name, what)

getattr(Person, 'name')
attr_name = 'name'
person = Person()
getattr(person, attr_name)
getattr(person, 'say')('Hello')

rawDescription: Why should I ever use "getattr()"?

description: Why should I ever use "getattr()"


rawDescription: Error when feeding a mysql db with a python-parsed data


code: '\n'.join(''.join(i) for i in zip(*s.split()))

rawDescription: Transpose block of text

description: Transpose block of text


code:
thelist = [[1, 2, 3, 4, 5], 5, 6, 7, 8, 10, [9, 0, 1, 8]]
# Remove the 5 from the first inner list because it was found outside.
# Remove the 8 from the other inner list, because it was found outside.
expected_output =[[1, 2, 3, 4], 5, 6, 7, 8, 10, [9, 0, 1]]

rawDescription: Iterate through a list of integer and lists in Python


rawDescription: Save multiple arrays to a csv file with column names


code:
x = open('C:/Users/Acer/Desktop/test3.txt', 'w')
for i in longlist:
    x.write("%s, " % i)
x.close()

rawDescription: How can I use the replace function to change the headers in a .txt file?

description: Use the replace function to change the headers in a .txt file


code:
class MyModelAdmin(admin.ModelAdmin):
    ...
    list_display = ('name', 'email', 'sender', 'send_email_html')

    def send_email_html(self, obj):
        # example using a javascript function send_email()
        return 'Send Now' % obj.id
    send_email_html.short_description = 'Send Email'
    send_email_html.allow_tags = True

rawDescription: Django Admin Customizing

description: Django Admin Customizing


code:
import os

fileSizeTupleList = []
largestSize = 0

for root, dirs, files in os.walk(os.curdir):
    for file in files:
        fileSizeTupleList.append((file, os.path.getsize(os.path.join(root, file))))

for fileName, fileSize in fileSizeTupleList:
    if fileSize > largestSize:
        largestSize = fileSize
        largestFile = fileName

print(largestFile, largestSize)

rawDescription: How to get largest file from this python 3 code?

description: Get largest file from this python 3 code


code:
class MyModel(db.Model):
    membership_id = db.Column(db.Integer, primary_key=True)

rawDescription: Is it possible to declare an optional and unique attribute for a class model in (Flask) SQLAlchemy?


code:
import sys
s = slice(0, sys.maxsize + 1)
s
s.stop
s.indices(sys.maxsize + 2)

rawDescription: Slice endpoints invisibly truncated

description: Slice endpoints invisibly truncated


code:
class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(200,100))
        self.panel =  wx.Panel(self, wx.ID_ANY)
        self.Bind(wx.EVT_KEY_DOWN, self.KeyDown)
        self.Bind(wx.EVT_KEY_UP, self.KeyDown)
        self.Bind(wx.EVT_CHAR, self.KeyDown)
        self.panel.SetFocus()

    def KeyDown(self, event=None):
        logging.warning("OnKeyDown event %s" % (event))

if __name__ == "__main__":
    app = wx.App(False)
    gui = MainWindow(None, "test")
    gui.Show()
    app.MainLoop()

rawDescription: wxpython capture keyboard events in a wx.Frame

description: Wxpython capture keyboard events in a wx.Frame


code:
import numpy as np

idx = t[np.abs(np.diff(data)) == 1]
lasting_times = idx[1::2] - idx[::2]

rawDescription: Getting delay time from a CSV data

description: Getting delay time from a CSV data


code:
list1 = [1,2,3,4,5,6,7,8,9,10]
list3 = []

for i in range(0, len(list1)-1, 2):
    firstnum = list1[i]
    secondnum = list1[i+1]
    print(firstnum, "+", secondnum)
    sumnum = firstnum + secondnum
    list3.append(sumnum)

print(list3)

rawDescription: Give a list of nums... Add every 2 numbers (ex: 1,2,3,4 -> 3, 7)?


code:
math.copysign(1, -4)
math.copysign(1, 3)

rawDescription: Why doesn't Python have a sign function?

description: Why doesn't Python have a sign function


code:
list_of_dicts = [{'column0':r0c0data, 'column1':r0c1data, 'column2':r0c2data},
                 {'column0':r1c0data, 'column1':r1c1data, 'column2':r1c2data}]

rawDescription: Add specific columns to a single row list (might be a little basic)


code: np.argmin(a[:, 1])

rawDescription: Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row


code: [list(t) for t in zip(*sorted(zip(*l)))]

rawDescription: Sorting a list of lists in python alphabetically by "column"


code:
class ParentClass:
    def f(self):
        print("Hi!");

class ChildClass(ParentClass):
    def f(self):
        super().f();
        print("Hello!");

rawDescription: Adding extra functionality to parent class method without changing its name


code: [(min(a), max(a)) for a in zip(*calib)]

rawDescription: Python 2.7 find min,max on list of lists


code: binarySearch( array, desiderata, iMin, midP - 1 )

rawDescription: Python function returns None (all trivial solutions checked and they do not work)


code:
new.foo = 'bar'
print(new.__dict__)
# {'foo': 'bar'}

rawDescription: Use class variables as instance vars?

description: Use class variables as instance vars


rawDescription: Fastest way to extract elements from a list that not matched condition in python


code: my_list_o_lists[0] = m0

rawDescription: Why can't I change a list within a list?

description: Why can't I change a list within a list


rawDescription: Convert data frame columns to dictionary


code:
from functools import partial

REPLACEMENTS = [
    partial(re.compile(r'(sample_pattern_1)').sub, r'REPLACE_1'),
    partial(re.compile(r'(sample_pattern_2)').sub, r'REPLACE_2'),
    # ..
    partial(re.compile(r'(sample_pattern_99)').sub, r'REPLACE_99'),
    partial(re.compile(r'(sample_pattern_100)').sub, r'REPLACE_100'),
]

rawDescription: List of compiled regexes in Python

description: List of compiled regexes in Python


code:
import functools

def memoize(f):
    @functools.wraps(f)
    def memoized(*args, _cache={}):
        # This abuses the normally-unwanted behaviour of mutable default arguments.
        if args not in _cache:
            _cache[args] = f(*args)
        return _cache[args]
    return memoized

rawDescription: add a decorate function to a class

description: Add a decorate function to a class


code: entity = WikiPage.query(WikiPage.your_id == 'hello').get()

rawDescription: Google App Engine: defining custom id and querying


code:
nil.to_i # 0
nil.to_f # 0.0 # But Integer(nil) or Float(nil) raise a TypeError.
nil.to_s # ""

rawDescription: Ruby use case for nil, equivalent to Python None or JavaScript undefined


code:
index = df.index
names = index.names
index = df.index.tolist()[:1]+[('x2','x2')]
df.index = pd.MultiIndex.from_tuples(index, names = names)

rawDescription: Replace a value in MultiIndex (pandas)

description: Replace a value in MultiIndex (pandas)


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

fig = plt.figure()
x = np.linspace(-10, 10, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
a = np.exp(-((X - 0) ** 2 + 3*(Y - 0) ** 2) / 4)
c = plt.contour(x, y, a)
plt.xlim(-10, 10)
plt.ylim(-2, 2)
plt.show()

rawDescription: matplotlib contour plot in given range

description: Matplotlib contour plot in given range


code:
item = normal_array[i]
'vn %.15f %.15f %.15f\n' % (item.x, item.y, item.z)

rawDescription: faster way to do .format()

description: Faster way to do .format()


code:
a
a.dtype
b = a.tolist()
b
type(b)
type(b[0])

rawDescription: Convert list of numpy.float64 to float in Python quickly


code:
A=np.append(A, [5,0])
A

rawDescription: Python: list vs. np.array: switching to use certain attributes


rawDescription: printing number of snmpwalk results

description: Printing number of snmpwalk results


code:
[Section]
my_option = 12.2
my_option2 = other_value

[Section2]
my_voption = my_value

rawDescription: "Standard" way of creating config file suitable for Python and Java together


rawDescription: String splitting in Python

description: String splitting in Python


code: clean = ''.join(l[:-1] for l in open('thefile.txt'))

rawDescription: Simple python/Regex problem: Removing all new lines from a file


rawDescription: Years to Decades

description: Years to Decades


code:
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

rawDescription: Store output of subprocess.Popen call in a string


code:
import re
with open('input.txt', 'r+') as f:
    newf = re.sub(r'(\s+[+-]?[0-9]+),([0-9]+\s+)',r'\1.\2', f.read())
    f.seek(0)
    f.write(newf)

rawDescription: match float with comma and then replace comma with dot?

description: Match float with comma and then replace comma with dot


code: list(map(range, lst[:-1], lst[1:]))

rawDescription: Generate ranges between pairs of consecutive values


code:
import os
newname = 'file_'+dt+'.txt'
os.rename('text.txt', newname)

rawDescription: Python - How To Rename A Text File With DateTime


code:
# Create my_type python objects
my_list = [my_type('a', '1', 'x'),
           my_type('b', '2', 'y'),
           my_type('c', '3', 'z'),
           ]

rawDescription: Passing in Oracle custom user types from Python/Django


code:
values_to_insert = [(1,"foo"), (2, "bar"), (3, "baz")]

cursor.executemany("""
    INSERT INTO some_table ('item_num', 'item_name')
    VALUES (?, ?)""", values_to_insert)

rawDescription: How do I use prepared statements for inserting MULTIPLE records in SQlite using Python / Django?

description: Use prepared statements for inserting MULTIPLE records in SQlite using Python / Django


code: pyversion

rawDescription: Sending JSON data over WebSocket from Matlab using Python Twisted and Autobahn


code:
import socket

def Main():
    UID = 1001
    sockets = []
    users = [] ## create usernames list
    sessionLimit = int(input("session Queue Limit: "))

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('192.168.1.74', 12127))
    s.listen(sessionLimit) ## listen for 1 connection at a time

    while True:
        c, addr = s.accept()
        sockets.append(c)
        users.append(c.recv(1024).decode('utf-8'))
        print("Connection from " + str(addr))

        data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
        if not data:
            break

        temp == data
        temp.split(" ")
        if temp[0] == "//": ## check to see if user has sent command
            if temp[1] == "msg":
                for i in range(len(users)):
                    if users[i] == temp[2]:
                        sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
        else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
            for sock in sockets:
                sock.send(data.encode('utf-8')) ## send to sockets[socket]

        ##print("From connected user: " + data)
        ##data = data.upper()
        ##print("Sending: " + data)
        ##c.send(data.encode('utf-8'))

        ## command listening
        commands = input("-> ")
        commands.split(" ")

        if commands[0] == "exit":
            c.close() ## close connection
        elif commands[0] == "/msg":
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
        """
        elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
        """
    c.close()

if __name__ == "__main__":
    Main()

rawDescription: Python imports module but doesn't recognize it when i initiate it?


code:
df
df["industry"] = pd.Series(d)
df

rawDescription: Add a new column to pandas data frame from dictionary


code: fun = (lambda x : (x + 1 if x < y else (lambda x : x - 1)))

rawDescription: Calling lambda-created functions returns functions?


code:
from string import Formatter
list(Formatter().parse('{foo} {bar:042d}'))

rawDescription: Dynamic fields in a Python string

description: Dynamic fields in a Python string


code:
from datetime import datetime

dates = (
    '2016-03-08 00:00:00',
    '2016-03-07 00:00:00',
    '2016-03-01 00:00:00',
    '2015-11-30 00:00:00',
    '2015-11-29 00:00:00',
    '2015-11-20 00:00:00',
)

#current_date = datetime.utcnow()
current_date = datetime(2016, 3, 8)
print('current', current_date)

for datestr in dates:
    updated_on = datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
    delta = (current_date - updated_on).days
    rank = max(0, 100 - delta)
    print('updated', updated_on, 'delta', delta, 'rank', rank)

rawDescription: getting difference between dates and create a rank in python

description: Getting difference between dates and create a rank in python


code:
from itertools import product

possible_observations = [
    ['Y'],             # X1
    ['N'],             # X2
    ['Y'],             # X3
    ['Y', 'N', 'NA'],  # X4
    range(1, 11)       # X5
]

print('\t'.join(('X1', 'X2', 'X3', 'X4', 'X5')))  # column headers
for row in product(*possible_observations):
    print('\t'.join(map(str, row)))

rawDescription: Creating a table with all possible variations of observations


code:
import re, os

input_file = 'input.txt'
output_file = 'output.txt'

with open(input_file, 'r') as f_in:
    with open(output_file, 'w') as f_out:
        for line in f_in.readlines():
            p = re.compile(r'[A-Z][a-z]+|\S+')

            matches = re.findall(p, line)
            matches = ' '.join(matches)

            f_out.write(matches+ os.linesep)

rawDescription: Separating joined words on uppercase letter


code:
def applyPlotStyle():
    plt.ylabel('Time(s)');

    plt.xticks(range(100), rotation=30, size='small')
    plt.grid(True)

def plotSeries():
    applyPlotStyle()
    plt.plot(xl, serial_full, 'r--')
    plt.plot(xl, acc, 'bs')
    plt.plot(xl, cublas, 'g^')

plt.suptitle('Matrix multiplication')
plt.subplot(211)
plotSeries()

plt.subplot(212)
plt.yscale('log')
plt.xlabel('Size')
plotSeries()

plt.show()

rawDescription: matplotlib subplots with same 'settings'

description: Matplotlib subplots with same 'settings'


code:
class DemoVar_addform(ModelForm):
    ...
    class Meta:
        model = DemoVar_model
        widgets = {
            'Welcome_sound': ShortNameClarableFileInput,
        }

rawDescription: Django : customizing FileField value while editing a model


code:
functions = {100:do_something,101:do_sth_different}
user_input = 100
try:
    functions[user_input]()
except KeyError:
    do_correct()

rawDescription: Pythonic way to check logics

description: Pythonic way to check logics


code:
import sys,os,time,logging

RUN_RELOADER = True

logger = logging.getLogger(__name__)

whitelist = ['webapp2', 'paste', 'logging']

# this code is from autoreloader
_mtimes = {}
_win = (sys.platform == "win32")
_error_files = []
_cached_modules = set()
_cached_filenames = []

def gen_filenames(only_new=False):
    global _cached_modules, _cached_filenames
    module_values = set(sys.modules.values())
    _cached_filenames = clean_files(_cached_filenames)
    if _cached_modules == module_values:
        # No changes in module list, short-circuit the function
        if only_new:
            return []
        else:
            return _cached_filenames + clean_files(_error_files)

    new_modules = module_values - _cached_modules
    new_filenames = clean_files(
        [filename.__file__ for filename in new_modules
         if hasattr(filename, '__file__')])

    _cached_modules = _cached_modules.union(new_modules)
    _cached_filenames += new_filenames
    if only_new:
        return new_filenames + clean_files(_error_files)
    else:
        return _cached_filenames + clean_files(_error_files)

def clean_files(filelist):
    filenames = []
    for filename in filelist:
        if not filename:
            continue
        if filename.endswith(".pyc") or filename.endswith(".pyo"):
            filename = filename[:-1]
        if filename.endswith("$py.class"):
            filename = filename[:-9] + ".py"
        if os.path.exists(filename):
            filenames.append(filename)
    return filenames

# this code is modified from autoreloader
def check_code_changed():
    global _mtimes, _win
    for filename in gen_filenames():
        stat = os.stat(filename)
        mtime = stat.st_mtime
        if _win:
            mtime -= stat.st_ctime
        if filename not in _mtimes:
            _mtimes[filename] = mtime
            continue
        if mtime != _mtimes[filename]:
            _mtimes = {}
            try:
                del _error_files[_error_files.index(filename)]
            except ValueError:
                pass
            mname = filename.split('/')[-1].split('.')[0]
            logger.info('CHANGED %s, RELOADING %s' % (filename,mname))
            try:
                reload(sys.modules[mname])
            except:
                pass

    return False

def reloader_thread():
    while RUN_RELOADER:
        check_code_changed()
        time.sleep(1)

rawDescription: webapp2: automatically reload code changes

description: Webapp2: automatically reload code changes


rawDescription: Python finite boundary Voronoi cells

description: Python finite boundary Voronoi cells


code: [v[0].rhs().n() for v in Vlist]

rawDescription: sagemath: Convert Fractions in Dictionaries in a list to Decimals for matplotlib

description: Sagemath: Convert Fractions in Dictionaries in a list to Decimals for matplotlib


code: x = zip(x['date'], x['users'])

rawDescription: How to structure data to easily build HTML tables in Flask

description: Structure data to easily build HTML tables in Flask


code: 'MATAT--LA-B'

rawDescription: Inserting missing portions of a sequence in python


code:
def iterate_fds(pid):
    dir = '/proc/'+str(pid)+'/fd'
    if not os.access(dir,os.R_OK|os.X_OK): return

    for fds in os.listdir(dir):
        for fd in fds:
            full_name = os.path.join(dir, fd)
            try:
                file = os.readlink(full_name)
                if file == '/dev/null' or \
                  re.match(r'pipe:\[\d+\]',file) or \
                  re.match(r'socket:\[\d+\]',file):
                    file = None
            except OSError as err:
                if err.errno == 2:
                    file = None
                else:
                    raise(err)

            yield (fd,file)

rawDescription: Check if a file is not open( not used by other process) in Python


code:
user_key = ndb.Key('Info_model', 'Bill')
user1 = user_key.get()

rawDescription: Retrieving Datastore Object With Key

description: Retrieving Datastore Object With Key


code: A = conv2(paddedTest, fil, 'valid');

rawDescription: Manipulations within sliding window functions (for image denoising)


code:
from __future__ import print_function # Python 2/3 compatibility

import sys
from time import sleep
from threading import Thread

if sys.version_info.major < 3:
    input = raw_input

def do_something():
    # doing the work
    sleep(1)

usrinpt = ''

def main():
    n = 1
    while usrinpt != 'stop':
        n += 1
        do_something()
    print('\nnumber of loops', n)

thread = Thread(target=main)
thread.start()

while True:
    print('Enter "stop" to terminate program')
    usrinpt = input().strip().lower()
    if usrinpt == 'stop':
        break

thread.join()

rawDescription: How to change parameters without stopping the program

description: Change parameters without stopping the program


code: users = User.objects(location = 'US').as_pymongo()

rawDescription: How to get dictionary object in Mongoengine Python?

description: Get dictionary object in Mongoengine Python


rawDescription: get python class parent(s)

description: Get python class parent(s)


rawDescription: Selecting only some values from dictionaries in list


rawDescription: pandas display results grouped by column

description: Pandas display results grouped by column


code: ks_summ = "K-S D-value = {}\nK-S p-value = {}".format(round(ks_D, 3), round(ks_p, 3))

rawDescription: How to set significant figures in pyplot annotation

description: Set significant figures in pyplot annotation


rawDescription: Regex to remove doubled double quotes from CSV


code:
from setuptools import Distribution
from setuptools.command.install import install

class OnlyGetScriptPath(install):
    def run(self):
        # does not call install.run() by design
        self.distribution.install_scripts = self.install_scripts

def get_setuptools_script_dir():
    dist = Distribution({'cmdclass': {'install': OnlyGetScriptPath}})
    dist.dry_run = True  # not sure if necessary, but to be safe
    dist.parse_config_files()
    command = dist.get_command_obj('install')
    command.ensure_finalized()
    command.run()
    return dist.install_scripts

rawDescription: Get entry point script file location in setuputils package?


code:
assert data1 == data2
assert dump_str != yaml_str

rawDescription: C# parse and change strings in yaml

description: C# parse and change strings in yaml


code: largest_key = max(my_dict, key=lambda x: x[1])

rawDescription: Return the largest value of a given element of tuple keys in a dictionary


code:
from django.shortcuts import redirect, render

def create_a_my_model(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST)
        if form.is_valid():
            my_model = form.save()
            return redirect(my_model) # if the model has `get_absolute_url()`
    else:
        form = MyModelForm()
    return render(request, 'template.html', {'form': form})

rawDescription: Django Forms vs Templates

description: Django Forms vs Templates


code: "My name is %s and I'm %.2f metres tall." % ('Li-aung',1.83211)

rawDescription: Basic decrement loop - PYTHON

description: Basic decrement loop - PYTHON


code:
class Foo(object):
    x = []

    def __init__(self):
        self.x = x

rawDescription: Something seems to be stuck in memory

description: Something seems to be stuck in memory


code: numpy.column_stack((A, A)).flatten()

rawDescription: Repeat each value of an array two times (numpy)


code:
import csv
with open('file2.txt') as file2:
    columns = [line.strip() for line in file2]
with open('file1.txt') as file1, open('out.txt', 'w') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    writer.writerow([''] + columns)
    for line in file1:
        row = line.strip()
        writer.writerow([row] + [1 if row==column else 0 for column in columns])

rawDescription: comparing two files using python to get a matrix

description: Comparing two files using python to get a matrix


code:
C = zip(A, B)
D = sorted(C, key=lambda x: x[1])
A2, B2 = zip(*D)

rawDescription: Merge two arrays into a matrix in python and sort


code:
A = np.zeros((100,100,100))
A[0,25:75,25:75] = 1
A[99,50,50] = 1

from math import sin, cos, atan2
dim = 100
for i99,j99 in np.swapaxes(np.where(A[dim-1]==1),0,1):
    for i0,j0 in np.swapaxes(np.where(A[0]==1),0,1):
        di = (i0-i99)
        dj = (j0-j99)
        dist = (di**2 + dj**2)**0.5
        ang = atan2(dj,di)
        for t in range(1,dim-1):
            ndist = dist * (1 - t/dim)
            pi = round(sin(ang)*ndist) + i99
            pj = round(cos(ang)*ndist) + j99
            A[t][pi][pj] = 1

rawDescription: merging 2D slices into 3D volume in python

description: Merging 2D slices into 3D volume in python


rawDescription: For loop item unpacking

description: For loop item unpacking


code: sum(list(filter(lambda x: x != '', aList)))/ len(aList)

rawDescription: My code works for a single list but not for a nested list. I need to improve it in means of functionality


code: min(x, key=lambda t: (t[1], -t[0]))

rawDescription: Return tuple with smallest y value from list of tuples


code:
with open('matrix.txt') as f:
    # Skip dims because redundant.
    f.readline()

    # Convert to int as we read.
    grid = [map(int, i.split()) for i in f]

# Define convenience vars (also for efficiency - rows is evaluated twice).
rows = grid[:-1]
totals = grid[-1]

# Verify row totals.
for (r, row) in enumerate(rows):
    assert sum(row[:-1]) == row[-1], 'row {}'.format(r)

# Verify column totals.
for (c, total) in enumerate(totals):
    assert sum(row[c] for row in rows) == total, 'col {}'.format(c)

rawDescription: python coding sum the rows and columns of a grid

description: Python coding sum the rows and columns of a grid


code:
from appscript import *
file_to_show = "/Applications/iTunes.app"
app("Finder").reveal(mactypes.Alias(file_to_show).alias)
#  Finder window of "Applications" folder appears with iTunes selected

rawDescription: Python "show in finder"

description: Python "show in finder"


rawDescription: Python matplotlib scientific axis formating


code:
L = [0, 23, 234, 89, None, 0, 35, 9]
[x for x in L if x is not None]

rawDescription: remove None value from a list without removing the 0 value

description: Remove None value from a list without removing the 0 value


code:
nStr = '000123000123'
pattern = '123'
count =0
flag=True
start=0
while flag:
    a = nStr.find(pattern,start)  # find() returns -1 if the word is not found,
                                  #start i the starting index from the search starts(default value is 0)
    if a==-1:          #if pattern not found set flag to False
        flag=False
    else:               # if word is found increase count and set starting index to a+1
        count+=1
        start=a+1
print(count)

rawDescription: Determining how many times a substring occurs in a string in Python


rawDescription: Updating array of dicts position field

description: Updating array of dicts position field


rawDescription: Writing Multiple Rows to CSV using Numpy Arrays without Brackets?


code: {"keys": ["ctrl+shift+e"], "command": "execute_external_program"},

rawDescription: Run external python script from Sublime Text passing active file as argument


code:
def parse_listing(self, response):
    # ... extract pdf urls
    for url in pdf_urls:
        yield Request(url, callback=self.save_pdf)

def save_pdf(self, response):
    path = self.get_path(response.url)
    with open(path, "wb") as f:
        f.write(response.body)

rawDescription: Should I create pipeline to save files with scrapy?


code:
class ProfilWizard(SessionWizardView):
  template_name = "gestionProfil/profil-step1.html"
  def done(self, form_list, **kwargs):
      form_data = process_form_data(self.request, form_list)
      return render_to_response('gestionProfil/profil.html', {'form_data': form_data})

  def process_form_data(self, request, form_list):
    form_data = [form.cleaned_data for form in form_list]
    username = form_data[0]['username']
    password = form_data[0]['password']
    email = form_data[0]['email']
    user = User.objects.create_user(username, email, password)
    user.first_name = form_data[1]['firstName']
    user.last_name = form_data[1]['lastName']
    user.save()
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)
    return form_data

rawDescription: Login after creating a user with formwizard-django


code:
def convert_arg_line_to_args(self, arg_line):
    for arg in arg_line.split():
        if not arg.strip():
            continue
        yield arg

rawDescription: using fromfile_prefix_chars with multiple arguments (nargs="*")

description: Using fromfile_prefix_chars with multiple arguments (nargs="*")


code: tmp_arr.append({"name": str(name[0])})

rawDescription: Select Postgresql Schemas in Python, output not as expected