code:
for i in range(2):
    Rxy[i], freqs_xy[i] = mlab.csd(x2[i], y2[i], NFFT=nfft, Fs=sfreq)

rawDescription: Splitted Array being filled in for loop by function calculating values from a splitted array


code:
import jsonpath_rw as jp
obj = {'y':{'x':{'g':{'t':0}}}}
jp.parse("`this`..t").find(jp.parse("y.x").find(obj)[0])[0].value

rawDescription: jsonpath_rw for Python: How to navigate relatively?

description: Jsonpath_rw for Python: How to navigate relatively


code: data = [ map( float, row) for row in csvreader]

rawDescription: get specific content from file python

description: Get specific content from file python


code:
vector<string> exch_symbols;
exch_symbols.push_back("1il");
exch_symbols.push_back("s5");
exch_symbols.push_back("b8");
exch_symbols.push_back("mn");

rawDescription: Concise lists/vectors in C++

description: Concise lists/vectors in C++


code:
import collections
class TraitsDict(collections.MutableMapping,dict):
    def __getitem__(self,key):
        return dict.__getitem__(self,key)
    def __setitem__(self, key, value):
        value = int(value)
        if not 1 <= value <= 10:
            raise ValueError('{v} not in range [1,10]'.format(v=value))
        dict.__setitem__(self,key,value)
    def __delitem__(self, key):
        dict.__delitem__(self,key)
    def __iter__(self):
        return dict.__iter__(self)
    def __len__(self):
        return dict.__len__(self)
    def __contains__(self, x):
        return dict.__contains__(self,x)

class Person(object):
    def __init__(self):
        self.traits=TraitsDict({'happy': 0, 'worker': 0, 'honest': 0})

p=Person()
print(p.traits['happy'])
# 0

p.traits['happy']=1
print(p.traits['happy'])
# 1

p.traits['happy']=14
# ValueError: 14 not in range [1,10]

rawDescription: Correct useage of getter/setter for dictionary values


code:
pattern = "()(this)(.*)(string)"
re.sub(pattern,
       lambda m: ''.join('<markup>%s</markup>' % s if n % 2 == 1
                         else s for n, s in enumerate(m.groups())),
       text)

rawDescription: replacing all regex matches in single line

description: Replacing all regex matches in single line


code:
from textwrap import wrap

text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."

wraped_text = "\n".join(wrap(text, 80)) # 80 is line width

t.textLines(wraped_text)

rawDescription: Reportlab new line in a long line

description: Reportlab new line in a long line


rawDescription: Remove unicode [u']

description: Remove unicode [u']


code:
with open('c:/tmp/textfile.TXT') as f:
    haystack = f.read()

if not haystack:
    sys.exit("Could not read haystack data :-(")

with open('c:/tmp/list.txt') as f:
    for needle in (line.strip() for line in f):
        if needle in haystack:
            print(needle, ',one_sentence')
        else:
            print(needle, ',another_sentence')

rawDescription: Python: search for strings listed in one file from another text file?


code:
def merge(*dicts):
    """Recursively merge the argument dictionaries."""
    out = {}
    for dct in dicts:
        for key, val in dct.items():
            try:
                out[key].append(val) # 3.
            except AttributeError:
                if out[key] == val:
                    pass # 2.
                elif isinstance(out[key], dict):
                    out[key] = merge(out[key], val) # 4.
                else:
                    out[key] = [out[key], val] # 5.
            except KeyError:
                out[key] = val # 1.
    return out

rawDescription: Merge duplicate entries in array of dict


code:
val1 = winsound.PlaySound("C:/Interactive Program/LIP Source Files/skyisup.wav", 2)
t1 = threading.Thread(target=val1, args=(None))
val2 = lipgui.msgbox("The sky is up.")
t2 = threading.Thread(target=val2, args=(None))

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

description: Run 2 different processes at once in Python


code: sum(a(*perm) for perm in permutations((j, j, k, l)))

rawDescription: Python : defining function that returns summation of all permutations


code:
weight.stack().replace(dict(zip(nodes.Label, nodes.Id))).unstack()
d = dict(zip(nodes.Label, nodes.Id))
weight.applymap(lambda x: d.get(x,x))

rawDescription: Replacing Names with Index From Separate File using Pandas


code:
import urllib2

CHUNK = 16 * 1024
file_checker = None
print("Please Wait...")
while True:
    try:
        req = urllib2.Request('http://www.voidspace.org.uk')
        response = urllib2.urlopen(req, timeout=1)
        print("Connected")
        with open("outdata", 'wb+') as out_data:
            while True:
                chunk = response.read(CHUNK)
                file_checker = open("outdata")
                if chunk and chunk not in file_checker.readlines():
                 out_data.write(chunk)
                else:
                    break
        break
    except urllib2.URLError:
        print("Connection Error!")
        print("Connecting again...please wait")
file_checker.close()
print("done")

rawDescription: Urllib2 Python - Reconnecting and Splitting Response


code:
n = 1000000
list_bar = [ None ] * n
for i in xrange(n):
    list_bar[i] = foo()

rawDescription: Python list of Objects taking up too much memory


code:
with open("datafile") as f:
    for line in f:  #Line is a string
        #split the string on whitespace, return a list of numbers
        # (as strings)
        numbers_str = line.split()
        #convert numbers to floats
        numbers_float = [float(x) for x in numbers_str]  #map(float,numbers_str) works too

rawDescription: Reading multiple numbers from a text file


code:
class Foo:
    pass

foo = Foo()
setattr(foo, 'bar', 42)
print(foo.bar)  # 42

rawDescription: Dynamically creating namespaces in Python


code: [list(accumulate(col)) for col in cols]

rawDescription: Cumulative addition whilst looping over a list


code:
account = AccountDetails.objects.raw(
    "SELECT * FROM yourapp_accountdetails FOR UPDATE WHERE user = %s", [user.id]
)

rawDescription: select_for_update kind of functionality in django 1.3 to avoid race condition

description: Select_for_update kind of functionality in django 1.3 to avoid race condition


code:
def readcountries():
    with open("countries.txt") as fh:
        rows = []
        for line in fh:
            name, area, population = line.split(',')
            rows.append([name.strip(), float(area), int(population)])

rawDescription: python binary search and file i/o

description: Python binary search and file i/o


rawDescription: Extract a particular number followed by a command line argument variable from a string in python


rawDescription: python - name of np array variable as string

description: Python - name of np array variable as string


code:
def encode (X):
    if len (X.shape) < 2:
        X = X.reshape (1, -1)

    tflearn.is_training (False, model.session)
    res = model.session.run (HIDDEN_STATE, feed_dict={INPUT.name:X})
    return res

def decode (X):
    if len (X.shape) < 2:
        X = X.reshape (1, -1)

    #just to pass something to place_holder
    zeros = np.zeros ((X.shape [0], train.shape [1]))

    tflearn.is_training (False, model.session)
    res = model.session.run (OUTPUT, feed_dict={INPUT.name:zeros, HIDDEN_STATE.name:X})
    return res

rawDescription: How to separate autoencoder into encoder and decoder (thensorflow + tflearn)

description: Separate autoencoder into encoder and decoder (thensorflow + tflearn)


code: sql = """SELECT MAX(id) FROM profiles"""

rawDescription: Converting a tuple into an integer in python 3?


code:
all_data_dict = {'abc':all_data, 'cde':all_data, 'fgh':all_data}
ids = set(['abc', 'fgh'])
dict(filter(lambda value: value[0] in ids, all_data_dict.items()))

rawDescription: Filtering a list based on a second list

description: Filtering a list based on a second list


rawDescription: How to create (in Flask using flask-SA etc.) an SQLite DB file with metadata.create_all(..)

description: Create (in Flask using flask-SA etc.) an SQLite DB file with metadata.create_all(..)


code:
class Login(webapp2.RequestHandler):

    def get(self, provider=None):

        # Show the login page and allow the user to select a provider
        if not provider:
            template = JINJA_ENVIRONMENT.get_template("login.html")
            self.response.write(template.render())

        # Only for admin login.  Use app engine login.
        elif provider == "gae":
            self.redirect(users.create_login_url("/"))

        # The user has selected a provider so we do oauth2 login.
        else:
            session = Webapp2Session(self, session=self.session)
            result = authomatic.login(Webapp2Adapter(self),
                                      provider,
                                      session=session,
                                      session_saver=session.save)
            ...

rawDescription: GAE, oauth2, and admin users

description: GAE, oauth2, and admin users


code:
from matplotlib.ticker import FixedLocator

majorLocator   = FixedLocator(np.linspace(20,40,5))
minorLocator   = FixedLocator(np.linspace(19,41,23))

rawDescription: Minor ticks with only major tick labels are shown


code:
from django.template.loader import render_to_string

# previous code ...
template_file = 'where/is/my/template.txt'
context_data = {'primary-firstname': 'Mr. Johnson',
                'product': 'banana',
                'maturity_date': '11-17-2011',
                'financial institution': 'something else'}
message = render_to_string(template_file, context_data)
# here you send the message to the user ...

rawDescription: Replacing text with variables

description: Replacing text with variables


code:
class Bigclass(object):

    from classdef1 import foo, bar, baz, quux
    from classdef2 import thing1, thing2
    from classdef3 import magic, moremagic
    # unfortunately, "from classdefn import *" is an error or warning

    num = 42   # add more members here if you like

rawDescription: Is there any Python equivalent to partial classes?


code:
def f(x,e,m):
    X = x
    E = e
    Y = 1
    while E > 0:
        if E % 2 == 0:
            X = (X * X) % m
            E = E/2
        else:
            Y = (X * Y) % m
            E = E - 1
    return Y

rawDescription: i was solving a sequence of large numbers, but python shell stop responding

description: I was solving a sequence of large numbers, but python shell stop responding


code:
{'Name': 'Nick', 'Designation': 'F4321', 'Type': 'Subject', 'Total': '29', 'First-term assessment': '10', 'Second-term assessment': '19', 'Description': 'D1234'}
{'Name': 'HTML', 'Designation': 'F4321', 'Type': 'Unit', 'Total': '', 'First-term assessment': '18', 'Second-term assessment': '', 'Description': 'D1234-1'}
{'Name': 'Tags', 'Designation': 'F4321', 'Type': 'Topic', 'Total': '', 'First-term assessment': '18', 'Second-term assessment': '', 'Description': 'First Term'}
{'Name': 'Review of representation of HTML', 'Designation': '', 'Type': 'Subtopic', 'Total': '', 'First-term assessment': '', 'Second-term assessment': '', 'Description': ''}

rawDescription: Python script reading from a csv file

description: Python script reading from a csv file


code: [i for i in range(20) if re.match(r'(A{2,})\1+$', 'A' * i)]

rawDescription: Composite number of occurrences of letter with regex


code:
from collections import Counter, OrderedDict
c = Counter(e for l in data for e in l)
c

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:
def setUp(self):
    self.username = "user"
    self.password = "Test_1234_pass"
    self.real_get_password_from_keyboard = pass_helper._get_password_from_keyboard
    pass_helper._get_password_from_keyboard = Mock(return_value=self.password)

def tearDown(self):
    pass_helper._get_password_from_keyboard = self.real_get_password_from_keyboard

def test_password(self):
    password = pass_helper._get_password_from_keyboard(self.username)
    self.assertEqual(password, self.password)

rawDescription: Python undo method mock

description: Python undo method mock


code:
from itertools import product

a = [1,2,3,4]
b = [6,7]
[dict(zip(('a','b'), (i,j))) for i,j in product(a,b)]

rawDescription: Combining all combinations of two lists into a dict of special form


code:
def destroy_the_universe():
    raise RuntimeError("Armageddon")

def useful_line():
    print("Kittens-r-us")

print(10)
import pdb; pdb.set_trace()
destroy_the_universe()
useful_line()

rawDescription: Python-pdb skip code (as in "not execute")


code:
def merge(left,right):
    left = iter(left)
    right = iter(right)
    left_val = next(left)
    right_val = next(right)
    try:
        while True:
            if left_val <= right_val:
                yield left_val
                left_val = next(left) #left.next() in python2
            else:
                yield right_val
                right_val = next(right)
    except StopIteration: #I have exhausted one of the iterators
        if left_val <= right_val:
            #left list depleted
            yield right_val
            for i in right: yield i #or use yield from right, if your python is fancy enough
        else:
            #right list depleted
            yield left_val
            for i in left: yield i

rawDescription: Pythonic style for stepping through two lists and avoiding idx?


code:
class ShadingInfoEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):
        jsonPlaceholderNames = (("_ShaderInfo", ShaderInfo),
                            ("_ShapeInfo", ShapeInfo),
                            ("_NodeInfo", NodeInfo))
        for jsonPlaceholderName, cls in customIterEncode:
            if isinstance(o, cls):
                yield '{"' + jsonPlaceholderName+ '": '
                for chunk in super(ShadingInfoEncoder, self)._iterencode(o, markers):
                    yield chunk
                yield '}'
                break
        else:
            for chunk in super(ShadingInfoEncoder, self)._iterencode(o, markers):
                yield chunk

rawDescription: Overriding nested JSON encoding of inherited default supported objects like dict, list


code:
interestingAttrs = ["type", ...] #all attributes you need
#inside the if in startElement
#python 2:
d = dict()
for a in interestingAttrs: d[a] = attrs[a]

#python 3:
d = {a: attrs[a] for a in interestingAttrs}

rawDescription: How to get tag name and its corresponding attributes as a key:value pair from a xsd file

description: Get tag name and its corresponding attributes as a key:value pair from a xsd file


code:
class Building:
    def __init__(self,posX,posY,color,name):
        self.hud = Hud(0,0,name)

rawDescription: how to reference an attribute before it exists python

description: Reference an attribute before it exists python


rawDescription: how to retrieve field value (values are itself string)in given line using regular expression in python

description: Retrieve field value (values are itself string)in given line using regular expression in python


rawDescription: Python replace middle digits with commas thousand separator


code:
import json
def getPhones(self,**kw):
        phones = json.loads(kw['phones'])
        ...

rawDescription: python unpack a dict from json

description: Python unpack a dict from json


code:
from django import forms
from my_project.my_app.models import Beverage

class InventoryForm(forms.ModelForm):
    units_reported = forms.IntegerField()
    class Meta:
        model = Beverage
        fields = ('name', 'id')

rawDescription: Django: creating dynamic forms

description: Django: creating dynamic forms


rawDescription: How to match a date pattern in strings

description: Match a date pattern in strings


rawDescription: set a pandas datetime64 pandas dataframe column as a datetimeindex without the time component

description: Set a pandas datetime64 pandas dataframe column as a datetimeindex without the time component


code:
from itertools import takewhile

def lstripped(s):
    return ''.join(takewhile(str.isspace, s))

def rstripped(s):
    return ''.join(reversed(tuple(takewhile(str.isspace, reversed(s)))))

def stripped(s):
    return lstripped(s), rstripped(s)

rawDescription: Function to return the stripped whitespace of a string


rawDescription: Collecting like term of an expression in Sympy


code:
def f(n):
    return x%n

if all(f(element) for element in lst):
    ...

rawDescription: Removing Redundancies/Condensing Code

description: Removing Redundancies/Condensing Code


code:
def present(a):
    # test whether an argument is 'present' or not
    # simple case, just check whether it is the default None or not
    if a is not None:
        return True
    else:
        return False

# sample namespace from parser
args = argparse.Namespace(x1='one',x2=None,y1=None,y2=3)

# a nested list defining the argument groups that need to be tested
groups=[[args.x1,args.x2],[args.y1,args.y2]]

# a test that applies 'any' test to the inner group
# and returns the number of groups that are 'present'
[any(present(a) for a in g) for g in groups].count(True)

rawDescription: Does argparse support multiple exclusive arguments?


code:
df =pd.DataFrame( range(200), index = pd.date_range('12/1/2012', periods=200, freq='D'))

from pandas.tseries.offsets import CustomBusinessMonthBegin
from pandas.tseries.holiday import USFederalHolidayCalendar
bmth_us = CustomBusinessMonthBegin(calendar=USFederalHolidayCalendar())

df.resample(bmth_us, how='mean')

rawDescription: Convert daily pandas stock data to monthly data using first trade day of the month


code:
x = os.system("echo 'shankar'")
print(x)

rawDescription: Stop a command line command in script

description: Stop a command line command in script


code:
True
False

rawDescription: Is there a significant difference between: if not a == 'bar' and if a != 'bar'?


code:
'Starting in {Duration}, the {Noun} will be {Adjective}'.format(Duration='24 hours', Noun='Coffee Maker', Adjective='broken')
'Starting in %(Duration)s, the %(Noun)s will be %(Adjective)s' % dict(Duration='24 hours', Noun='Coffee Maker', Adjective='broken')

rawDescription: Replacing words in a sentence from database (Python/Django)


code:
def createSphere(r, N=10):
    lst = []
    for phi in [(pi*i)/(N-1) for i in range(N)]:
        M = int(sin(phi)*(N-1))+1
        for theta in [(2*pi*i)/M for i in range(M)]:
            x = r * sin(phi) * cos(theta)
            y = r * sin(phi) * sin(theta)
            z = r * cos(phi)
            lst.append((x, y, z))
    return lst

rawDescription: Python program to create sphere coordinates not working


code:
xscan = concatenate([xgrid[::(-1)**i] for i in range(len(ygrid))])
yscan = repeat(ygrid, len(xgrid))

rawDescription: Raster scan pattern python

description: Raster scan pattern python


rawDescription: Fill in missing values with nearest neighbour in Python numpy masked arrays?


code: df['std'].resample('D', how='mean')

rawDescription: Python: look back n days rolling standard deviation


code:
def test(this=1, that=2):
    ...

rawDescription: Python: setting configuration parameters


code:
[{u'Price': u'21.00', u'Code': u'900321', u'Description': u'TIG 2.4MM TUNGSTEN (EACH ROD)', u'Line Total': u'42.00', u'Quantity': u'2'},
{u'Price': u'2.60', u'Code': u'92.01.15.08', u'Description': u'BINZEL .8MM MIG TIPS MB15', u'Line Total': u'15.60', u'Quantity': u'6'}]

rawDescription: Merge every Every 6 dictionary into single dictionary of List


code:
class Event(object):

    def __init__(self, metadata, action):
        pass

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


rawDescription: creating list of random numbers in python

description: Creating list of random numbers in python


code: players.sort(key=lambda p: float(p[1]) / float(p[2]))

rawDescription: querying an sqlite3 database

description: Querying an sqlite3 database


code: np.where(k > np.min(k[np.where(np.diff(np.sign(np.diff(k))) > 0)[0] + 1]))[0][0]

rawDescription: Is there a fast way to compare one element in a numpy array to the rest of the elements in that array?


code:
for index, entry in enumerate(datas):
    ...

rawDescription: Function awfully slow

description: Function awfully slow


code:
from django.core.urlresolvers import reverse

my_url = reverse('ACB')

rawDescription: Get urls in views.py - python django

description: Get urls in views.py - python django


code: indices = np.random.choice(x.size, 2, replace=False)

rawDescription: Numpy Choose Elements from 2 arrays

description: Numpy Choose Elements from 2 arrays


code:
e_value  = float(linearr[6])

if e_value > 1.0e-10:
  continue

rawDescription: e value script program

description: E value script program


code: indices = l_distv("ab", a) < 2 # you wanted to move evrything below 2 at the front

rawDescription: Efficient way to sort an array with a condition


code:
from first import replaceProgramFilesPath
# now replaceProgramFilesPath can be used in this script.

rawDescription: Is there a way to convert code to a string and vice versa in Python?


code:
from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

rawDescription: Python 2.6 - Parse arguments

description: Python 2.6 - Parse arguments


code:
output = {}
for line in input:
    key, values = line.strip().split('=', 1)
    data = values.split(',')
    output['record' + key[5:]] = dict(name=data[0], addr=data[1], phone=data[2])

rawDescription: How do I convert strings separated by comma into dictionary in python?

description: Convert strings separated by comma into dictionary in python


code:
dic = {}
dic["a", 1] = 0
dic["a", 2] = 2
dic["b", 1] = 5
dic["b", 2] = 0
...

for [co, l], ch in dic.items():
    if ch == 0:
        print("The value for key {}, {} was 0".format(co, l))

rawDescription: For loops in a dictionary and if statement


code:
gridTiles = []

for r in range(totalSpaces):
    row = []

    for c in range(totalSpaces):
        tiles = Rectangle(Point(borderSet + r * spaceSize, borderSet + c * spaceSize), Point(borderSet + (r + 1) * spaceSize, borderSet + (c + 1) * spaceSize))
        tiles.setWidth(2)
        tiles.draw(board)

        row.append(tiles)
    gridTiles.append(row)

rawDescription: Python 3.2.1: Can't Index Shape, Need to Access a Particular Rectangle Later


code:
from django.core.files import ContentFile
from django.conf import settings
from zipfile import ZipFile

def save(self, delete_zip_import=True, *args, **kwargs):
    """
    If a zip file is uploaded, extract any images from it and add
    them to the gallery, before removing the zip file.
    """
    super(BaseGallery, self).save(*args, **kwargs)
    if self.zip_import:
        zip_file = ZipFile(self.zip_import)
        for name in zip_file.namelist():
            data = zip_file.read(name)
            try:
                from PIL import Image
                image = Image.open(BytesIO(data))
                image.load()
                image = Image.open(BytesIO(data))
                image.verify()
            except ImportError:
                pass
            except:
                continue
            name = os.path.split(name)[1]
            # You now have an image which you can save
            path = os.path.join(settings.MEDIA_ROOT, "galleries",
                                    native(str(name, errors="ignore")))
            saved_path = default_storage.save(path, ContentFile(data))
            self.images.create(file=saved_path)
        if delete_zip_import:
            zip_file.close()
            self.zip_import.delete(save=True)

rawDescription: Django-admin: images in zip file and inserting each image info in a database


code:
trip_id, service_id, route_id, shape_id= range(4)
first_trip_id= my_table_no_headers[0][trip_id]

rawDescription: How can I store a 2D array in python, like table in MySQL?

description: Store a 2D array in python, like table in MySQL


rawDescription: How to make shift('w','f') return 'b'?

description: Make shift('w','f') return 'b'


code:
def xyz(self, other):
    if isinstance(other, self.__class__):
       ...

rawDescription: inheritance in python - how to make a method both a classmethod and a regular method?

description: Inheritance in python - how to make a method both a classmethod and a regular method


code:
from string import punctuation

def unique_func(sentence, number):
    cnt = 0
    sentence = sentence.translate(None, punctuation).lower()
    for w in set(sentence.split()):
        if len(w) >= number:
            cnt += 1
    return cnt

rawDescription: Counting unique words of a minimum length in a string


rawDescription: Numpy extract arbitrary subarray along one axis


code:
if test in ('a', 'b', 'c', 'd'): #tuple
   do_something()

rawDescription: Is it possible to check if a value is equal to another in python quickly when referring it to a list?


code:
import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)

rawDescription: Issues with time.sleep and Multithreading in Python


code:
from some_other_module import a, b
ainst = a("Wow")
binst = b("Hello")
ainst.speak()
binst.speak()

rawDescription: Overwrite Python library dependencies

description: Overwrite Python library dependencies


code:
string = '10M26S'
re.findall(r'(\d+)S',string)
string = '18S8M10S'
re.findall(r'(\d+)S',string)
string = '7S29M'
re.findall(r'(\d+)S',string)

rawDescription: Extract digits from string by condition

description: Extract digits from string by condition


rawDescription: Regular expression in python to capture first operator


code:
import zope.schema
import zope.interface
from zope.schema.vocabulary import SimpleVocabulary

emailVocab = SimpleVocabulary.fromItems((
    ('sysn', u'System notifications (strongly recommended)'),
    ('mark', u'Marketing emails'),
    ('offe', u'Special offers')))

def default_email():
    return [u'Special offers']  # example

class IEmailPreference(zope.interface.Interface):

    # ...

    email_optin = zope.schema.List(
        title=u'',
        description=u'',
        required=False,
        value_type=zope.schema.Choice(source=emailVocab),
        defaultFactory=default_email,
    )

rawDescription: Pre-tick specific checkbox in z3c.form list


code: [item for item in Arr1 if item not in Arr2]

rawDescription: Pythonic way to write for x in Y and not in Z


code:
from collections import defaultdict
d = defaultdict(int)
for x in items:
    d[x] += 1

print(min(elems, key=d.__getitem__))
# or print(min(elems, key=lambda x: d[x])) - gives same result

rawDescription: Python: Find the list element that is contained least times in another list


code:
import weakref

class CSVGenerator:
    CACHE = {}
    CACHELOCK = threading.Lock()

    def __new__(cls, csvfilename):
        canonicalname = os.path.realpath(csvfilename)
        newself = super().__new__(cls)
        with cls.CACHELOCK:
            self = cls.CACHE.setdefault(canonicalname, newself)
            if newself is self:
                # First time we opened this file, clear file and initialize instance
                with open(canonicalname, 'w') as f:
                    pass
                self.csvfilename = canonicalname
                self.appendlock = threading.Lock()
        return self

    def generateCSVfile(self, fileName, fileDescription, fileLocation, md5Hash):
        with newself.appendlock, open(self.csvfilename, 'a', newline='') as csvfile:
            createRow = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
            # Perform writes to file

rawDescription: open a CSV file once and write several lines to it from a loop python

description: Open a CSV file once and write several lines to it from a loop python


code:
pattern = """
    (?:January|February|March|April|May|June|
       July|August|September|October|November|December)
    ,[ ]
    [0-3]?\d
    ,[ ]
    (?:19|20)\d\d
"""

rawDescription: How do I put all the strings that match my regular expression into a list in Python?

description: Put all the strings that match my regular expression into a list in Python


rawDescription: excluding lists that have more than one x

description: Excluding lists that have more than one x


code:
def add_score(user, score, text_file):
    lines = text_file.splitlines()
    count = len(lines)
    user_exists = False
    user_index = -1
    num_scores = 3
    user_num_scores = 0
    for i in range(count-1):
        line = lines[i]
        if user == line:
            # user previous scores start after here
            user_exists = True
            user_index = i
            break

    if not user_exists:
        # user does not exist, create by appending
        lines.append(user)
        lines.append(str(score))
    else: # user exists, fix the scores
        j=1
        while j <= num_scores:
            line = lines[user_index+j]
            j += 1
            if line.isdigit():
               # user score line
               user_num_scores +=1
        if user_num_scores == num_scores:
            for i in range(1,num_scores-1): lines[user_index+i] = lines[user_index+i+1] # shift up
            lines[user_index+num_scores] = str(score) # add the latest score
        else: # just append/insert the score, as the previous scores are less than num_scores
            lines.insert(user_index+user_num_scores, str(score))

    return "\n".join(lines)   # return the new text_file back

rawDescription: Deleting and inserting a score into a text file form python


code:
class C(object): pass
a = C()
class C(object): pass
isinstance(a, C)

rawDescription: isinstance() is not behaving as I expect

description: Isinstance() is not behaving as I expect


code: [n for n in line.strip().split(' | ')]

rawDescription: Only the last row is inserted to my sql database from a text file after splitting it with PYTHON


code:
x = ['a', 'b']
y = [1, 2]
z = ['orange', 'apple']
[j for i in zip(x,y,z) for j in i]

rawDescription: Can anyone help me with the following 2.7 Python assignment? [Adding/Sorting List]


code:
import unidecode
from unidecode import unidecode
unidecode(u'διακριτικός')

rawDescription: How to make Django slugify work properly with Unicode strings?

description: Make Django slugify work properly with Unicode strings


code:
def merge(a, b):
    max_offset = len(b)  # can't overlap with greater size than len(b)
    for i in reversed(range(max_offset+1)):
        # checks for equivalence of decreasing sized slices
        if a[-i:] == b[:i]:
            break
    return a + b[i:]

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


code:
#!/usr/bin/env python3
# vim:fileencoding=utf-8:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Last modified: 2015-09-22 21:41:17 +0200
#
# To the extent possible under law, Roland Smith has waived all copyright and
# related or neighboring rights to vid2mp4.py. This work is published from the
# Netherlands. See http://creativecommons.org/publicdomain/zero/1.0/

"""Convert all video files given on the command line to H.264/AAC streams in
an MP4 container."""

__version__ = '1.1.1'

from multiprocessing import cpu_count
from time import sleep
import logging
import os
import subprocess
import sys

def main(argv):
    """
    Entry point for vid2mp4.

    Arguments:
        argv: All command line arguments.
    """
    if len(argv) == 1:
        binary = os.path.basename(argv[0])
        print("{} version {}".format(binary, __version__), file=sys.stderr)
        print("Usage: {} [file ...]".format(binary), file=sys.stderr)
        sys.exit(0)
    logging.basicConfig(level="INFO", format='%(levelname)s: %(message)s')
    checkfor(['ffmpeg', '-version'])
    vids = argv[1:]
    procs = []
    maxprocs = cpu_count()
    for ifile in vids:
        while len(procs) == maxprocs:
            manageprocs(procs)
        procs.append(startencoder(ifile))
    while len(procs) > 0:
        manageprocs(procs)

def checkfor(args, rv=0):
    """
    Make sure that a program necessary for using this script is available.

    Arguments:
        args: String or list of strings of commands. A single string may
            not contain spaces.
        rv: Expected return value from evoking the command.
    """
    if isinstance(args, str):
        if ' ' in args:
            raise ValueError('no spaces in single command allowed')
        args = [args]
    try:
        rc = subprocess.call(args, stdout=subprocess.DEVNULL,
                             stderr=subprocess.DEVNULL)
        if rc != rv:
            raise OSError
    except OSError as oops:
        outs = "required program '{}' not found: {}."
        logging.error(outs.format(args[0], oops.strerror))
        sys.exit(1)

def startencoder(fname):
    """
    Use ffmpeg to convert a video file to H.264/AAC streams in an MP4
    container.

    Arguments:
        fname: Name of the file to convert.

    Returns:
        A 3-tuple of a Process, input path and output path.
    """
    basename, ext = os.path.splitext(fname)
    known = ['.mp4', '.avi', '.wmv', '.flv', '.mpg', '.mpeg', '.mov', '.ogv']
    if ext.lower() not in known:
        ls = "File {} has unknown extension, ignoring it.".format(fname)
        logging.warning(ls)
        return (None, fname, None)
    ofn = basename + '.mp4'
    args = ['ffmpeg', '-i', fname, '-c:v', 'libx264', '-crf', '29', '-flags',
            '+aic+mv4', '-c:a', 'libfaac', '-sn', ofn]
    with open(os.devnull, 'w') as bitbucket:
        try:
            p = subprocess.Popen(args, stdout=bitbucket, stderr=bitbucket)
            logging.info("Conversion of {} to {} started.".format(fname, ofn))
        except:
            logging.error("Starting conversion of {} failed.".format(fname))
    return (p, fname, ofn)

def manageprocs(proclist):
    """
    Check a list of subprocesses tuples for processes that have ended and
    remove them from the list.

    Arguments:
        proclist: a list of (process, input filename, output filename)
    tuples.
    """
    nr = '# of conversions running: {}\r'.format(len(proclist))
    logging.info(nr, end='')
    sys.stdout.flush()
    for p in proclist:
        pr, ifn, ofn = p
        if pr is None:
            proclist.remove(p)
        elif pr.poll() is not None:
            logging.info('Conversion of {} to {} finished.'.format(ifn, ofn))
            proclist.remove(p)
    sleep(0.5)

if __name__ == '__main__':
    main(sys.argv)

rawDescription: ffmpeg converts anything to mp4

description: Ffmpeg converts anything to mp4


code:
ITEM_PIPELINES = {
    'yourproject.pipelines.DuplicatesPipeline': 300,
}

rawDescription: DropItem if parsed url contains key words (pipeline)


code:
import netsnmp
oid = netsmp.Varbind('1.3.6.1.2.1.6.13.1.1.0.0.0.0.80.0.0.0.0.0')
result = netsnmp.snmp(oid,
                      Version = 2,
                      DestHost="192.168.10.1",
                      Community="public")

rawDescription: Check ports with SNMP (net-snmp)

description: Check ports with SNMP (net-snmp)


code:
from app1.api.my_module import API
from common.api.login_api import LoginAPI

class Foo():
    ...

rawDescription: How to organize a multiple apps server with CherryPy?

description: Organize a multiple apps server with CherryPy


rawDescription: Change only one element in list to float or other transformation


code:
with open(inputfile) as infile, open(outputfile, 'wb') as outfile:
    csvwriter = csv.writer(outfile)
    csvwriter.writerows(per_section(infile))

rawDescription: creating list from separated lines

description: Creating list from separated lines


code:
if __name__ == "__main__":
    start = time.time()
    fetch_hosts(['a', 'b', 'c', 'd', 'e'])
    end = time.time()
    print("Total time: {}".format(end-start))

rawDescription: Python : efficiency concerns in parallel async calls to fetch data from web services


code:
cids = [c['id'] for c in completes]
for project in projects:
    project["complete"] = project["id"] in cids

rawDescription: Update list of dictionaries based on another list of dictionaries


rawDescription: order all row according to contents of a row

description: Order all row according to contents of a row


rawDescription: How should python dictionaries be stored in pytables?


code:
def targets(x,y):
    yield (x,y) # Center
    yield (x+1,y) # Left
    yield (x-1,y) # Right
    yield (x,y+1) # Above
    yield (x,y-1) # Below
    yield (x+1,y+1) # Above and to the right
    yield (x+1,y-1) # Below and to the right
    yield (x-1,y+1) # Above and to the left
    yield (x-1,y-1) # Below and to the left

rawDescription: PIL Best Way To Replace Color?

description: PIL Best Way To Replace Color


rawDescription: Multiple dot syntax in python and matplotlib


code:
size = (n + n + 1) * (2 * m + 1)
histogram = zeros(size, Int)

rawDescription: better algorithm for checking 5 in a row/col in a matrix

description: Better algorithm for checking 5 in a row/col in a matrix


code:
A
from scipy.sparse import csc_matrix
C = csc_matrix(A)
C.indptr
C.indices
D = [set(C.indices[C.indptr[i]:C.indptr[i+1]]) for i in range(C.shape[1])]
D

rawDescription: Fastest way from logic matrix to list of sets


code: df2 = df1.dropna()

rawDescription: Python pandas: How do I drop specific levels in a hierarchical index if any column values are NaN?


code: result['Last']

rawDescription: pandas - merging multiple DataFrames

description: Pandas - merging multiple DataFrames


code:
# Assign a dict to the name `sub_dict`
sub_dict = base_system_dict["base_system"]
if name == sub_dict["name"]:
    # Update *that name* to point at a new dictionary
    sub_dict = changed_json_dict

rawDescription: Does changing a global variable in a recursive function change the top level


code: a.reshape(-1, 1)

rawDescription: Add two arrays without using for. Python


code:
unique,pos = np.unique(A,return_inverse=True) #Finds all unique elements and their positions
counts = np.bincount(pos)                     #Count the number of each unique element
maxpos = counts.argmax()                      #Finds the positions of the maximum count
(unique[maxpos],counts[maxpos])

rawDescription: how to find most frequent string element in numpy ndarray?

description: Find most frequent string element in numpy ndarray


code:
from simplecrypt import encrypt
ciph = encrypt('password', "12345678")
line = "Password: " + ciph
line
line.split(None,1)[1]
decrypt("password",line.split(None,1)[1])
"12345678" == decrypt("password",line.split(None,1)[1])

rawDescription: Read specific area or string in a text file - Python 3.4.2


code:
def export_csv(modeladmin, request, queryset):

    queryset_f1 = queryset
    response_f1 = export_f1(modeladmin, request, queryset_f1)

    queryset_f2 = queryset
    response_f2 = export_f2(modeladmin, request, queryset_f2)

    return (response_f1,response_f2)

rawDescription: django queryset iterator not returning records in action

description: Django queryset iterator not returning records in action


code:
class CakeFactory:
    @staticmethod
    def create(name):
        if name == 'banana':
            return BananaCake()         # call the constructor
        elif name == 'chocolate':
            return ChocolateCake()      # call the constructor
        else:
            return None

rawDescription: Using Python's isinstance

description: Using Python's isinstance


code:
import numpy as np

a = np.array([[1,  2, 2, 3,  4, 5],
              [1,  2, 3, 3,  4, 5],
              [1,  2, 3, 4,  4, 5],
              [1,  2, 3, 4,  5, 5],
              [1,  2, 3, 4,  5, 6]])

def count_unique_by_row(a):
    weight = 1j*np.linspace(0, a.shape[1], a.shape[0], endpoint=False)
    b = a + weight[:, np.newaxis]
    u, ind, cnt = np.unique(b, return_index=True, return_counts=True)
    b = np.zeros_like(a)
    np.put(b, ind, cnt)
    return b

rawDescription: Count unique elements row wise in an ndarray


rawDescription: Dynamically building an "array of strcuts" in Python


rawDescription: Python array manipulation

description: Python array manipulation


code:
"""Provide a way to run instance methods on a single thread.

This module allows hierarchical classes to be cloned so that their instances
run on one thread. Method calls are automatically routed through a special
execution engine. This is helpful when building thread-safe GUI code."""

__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '9 October 2012'
__version__ = 1, 0, 1

################################################################################

import functools
import affinity

################################################################################

class _object: __slots__ = '_MetaBox__exec', '__dict__'

################################################################################

class MetaBox(type):

    "MetaBox(name, bases, classdict, old=None) -> MetaBox instance"

    __REGISTRY = {object: _object}
    __SENTINEL = object()

    @classmethod
    def clone(cls, old, update=()):
        "Creates a class preferring thread affinity after update."
        classdict = dict(old.__dict__)
        classdict.update(update)
        return cls(old.__name__, old.__bases__, classdict, old)

    @classmethod
    def thread(cls, func):
        "Marks a function to be completely threaded when running."
        func.__thread = cls.__SENTINEL
        return func

    def __new__(cls, name, bases, classdict, old=None):
        "Allocates space for a new class after altering its data."
        assert '__new__' not in classdict, '__new__ must not be defined!'
        assert '__slots__' not in classdict, '__slots__ must not be defined!'
        assert '__module__' in classdict, '__module__ must be defined!'
        valid = []
        for base in bases:
            if base in cls.__REGISTRY:
                valid.append(cls.__REGISTRY[base])
            elif base in cls.__REGISTRY.values():
                valid.append(base)
            else:
                valid.append(cls.clone(base))
        for key, value in classdict.items():
            if callable(value) and (not hasattr(value, '_MetaBox__thread') or
                                    value.__thread is not cls.__SENTINEL):
                classdict[key] = cls.__wrap(value)
        classdict.update({'__new__': cls.__new, '__slots__': (), '__module__':
                          '{}.{}'.format(__name__, classdict['__module__'])})
        cls.__REGISTRY[object() if old is None else old] = new = \
            super().__new__(cls, name, tuple(valid), classdict)
        return new

    def __init__(self, name, bases, classdict, old=None):
        "Initializes class instance while ignoring the old class."
        return super().__init__(name, bases, classdict)

    @staticmethod
    def __wrap(func):
        "Wraps a method so execution runs via an affinity engine."
        @functools.wraps(func)
        def box(self, *args, **kwargs):
            return self.__exec(func, self, *args, **kwargs)
        return box

    @classmethod
    def __new(meta, cls, *args, **kwargs):
        "Allocates space for instance and finds __exec attribute."
        self = object.__new__(cls)
        if 'master' in kwargs:
            self.__exec = kwargs['master'].__exec
        else:
            valid = tuple(meta.__REGISTRY.values())
            for value in args:
                if isinstance(value, valid):
                    self.__exec = value.__exec
                    break
            else:
                self.__exec = affinity.Affinity()
        return self

rawDescription: Send/sync variable/text over LAN in Python 3


code:
def get_diagonal(t, x, y, length=4):
    rays = []
    diagonal_directions = [(1,1),(1,-1),(-1,1),(-1,-1)]
    for dx, dy in diagonal_directions:
        if not ((0 <= (x+dx*(length-1)) < len(t[0])) and
                (0 <= (y+dy*(length-1)) < len(t))):
            ray = []
        else:
            ray = [t[y+dy*i][x+dx*i] for i in range(length)]
        rays.append(ray)
    return rays

rawDescription: finding diagonal numbers

description: Finding diagonal numbers


rawDescription: Python pandas column merging

description: Python pandas column merging


code:
@module('app.templatetags.extras')
class TemplateExtras(object):
    class register:
        tags    = {}
        filters = {}

# Optional: avoid using {% load %}:
django.template.libraries['app.templatetags.extras'] = TemplateExtras
django.template.base.add_to_builtins('app.templatetags.extras')

rawDescription: django: defining tags/filters/manager actions with less ceremony

description: Django: defining tags/filters/manager actions with less ceremony


code:
ret = getattr(mymodel,'objects')
self.dbobject = getattr(ret,'all')

rawDescription: Python, Django, how to use getattr (or other method) to call object that has multiple attributes?


code:
def shift(l, n):
  return l[n:] + l[:n]

rawDescription: Students at Table Permutation

description: Students at Table Permutation


code:
fileh = logging.FileHandler('file.log')
fileh.setFormatter(logging.Formatter('%(message)s')) # remove the color code.
logger.addHandler(fileh)

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


code:
soup = BeautifulSoup(table)

res = []
for a in soup.find_all('table')[0].find_all('tr')[2:3]:
    if 'white' in a.text.lower():
        text = a.text.encode('ascii', 'ignore').replace(':','').split()
        res.append(text)

rawDescription: Python + BS Picking a specific word(location) form webpage table


code:
import random

some_list=["-","-","-","-","-","-","-"]

n=8
if n>len(some_list):
    some_list=["*" for i in some_list]
else:
    for i in range(n):
           position=random.randrange(0,len(some_list))
           while some_list[position]=="*":
                   position=random.randrange(0,len(some_list))
           some_list[position]="*"

print(some_list)

rawDescription: How to randomly replace a string in a list

description: Randomly replace a string in a list


rawDescription: How to capture special keys for python console application

description: Capture special keys for python console application


code: df['modifiedAmount'] =df.apply(lambda x: np.nan if x.modifiedAmount == x.lineAmount else x.modifiedAmount, axis =1)

rawDescription: How do I take a column of pandas data based on a scalar condition AND a column comparison?

description: Take a column of pandas data based on a scalar condition AND a column comparison


rawDescription: putting value of one array into a list in python

description: Putting value of one array into a list in python


code:
from Queue import Queue
import threading

class myQueue(Queue):
    def __init__(self, *args, **kwargs):
        Queue.__init__(self, *args, **kwargs)
        self.mutex = threading.RLock()
        self.not_empty = threading.Condition(self.mutex)
        self.not_full = threading.Condition(self.mutex)
        self.all_tasks_done = threading.Condition(self.mutex)

    def putall(self , objects , *args):
        with self.mutex:
            for object in objects:
                self.put(object, *args)

    def getall(self , number , *args ):
        with self.mutex:
            return [self.get(*args) for _ in xrange(number)]

q = myQueue()
q.putall(["1", "2", "3"])

print(q.getall(2))

rawDescription: How can I make putall and getall methods of a Queue subclass atomic?

description: Make putall and getall methods of a Queue subclass atomic


rawDescription: accumulating results for each row in a text while looping

description: Accumulating results for each row in a text while looping


code:
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[-1, 1], [-2,-1], [-3, -2], [1, 1], [2, 1], [3, 2]])
plt.plot(X.T[0], X.T[1])
plt.show()

rawDescription: Matplotlib plot axis reversed for numpy plot


rawDescription: python and / or operators return value

description: Python and / or operators return value


code:
from fractions import Fraction
Fraction(0x9481ef80, 2**32) + Fraction(0x4ca1f350)
float(_)

rawDescription: Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal)


code:
class MyClass:

     @classmethod
     def get_instance(cls):
         if not hasattr(cls, "_instance"):
             cls._instance = cls()
         return cls._instance

instance = MyClass.get_instance()

rawDescription: How to delete (tearDown) a singleton instance decorator in Python for unit testing?

description: Delete (tearDown) a singleton instance decorator in Python for unit testing


code:
df3 = df1.select_dtypes(include = ['int64', 'float64'])
print(df3)

rawDescription: how to exclude the non numerical integers from a data frame in Python

description: Exclude the non numerical integers from a data frame in Python


code:
import matplotlib.pylab as pylab

logfile = file('sensorlog.txt','r')
pylab.figure(1)
pylab.xlabel('Time Steps')
pylab.ylabel('Fan Temperature')
temperatures = []
for line in logfile:
    if line[0].isdigit():
        temperatures.append(float(line.split(',')[4].strip()))
timesteps = np.arange(len(temperatures))
pylab.plot(timesteps, temperatures, color='green')
pylab.show()

rawDescription: Pylab plot shows no plot points

description: Pylab plot shows no plot points


code:
import string
a = list(string.lowercase[:7])
a[1:3] + a[4:6]

rawDescription: Discontiguous array slices in Python

description: Discontiguous array slices in Python


code:
@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

rawDescription: Loading static files in a Bottle.py application on openshift


code: sum(sum(1 for i in row if i) for row in rows)

rawDescription: Python Multidimensional Arrays - most efficient way to count number of non-zero entries


code:
k = [x for x in range(3)]
w = [n for n in range(4)]
i=0
j=0

def countt(pitch):
    global i
    global j
    if pitch == 'strike':

        if i==len(k)-1:
            i=0
        else:i=i+1
        return k[i],w[j]

    elif pitch =='ball':
        if j==len(w)-1:
            j=0
        else:j=j+1
        return w[j],k[i]

rawDescription: Multiple Generators

description: Multiple Generators


rawDescription: Named Entity Recognition (regex for places)


code:
for line in files:
    stdout.write("\rCurrent file is: " + line)
stdout.write("\n")

rawDescription: Python - how to get text to appear on same line when iterating?


code:
import resource
import unittest
import uuid

class TestSelfGarbageCollection(unittest.TestCase):

    def setUp(self):
        # Create an object that will use lots of memory
        self.large_list = []
        for _ in range(300000):
            self.large_list.append(uuid.uuid4())

    def tearDown(self):
        # Without the following line a copy of large_list will be kept in
        # memory for each test that runs, uncomment the line to allow the
        # large_list to be garbage collected.
        # self.large_list = None
        mb_memory = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000
        print("Memory usage: %s MB" % mb_memory)

    def test_memory1(self):
        pass

    def test_memory2(self):
        pass

    def test_memory3(self):
        pass

    def test_memory4(self):
        pass

    def test_memory5(self):
        pass

rawDescription: Unittest teardown() del all attributes

description: Unittest teardown() del all attributes


code:
@pytest.fixture(params=[1, 2])
def make(request):
    return request.param

def test_make(make):
    # Run your test
    pass

rawDescription: output of fixture in params in pytest

description: Output of fixture in params in pytest


code:
with Image(filename='source.jpg') as img:
    with img[100:200, 100:200] as cropped:
        # The `cropped' is an instance if wand.image.Image,
        # and can be manipulated independently of `img' instance.
        pass

rawDescription: Slice image with Wand

description: Slice image with Wand


code:
def f(speeds):
    count = Counter(map(int, speeds))
    for speed in reversed(sorted(speeds)):
        if 5 <= speed <= 30 and (speed <= 14 or count[int(speed)] >= 10):
            return speed
    return False

rawDescription: How to improve the speed of my selection process, python

description: Improve the speed of my selection process, python


rawDescription: Run Django unit tests from custom management command


code:
import nltk.data
text = """
Punkt knows that the periods in Mr. Smith and Johann S. Bach
do not mark sentence boundaries.  And sometimes sentences
can start with non-capitalized words.  i is a good variable
name.
"""
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
tokenizer.tokenize(text.strip())

rawDescription: Creating a new corpus with NLTK

description: Creating a new corpus with NLTK


code:
nli=[ [None for x in xrange(3)] for y in xrange(4)]
nli
nli[0][1]=True
nli

rawDescription: best way to make nested lists?

description: Make nested lists


rawDescription: Storing an ascii lookup table in a file in Python


code:
from scipy import linalg

x = linalg.solve(M, np.zeros(M.shape[0]))

rawDescription: I'm having difficulty understanding the syntax of scipy.optimize


code:
print((df['dates'] != df['using_tzset']).sum())
11

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


code: dump_coordinates("Coordinates searching from (1,3)", find_connected(1, 3, colors, true));

rawDescription: Finding out same colored block in a 2D matrix


rawDescription: Python IP Parsing

description: Python IP Parsing


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

C(12) == C(12)

rawDescription: Python pickle: pickled objects are not equal to source objects


code:
data = '''<data>
    <from>A</from>
    <to>B</to>
    <data>
        <name>EXAMPLE ONE</name>
        <info>
            <some_data>1</some_data>
            <more_data>2</more_data>
        </info>
        <random>
            <some_tag>
            </foobar>
            <foo>
                <bar />
           </foo>
        </random>
    </data>
    <data>
        <name>EXAMPLE TWO</name>
        <info>
            <some_data>3</some_data>
            <more_data>4</more_data>
        </info>
        <random>
            <some_tag>
            </foobar>
            <foo>
                <bar />
           </foo>
        </random>
   </data>
</data>
<data>
    <from>C</from>
    <to>D</to>
    <data>
        <name>EXAMPLE</name>
        <info>
            <some_data>1</some_data>
            <more_data>2</more_data>
        </info>
        <random>
            <some_tag>
            </foobar>
            <foo>
                <bar />
           </foo>
        </random>
    </data>
 </data>'''

rawDescription: Extract and group elements/tags with BeautifulSoup


rawDescription: How to compare list in Python?

description: Compare list in Python


code:
from PyQt4 import QtCore, QtGui
import Queue as queue
import time

class Signal(QtCore.QObject):
    sig = QtCore.pyqtSignal(int)

class Worker(QtCore.QRunnable):
    def __init__(self, theQueue, sig):
        QtCore.QRunnable.__init__(self)
        self.theQueue = theQueue
        self.signal = sig

    def run(self):
        while True:
            task = self.theQueue.get()
            if task is None:
                self.theQueue.task_done()
                return
            time.sleep(1)
            print(task)
            self.signal.sig.emit(int(task))
            self.theQueue.task_done()

def result_callback(result):
    print("Got {}".format(result))

MAX_THREADS = 2
def launch_threads():
    theQueue = queue.Queue()
    pool = QtCore.QThreadPool()
    pool.setMaxThreadCount(MAX_THREADS)
    for task in range(MAX_THREADS):
        sig = Signal()
        sig.sig.connect(result_callback)
        pool.start(Worker(theQueue, sig))

    for i in range(MAX_THREADS * 6): # Sending more values than there are threads
        theQueue.put(i)

    # Tell the threads in the pool to finish
    for i in range(MAX_THREADS):
        theQueue.put(None)

    pool.waitForDone()
    QtCore.QTimer.singleShot(0, QtGui.QApplication.instance().exit)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    QtCore.QTimer.singleShot(0, launch_threads)
    app.exec_()

rawDescription: How to limit QThread number

description: Limit QThread number


code:
def _copy_immutable(x):
    return x
for t in (type(None), int, long, float, bool, str, tuple,
          frozenset, type, xrange, types.ClassType,
          types.BuiltinFunctionType, type(Ellipsis),
          types.FunctionType, weakref.ref):
    d[t] = _copy_immutable
for name in ("ComplexType", "UnicodeType", "CodeType"):
    t = getattr(types, name, None)
    if t is not None:
        d[t] = _copy_immutable

rawDescription: Does deepcopy use copy-on-write?

description: Does deepcopy use copy-on-write


code: group

rawDescription: Finding the sets of columns/rows that overlap


rawDescription: Python why does int("0") return false

description: Python why does int("0") return false


rawDescription: (Python--numpy) how to resize and slice an numpy array with out a loop?


code:
def is_odd(x):
    return x%2==1

result = all(is_odd(x) for x in [1,3,5,7])

rawDescription: Equivalent for inject() in Python?

description: Equivalent for inject() in Python


rawDescription: Fast rolling-sum

description: Fast rolling-sum


code: path

rawDescription: Python class inheritance: dynamic attribute creation


rawDescription: Pandas reset index on series to remove multiindex


code:
def process_text(text):
    b_text = bundle_dialogue_items(text)
    f_text = filter_dialogue_items(b_text)
    c_text = clean_dialogue_items(f_text)

rawDescription: Python: How to sum up the word count for each person in a dialogue?


code:
n = 13
A = np.array(([[x[j], 1] for j in range(n)]))
B = np.array(yl[0:n])
A = np.array(([[x[j], 1] for j in range(n)]))
B = np.array(y_ln[0:n])

X = np.linalg.lstsq(A,B)[0]
a=X[0]; b=X[1]

plt.figure()
plt.plot(x[0:n], np.exp(a*x[0:n]+b), '--')
plt.plot(x, y, 'o')
plt.ylabel('y')
plt.xlabel('x values')
plt.yscale('log')
plt.show()

rawDescription: How to fit to a log scale

description: Fit to a log scale


rawDescription: Filter an array based on density

description: Filter an array based on density


code: bar = Bar(**dict(a=1, b=2))

rawDescription: Formulating a dynamic class in Python

description: Formulating a dynamic class in Python


code:
import urllib2
import json

def get_contacts(guid):
    url = 'http://social.yahooapis.com/v1/user/{}/contacts.json'.format(guid)
    page = urllib2.urlopen(url)
    return json.load(page)['contacts']['contact']

rawDescription: Import contacts from yahoo in python

description: Import contacts from yahoo in python


code:
a = [1, 2, 3, 4, 5]
b = [14, 17, 9, 3, 8]
next(element for element in a if element in b)

rawDescription: Finding if any element in a list is in another list and return the first element found


code:
import mx.DateTime
mx.DateTime.Parser.DateTimeFromString("Today 3:20 PM")
mx.DateTime.Parser.DateTimeFromString("Tomorrow 5:50 PM")

rawDescription: What's the best way to make a time from "Today" or "Yesterday" and a time in Python?


code:
import Tkinter as tk

class Page1(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="This is page 1")
        label.pack(fill ="both", expand=True, padx=20, pady=10)

rawDescription: TTK Notebook Share data between imported tabs


code:
#!/usr/bin/env python3

import json
import datetime
from collections import OrderedDict

# Test dictionary
a = OrderedDict([('a', datetime.datetime(2015, 6, 15, 15, 58, 54, 884000)),
                 ('b', 'b'), ('c', 'c'), ('d', 'd')])
print(a)

# Encoder for datetime
def encoder(obj):
    if type(obj) is datetime.datetime:
        return {'$date$': obj.timestamp()}
    raise TypeError

# Encode
s = json.dumps(a, default=encoder)
print("JSON:", s)

# Decoder for OrderedDict and datetime
def decoder(obj):
    if len(obj) == 1 and len(obj[0]) == 2 and obj[0][0] == '$date$':
        return datetime.datetime.fromtimestamp(obj[0][1])
    else:
        return OrderedDict(obj)

# Decode
b = json.loads(s, object_pairs_hook=decoder)
print(b)

# Compare
print("Comparing:", a == b)

rawDescription: python - using json with OrderedDict and Datetime

description: Python - using json with OrderedDict and Datetime


code:
[[str(int(i, 2)) for i in  item.split()] for item in mylist]
list(zip([[str(int(i, 2)) for i in  item.split()] for item in mylist], slashes))

rawDescription: How to make a list of Binary numbers a list of Dotted Decimal Numbers?

description: Make a list of Binary numbers a list of Dotted Decimal Numbers


rawDescription: matlab find() for nonzero element in python

description: Matlab find() for nonzero element in python


rawDescription: Optimal strategy for choosing pairs from a list of combinations


code:
i = (-a).argsort(axis=None, kind='mergesort')
j = np.unravel_index(i, a.shape)
np.vstack(j).T

rawDescription: Python numpy keep a list of indices of a sorted 2D array


code:
# first.py
import sys
for line in open("input.txt"):
    processed_line = process_line(line)
    sys.stdout.write(processed_line)

# second.py
import sys
for line in sys.stdin:
    processed_line = process_line(line)
    sys.stdout.write(processed_line)

rawDescription: Python - a subprocess writing to stdin so that the main program can read it from the stdin


code:
for item_index in range(len(data)):
    item = data[item_index]

    for subitem in re.findall("(.*?) \((.*?)\)", item[2]):
        # part before the ( )
        temp_split = [subitem[0]]
        # part in the ( )
        temp_split.extend(subitem[1].split("/"))

    temp_item = item[:2]
    temp_item.extend(temp_split)
    temp_item.extend(item[3:])

    data[item_index] = temp_item

rawDescription: python split list column into multiple columns in original list

description: Python split list column into multiple columns in original list


code:
def eliminate_consonants(x):
    for char in x:
        if char in 'aeiou':
            print(char,end = "")

rawDescription: Deleting consonants from a string in Python


code:
@gen.coroutine
def refresh_loop(interval=3600):
    next_time = IOLoop.current().time()
    while True:
        next_time += interval
        yield refresh()
        while next_time <= IOLoop.current().time():
            next_time += interval
        yield gen.Task(IOLoop.current().call_at, next_time)

rawDescription: Schedule read operation in Tornado

description: Schedule read operation in Tornado


code:
text = [str(i) for i in range(36)] # raw data!
text_display(text,screen) # text is displayed
pygame.display.update() # screen updated

rawDescription: Python - Display Excel database in a grid


code:
a = [(1, 'CA'), (2, 'NY')]
b = [2,3,4,5,6]
bset = set(b)

a = [el for el in a if el[0] in bset]
print(a)

rawDescription: Python3 List: How do I remove el in list_a if el[0] is not in list_b?


rawDescription: How to sort this list in Python?

description: Sort this list in Python


code:
class M2MPostSaveModelAdmin(ModelAdmin):

    def save_related(self, request, form, formsets, change):
        super(M2MPostSaveModelAdmin, self).save_related(request, form, formsets, change)
        m2m_post_save.send(sender=self.__class__, instance=form.instance)

rawDescription: Django multiple many to many and post_save processing


code: df4 = pd.concat([df1, df2])

rawDescription: Pandas Dataframe - Count values based on index position


code:
from nltk.corpus import treebank
from nltk.corpus import brown
treebank.tagged_words()
brown.tagged_words()
type(treebank.tagged_words())
type(brown.tagged_words())
from nltk import ConditionalFreqDist as cfd
cfd(brown.tagged_words())
cfd(treebank.tagged_words())

rawDescription: Create Dictionary from Penn Treebank Corpus sample from NLTK?


code:
for i, chunk in enumerate(chunks):
    chunk.export("/path/to/ouput/dir/chunk{0}.wav".format(i), format="wav")

rawDescription: Using pyDub to chop up a long audio file


code:
def readLastNames ():
    for i in master_file:
            columns = re.split('\s{2,}', i)
            last_name = columns[1]
            yield last_name

for last_name in readLastNames ():
    print (last_name)

rawDescription: Exiting out of for loop and returning when at the end of a file


code: app = Flask(__name__, static_folder='../static')

rawDescription: Referencing static files above parent directory in flask


code:
import array
array.array('B', foo)

rawDescription: Python 2 and 3 compatible method to convert bytes to integer


code:
{'__version__': '1.0',
 '__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Mon May 25 09:19:36 2015',
 '__globals__': [],
 'alist': array([[1, 2, 3]])}

rawDescription: Can someone explain mdict in python (scipy.io), for example in scipy.io.savemat()?


code:
def new_or_used(value):
    return value.lower() in {"new", "used"}
validate_input("New, or used?", new_or_used)

rawDescription: How to redo an input if user enters invalid answer

description: Redo an input if user enters invalid answer


code:
{
    u'STD': u'06:30',
    u'Status': u'Scheduled',
    u'ATD': u'-',
    u'From': u'Singapore  (SIN)',
    u'STA': u'07:55',
    u'\xa0': u'', #This is the last column and have no meaning
    u'To': u'Penang  (PEN)',
    u'Aircraft': u'-',
    u'Date': u'2015-04-19'
}

rawDescription: Scraping with Beautiful Soup

description: Scraping with Beautiful Soup


code: u"\xff and \ubd23".translate({0xff: u"255", 0xbd23: u"something else"})

rawDescription: Optimizing find and replace over large files in Python


code:
import collections #note that collections is a C extension in Python 2.5
collections.__file__

rawDescription: Relative paths in Python

description: Relative paths in Python


code:
trace_vdelete('w', self.trace_id )
self.on_off.set(status["power"])
self.trace_id = self.on_off.trace("w",self.on_off_changed)

rawDescription: Different callback when widget changed by user/programatically


code:
def harvest_emails(target):
    """"Takes string, splits it on \n, then yields each line formatted as:
datecode, email, identifier
"""
    import re

    for line in target.splitlines():
        t = line.split(",")
        yield (
            t[0].strip(),
            ','.join(
                re.findall("\S+@\S+\.(?:com|org|net)",
                           ''.join(t[1:-1]).strip(),re.I)[0:]),
            t[-1].strip())

rawDescription: Replace part of a string with single word from the same string


rawDescription: How do I get str.translate to work with Unicode strings?

description: Get str.translate to work with Unicode strings


code: k = dict((x,v) for x,v in k.iteritems() if x!=1)

rawDescription: What is the proper way of deleting item from a dictionary  in "for" loop (Python)?


code:
def handle_xml_upload(request):
    xmlfile = request.FILES['xmlfile']
    tree = ET.parse(xmlfile)
    # ...

rawDescription: Django: Uploading an XML file from HTML page


code:
Macro
RunCode: TestMe()

rawDescription: Python code for running ms-Access Module Subroutine


code:
def join_lists(*args):
    return [i for L in args for i in L]

rawDescription: concatenate splatted lists

description: Concatenate splatted lists


code:
def value(c):
    for b in c:
        containsdigit = any(a.isdigit() for a in b)
        if containsdigit:
            print("The result of : "+ b + " is 1")
        else:
            print("The result of : " + b +" is 0")

rawDescription: Python Detect numbers in string by a list of sample


code:
import urllib2
import socket
import random
import StringIO
import gzip

def download(source_url):
    try:
        socket.setdefaulttimeout(10)
        agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)']
        ree = urllib2.Request(source_url)
        ree.add_header('User-Agent',random.choice(agents))
        ree.add_header('Accept-encoding', 'gzip')
        opener = urllib2.build_opener()
        response = opener.open(ree)
        encoding=response.headers.getheader('Content-Encoding')
        content = response.read()
        if encoding and 'gzip' in encoding:
            compressedstream = StringIO.StringIO(content)
            gzipper = gzip.GzipFile(fileobj=compressedstream)
            data = gzipper.read()
            return data
        else:
            return content
    except urllib2.URLError as e:
        return ""

data=download('http://api.stackoverflow.com/1.0/questions/3708418?type=jsontext')
print(data)

rawDescription: How do I modify this download function in Python?

description: Modify this download function in Python


code: from vardata import *

rawDescription: python using variables from another file

description: Python using variables from another file


code: rephraser('The Toyota is red. The Honda is red. The BMW is red. The Mercedes is green.')

rawDescription: Reduce redundant block of text

description: Reduce redundant block of text


code: ['Summerdale', 'Bellows', 'Parsons', 'Alan', 'Clements']

rawDescription: chunks using python

description: Chunks using python


code:
regex = r"""
(                # Capture in group #1
    "[\w\s]+"    # Three sequences of quoted letters and white space characters
    \s+          # followed by one or more white space characters
    "[\w\s]+"
    \s+
    "[\w\s]+"
    \s+
)
"(\d{10,})"      # Match a quoted set of at least 10 integers into group #2
(^^\s+\.\s+)     # Match by two circumflex characters, whitespace and a period
                 # into group #3
(.*)             # Followed by anything at all into group #4
"""

COMPILED_REGEX = re.compile(regex, re.VERBOSE)

rawDescription: How to substitute specific patterns in python

description: Substitute specific patterns in python


code:
import pylab
pylab.plot(0,0,'ro', label = 'one point')
pylab.legend(loc = "lower left")

modify_legend(numpoints = 1)

pylab.show()

rawDescription: How to modify matplotlib legend after it has been created?

description: Modify matplotlib legend after it has been created


code: def integral2(function, n=1000, start=0, stop=100): return (float(1)/n) * sum([eval(function) for x in [(float(x) / n) for x in range(start*n, (stop*n)+1)]])

rawDescription: Calculating Integrals: One-liner solution?


code:
f = open('e:\\text.txt','wt',encoding="utf-8")
f.write(chr(510))
f.close()

rawDescription: How to print non-ascii characters to file in Python 2.7

description: Print non-ascii characters to file in Python 2.7


code: return query.all()

rawDescription: SQLAlchemy: One-Way Relationship, Correlated Subquery


code:
highest_fruits = df.groupby(['test', 'analysis']).apply(lambda x: [f for f in np.where(x.second_pass == np.amax(x.second_pass), x.fruit.tolist(), '').tolist() if f!='']).reset_index()
df =df.merge(highest_fruits, on=['test', 'analysis'], how='left').rename(columns={0: 'highest_fruit'})

rawDescription: Pandas DataFrame Window Function

description: Pandas DataFrame Window Function


code:
for obj, value in results:
    if value == key:
        result = (obj, value)

rawDescription: Get item with value from tuple in python


code:
dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
lines =[dic[k] for k in dic if k[1]=='c']  #returns all matching items
lines

rawDescription: Referencing to elements of tuples when used as keys in a python dictionary


code:
print(operator.sub.__doc__)
minus1 = functools.partial(operator.sub, b=1)
minus1(5)
minus1 = lambda x: operator.sub(x, 1)
minus1(9)

rawDescription: Python callback function placeholders?

description: Python callback function placeholders


code: exec("print 'hi'")

rawDescription: Execute a string as a command

description: Execute a string as a command


code:
#coding:utf-8
import scrapy

class WikipediaItem(scrapy.Item):
    category_name = scrapy.Field()
    category_url = scrapy.Field()
    letter_name = scrapy.Field()

rawDescription: Scraping in python

description: Scraping in python


code:
def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return F(n-1)+F(n-2)

rawDescription: How to write the Fibonacci Sequence in Python

description: Write the Fibonacci Sequence in Python


code:
import zipfile

fh = open('test.zip', 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
    outpath = "C:\\"
    z.extract(name, outpath)
fh.close()

rawDescription: Extracting zip file contents to specific directory in Python 2.7


code:
from datetime import datetime
from pyspark.sql import Row
from pyspark.sql import HiveContext

sqlContext = HiveContext(sc)

row = Row("individual", "area_id", "datetime")
fmt = "%d/%m/%Y %H:%M"
df = rdd.map(lambda r: row(r[0], r[1], datetime.strptime(r[2], fmt))).toDF()

rawDescription: PySpark - Combining Session Data without Explicit Session Key / Iterating over All Rows


code:
from itertools import combinations

consensus = 0
wsp = 0
for position in zip(seq1, seq2, seq3): # sets at same position
    for pair in combinations(position, 2): # pairs within set
        consensus+= distance(*pair) # calculate distance
        wsp += w_sum(*pair) # calculate pair sum

rawDescription: consensus score and WSP score in python

description: Consensus score and WSP score in python


rawDescription: An unusual Python syntax element frequently used in Matplotlib


code: [ord(c) for c in 'Hello World!']

rawDescription: Python3 convert Unicode String to int representation


rawDescription: Django contains None (or reversed contain)


rawDescription: pandas unique values multiple columns

description: Pandas unique values multiple columns


rawDescription: How to write a simple lexer/parser for user input commands in Python?

description: Write a simple lexer/parser for user input commands in Python


code:
from sqlalchemy.sql import literal, tuple_

# There's already built-in any() function in Python, we don't want to
# shadow that.
def any_(value, col):
    return literal(value).op('= ANY')(tuple_(col))

q = Comment.query.filter(any_(11, Comment.path))

rawDescription: How to use SQLAlchemy to select value at a position in a PostgreSQL ARRAY?

description: Use SQLAlchemy to select value at a position in a PostgreSQL ARRAY


code:
seen = {}
for n, L in enumerate(f):
    if L in seen:
        print("Line %i is a duplicate of line %i" % (n, seen[L]))
    else:
        seen[L] = n

rawDescription: Find double lines; a faster way

description: Find double lines; a faster way


code:
import csv

match = "JB74XYZ"

matched_row = None
with open("RegDD.txt", "r") as file:
    # Read file as a CSV delimited by tabs.
    reader = csv.reader(file, delimiter='\t')
    for row in reader:
        # Check the first (0-th) column.
        if row[0] == match:
            # Found the row we were looking for.
            matched_row = row
            break

print(matched_row)

rawDescription: Python regex findall to read line in .csv file


code: ax.bar(angles, np.full(100, 0.9), width=0.05, bottom=0.89, color='r', linewidth=0)

rawDescription: How to plot points on a clock

description: Plot points on a clock


code:
text = str(row[0])
for replacement in REPLACEMENTS:
    text = replacement(text)

rawDescription: List of compiled regexes in Python

description: List of compiled regexes in Python


code:
def to_secs(hours, minutes, seconds):
    return hours * 3600 + minutes * 60 + seconds

to_secs(2, 30, 10) == 9010

rawDescription: In Python I need a to_secs function to convert into seconds


code: dic2 = dict((item,i) for i,item in enumerate(list2))

rawDescription: Comparing list values by index in Python


code: max(d, key=lambda x: d[x]['green'])

rawDescription: How to find the key corresponding to the maximum value in a dictionary of dictionary using max() function?

description: Find the key corresponding to the maximum value in a dictionary of dictionary using max() function


code:
strs="I am a string"
spl=strs.split()    #use set(strs.split()) if the list returned is huge
any(x in spl for x in lis)
strs="Iamastring"
spl=strs.split()
any(x in spl for x in lis)

rawDescription: Multi-condition regex in Python

description: Multi-condition regex in Python


rawDescription: Calculate weighted average using a pandas/dataframe


code:
def _timed_method_wrapper(TestClass_object, return_queue):
    return TestClass_object(return_queue)

rawDescription: Limit function execution in Python

description: Limit function execution in Python


rawDescription: ILOG OPL vs. Python

description: ILOG OPL vs. Python


code:
from mypackage.mymodule import MY_CONSTANT

# elsewhere
mymodule.MY_CONSTANT = 'new_value'

rawDescription: Reloading global Python variables in a long running process


code:
import hashlib
h = hashlib.md5("something")
h.digest()
hextxtdigest = h.hexdigest()
hextxtdigest
# The next line reinvents the wheel.
whatyouwant = "".join([chr(int(hextxtdigest[x:x + 2], 16)) for x in xrange(0, len(hextxtdigest), 2)])
whatyouwant == h.digest()

rawDescription: Converting md5sum with python

description: Converting md5sum with python


code:
from __future__ import print_function
import json
import subprocess
import sys

sensor_dict = {}

py3 = False

# python version check determines string handling

try:
    if (sys.version_info > (3, 0)):
        py3 = True
except:
    pass

try:

    subp_ret = subprocess.check_output(["./mlx90614_query"])

    # at this point, subprocess succeeded and subp_ret holds your output

    if py3:
        subp_ret = subp_ret.decode('utf8')

    sensor_dict = json.loads(subp_ret.split("|")[1].strip())

    # cast temperatures to float and print

    for k in sensor_dict["data"]:
        val = float(sensor_dict["data"][k])
        sensor_dict["data"][k] = val
        print (k, "\t", val)

    # cast date/time segments to int and print

    for k in sensor_dict["time"]:
        val = int(sensor_dict["time"][k])
        sensor_dict["time"][k] = val
        print (k, "\t", val)

    # Now go win that race! :P

except Exception as e:
    print(str(e))

rawDescription: Raspberry Pi - Interfacing with an i2c enabled IR temp sensor (MLX90614)


code:
import numpy as np

...

mybins = np.arange(0,48,2)

n, bins, patches = plt.hist(setA, bins=mybins, alpha=0.40 , label = 'setA', normed=True)
n, bins, patches = plt.hist(setB, bins=mybins, alpha=0.40 , label = 'setB', normed=True)
n, bins, patches = plt.hist(setC, bins=mybins, alpha=0.40 , label = 'setC', normed=True)

rawDescription: Normalising Histograms Matplotlib

description: Normalising Histograms Matplotlib


code:
df["closePrice"] > df["openPrice"]
(df["closePrice"] > df["openPrice"]) * 2 - 1

rawDescription: How to add another label-like column for a dataframe in python?

description: Add another label-like column for a dataframe in python


code:
a
b
n = b.shape[1]
mask
mask*b

rawDescription: Python - numpy : 'dimension dependent indexing'


code:
# Get masks comparing all rows of A with B and then B with C
M1 = (A[:,None,:2] == B[:,:2])
M2 = (B[:,None,:2] == C[:,:2])

# Get a joint 3D mask of those two masks and get the indices of matches.
# These indices (I,J,K) of the 3D mask basically tells us the row numbers
# correspondng to each of the input arrays that are present in all of them.
# Thus, in (I,J,K), I would be the matching row number in A, J in B & K in C.
I,J,K = np.where((M1[:,:,None,:] & M2).all(3))

# Finally, select rows of A, B and C with I, J and K respectively
A_new = A[I]
B_new = B[J]
C_new = C[K]

rawDescription: Remove rows from numpy array based on presence/absence in other arrays


code:
formatter = get_ipython().display_formatter.formatters['text/plain']
formatter.for_type(int, lambda n, p, cycle: p.text("%X" % n))
1
100
255

rawDescription: How can I configure ipython to display integers in hex format?

description: Configure ipython to display integers in hex format


code:
regex = re.compile("file:///c:/([^/]+)/nameList.json#/")
replacer = lambda g: '< {0}="{0}://{0}.com/{0}//nameList.md">nameList /{0}/'.format(g.groups()[0])

with open("output.txt","w") as f:
    for line in open("input.txt"):
         f.write(re.sub(regex,replacer,line))

rawDescription: how to edit a line (overwright and replace) in python

description: Edit a line (overwright and replace) in python


code:
from collections import Counter
text_count_1 = Counter(text_1)
text_count_2 = Counter(text_2)

delta = len(list((text_count_2 - text_count_1).elements())) \
      - len(list((text_count_1 - text_count_2).elements()))

print(delta)

rawDescription: Delta words between two TXT files

description: Delta words between two TXT files


code: from __future__ import division

rawDescription: Error while I use math.atan in Python!

description: Error while I use math.atan in Python!


code:
X.iloc[[0,1], X.columns.get_indexer_for(['var2', 'var3'])] = 100
X

rawDescription: Subsetting DataFrame using ix in Python

description: Subsetting DataFrame using ix in Python


code:
import apt_pkg
apt_pkg.init_system()

a = '1:1.3.10-0.3'
b = '1.3.4-1'
vc = apt_pkg.version_compare(a,b)
if vc > 0:
    print('version a > version b')
elif vc == 0:
    print('version a == version b')
elif vc < 0:
    print('version a < version b')

rawDescription: How to compare Debian package versions

description: Compare Debian package versions


code:
from datetime import datetime
startdate = datetime.strptime("1999-10-20", "%Y-%m-%d")
enddate = datetime.strptime("2003-02-28", "%Y-%m-%d")
delta = enddate - startdate # difference in days

rawDescription: Need to do a math operation on every line in several CSV files in Python


code: df.groupby('class').agg({'xer': lambda L: reduce(pd.np.divide, L)})

rawDescription: Pandas group by aggregate using division


rawDescription: Python tuple to json structure

description: Python tuple to json structure


code:
import numpy as np
from sklearn.cluster import KMeans
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target

estimator = KMeans(n_clusters=3)
estimator.fit(X)

rawDescription: cluster points after KMeans clustering (scikit learn)

description: Cluster points after KMeans clustering (scikit learn)


code:
#!/usr/bin/env python
from itertools import imap, islice, izip
from operator  import itemgetter
from xml.etree import cElementTree as etree

def parsexml(filename):
    it = imap(itemgetter(1),
              iter(etree.iterparse(filename, events=('start',))))
    root = next(it) # get root element
    for elem in it:
        if elem.tag == '{http://psi.hupo.org/ms/mzml}instrumentConfiguration':
            values = [('Id', elem.get('id')),
                      ('Parameter1', next(it).get('name'))] # cvParam
            componentList_count = int(next(it).get('count'))
            for parent, child in islice(izip(it, it), componentList_count):
                key = parent.tag.partition('}')[2]
                value = child.get('name')
                assert child.tag.endswith('cvParam')
                values.append((key, value))
            yield values
            root.clear() # preserve memory

def print_values(it):
    for line in (': '.join(val) for conf in it for val in conf):
        print(line)

print_values(parsexml(filename))

rawDescription: Efficient way of XML parsing in ElementTree(1.3.0) Python


code:
elements = ['|L |'] + L
text = ''.join(map(str, elements))

rawDescription: How can I count the length of the output of print in Python?

description: Count the length of the output of print in Python


code:
user_jsons = []
with open("followers.txt", 'rb') as f:
    for line in f:
        while True:
            try:
                jfile = json.loads(line)
                break
            except ValueError:
                # Not yet a complete JSON value
                line += next(f)
        user_jsons.append(jfile)

rawDescription: Extracting data in Tweepy in useable form (JSON)


code:
import matplotlib.pyplot as plt

img = [[0.9, 0.3], [0.2, 0.1]]

cmap = plt.get_cmap('jet')

rgba_img = cmap(img)
rgb_img = np.delete(rgba_img, 3, 2)

rawDescription: Converting a grayscale image to an RGB heatmap image with matplotlib


code:
teams = {
"Niners" : ("Gabbert", "02" ),
"Bears" : ("CUTLER, JAY","06"),
"Bengals" : ("Dalton, Andy","14"),
"Bills" : (" Taylor, Tyrod", "05")} #etc
# Again, not including the whole dictionary for brevity's sake

def decor(func):
    def wrap():
        print("===============================")
        func()
        print("===============================")
    return wrap

def print_text():
    print("Who\s your NFL Quarterback? ")

decorated = decor(print_text)
decorated()

team = input("Enter your teams name here:").capitalize()
print(teams[team][0], teams[team][1])

rawDescription: calling class with user input

description: Calling class with user input


code:
from collections import defaultdict
dic={}
for g in ['male', 'female']:
  dic[g]=defaultdict(dict)
  for y in [2013, 2014]:
    dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict

rawDescription: how do you filter pandas dataframes by multiple columns

description: Filter pandas dataframes by multiple columns


code:
his = np.histogram(a,bins=range(5))
fig, ax = plt.subplots()
offset = .4
plt.bar(his[1][1:],his[0])
ax.set_xticks(his[1][1:] + offset)
ax.set_xticklabels( ('1', '2', '3', '4') )

rawDescription: How to center labels in histogram plot

description: Center labels in histogram plot


code:
from PyQt4 import QtGui
from enchant.checker import SpellChecker
import re
import sys

class Main(QtGui.QMainWindow):

    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self,parent)
        self.initUI()

    def initToolbar(self):
        self.spellcheckAction = QtGui.QAction(QtGui.QIcon("icons/logo.png"),"Spellcheck",self)
        self.spellcheckAction.setStatusTip("Spell Check document")
        self.spellcheckAction.setShortcut("Ctrl+S")
        self.spellcheckAction.triggered.connect(self.spellcheckHandler)
        self.toolbar = self.addToolBar("Options")
        self.toolbar.addAction(self.spellcheckAction)

    def initUI(self):
        self.text = QtGui.QTextEdit(self)
        self.initToolbar()
        self.text.setTabStopWidth(33)
        self.setCentralWidget(self.text)
        self.setGeometry(100,100,1030,800)
        self.setWindowTitle("Writer")
        self.setWindowIcon(QtGui.QIcon("icons/icon.png"))

    def spellcheckHandler(self):
        chkr = SpellChecker("en_US")
        s = str(self.text.toPlainText())
        chkr.set_text(s)
        for err in chkr:
            self.replaceAll(err.word)

    def find(self, query):
        text = self.text.toPlainText()
        query = r'\b' + query + r'\b'
        flags = 0
        pattern = re.compile(query,flags)
        start = self.lastMatch.start() + 1 if self.lastMatch else 0
        self.lastMatch = pattern.search(text,start)
        if self.lastMatch:
            start = self.lastMatch.start()
            end = self.lastMatch.end()
            self.moveCursor(start,end)
        else:
            self.text.moveCursor(QtGui.QTextCursor.End)

    def replace(self):
        cursor = self.text.textCursor()
        if self.lastMatch and cursor.hasSelection():
            self.text.setTextBackgroundColor(QtGui.QColor(0,255,0))
            self.text.setTextCursor(cursor)

    def replaceAll(self, query):
        self.lastMatch = None
        self.find(query)
        while self.lastMatch:
            self.replace()
            self.find(query)

    def moveCursor(self,start,end):
        cursor = self.text.textCursor()
        cursor.setPosition(start)
        cursor.movePosition(QtGui.QTextCursor.Right,QtGui.QTextCursor.KeepAnchor,end - start)
        self.text.setTextCursor(cursor)

def main():
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

rawDescription: PyQt4 Spell Check with syntax highlighter


code:
class sendFleet(forms.Form):
    [...]
    ship1 = forms.IntegerField(initial=0)
    ship2 = forms.IntegerField(initial=0)

    def visible_fields(self):
        # create a list of fields you don't want to display
        invisibles = []
        if self.instance.ship1 == 0:
            invisibles.append(self.fields['ship1'])

        # remove fields from the list of visible fields
        visibles = super(MailForm, self).visible_fields()
        return [v for v in visibles if v.field not in invisibles]

rawDescription: Django form don't show specific inputs

description: Django form don't show specific inputs


code: [ [ item for item in x if item ] for x in oldlist ]

rawDescription: How do I create a new list with specific items from an old list in Python 2?

description: Create a new list with specific items from an old list in Python 2


code:
import sys
sys.stderr = open('logfile.txt', 'w')
httpd.serve_forever()

rawDescription: Save logs - SimpleHTTPServer

description: Save logs - SimpleHTTPServer


code:
s = "aaaXXXbbbXXXcccXdddXXXXXeXf"
import itertools
sum(e == 'X' for e, g in itertools.groupby(s))

rawDescription: Count character repeats in Python

description: Count character repeats in Python


code:
v=u'債務の天井'
vocab=v.encode('utf-8')   # val['text']

rawDescription: iterate through unicode strings and compare with unicode in python dictionary

description: Iterate through unicode strings and compare with unicode in python dictionary


rawDescription: How to use *args to combine multiple lists?

description: Use *args to combine multiple lists


code:
def number_of_partitions(max_range, max_sum):
    '''
    Returns an array arr of the same shape as max_range, where
    arr[j] = number of admissible partitions for
             j summands bounded by max_range[j:] and with sum <= max_sum
    '''
    M = max_sum + 1
    N = len(max_range)
    arr = np.zeros(shape=(M,N), dtype = int)
    arr[:,-1] = np.where(np.arange(M) <= min(max_range[-1], max_sum), 1, 0)
    for i in range(N-2,-1,-1):
        for j in range(max_range[i]+1):
            arr[j:,i] += arr[:M-j,i+1]
    return arr.sum(axis = 0)

rawDescription: Generating a numpy array with all combinations of numbers that sum to less than a given number


code:
import imghdr
imghdr.what('ignore', img)

rawDescription: How do I copy a remote image in python?

description: Copy a remote image in python


code: sites = response.xpath("//td/div[@id]")

rawDescription: Why scrapy not giving all the results and the rules part is also not working?


code:
A = np.random.rand(6,3,4,5)
C=np.empty(shape=(6,3))
shp = A.shape
np.allclose(C,out)

rawDescription: Numpy: Multidimensional index. Row by row with no loop


code: backend: Agg

rawDescription: Why does matplotlib not work on a digitalocean VPS with web2py?


code:
import requests
import json

url = 'http://stats.nba.com/stats/leaguedashteamshotlocations?Conference=&DateFr' + \
      'om=&DateTo=&DistanceRange=By+Zone&Division=&GameScope=&GameSegment=&LastN' + \
      'Games=0&LeagueID=00&Location=&MeasureType=Opponent&Month=0&OpponentTeamID' + \
      '=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerExperien' + \
      'ce=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2014-15&SeasonSegment=&Seas' + \
      'onType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision='
print(url)

import sys, os, pickle
file_name = 'result_sets.pickled'

if os.path.isfile(file_name):
  result_sets = pickle.load(open(file_name, 'rb'))
else:
  response = requests.get(url)
  response.raise_for_status()
  result_sets = response.json()['resultSets']
  pickle.dump(result_sets, open(file_name, 'wb'))

print(result_sets.keys())
print(result_sets['headers'][1])
print(result_sets['rowSet'][0])
print(len(result_sets['rowSet']))

rawDescription: How to work with data from NBA.com?

description: Work with data from NBA.com


code:
from collections import defaultdict

result = defaultdict(int)
for name, count in a_list:
    result[name] += count

rawDescription: Adding and combining values with dictionary comprehensions?


code: sorted(d, key=lambda x: (x[1], x[0]) if len(x) == 2 else (x[0], ','))

rawDescription: Advanced List sorting Python

description: Advanced List sorting Python


code:
def dictionary_tuples(key, values):
    return [(key, item) for item in values[key]]

rawDescription: Python Build tuples from a dictionary with key and multiple values


code:
for i, sublist in enumerate(b):
    b[i] = [int(x) for x in sublist]

rawDescription: Change a list of list of str to list of list of int


code:
class Meta(type):

    def __new__(mcls, name, bases, dikt):
        fgetattr = dikt.get('__getattr__')
        if fgetattr is not None:
            setattr(mcls, '__getattr__', fgetattr)
        return super(Meta, mcls).__new__(mcls, name, bases, dikt)

class Generator(object):
    __metaclass__ = Meta

    def __getattr__(obj, name):

        def f(self):
            return "Result of %s for %r" % (name, self)
        f.__name__ = name

        if isinstance(obj, type):
            setattr(obj, name, f)
        else:
            setattr(type(obj), name, f)
        return getattr(obj, name)

rawDescription: Dynamic method generation in python

description: Dynamic method generation in python


code:
"""
  Class: MyClass
  Describe the class here.

  Attributes:
    attr1 - First attribute of the class
    attr2 - Second one
"""
class MyClass:

    def __init__(self, arg1):
        self.attr1 = arg1
        self.attr2 = "attr2"

rawDescription: How to document class attributes with NaturalDocs

description: Document class attributes with NaturalDocs


code:
res = signal.detrend(y_observed, axis=0)
(res - y0).var()
(y_detrended - y0).var()
(res - y_detrended).var()

rawDescription: Detrending a time-series of a multi-dimensional array without the for loops


code:
DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'USER': 'postgres_user',
        'PASSWORD': 's3krit'
    },
    'users': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}

rawDescription: Get the version of Django for application


code:
import pandas as pd

df = pd.DataFrame([['1/1/15', '5/22/14', '7/12/13', 5, 6, 3]],
                  columns=['DATE1', 'DATE2', 'DATE3', 'AMOUNT1', 'AMOUNT2', 'AMOUNT3'])

result = pd.lreshape(df, {'AMOUNT': ['AMOUNT1', 'AMOUNT2', 'AMOUNT3'],
                          'DATE': ['DATE1', 'DATE2', 'DATE3']})
print(result)

rawDescription: Difficult Dataframe Reshape in Python Pandas


code:
import subprocess
import tempfile
import os
import stat

with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    f.write('''\
#!/bin/bash
source ~/scripts/mySetUpFreeSurfer.sh
source /usr/local/freesurfer/FreeSurferEnv.sh
''')
    root = "/media/foo/"
    for sub_dir in os.listdir(root):
        sub = "s" + sub_dir[0:4]
        anat_dir = os.path.join(root, sub_dir, "anatomical")
        for directory in os.listdir(anat_dir):
            time_dir = os.path.join(anat_dir, directory)
            for d in os.listdir(time_dir):
                dicoms_dir = os.path.join(time_dir, d, 'dicoms')
                dicom_list = os.listdir(dicoms_dir)
                dicom = dicom_list[0]
                path = os.path.join(dicoms_dir, dicom)
                cmd1 = "recon-all -i {}  -subjid {}\n".format(path, sub)
                f.write(cmd1)
                cmd2 = "recon-all -all -subjid {}\n".format(sub)
                f.write(cmd2)

filename = f.name
os.chmod(filename, stat.S_IRUSR | stat.S_IXUSR)
subprocess.call([filename])
os.unlink(filename)

rawDescription: how to make subprocess called with call/Popen inherit environment variables

description: Make subprocess called with call/Popen inherit environment variables


code: [list(group) for key,group in itertools.groupby(data,operator.itemgetter(1))]

rawDescription: Split a list of tuples into sub-lists of the same tuple field


code:
soup = BeautifulSoup('<b class="boldest">A bold statement.</b>')
tag = soup.b
tag.__module__                # module of a Tag object

rawDescription: Test for which module an object is from rather than which type it is


rawDescription: Explicitly select items from a Python list or tuple


code:
from django.core.files.base import ContentFile
import urllib2

class PostForm(forms.ModelForm):

    image_url = forms.URLField(max_length=200, required=False)

    class Meta:
        model = Post
        fields = [
            "title", "content", "image", "image_url", "draft", "publish",
        ]

    def save(self, commit=True, *args, **kwargs):
        instance = super(PostForm, self).save(commit=False, *args, **kwargs)
        image_url = self.cleaned_data.get('image_url',None)
        if image_url and not self.cleaned_data.get('image', None):
            try:
                filename = image_url.split('/')[-1].split('#')[0].split('?')[0]
                imgdata = urllib2.urlopen(image_url).read()
                instance.image.save(filename, ContentFile(imgdata), save=False)
            except:
                pass # Add Exception handling here
        if commit:
            instance.save()
        return instance

rawDescription: creating img_upload_url using django

description: Creating img_upload_url using django


rawDescription: How to split a matrix in two in python in a memory effecient way?

description: Split a matrix in two in python in a memory effecient way


code:
class ReviewPhotosForm(forms.Form):
    DECISION_CHOICES = ( ('approve', 'Approve'), ('reject', 'Reject') )
    ROTATE_CHOICES = ( ('none,', 'None'), ('right', 'Right'), ('left', 'Left'), ('flip', 'Flip') )

    # hidden field to associate radio buttons with a photo
    photo_name = forms.CharField(widget=forms.HiddenInput)

    approve = forms.ChoiceField(
        label='Approve or reject?',
        choices=self.DECISION_CHOICES,
         widget=forms.RadioSelect(renderer=widget.HorizontalRadioRenderer),
        initial='approve')

    rotate = forms.ChoiceField(
        label='Rotate?',
        choices=self.ROTATE_CHOICES,
        widget=forms.RadioSelect(renderer=widget.HorizontalRadioRenderer),
        initial='none')

rawDescription: How to create Django form for a photo grid?

description: Create Django form for a photo grid


code:
functions = {
    'selection1': func1,
    'selection2': func2,
    'selection3': func3,
}

functions[self.function_to_select]()

rawDescription: most efficient way to selection specific function based on input

description: Most efficient way to selection specific function based on input