code: filter(lambda x: x['author'] == 'Shakespeare' and x['year'] == 1611, listOfPlays)

rawDescription: javascript's _.where in python

description: Javascript's _.where in python


code:
import example
x = example.X()
str(x)
repr(x)

rawDescription: boost::python::class: programatically obtaining the class name

description: Boost::python::class: programatically obtaining the class name


rawDescription: MongoDB / MongoEngine - Query for Item in List


code:
with open('/proc/stat') as f:
    for ln in f.readlines():
        if ln.startswith('btime'):
            btime = int(ln.split()[1])

rawDescription: Convert "jiffy" time

description: Convert "jiffy" time


code: d.text = ','.join('%s=%s' % (k, xml_dict[k]) for k in sorted(xml_dict.keys()))

rawDescription: Update dictionary in xml from csv file in python


rawDescription: How to let the python descriptor know that an instance of the owning class was deleted

description: Let the python descriptor know that an instance of the owning class was deleted


code:
parser=argparse.ArgumentParser()
arg1= parser.add_argument("num",help="The fibnocacci number to calculate:", type=int)
arg2=parser.add_argument("-f","--file",help="Output to the text file",action="store_true")
arg1
arg2
parser._actions

rawDescription: Extract values from parse.add_argument in Argparse - python


code:
f=plt.figure()
ax=f.add_subplot(1,1,1)
ax.bar([1,2,3,4], [1,2,3,4])
ax.get_children()
ax.get_children()[2].set_color('r')

rawDescription: Setting Different Bar color in matplotlib Python


code:
...

if __name__ == '__main__':
   import os
   os.environ['PYTHONINSPECT'] = '1'
   main()

rawDescription: How do you return to the prompt with access to all objects after a script is finished?

description: Return to the prompt with access to all objects after a script is finished


code:
import urllib

inputfile = urllib.urlopen("http://standards.ieee.org/develop/regauth/oui/oui.txt")
data = inputfile.read()

entries = data.split("\n\n")[1:-1] #ignore first and last entries, they're not real entries

d = {}
for entry in entries:
    parts = entry.split("\n")[1].split("\t")
    company_id = parts[0].split()[0]
    company_name = parts[-1]
    d[company_id] = company_name

rawDescription: Process .txt file into dictionary (Python v2.7)


code: next(iter(grouped))

rawDescription: Pandas stack/groupby to make a new dataframe


rawDescription: BS4 grabbing the contents of a tag with an unusual attribute


code:
if not any(x.value == value for x in some_list):
    print("Not Found.")

rawDescription: How can you execute a command at the end of a for loop?

description: Execute a command at the end of a for loop


rawDescription: Python 2.7+: What's the correct way to format a float in non-scientific notation with certain precision?


code: list(chunks(l, 3))

rawDescription: How do I interpret this Python Code?

description: Interpret this Python Code


code:
img = Image.open('picture.jpg')
img._getexif()
exif_human = { ExifTags.TAGS[k]: v for k, v in img._getexif().items() if k in ExifTags.TAGS}
exif_human

rawDescription: Using Python to extract EXIF tags added by Windows Photo Gallery 2012


code:
"from_user","month","full_text"
"bellaboo",4,"RT @BodilMalmsten: \"om man klarar av att föra ett bestick till munnen eller behöver hjälp på toaletten\"Have a heart, borgarrådet Have a hea,RT @BodilMalmsten: Borgarrådet om riktlinjerna \"om man klarar av att föra ett bestick till munnen eller behöver hjälp på toaletten\" Hjälp 1 min dröm 2 allas önskningar 3 viljan att segra H,RT @BodilMalmsten: Klarar du av att föra ett bestick till munnen eller behöver hjälp på toaletten? http://t.co/fcvcf0U2dW"

rawDescription: regex to delete whitespace in csv-file with quotes to separate text?

description: Regex to delete whitespace in csv-file with quotes to separate text


code:
result = []
with open('file.txt') as f:
    for line in f:
        if line.startswith('chr'):
            label = line.strip()
        elif line[0] == ' ':
            # short sequence
            length = len(line.strip())
            # find the index of the beginning of the short sequence
            for i, c in enumerate(line):
                if c.isalpha():
                    short_index = i
                    break
        elif line[0].isdigit():
            # long sequence
            n = line.split(' ')[0]
            # or
            # n = line[:line.index(' ')]
            # find the index of the beginning of the long sequence
            for i, c in enumerate(line):
                if c.isalpha():
                    long_index = i
                    break
            start = int(n) + short_index - long_index
            # start -= 1
            end = start + length
            result.append('{} {} {}'.format(label, start, end))
            offset, n, start, length = 0, 0, 0, 0

rawDescription: How to extract the location of shorter sequence based on longer sequence using Python?

description: Extract the location of shorter sequence based on longer sequence using Python


code:
momx = ex.dot(f.reshape(f.shape[0],-1)).reshape(f.shape[1:])
momx = np.einsum('ijk,i->jk',f,ex)

rawDescription: multiply-accumulate using numpy

description: Multiply-accumulate using numpy


code: next(base)

rawDescription: Pi calculation in python

description: Pi calculation in python


code:
def all_acknowledged(dict):
    for k in dict:
        if not dict[k]['ack']:
            return False
    return True

rawDescription: python acknowlage in pushover using dict

description: Python acknowlage in pushover using dict


code:
session_manager = SessionManager()
db_session = LocalProxy(session_manager.get_session)

rawDescription: Flask SQLAlchemy setup dynamic URI

description: Flask SQLAlchemy setup dynamic URI


code:
from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
input_zips = []
input_zips = raw_input("Enter zip codes (separated by comma): ").replace(" ", "").split(",") # Remove whitespace and split by comma to list
input_radius = raw_input("Enter radius from entered zip code (in km): ") # In Python 3.x change both raw_input() to input()
for y in range(0, len(input_zips)): # Loop to find and print radius lists
    in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(input_zips[y], input_radius)] # ('ZIP', radius in km)
    radius_utf = map(int, [x.encode('UTF-8') for x in in_radius]) # Unicode list to UTF list and map to convert str list to int list
    print("Target zip: %s, Radius %s km, List of zip codes in radius:\n%s\n" %(input_zips[y], input_radius, radius_utf))

rawDescription: Could I use python to retrieve a number of zip code within a radius


code: py2exe_data_files += add_path_tree( '', 'templates' )

rawDescription: Django translation and py2exe

description: Django translation and py2exe


code: result = [r[0] for r in result]

rawDescription: How to retrieve python list of SQLAlchemy result set?

description: Retrieve python list of SQLAlchemy result set


code:
def foo():
    pass

def bar():
    return foo()

import dis
dis.dis(bar)

rawDescription: Python Function calls are really slow

description: Python Function calls are really slow


code:
import time
interval = 5
next_run = 0
while True:
   time.sleep(max(0, next_run - time.time()))

   next_run = time.time() + interval
   action_print()

rawDescription: python process  takes 100% CPU

description: Python process  takes 100% CPU


code:
from colorExtentions import *

colors = Color.__subclasses__()

rawDescription: python list all imported modules imported via *, the pythonic way

description: Python list all imported modules imported via *, the pythonic way


code:
# Setting the palette using defaults only finds 6 colors
sb.set_palette(cmap)
sb.palplot(sb.color_palette() )
sb.palplot(sb.color_palette(n_colors=8) )

# but setting the number of colors explicitly allows it to use them all
sb.set_palette(cmap, n_colors=8)
# Even though unless you explicitly request all the colors it only shows 6
sb.palplot(sb.color_palette() )
sb.palplot(sb.color_palette(n_colors=8) )

rawDescription: Seaborn palettes - prevent recycling of colors


code:
df['price_bool'] = df.price_change != ' '
df['qty_bool'] = df.qty_change != ' '

rawDescription: Pandas groubpy index count nonblanks

description: Pandas groubpy index count nonblanks


code:
addedText = 'Hello World!'
with open('file.txt', 'r+') as myFile:
    filecontents = myFile.read()
    myFile.seek(0,0)
    f.write(addedText.rstrip('\r\n') + '\n' + filecontents)

rawDescription: Python: Putting Charater in front or behind a file


code:
urls = [re.findall(r'file : "(.*)"', line)[0].replace(',', '')
        for line in file if 'file :' in line]

rawDescription: get line of a predefined sentence that in a txt file line?

description: Get line of a predefined sentence that in a txt file line


code:
while gtk.events_pending():
    gtk.main_iteration()

rawDescription: Using Gtk.spinner with a long time function


code: dict((a, {"b": b, "c": c}) for a, b, c in rows)

rawDescription: What's a better way to handle this in Python


code: {{ forloop.counter0|chr }}

rawDescription: Convert int to ascii [chr()] in django template


rawDescription: Preparing a list from a dictionary in python


code:
y = np.arange(12).reshape(3,4)

b = y < 6
b1 = np.all(b, axis=0)
b2 = np.all(b, axis=1)

y1 = y[b1]
y2 = y[b2]

rawDescription: getting all rows where complex condition holds in scipy/numpy

description: Getting all rows where complex condition holds in scipy/numpy


code:
fig = plt.gcf()
fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)

rawDescription: Disable matplotlib's default arrow key bindings


rawDescription: 2D Array - Select range of columns

description: 2D Array - Select range of columns


code: chkseq = map(int, open("sequence.txt"))

rawDescription: strip ' from all members in a list

description: Strip ' from all members in a list


code:
a = np.arange(0, 10, 2)
b = np.arange(1, 8, 3)
a
b

rawDescription: Using np.searchsorted to find the most recent timestamp


code:
import requests, re
token_pattern = re.compile(r'"csrf_token":\s*"([^"]+)"')
OAuthURL = "https://api.instagram.com/oauth/authorize/?client_id=cb0096f08a3848e65f&redirect_uri=https://www.smashboarddashboard.com/whathappened&response_type=code"
token_pattern.search(requests.post(OAuthURL).content).group(1)

rawDescription: Parse request response for key, value pairs


code:
import numpy
values = numpy.arange(10, dtype=int)
bins = numpy.arange(-1, 11)
freq, bins = numpy.histogram(values, bins)
# freq is now [0 1 1 1 1 1 1 1 1 1 1]
# bins is unchanged

rawDescription: assigning points to bins

description: Assigning points to bins


rawDescription: Find count of unique column elements after using groupby with pandas


rawDescription: how django handle binary post data?

description: How django handle binary post data


code:
import re
s = 'randomwordabcrandomwordsxyzrandomwords'
m = re.search('(abc.*?xyz)', s)
m.group()

rawDescription: Extracting part of a string

description: Extracting part of a string


rawDescription: In python, how can you retrieve a key from a dictionary?


rawDescription: Using decorators at functions call instead of function definitions


rawDescription: Adding labels to Key Value Pairs in JSON


code:
lst = ['GATTACA', 'etc']
[x for x in ''.join(',' if not e else e for e in lst).split(',') if x]

rawDescription: How to join certain items in list

description: Join certain items in list


code:
def is_numeric(s):
    is_digit = True

    for char in s:
        if not char.isdigit() and char not in [" ", ".", ","]:
            is_digit = False
            break

    return is_digit

rawDescription: Creating a list from a string that contains numbers separated by commas; Python 3


code:
from Bio.SeqIO import FastaIO
fasta_out = FastaIO.FastaWriter(handle, wrap=None)
fasta_out.write_file(data)

rawDescription: Using Bio.SeqIO to write single-line FASTA


code:
from datetime import datetime

from scrapy import signals
from twisted.internet.task import LoopingCall

class SpiderDetails(object):
    """Extension for collect spider information like start/stop time."""

    update_interval = 5  # in seconds

    def __init__(self, crawler):
        # keep a reference to the crawler in case is needed to access to more information
        self.crawler = crawler
        # keep track of polling calls per spider
        self.pollers = {}

    @classmethod
    def from_crawler(cls, crawler):
        instance = cls(crawler)
        crawler.signals.connect(instance.spider_opened, signal=signals.spider_opened)
        crawler.signals.connect(instance.spider_closed, signal=signals.spider_closed)
        return instance

    def spider_opened(self, spider):
        now = datetime.utcnow()
        # store curent timestamp in db as 'start time' for this spider
        # TODO: complete db calls

        # start activity poller
        poller = self.pollers[spider.name] = LoopingCall(self.spider_update, spider)
        poller.start(self.update_interval)

    def spider_closed(self, spider, reason):
        # store curent timestamp in db as 'end time' for this spider
        # TODO: complete db calls

        # remove and stop activity poller
        poller = self.pollers.pop(spider.name)
        poller.stop()

    def spider_update(self, spider):
        now = datetime.utcnow()
        # update 'last update time' for this spider
        # TODO: complete db calls
        pass

rawDescription: How to get Python Scrapy Crawler details?

description: Get Python Scrapy Crawler details


code:
# dvf is an instance of DumbVectorFloat
import numpy as np
my_numpy_array = np.asarray( dvf )

rawDescription: Fast conversion of C/C++ vector to Numpy array


code:
new_col = pd.DataFrame(df[k]==v for k,v in di.iteritems()).all()
df['col3'] = new_col

rawDescription: pandas: select all rows matching multiple conditions

description: Pandas: select all rows matching multiple conditions


rawDescription: save simulation data in python

description: Save simulation data in python


code:
s = "accggt agctta gggatc gactta ccttgg"
chks = s.split(" ");
for word in chks:
    for nextWord in chks:
        if word != nextWord:
            if [x == y for (x, y) in zip(word, nextWord)].count(True) == 0:
                print([word, nextWord])

rawDescription: Compare strings and just keep those who have on same positions different characters


code: api.users # via api.__getattr__('users')

rawDescription: Why can I call all these methods that aren't explicitly defined in a class?


code:
req = mechanize.Request("http://www.google.com")
req.set_proxy("localhost:8888","http")
mechanize.urlopen(req)

rawDescription: Programmatic Web Browsing via a Proxy

description: Programmatic Web Browsing via a Proxy


code:
import sys
import imp
import warnings

class TabCheckImporter(object):

    """Finder and loader class for checking for the presence of tabs

    """

    def find_module(self, fullname, path=None):
        """Module finding method

        """
        # Save the path so we know where to look in load_module
        self.path = path
        return self

    def load_module(self, name):
        """Module loading method.

        """
        # Check if it was already imported
        module = sys.modules.get(name)
        if module is not None:
            return module

        # Find the module and check for tabs
        file_, pathname, description = imp.find_module(name, self.path)
        try:
            content = file_.read()
            tab = content.find("\t")
            if tab > -1:
                lineno = content[:tab].count("\n") + 1
                warnings.warn_explicit(
                        "module '{0}' contains a tab character".format(name),
                        ImportWarning,
                        pathname,
                        lineno)
        except Exception as e:
            warnings.warn("Module '{0}' could not be checked".format(name),
                          ImportWarning)

        # Import the module
        try:
            module = imp.load_module(name, file_, pathname, description)
        finally:
            if file_:
                file_.close()

        sys.modules[name] = module
        return module

# Register the hook
sys.meta_path = (sys.meta_path or []) + [TabCheckImporter()]

# Enable ImportWarnings
warnings.simplefilter("always", ImportWarning)

rawDescription: Is there a way to enable the inconsistent whitespace check (-t) in Python by default


code:
import sys
from StringIO import StringIO

sys.stdout = StringIO()

rawDescription: Python 2.7 Keeping track of what's been printed


code:
ymax = np.zeros(13)
month=1
day=0
for j in range(0, len(xmax)):
    if xmax[j]>ymax[month]:
        ymax[month]=xmax[j]
    day = day+1
    if (day>30):
        month = month+1
        day = 0

rawDescription: Monthly mean from daily maxima data text file


code:
form = MyForm(obj=myDataRow)
fields = [val for val in form._fields]
for fieldName in fields:
    fieldProp = getattr(form, fieldName)
    setattr(fieldProp, 'widget', PlainTextWidget())

rawDescription: WTForms - display property value instead of HTML field


code:
def find_name(d, name):
    if d["name"] == name:
        return d
    for d2 in d["decendent"] or []:
        res = find_name(d2, name)
        if res:
            return res

rawDescription: How to get a dictionary and all its elements by key?

description: Get a dictionary and all its elements by key


rawDescription: iterating over a tuple of iterables returned from a function

description: Iterating over a tuple of iterables returned from a function


code:
def add_tests(args_sequence, kwargs_sequence, name_builder, test_func=None):
   def decorator(cls):
      if test_func is None:
          test_func = cls.test_body      # fall back on your current behavior
      elif isinstance(test_func, str):
          test_func = getattr(cls, test_func)
      for args, kwargs in zip(args_sequence, kwargs_sequence):
          def tb(a, kw):
              return lambda self: test_func(self, *a, **kw)
          setattr(cls, name_builder(args, kwargs), tb(args, kwargs))
      return cls

rawDescription: Dynamically adding tests to my Test Cases


rawDescription: Windows Common Item Dialog: ctypes + COM access violation


code:
x = 'foo'
eval(repr(x)) == x

rawDescription: Python __repr__ and None

description: Python __repr__ and None


code:
class Child3(Parent):
    pass

rawDescription: How to enforce (with a warning) that parent functions are called by the children that override them?

description: Enforce (with a warning) that parent functions are called by the children that override them


code:
list_by_fours = []
list_len = len(c.list)
last_point = 0
next_point = 4

while last_point < list_len:
  if next_point > list_len:
    next_point = list_len
  list_by_fours.append(c.list[last_point:next_point])
  last_point += 4
  next_point += 4

#Make sure you add list_by_fours to the template context

rawDescription: issue with printing the elements of an array in django?

description: Issue with printing the elements of an array in django


code:
col_order = (df == 0).sum().sort(inplace=False).index
df[col_order]

rawDescription: Order columns of DataFrame according to values


code:
Element in E
Element in G
Element in F
Element in D

rawDescription: How to print the variables represent instead of the variable?

description: Print the variables represent instead of the variable


code: name = line.split()[-1]

rawDescription: Trying to read all lines in a file and pick out the ones that begin with 'H' or 'S'


rawDescription: How to call a system command with specified time limit in Python?

description: Call a system command with specified time limit in Python


code: getattr(customer, a)

rawDescription: Get properties of object from list

description: Get properties of object from list


rawDescription: counter in loop /list/ count same vale if they are one after another (python)

description: Counter in loop /list/ count same vale if they are one after another (python)


code:
result = []
for d in dict1:
    if regex.search(d):
       result.extend(dict1[d])

rawDescription: how to get dict value by regex in python

description: Get dict value by regex in python


code: t = [i for i in product(*(range(i+1) for i in maxvalues)) if sum(i) == k]

rawDescription: Python: finding all tuples with constrained elements that add up to a constant


code:
from functools import partial
from multiprocessing import Pool

f_in = 'foreman_cif.yuv'
f_out = 'py_10bpp.yuv'

def convert(chunk):
    data = bytearray() # [] -> bytearray(): 17 -> 15 seconds
    data_append = data.append # 15 -> 12  seconds
    for b in bytearray(chunk): # on Python 3: `for b in chunk:`
        data_append((b << 2) & 0xff)
        data_append((b >> 8) & 0xff)
    return data

def main(): # put in main(): # 25 -> 17 seconds
    pool = Pool(processes=2) # 12 -> 6.7 seconds
    with open(f_in, 'rb') as fd_in, open(f_out, 'wb') as fd_out:
        for data in pool.imap(convert, iter(partial(fd_in.read, 8192), b'')):
            fd_out.write(data)
main()

rawDescription: python performance dealing with binary files

description: Python performance dealing with binary files


code:
from scipy.stats import pearsonr
import numpy as np
import pandas as pd

# make some small data
df = pd.DataFrame(np.random.rand(100, 40))

C1 = np.array([[pearsonr(df[i], df[j])[0] for i in df] for j in df])
C2 = np.corrcoef(df.values.T)
np.allclose(C1, C2)
# True

rawDescription: Efficiently calculate and store similarity matrix


code:
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'

rawDescription: how to use bootstrap for the field that's being displayed with {{ form|crispy }} for django

description: Use bootstrap for the field that's being displayed with {{ form|crispy }} for django


code:
mButton = Button(mGui, text = "CON", command = lambda: assign("CON")).pack()
mButton = Button(mGui, text = "MS", command = lambda: assign("MS")).pack()
mButton = Button(mGui, text = "DRN", command = lambda: assign("DRN")).pack()

rawDescription: Using tkinter to assign a global variable and destroy the gui


code:
instances = []
with open('c:/tempdata/test_sort_data.csv') as data:
     for line in data:
         name, c1, c2, c3 = line.strip().split(",")
         c1, c2, c3 = map(int, (c1, c2, c3))
         instances.append(Art(name, c1, c2, c3))

rawDescription: How do i apply a class structure to a csv and then sort it?

description: Apply a class structure to a csv and then sort it


rawDescription: how can I have commas instead of space in a given set of number

description: Have commas instead of space in a given set of number


code:
import os
os.system('ifconfig eth0 192.168.1.5 netmask 255.255.255.0 up')
os.system('ifconfig eth0')

rawDescription: Script downloading file from filesonic

description: Script downloading file from filesonic


code:
def templatetag(f):
    return TemplateExtras.register.tags.setdefault(f.__name__, f)

def templatefilter(f):
    return TemplateExtras.register.filters.setdefault(f.__name__, f)

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

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


code:
import gc
gc.collect()

rawDescription: Understanding reference count of class variable


rawDescription: How to get synonyms from nltk WordNet Python

description: Get synonyms from nltk WordNet Python


rawDescription: Python: how to get this elegantly?

description: Python: how to get this elegantly


rawDescription: Writing a 3D numpy array to files including its indices


code: sorted(yourcounter, key=lambda i: -yourcounter[i])

rawDescription: Put counter into a frequency ordered list


code:
import pandas as pd
import statsmodels.api as sm

NBA = pd.read_csv("NBA_train.csv")
y = NBA['W']
X = NBA[['PTS', 'oppPTS']]
X = sm.add_constant(X)
model11 = sm.OLS(y, X).fit()
model11.summary()

rawDescription: Multiple linear regression in pandas statsmodels: ValueError


code:
from cStringIO import StringIO

output = StringIO()
im.save(output, format='JPEG')
im_data = output.getvalue()

rawDescription: Is it possible to create encodeb64 from Image object?


code:
import ast
source = 'self.labelVariable.set( self.entryVariable.get()+" (You clicked the button)" )'
ast_tree = ast.parse(source, 'adapt.py')
visitor = SelfAttributesVisitor()
visitor.visit(ast_tree)
visitor.attributes

rawDescription: python print variables of a specific line

description: Python print variables of a specific line


code:
import numpy as np
...
img = base64.b64decode(msg.payload)
npimg = np.fromstring(img, dtype=np.uint8)

rawDescription: From JPG to b64encode to cv2.imread()

description: From JPG to b64encode to cv2.imread()


rawDescription: Find author name in multiple files and folders in python


code:
def add_child(self, node):
    node.parent = self
    node.level = self.level + 1
    self.children.append(node)
    return node

rawDescription: clustering based on thresholds

description: Clustering based on thresholds


code:
user = auth_with_password(email, password)
token = user['user']['token']
FIREBASE.child('/messages/').get(token=token)

rawDescription: Python Firebase authentication

description: Python Firebase authentication


rawDescription: Saving all open matplotlib figures in one file at once


code:
from mod_m import ModM
from package_p import SubModS

s0 = SubModS()
s0.see_class('ModM')
s0.see_class('UnBasedClass')
s0.create_inst('ModM')

m0 = ModM()
m0.see_class('SubModS')
m0.create_inst('SubModS')

rawDescription: least burdensome technique for package submodule to see all classes of importer

description: Least burdensome technique for package submodule to see all classes of importer


rawDescription: Merge lists of different size with order


code:
class MyObject(object):
    def __init__(self, attr1 = default1, attr2 = default2):
        self.attr1 = attr1
        self.attr2 = attr2

rawDescription: How to define a default list of attributes for a Python object?

description: Define a default list of attributes for a Python object


code: open(file, "a")

rawDescription: Open/write deleting txt file contents?

description: Open/write deleting txt file contents


code:
df1 = pd.read_csv(io.StringIO("""
a b
1 10
12 15
18 19
"""), delim_whitespace=True)

df2 = pd.read_csv(io.StringIO("""
a b
1 5
2 10
12 13
13 20
50 60
"""), delim_whitespace=True)

rawDescription: Determine if one range is within another


code:
xpp = (x.ctypes.data + np.arange(x.shape[0]) * x.strides[0]).astype(np.uintp)
doublepp = np.ctypeslib.ndpointer(dtype=np.uintp)

rawDescription: Pass a 2d numpy array to c using ctypes

description: Pass a 2d numpy array to c using ctypes


rawDescription: Fill zero values of 1d numpy array with last non-zero values


code: objOut.obj = np.append(objOut.obj, [0.25])

rawDescription: Modify a member variable outside the class object and have changes in the class object


rawDescription: how django handle binary post data?

description: How django handle binary post data


code:
first_list = ['abcdfghij', 'xyzxyzxyz', 'fjgjgggjhhh']
second_list = ['abcdfghi', 'xyzxyzxy', 'xxx']
second_set = set(second_list)
third_list = [value for value in first_list if value[:8] in second_set]
third_list

rawDescription: Efficient way to loop on comparing string list element to a string list sub-element


code: numeric_lis_of_cols, = np.in1d(df.columns, list_of_columns).nonzero()

rawDescription: pandas get numpy ndarray using series.values

description: Pandas get numpy ndarray using series.values


code:
var1 = 1
var2 = 2

def myFunc(varname):
    globals()[varname] = 10

print(var1, var2)

myFunc("var1")
myFunc("var2")

print(var1, var2)

rawDescription: Python: modify global var from a function argument


rawDescription: python button does not work when image is added

description: Python button does not work when image is added


rawDescription: generating random values based on condition in structured array python

description: Generating random values based on condition in structured array python


code:
def path_file():
    def wrapper(user, filename):
        file_upload_dir = os.path.join(settings.MEDIA_ROOT, 'file_upload')
        if os.path.exists(file_upload_dir):
            import shutil
            shutil.rmtree(file_upload_dir)
        return os.path.join(file_upload_dir, filename)
    return wrapper

rawDescription: Delete a media file after each succesive upload in Django


code:
import datetime as dt
date = dt.datetime(1970, 1, 1)
dates = [dt.datetime(1970, 1, 2), dt.datetime(1970, 1, 3)]
min(dates, key=lambda d: abs(d - date))

rawDescription: Get the closest datetime from a list

description: Get the closest datetime from a list


rawDescription: How to make an unaware datetime timezone aware in python

description: Make an unaware datetime timezone aware in python


code:
for rdir, directory, files in os.walk(r'/home/pawel/Documents'):
         for f in files:
             match = re.findall(pdf_re, f)
             if match:
                 matching_file = os.path.join(rdir, f)
                 target_location = os.path.join(pdfdir, f)
                 os.rename(matching_file, target_location)

rawDescription: Finding and moving PDF and DOC files to different directories using python


rawDescription: How to convert a string representing a binary fraction to a number in Python

description: Convert a string representing a binary fraction to a number in Python


rawDescription: Python- My for loop only converts half the list from str to int


rawDescription: pandas rolling sum of last five minutes

description: Pandas rolling sum of last five minutes


code:
class ThingWithStats(object):
    def __init__(self, name, stats):
        self.name = name
        self.stats = Stats(*stats)
    def __str__(self):
        return self.name + " (" + str(self.stats) + ")"

class Driver(ThingWithStats):
    pass

class Vehicle(ThingWithStats):
    pass

class Combination(ThingWithStats):
    def __init__(self, driver, vehicle):
        self.name = driver.name + " riding " + vehicle.name
        self.stats = add_stats(driver.stats, vehicle.stats)

rawDescription: What is an elegant way to solve this max and min problem in Ruby or Python?


rawDescription: Efficient storage of large string column in pandas dataframe


code:
if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    wsgi_mounter = WsgiMounter({
        'app1': app1,
        'app2': app2,
    })
    server = make_server('0.0.0.0', 8000, wsgi_mounter)
    server.serve_forever()

rawDescription: Multiple namespaces in spyne SOAP web service


code:
import base64
bcode = base64.encodestring(code)
bcode
base64.decodestring(bcode)

rawDescription: Python: remove ^A in a string

description: Python: remove ^A in a string


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')

driver = webdriver.Chrome(chrome_options=options)
driver.get('https://www.ihp.hku.hk/sfb.html')

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "frameset")))
driver.switch_to.frame(1)

driver.find_element_by_link_text('Badminton: max 4 persons per court').click()

rawDescription: Selenium Webdriver give NoSuchFrameException


rawDescription: Create a Series from a Pandas DataFrame by choosing an element from different columns on each row


code:
from datetime import date
a = date(2014,11,10)
b = date(2014,12,24)
b-a
(b-a).days   # if you need the number of days as an integer

rawDescription: Python Calculation

description: Python Calculation


rawDescription: How to get the index and occurance of each item using itertools.groupby()

description: Get the index and occurance of each item using itertools.groupby()


code:
class Foo(object):
    def produce_nested_scope():
        class Bar(object):
            pass
        class Baz(object):
            class InnerBar(Bar):
                pass
        return Bar, Baz
    Bar, Baz = produce_nested_scope()
    del produce_nested_scope

rawDescription: Possible to achieve inheritance from nested class definitions?


code:
import random

with open("file.txt") as x:
    words = x.read().splitlines()

def c_grid(l):
    grid = [listofwords[i:i + 5] for i in range(0, len(listofwords), 5)]
    for l in grid:
        print("".join("{:10}".format(i) for i in l))

listofwords = [words.pop(random.choice(range(len(words)))) for x in range(25)]
print(listofwords)
c_grid(listofwords)

rawDescription: Python - Using Random with No Repeated Words and Selecting a Spare Word from a List


code: elem.appendChild( some_other_elem )

rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code:
if shippingDest == "Spain":
    shippingRegion = "Spain"
elif shippingDest == "Portugal":
    shippingRegion = "Portugal"
elif shippingDest in ["France", "Germany", "Luxembourg", "Belgium", "United Kingdom"]:
    shippingRegion = "Euro1"
elif shippingDest in ["Albania", "Andorra", "Austria", "Belarus", "Bosnia and Herzegovina", "Bulgaria", "Croatia", "Czech Republic", "Denmark", "Estonia", "Faroe Islands", "Finland", "Georgia", "Gibraltar", "Greece", "Hongary", "Iceland", "Ireland", "Italy", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Malta", "Moldova", "Monaco", "Montenegro", "Netherlands", "Norway", "Poland", "Romania", "Russia", "San Marino", "Serbia", "Slovenia", "Svalbard and Jan Mayen", "Sweden", "Switzerland", "Ukraine", "Vatican City State"]:
    shippingRegion = "Euro2"
else:
    shippingRegion = "World"

rawDescription: Python - Check if word matches list of words with IF statement


code:
#!/usr/bin/env python

# smooth.py
__version__ = 0.1

# Version 0.1    29 Feb 2016    ELH    Test release

import numpy as np
import matplotlib.pyplot as mp

def Smooth(v1, w, nanopt):

    # v1 is the input 2D numpy array.
    # w is the width of the square window along one dimension
    # nanopt can be replace or propagate

    '''
    v1 = np.array(
    [[3.33692829e-02, 6.79152655e-02, 9.66020487e-01, 8.56235492e-01],
    [3.04355923e-01, np.nan        , 4.86013025e-01, 1.00000000e+02],
    [9.40659566e-01, 5.23314093e-01, np.nan        , 9.09669768e-01],
    [1.85165123e-02, 4.44609040e-02, 5.10472165e-02, np.nan ]])
    w = 2
    '''

    mp.imshow(v1, interpolation='None', cmap='autumn')
    mp.show()

    # make a copy of the array for the output:
    vout=np.copy(v1)

    # If w is even, add one
    if w % 2 == 0:
        w = w + 1

    # get the size of each dim of the input:
    r,c = v1.shape

    # Assume that w, the width of the window is always square.
    startrc = (w - 1)/2
    stopr = r - ((w + 1)/2) + 1
    stopc = c - ((w + 1)/2) + 1

    # For all pixels within the border defined by the box size, calculate the average in the window.
    # There are two options:
    # Ignore NaNs and replace the value where possible.
    # Propagate the NaNs

    for col in range(startrc,stopc):
        # Calculate the window start and stop columns
        startwc = col - (w/2)
        stopwc = col + (w/2) + 1
        for row in range (startrc,stopr):
            # Calculate the window start and stop rows
            startwr = row - (w/2)
            stopwr = row + (w/2) + 1
            # Extract the window
            window = v1[startwr:stopwr, startwc:stopwc]
            if nanopt == 'replace':
                # If we're replacing Nans, then select only the finite elements
                window = window[np.isfinite(window)]
            # Calculate the mean of the window
            vout[row,col] = np.mean(window)

    mp.imshow(vout, interpolation='None', cmap='autumn')
    mp.show()

    return vout

rawDescription: Replicate IDL 'smooth' in Python 2.7

description: Replicate IDL 'smooth' in Python 2.7


rawDescription: Basic Python methods & GUI assistance

description: Basic Python methods & GUI assistance


code: name_story.name = dict['data']['name']

rawDescription: Layer between data extraction and storage


code: from __future__ import absolute_import

rawDescription: Basic Python imports question

description: Basic Python imports question


code:
def test():
   return 1,2,3

def test2(arg1, arg2, arg3):
   print(arg1, arg2, arg3)

test2(*test())

rawDescription: accepting return values for arguments to a function

description: Accepting return values for arguments to a function


code: new_list = [[i, 0 if sublist[0] is 'A' else 1, sublist[1], -1 if sublist[0] is 'A' else 1.2*sublist[1]] for i, sublist in zip(xrange(0, len(plot)), plot)]

rawDescription: Edit and append items to nested list - Python 2.7


code:
with open('Franchise_Name_Scrub_List.csv', 'rb') as f1, \
     open('sample_FACTS_bronto_import_add.csv', 'ab') as f2:
    f2.writelines(f1)

rawDescription: Writing csv in python

description: Writing csv in python


code:
def integrate(f, a, b):
    h = float(b-a)/10
    I = 0;
    for i in range(10):
        I += f(h*i)

    return I

A = zeros(N)
for k in range(N):
    A[k] = integrate(lambda x: cos(k*x), a, b)

rawDescription: Python changing function definition in loop?


code: {{ grains.fqdn_ip }}

rawDescription: How to get IP address of hostname inside jinja template

description: Get IP address of hostname inside jinja template


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: python -> combinations of numbers and letters

description: Python -> combinations of numbers and letters


code:
from distutils.core import setup, Extension
setup(name='myext', ext_modules=[
    Extension('myext', ['myext.c'], extra_objects=['myfunc.obj'])])

rawDescription: How to get Python to use Assembly

description: Get Python to use Assembly


rawDescription: Dictionary not recognizing floating point keys


code: voxel_adjacency(numpy.array([0, 3, 1, 1, 0, 2]))

rawDescription: Fill scipy / numpy matrix based on indices and values


rawDescription: How do I fill two (or more) numpy arrays from a single iterable of tuples?

description: Fill two (or more) numpy arrays from a single iterable of tuples


code:
D = {u'0HmZNYSfb2': [u'1TkTcV', u'1T8eDK', u'1T2fP4'],
     u'0HYrcjO26wS': [],
     u'0HsGjvej6U': [u'1TzoWb', u'1TbQQl'],
     u'0HsYF0oEuQ': [u'1Tgcdf'],
     u'0Ht2wIpTTc': [] }
df = pd.DataFrame.from_dict(D, orient="index")

rawDescription: Unrolling / expanding a dictionary of iterables into a dataframe


rawDescription: How can I merge one dataframe into another, inserting rows that do not exist?

description: Merge one dataframe into another, inserting rows that do not exist


code: bge.logic.globalDict['mysubdictionaryName'] = { 'namestring' : False}

rawDescription: How to permanently change a variable in a Python game loop

description: Permanently change a variable in a Python game loop


code:
class Animal(object):
    def interact(self):
        print('I am a {}, I say "{}"'.format(self.name(), self.speak()))

class Dog(Animal):
    def name(self):
        return 'dog'
    def speak(self):
        return 'woof'

rawDescription: Python method override rule

description: Python method override rule


code:
t = threading.Timer(10, runCallback, args=[uniqueId, funcs])
t.start()
timers.append((t, uniqueId))
# do other stuff
# ...
# run callbacks right now
for t, uniqueId in timers:
    t.cancel() # after this the `runCallback()` won't be called by Timer()
               # if it's not been called already
    runCallback(uniqueId, funcs)

rawDescription: Python and multiprocessing... how to call a function in the main process?


rawDescription: Python dictionary with list keyword

description: Python dictionary with list keyword


code:
idy, idx = np.unravel_index(cells, dims=(M, N))
neigh_idx = np.vstack((idx-1, idx+1, idx, idx))
neigh_idy = np.vstack((idy, idy, idy-1, idy+1))
np.ravel_multi_index((neigh_idy, neigh_idx), dims=(M,N))

rawDescription: Python, neighbors on a regular grid

description: Python, neighbors on a regular grid


rawDescription: Re-mapping a sorted list into a dictionary


code:
names = dataList.keys()
dfs = dataList.values()
longind = max(dfs, key=len).index
df = pd.concat(dfs, axis=1, keys=names).interpolate('time').loc[longind]

rawDescription: Resampling and merging data frame with python


code:
import numpy as np
np.random.seed(0)
r = np.random.rand(10,2)-0.5
v = np.random.rand(10) + np.random.rand(10)*1j

rawDescription: How to efficiently split a pair of arrays based on a condition on one of them

description: Efficiently split a pair of arrays based on a condition on one of them


code:
from django.db.models import F
Book.objects.all().update(activity=F('views')*4)

rawDescription: Iterating over a large Django queryset while the data is changing elsewhere


code:
from ctypes import *
from ctypes.wintypes import *

kernel32 = WinDLL("kernel32")

ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID = 0x001
ACTCTX_FLAG_LANGID_VALID = 0x002
ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004
ACTCTX_FLAG_RESOURCE_NAME_VALID = 0x008
ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x010
ACTCTX_FLAG_APPLICATION_NAME_VALID = 0x020
ACTCTX_FLAG_HMODULE_VALID = 0x080
DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION = 1

INVALID_HANDLE_VALUE = HANDLE(-1).value
ULONG_PTR = WPARAM  # pointer-sized unsigned integer

class ACTCTX(Structure):
    _fields_ = (("cbSize", ULONG),
                ("dwFlags", DWORD),
                ("lpSource", LPCWSTR),
                ("wProcessorArchitecture", USHORT),
                ("wLangId", LANGID),
                ("lpAssemblyDirectory", LPCWSTR),
                ("lpResourceName", LPCWSTR),
                ("lpApplicationName", LPCWSTR),
                ("hModule", HMODULE))

    def __init__(self, *args, **kwds):
        super(ACTCTX, self).__init__(sizeof(self), *args, **kwds)

CreateActCtxW = kernel32.CreateActCtxW
CreateActCtxW.restype = HANDLE
CreateActCtxW.argtypes = (POINTER(ACTCTX),)
ReleaseActCtx = kernel32.ReleaseActCtx
ReleaseActCtx.restype = None
ReleaseActCtx.argtypes = (HANDLE,)
ActivateActCtx = kernel32.ActivateActCtx
ActivateActCtx.argtypes = (HANDLE, POINTER(ULONG_PTR))
DeactivateActCtx = kernel32.DeactivateActCtx
DeactivateActCtx.argtypes = (DWORD, ULONG_PTR)

if __name__ == "__main__":
    manifest_path = "actctx.manifest" # keep ref
    ctx = ACTCTX(lpSource=manifest_path)
    hActCtx = CreateActCtxW(byref(ctx))
    if hActCtx == INVALID_HANDLE_VALUE:
        raise WinError()

    cookie = ULONG_PTR()
    if not ActivateActCtx(hActCtx, byref(cookie)):
        raise WinError()
    msvcr90 = CDLL("msvcr90")
    if not DeactivateActCtx(0, cookie):
        raise WinError()

    ReleaseActCtx(hActCtx)

    # show DLL path
    hModule = HANDLE(msvcr90._handle)
    path = (c_wchar * 260)()
    kernel32.GetModuleFileNameW(hModule, path, len(path))
    print(path.value)

rawDescription: How do I load a C DLL from the SXS in Python?

description: Load a C DLL from the SXS in Python


code: merge_d = {d1k: d1v+Data2Dict.get(d1k[-5:],[]) for d1k,d1v in Data1Dict.items() }

rawDescription: Merge Dictionaries with different TimeStamp


code:
import re

class ZipRelPath:
    FILE_NAME_RE = re.compile(u"^[a-zA-Z0-9 \$\%\'\-_@~\(\)&+,=\[\]\.\u0080-\uFFFF]+$")
    LANG_TAG_RE  = re.compile("^[a-z]{1,8}(\-[a-z0-9]{1,8})*$")
    LOCALES      = "locales/"

    def __init__(self, path):
        self.path = path
        self.lang_tag = None
        self.folders = []
        self.file_name = None

        self._parse_locales()
        self._parse_folders()

    def _parse_locales(self):
        """Consumes any leading 'locales' and lang-tag"""
        if self.path.startswith(ZipRelPath.LOCALES):
            self.path = self.path[len(ZipRelPath.LOCALES):]
            self._parse_lang_tag()

    def _parse_lang_tag(self):
        """Parses, consumes and validates the lang-tag"""
        self.lang_tag, _, self.path = self.path.partition("/")
        if not self.path:
            raise ValueError("lang-tag missing closing /")
        if not ZipRelPath.LANG_TAG_RE.match(self.lang_tag):
            raise ValueError(u"'%s' is not a valid language tag" % self.lang_tag)

    def _parse_folders(self):
        """Handles the folders and file-name after the locale"""
        while (self.path):
            self._parse_folder_or_file()

        if not self.folders and not self.file_name:
            raise ValueError("Missing folder or file name")

    def _parse_folder_or_file(self):
        """Each call consumes a single path entry, validating it"""
        folder_or_file, _, self.path = self.path.partition("/")
        if not ZipRelPath.FILE_NAME_RE.match(folder_or_file):
            raise ValueError(u"'%s' is not a valid file or folder name" % folder_or_file)
        if self.path:
            self.folders.append(folder_or_file)
        else:
            self.file_name = folder_or_file

    def __unicode__(self):
        return u"ZipRelPath [lang-tag: %s, folders: %s, file_name: %s" % (self.lang_tag, self.folders, self.file_name)

rawDescription: How do I check a string, using python, against some specific ABNF rules?

description: Check a string, using python, against some specific ABNF rules


rawDescription: Python re.split with comma and parenthesis "(" and ")"


code: (r'^dashboard$', 'dashboard_view'),

rawDescription: Showing Django Admin actions on template


rawDescription: HTML-escaping replacement fields when using str.format() in Python


code:
xpr = User.name.match("John Jacob Jingleheimer Schmidt").label("match_result")
q = session.query(User, xpr).filter(xpr > 1)

rawDescription: What's the equivalent of using `select()` with `text()` using the ORM?


code:
#simple transfer files server
import socket, sys

SRV_ADDR = ""
SRV_PORT = 9900

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SRV_ADDR, SRV_PORT))
s.listen(1)

while 1:
    connection, address = s.accept()
    pippo = connection.recv(1024)

    if(pippo.decode('utf-8') == '3'):
       riceivename=connection.recv(1024)
       lettore=riceivename.decode('utf-8')
       file = open(lettore, 'rb')

       while 1:
           data = file.read(1024)
           if not data: break
           connection.sendall(data)
       connection.close()
       file.close()
       print("ok end cicle")

    elif(data.decode('utf-8') == '0'):
          connection.close()

rawDescription: python: not write last bytes tcp?

description: Python: not write last bytes tcp


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *

rawDescription: Running python files

description: Running python files


code:
"ggg".split(",") #no commas to split by.
"g,g,g".split(",") #works when it is seperated by commas

rawDescription: Import text from a txt file as a list within a list, and manipulate that data with column / row coordinates


code:
import itertools

peek = iterable.next()
iterable = itertools.chain([peek], iterable)

rawDescription: How do I check the content of iterable object?

description: Check the content of iterable object


code: pprint([tuple(items) for items in product(l2, [l1[0]], l3)])

rawDescription: How to append elements from 2 short lists into another big list of tuples?

description: Append elements from 2 short lists into another big list of tuples


code:
x = C()
for i in xrange(100000):
    x.update([i])

rawDescription: Fastest way to grow a numpy numeric array


code: {col: df1.loc[df1[col].lt(0), col].to_dict() for col in ['cell_1', 'cell_2']}

rawDescription: Pandas dataframe into sparse dictionary of dictionaries


code:
print(*sorted(pythons_tasklist[0]), sep='\n')
pythons_tasklist[0]['Mem Usage']

rawDescription: How to detect if a process is running using Python on Win and MAC

description: Detect if a process is running using Python on Win and MAC


code:
def add_dict(d, **kw):
    x = d.copy()
    x.update(kw)
    return x

d = { 'foo' : very_long_argument }

urlpatterns = patterns('',
    url('^aaaa/$', 'aaa', d),
    url('^bbbb/$', 'bbb', d),
    url('^cccc/$', 'ccc', add_dict(d, bar = 'xxx')),
)

rawDescription: Django optional url parameter for each url() in a pattern()


code:
from scipy import * # rand
from pylab import * # figure, imshow
from scipy.ndimage import gaussian_filter

# random "image"
I = rand(100, 100)
figure(1)
imshow(I)

# gaussian filter
J = gaussian_filter(I, sigma=10)
figure(2)
imshow(J)

rawDescription: "painting" one array onto another using python / numpy


code:
# helper
def cl(n, func):
    # return a lambda, that returns a list, where func(tion) is called
    return (lambda: [func() for _ in range(n)])

def matrix(base, *ns):
    # the grid lambda (at the start it returns the base-element)
    grid = lambda: base

    # traverse reversed, to handle the midmost values first
    for n in reversed(ns):
        # assign a new lambda with the last grid within (and call it)
        grid = cl(n, grid)

    return grid() # call the full grid (but the matrix calls you ^^)

rawDescription: More elegant way to initialize list of duplicated items in Python


code:
import argparse

parser = argparse.ArgumentParser( version='pyargparsetest 1.0' )
subparsers = parser.add_subparsers(help='commands')

# all
all_parser = subparsers.add_parser('all', help='process all apps')
all_parser.set_defaults(which='all')

# app
app_parser = subparsers.add_parser('app', help='process a single app')
app_parser.add_argument('appname', action='store', help='name of app to process')
app_parser.set_defaults(which='app')

rawDescription: argparse: identify which subparser was used

description: Argparse: identify which subparser was used


code:
windows = rolling_window(a, 3)
sub = [8, 4, 0]
hits = numpy.ones((len(a) - len(sub) + 1,), dtype=bool)
for i, x in enumerate(sub):
    hits &= numpy.in1d(windows[:,i], [x])

hits
hits.nonzero()

rawDescription: Python/NumPy first occurrence of subarray


code:
prev = None
for cur in some_list:
   if (prev is not None) and (prev > cur):
       do_something()
   prev = cur

rawDescription: how to iterate/loop over a list and reference previous (n-1) element

description: Iterate/loop over a list and reference previous (n-1) element


code:
names = ["Name1", "Name2", "Name3"]
f = open("names.txt", "a")
for i in names:
    f.write(i + "\n")
f.close()

rawDescription: Pygame: Writing Multiple Lines

description: Pygame: Writing Multiple Lines


code:
def AllCountries(request):
    country_names = list(Countries.objects.values_list('country_name', flat=True))
    data = {'country_names': country_names}
    return JsonResponse(data)

rawDescription: How to get the values in django model field?

description: Get the values in django model field


code:
MAX_NUM_ELEMS = 2 #you'll want this to be 200
nameCounter = 1
numElemsCounter = 0
with open('bigfile.txt', 'r') as bigfile:
    outputFile = open('output' + str(nameCounter) + '.txt', 'a')
    for letter in bigfile.read():
        if letter == ',':
            numElemsCounter += 1
        if numElemsCounter == MAX_NUM_ELEMS:
            numElemsCounter = 0
            outputFile.close()
            nameCounter += 1
            outputFile = open('output' + str(nameCounter) + '.txt', 'a')
        else:
            outputFile.write(letter);
    outputFile.close()

rawDescription: Python 2.7 - Split comma separated text file into smaller text files


code:
def get(x, axis=0, index=0):
    return np.rollaxis(x, axis, 0)[index]

x = np.arange(27).reshape(3, 3, 3)

assert np.all(get(x, 1, 2) == x[:, 2, :])

rawDescription: Copy a single axis of a numpy array by index


rawDescription: How to retrieve the storyline paragraph with imdbpy?

description: Retrieve the storyline paragraph with imdbpy


code:
homes = [i.home for i in fixtures[:5]]
aways = [i.away for i in fixtures[:5]]

rawDescription: How to slice a list of objects in association of the object attributes

description: Slice a list of objects in association of the object attributes


code:
{'corse': 378, 'cielo': 209, 'mute': 16}
{'corse': 'Definition of "corse"', 'cielo': 209, 'mute': 16}

rawDescription: Python dictionary replace values

description: Python dictionary replace values


rawDescription: Package data with relative path

description: Package data with relative path


code: price_str = price.get_text() # $17.95

rawDescription: Parsing text in BS4

description: Parsing text in BS4


code:
def create_avg(*args):
    data = {}
    for field_name in Avg._meta.get_all_field_names():
        if field_name != 'id':
            for instance in args:
                if hasattr(instance, field_name):
                    data[field_name] = getattr(instance, field_name)
                    break
    Avg.objects.create(**data)

rawDescription: Django easy way to create model from a multiple models


code:
def getImages(self, img_list) :
    nb_img = len(img_list)
    i = 1.0
    for img in img_list :
        self.progress_interface.set_progress(i, nb_img)
        gtk.gdk.threads_enter()
        get_maps.download_image(img)
        gtk.gdk.threads_leave()
        i += 1.0
        yield True
    self.progress_interface.progress_bar.set_text("Les images sont à jour")
    self.progress_interface.progress_bar.set_fraction(1)
    map_loading = self.loadMap()
    gobject.idle_add(map_loading.next)
    yield False

def loadMap(self, step=128) :
    i = 1.0
    nb_tiles = len(self.graph) * len(self.graph[0])
    self.grid.iconview.freeze_child_notify()
    for row in self.graph :
        for col in row :
            ...
            self.grid.listStore.append(...)
            self.progress_interface.progressbar_map.set_fraction(i/nb_tiles)
            self.progress_interface.progressbar_map.set_text("Chargement des tuiles en cours ...")
            i += 1.0
            if (i % step) == 0:
                self.grid.iconview.thaw_child_notify()
                yield True
                self.grid.iconview.freeze_child_notify()
    self.grid.iconview.set_model(self.grid.listStore)
    self.grid.iconview.thaw_child_notify()
    yield False

rawDescription: Is there a way to continue only when gobject.idle_add() function terminate?


code:
tests.py
import io

from django.test import TestCase
from django.template.engine import Engine

from core.loader import CustomLoader as BaseLoader  # this is your custom template loader you want to test

class HelperLoader(BaseLoader):
    is_usable = True

    def load_template_source(self, template_name, template_dirs=None):
        out_source, path = super(HelperLoader, self).load_template_source(template_name, template_dirs=None)
        self.out_source = out_source
        return out_source, path

    class CustomLoaderTest(TestCase):
        def test_custom_loader(self):
            template_path = 'index.html'
            engine = Engine()
            engine.dirs = ['core/templates',]  # `core/templates` is where your test template_path is located.
            out = HelperLoader(engine)
            template = out.load_template(template_path )
            self.assertEqual('template source with updated content.', out.out_source)

rawDescription: Having issues in Unit TestCases for Custom Loader for template in django


code: bb = bb.swapaxes(1,2)

rawDescription: Select values from a set of arrays according to an array of permutations


code:
browser = mechanize.Browser()
browser.set_proxies({"http": "111.11.11.11"})
response = browser.open("http://google.com")

rawDescription: Programmatic Web Browsing via a Proxy

description: Programmatic Web Browsing via a Proxy


code:
import time

def localTzname():
    if time.daylight:
        offsetHour = time.altzone / 3600
    else:
        offsetHour = time.timezone / 3600
    return 'Etc/GMT%+d' % offsetHour

rawDescription: How to get system timezone setting and pass it to pytz.timezone?

description: Get system timezone setting and pass it to pytz.timezone


code:
for cards in jsonList:
    cardData = {}
    cardData['name'] = cards['name']
    data.append(cardData)

rawDescription: Django Iterating Json Response In Template


code:
class Circle:
    @annotate_from(Shape.area)
    def area(self):
        return math.pi * self.radius ** 2

class Rectangle:
    @annotate_from(Shape.area)
    def area(self):
        return self.height * self.width

rawDescription: How to type annotate overrided methods in a subclass?

description: Type annotate overrided methods in a subclass


code:
class ProductList(ListView):
    template = 'template.html'
    queryset = Product.objects.all()

rawDescription: django queryet to print product and it's models

description: Django queryet to print product and it's models


code:
gauss_toler = 0.3
value = chi2.ppf(gauss_toler,3)
lb = 1; ub = 5; runpts = 10000;
if sdwidth == None:
     sstore = -1
     sdb = 100
     alpha = 0
     i = 0
     if type(which_people) == int:
         indices = intersect1d(where( pet_bar[:,0] == 1)[0], where( pet_bar[:,2] == i+1)[0])
     else:
         indices = intersect1d(where( pet_bar[:,0] > 0)[0], where( pet_bar[:,2] == i+1)[0])
     # determines whether take all or >0 just takes unanimously heard correctly
     if unanimous_only == True:
         indices = intersect1d(indices, where(pet_bar[:,3] > 0.5)[0])
     pet_bar_anal = pet_bar[indices,-3:]
     cov_mat[i] = cov(pet_bar_anal, rowvar=False)
     means_mat[i] = mean(pet_bar_anal, axis=0)
     x, y, z = sphere(1, (npts,npts))
     ap = vstack((x.flatten(),y.flatten(),z.flatten()))
     d, v = eig(cov_mat[i])
     for sdwidth in linspace(lb,ub,runpts):
          n = dot(v, (sdwidth*sqrt(d))*eye(3,3))
          out = dot(n,ap)
          bp = out + tile(means_mat[i], (npts**2,1)).T
          xp = points_mat[i,0] = reshape(bp[0], x.shape)
          yp = points_mat[i,1] = reshape(bp[1], x.shape)
          zp = points_mat[i,2] = reshape(bp[2], x.shape)
          poi = array((points_mat[i,0,0,0], points_mat[i,1,0,0], points_mat[i,2,0,0]))
          temp_cov = cov_mat[i]
          temp_me = means_mat[i]
          a = dot(dot((poi-temp_me).T,inv(temp_cov)),poi-temp_me)
          if abs(a-value) < sdb:
             sstore = sdwidth
             alpha = a
             sdb = abs(a-value)
     sdwidth = sstore

rawDescription: Drawing from certain probabilities in Gaussian Normal Multivariate Distribution in numpy


code: os.system("start " + content)

rawDescription: Open new prompts to run binaries in python


code:
def __iadd__(self, other):
    self.update(other)
    return self

def __add__(self, other):
    return self.value + other

def __str__(self):
    return str(self.value)

rawDescription: Can I make a class which behaves like an immutable (float)?

description: Make a class which behaves like an immutable (float)


code:
df["Order"] = df.groupby("PersonID")["DateTime"].rank()
df

rawDescription: How can I do a sequential count based on column value and timestamp in pandas?

description: Do a sequential count based on column value and timestamp in pandas


code:
class Result():
    def __init__(self, result, notes=[]):
        self.Res = result
        self.Notes  = notes   # List of strings
    # ...

rawDescription: How do I live with variables not being local in for loop in Python

description: Live with variables not being local in for loop in Python


code:
def bisect_iter_to_list(pred, it):
    l1 = []
    for i in it:
        if pred(i):
            l1.append(i)
        else:
            l2 = [i]
            l2.extend(it)
    return l1, l2

bisect_iter_to_list(str.isalpha, iter(l))

rawDescription: how to split a list in two at the point where predicate is first False

description: Split a list in two at the point where predicate is first False


code:
from cStringIO import StringIO
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage

def convert(fname, pages=None):
    if not pages:
        pagenums = set()
    else:
        pagenums = set(pages)

    output = StringIO()
    manager = PDFResourceManager()
    converter = TextConverter(manager, output, laparams=LAParams())
    interpreter = PDFPageInterpreter(manager, converter)

    infile = file(fname, 'rb')
    for page in PDFPage.get_pages(infile, pagenums):
        interpreter.process_page(page)
    infile.close()
    converter.close()
    text = output.getvalue()
    output.close
    return text

rawDescription: I want to extract text from a PDF to a .text file using PDFminer. I have found the code but I have no idea how to use it


code: {'subject': 'A subject', 'title': 'A title'}

rawDescription: Is there any way to pass all variables in the current scope to Mako as a context?


code:
for e in edge_groups:
    print('NEW EDGE GROUP')
    x = random.choice(MSO)
    for p in e:
        p.setAttribute('speed', x)
        print('  E from "%s" to "%s" at "%s"' % (p.getAttribute('from'), p.getAttribute('to'), x))

rawDescription: Pair items of a list depending on value

description: Pair items of a list depending on value


code:
from bottle import route, run, request

@route('/calculate')
def index():
    if request.GET.get('operation') == 'addition':
        return str(int(request.GET.get('number1')) + int(request.GET.get('number2')))
    else:
        return 'Unsupported operation'

if __name__ == '__main__':
    run(host='123.45.67.89', port=12345)

rawDescription: What's a simple way to build a python web service which will take arguments and return a value?


code:
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(self, parent)
        UiLoader().loadUi('main.ui', self)
        self.listWidget.addItems(['Item {0}'.format(x) for x in range(100)])

rawDescription: How do I load children from .ui file in PySide?

description: Load children from .ui file in PySide


code:
def calculate_factorial_multi2(number):
    prime = [True]*(number + 1)
    result = 1
    factor2 = 0
    factor5 = 0
    for i in xrange (2, number+1):
        if prime[i]:
            #update prime table
            j = i+i
            while j <= number:
                prime[j] = False
                j += i
            #calculate the number of i in factors of n!
            sum = 0
            t = i
            while t <= number:
                sum += number/t
                t *= i
            if i == 2:
                factor2 = sum
            elif i == 5:
                factor5 = sum
            else:
                result *= i**sum

    return (result << (factor2 - factor5))*(10**factor5)

rawDescription: Calculating the factorial without trailing zeros efficiently?


code:
@property
def ix(self):
    return self.data.ix

def __getitem__(self, key):
    return self.data.__getitem__(key)

rawDescription: Dynamically Generating Pandas Views

description: Dynamically Generating Pandas Views


rawDescription: Mocked Class & Asserting Method Calls

description: Mocked Class & Asserting Method Calls


rawDescription: Python splitting with string as delimiter


code:
class PostForm(ModelForm):
    class Meta:
        model = models.Post
        fields = ['text', 'products', 'image']
        widgets = {
            'text': Textarea(attrs={'cols': 80, 'rows': 10}),
            'products': SelectMultiple(),
        }

class PostView(AuthenticatedUserView):
    template_name = 'myapp/post.html'

    def get_if_authenticated(self, request, user):
        form = PostForm()
        return render(request, self.template_name, {"form": form})

    def post_if_authenticated(self, request, user):
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = user
            post.save()
            return HttpResponseRedirect(reverse('myapp:actions'))
        return render(request, self.template_name, {"form": form})

rawDescription: Unable to get post data in a multipleChoiceField with django


code:
for r in range(len(dic[j][2])):
    if(dic[j][2][r] in dic[k][2]):
        temp_score += 1

rawDescription: How to reduce the number of for-loops for shortening running time in Python programming?

description: Reduce the number of for-loops for shortening running time in Python programming


code:
{'available': 1,
 'code': 'chateau-des-tours-brouilly-2009-1',
 'image': 'http://ei.isnooth.com/wine/b/7/8/wine_6316762_search.jpeg',
 'link': 'http://www.snooth.com/wine/chateau-des-tours-brouilly-2009-1/',
 'name': 'Chateau des Tours Brouilly',
 'num_merchants': 10,
 'num_reviews': 1,
 'price': '14.98',
 'region': 'France > Burgundy > Beaujolais > Brouilly',
 'snoothrank': 3,
 'tags': 'colorful, mauve, intense, purple, floral, violet, lively, rich, raspberry, berry',
 'type': 'Red Wine',
 'varietal': 'Gamay',
 'vintage': '2009',
 'winery': 'Chateau Des Tours',
 'winery_id': 'chateau-des-tours'}

rawDescription: formatting string output with linebreaks and tabs in Python?

description: Formatting string output with linebreaks and tabs in Python


code:
def serve_forever(self, poll_interval=0.5):
    """Handle one request at a time until shutdown.

    Polls for shutdown every poll_interval seconds. Ignores
    self.timeout. If you need to do periodic tasks, do them in
    another thread.
    """
    self.__is_shut_down.clear()
    try:
        while not self.__shutdown_request:
            # XXX: Consider using another file descriptor or
            # connecting to the socket to wake this up instead of
            # polling. Polling reduces our responsiveness to a
            # shutdown request and wastes cpu at all other times.
            r, w, e = _eintr_retry(select.select, [self], [], [],
                                   poll_interval)
            if self in r:
                self._handle_request_noblock()
    finally:
        self.__shutdown_request = False
        self.__is_shut_down.set()

def shutdown(self):
    """Stops the serve_forever loop.

    Blocks until the loop has finished. This must be called while
    serve_forever() is running in another thread, or it will
    deadlock.
    """
    self.__shutdown_request = True
    self.__is_shut_down.wait()

rawDescription: Shutting down python TCPServer by custom handler


code:
@callonce
def long_running_function(x, y, z):
    # do something expensive with x, y, and z, producing result
    return result

rawDescription: Function which computes once, caches the result, and returns from cache infinitely (Python)


code:
myprint(a)
myprint(b)
myprint(c)

rawDescription: Python 3: Change default values of existing function's parameters?


code:
import pywapi
import time
import serial #The PySerial module

# create a file
file = open("weatherData.txt", "w+")
file.close()

ser = serial.Serial("COM3", 9600) #Change COM3 to whichever COM port your arduino is in

for i in range(0,10):
    weather = pywapi.get_weather_from_weather_com("90210")['current_conditions']['text']
    print(weather)

    if "rain" or "showers" in weather:
        weatherValue = "4"

    if "Sun" in weather:
        weatherValue = "2"
    if "thunder" in weather:
        weatherValue = "5"
    #elif "Cloud" in weather:
    if "Cloudy" in weather:
        weatherValue = "3"
        print(weatherValue)

    # append the file with number
    # append with a comma after and space
    file = open("weatherData.txt","a")
    file.write(weatherValue + ", ")
    file.close()

    #Sending the file via serial to arduino
    byte_signal = bytes([weatherValue])
    ser.write(byte_signal)

    time.sleep(10)

rawDescription: Arduino Reading from a constantly updating file


code: chroot /mnt

rawDescription: Generating requirements.txt from mounted filesystem?


code:
import json
import datetime

data = json.loads(your_json_value)

for _, date in data['values']:
    date = datetime.datetime.strptime(date, '%Y-%m-%d').date()

rawDescription: JSON value parse with Python

description: JSON value parse with Python


rawDescription: Stepping dates with timedelta in months for Python


code:
seen = set()
block = [row for row in block if row[0] not in seen and not seen.add(row[0])]

rawDescription: Delete same rows from list of lists in python


code: json.loads(s, object_pairs_hook=(lambda x:  x))

rawDescription: Python JSON parse duplicate records

description: Python JSON parse duplicate records


code: strains = [[] for _ in xrange(11)]

rawDescription: How can I use the command vars()[x] into a function?

description: Use the command vars()[x] into a function


code:
import pandas as pd
from StringIO import StringIO

data = """
date,   c1
2012-07-31 02:00, 1.1
2012-07-31 02:15, 2.2
2012-07-31 02:30, 3.3
"""

df = pd.read_csv(StringIO(data), parse_dates=['date'])

rawDescription: Reading in datetime pandas without having to convert


code: x = sum(L[i]) / n

rawDescription: Algorithm to find least sum of squares of differences


code:
def numVowels(file):
    with open(file) as f:
        return sum(1 for content in f for char in content if char.lower() in 'aeiou')

rawDescription: Check for letter in text file python

description: Check for letter in text file python


code: _ = [print ('Fight!'), print ('You won.' if (lambda a, b: (lambda a, *b: a (a, *b) ) ( (lambda a, b, c, d, e: e if max (e) == 2 else a (a, b, c, c (b), [print ('Nice job, you knocked him out.'), (1 + e [0], 0 + e [1] )] [1] if d [1] in input ('He throws a {} hook, which way will you dodge? '.format (d [0] ) ) else [print ('Oh no, he knocked you out.'), (0 + e [0], 1 + e [1] )] [1] ) ), b, a, a (b), (0, 0) ) ) ( (lambda a: ('left', 'right') if a.randint (0, 1) else ('right', 'left') ), __import__ ('random') ) [0] == 2 else 'He won.') ]

rawDescription: Using a class to keep score in python

description: Using a class to keep score in python


code: dist = np.sqrt(grp['Latitude'].diff()**2 + grp['Longitude'].diff()**2)

rawDescription: pandas - apply time and space functions to groupby

description: Pandas - apply time and space functions to groupby


code:
with open('your_file') as fin:
    data = (i for i in fin if not i.isspace())
    for row in data:
        row = next(data)
        # ... do something with every second non empty row

rawDescription: Shortest way to read every second row from file in python


code:
data = ['\n\t\t\tCC=O']
data[0].strip()

rawDescription: How to remove the line breaks in front of a tag in Xpath

description: Remove the line breaks in front of a tag in Xpath


code: ['CC', 'PP<PP-LOC-CC-PP>']

rawDescription: How to split some parts of a line?

description: Split some parts of a line


code:
def example(var1=None, var2=None, var3=None, multi_values=None):
    if multi_values is None:
        multi_values = []
    # whatever

rawDescription: How to use optional named parameters and *mulit_vars in same function call?

description: Use optional named parameters and *mulit_vars in same function call


code:
class ManagerPage(webapp2.RequestHandler):

    def get(self):

        # This returns a Manager entity after the user has logged in with
        # Oauth2. If the user is logging in for the first time, this will
        # be a blank Manager entity.
        self.get_manager()

        # Temporary processing to link accounts.  If the user is still logged
        # as a Google user (because that cookie hasn't expired), then we
        # automatically transfer their old information to the new Manager
        # entity.  In doing the conversion below, manager.linked is set to
        # True so this can't happen more than once.  Now that the Manager
        # entity has been updated, redirect back to the same page.
        gae_user = users.get_current_user()
        if not manager.linked and gae_user:
            manager.convert_old_manager(gae_user)
            self.redirect("/manager")

        # Present info to the manager
        ...
        template = JINJA_ENVIRONMENT.get_template("manager.html")
        self.response.write(template.render(template_values))

rawDescription: GAE: converting users from users service to oauth2


code:
import sys

with open(sys.argv[1]) as fh:
    for line in fh:
        if "admin_" in line:
            print(line)

rawDescription: python 3.3 user input

description: Python 3.3 user input


code:
p = sum([Counter({k: ((float(d**2) / len(cs))) for (k, d) in cn.iteritems()}) \
     for cn in cs])

rawDescription: Pythonic way to calculate the mean and variance of values in Counters


code:
g = dfalph[['token', 'year', 'uses', 'books']].groupby(['token', 'year'], as_index=False).sum()
g

rawDescription: How to move pandas data from index to column after multiple groupby

description: Move pandas data from index to column after multiple groupby


code:
result_list = map(dict, itertools.combinations(
    combination_dict.iteritems(), 2))

rawDescription: Getting all combinations of key/value pairs in Python dict


code: board[1] = deck1[:]  # the slicing operator copies a subset or the whole list

rawDescription: The Python assignment operator, function definitions, and variable definitions


code:
parentchild_map = {}
for line in lines:
    if ':' not in line:
         continue
    mother, multichildren = line.split(':')
    children = multichildren.strip().split(', ')
    parentchild_map[mother] = children

rawDescription: Utilising Python dictionaries

description: Utilising Python dictionaries


code:
API_NAME = "gametest"

CACHE_CONTROL = "max-age=20"
CACHE_EXPIRES = 20
MONGO_DBNAME = "gametest"
MONGO_HOST = "localhost"
MONGO_PORT = 27017
PUBLIC_ITEM_METHODS = ["GET"]
RESOURCE_METHODS = ["GET"]

accounts_schema = {
    "username": {
        "type": "string",
        "required": True,
        "unique": True
    },
    "password": {
        "type": "string",
        "required": True
    }
}

accounts = {
    # the standard account entry point is defined as
    # '/accounts/<ObjectId>'. We define  an additional read-only entry
    # point accessible at '/accounts/<username>'.
    "additional_lookup": {
        "url": "regex('[\w]+')",
        "field": "username",
    },

    # We also disable endpoint caching as we don't want client apps to
    # cache account data.
    "cache_control": "",
    "cache_expires": 0,

    # Finally, let's add the schema definition for this endpoint.
    "schema": accounts_schema,
    "public_methods": ["POST"],
    "resource_methods": ["POST"]
}
games_schema = {
    "game_id": {
        "type": "objectid",
        "required": True
    },
    "title": {
        "type": "string",
        "required": True
    }
}

games = {
    "item_title": "game",
    "schema": games_schema
}

orders = {
    "schema": {
        "game": {
            "type": "objectid",
            "required": True,
        }
    },
    "resource_methods": ["GET", "POST"]
}

DOMAIN = {
    "accounts": accounts,
    "orders": orders,
    "games": games
}

rawDescription: In Eve, how can you store the user's password securely?


code: df.loc[df[df<0].dropna().index] = -df

rawDescription: Python Pandas replace values by their opposite sign


code: fd = open('myfilename.tga', 'rb')

rawDescription: PyInstaller: IOError: [Errno 2] No such file or directory:


code:
from flask.ext.login import login_user, logout_user, current_user, login_required

@app.route('/authorize/<provider>')
def oauth_authorize(provider):
    # Flask-Login function
    if not current_user.is_anonymous():
        return redirect(url_for('index'))
    oauth = OAuthSignIn.get_provider(provider)
    return oauth.authorize()

@app.route('/callback/<provider>')
def oauth_callback(provider):
    if not current_user.is_anonymous():
        return redirect(url_for('index'))
    oauth = OAuthSignIn.get_provider(provider)
    username, email = oauth.callback()
    if email is None:
        # I need a valid email address for my user identification
        flash('Authentication failed.')
        return redirect(url_for('index'))
    # Look if the user already exists
    user=User.query.filter_by(email=email).first()
    if not user:
        # Create the user. Try and use their name returned by Google,
        # but if it is not set, split the email address at the @.
        nickname = username
        if nickname is None or nickname == "":
            nickname = email.split('@')[0]

        # We can do more work here to ensure a unique nickname, if you
        # require that.
        user=User(nickname=nickname, email=email)
        db.session.add(user)
        db.session.commit()
    # Log in the user, by default remembering them for their next visit
    # unless they log out.
    login_user(user, remember=True)
    return redirect(url_for('index'))

rawDescription: Using Google OAuth2 with Flask

description: Using Google OAuth2 with Flask


rawDescription: Regular expression for extracting fields from wiki template markup


code:
find_re_results('\d+', '\t', 'Preceding 123:;[]\\:the rest')
find_re_results('\d+', '\W+', 'Preceding 123:;[]\\:the rest')
find_re_results('\t', '\W+', 'Preceding 123:;[]\\:the rest')

rawDescription: Returning NoneType vs. returning "" in re.search


code: modules = [__import__(module) for module in module_files]

rawDescription: Dynamically load python modules

description: Dynamically load python modules


code:
import re

fn = r'D:\temp\.data\36972593_header.csv'
with open(fn) as f:
    data = f.read()

# it will also tolerate if `List(...) is not in the first line`
cols = ['Date'] + re.sub(r'.*List\((.*)\).*', r'\1', data, flags=re.S|re.I|re.M).replace(' ', '').split(',')

fn = r'D:\temp\.data\36972593_data.csv'
# this will also parse `Date` column as `datetime`
df=pd.read_csv(fn, sep=r'\s+', names=cols, parse_dates=[0])

rawDescription: match the dataframe with the list of columns names

description: Match the dataframe with the list of columns names


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

x = np.linspace(0, 10, 1000) # Using a series of 1000 points...
y = np.sin(x)

# Make *y* increment in steps of 0.3
y -= y % 0.3

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

rawDescription: Matplotlib animation of a step

description: Matplotlib animation of a step


code:
from itertools import repeat

mems = range(1, 50000, 2)
mem = 8

def zipij7(m=mem, ms=mems):
  cpy = sorted(ms + [m])
  loc = cpy.index(m)

  return zip(ms[:(loc)], repeat(m)) + zip(repeat(m), ms[(loc):])

def zipinline(m=mem, ms=mems):
  return [(i, m) if i < m else (m, i) for i in ms]

rawDescription: Efficient reordering of coordinate pairs (2-tuples) in a list of pairs in Python


code:
from bs4 import BeautifulSoup
sample = '''\

'''
soup = BeautifulSoup(sample)
soup.select('div[id^=content]')
soup.find_all('div', id=re.compile('^content'))

rawDescription: How to get scrape DIV having Class or ID containing specific text

description: Get scrape DIV having Class or ID containing specific text


code:
class ExampleListView(ListView):
    paginate_by = 10
    paginator_class = ShuffledPaginator
    ...

rawDescription: Django: Randomizing queryset with pagination in class based view


code:
first = named_parameter("firstname", quotedString)
last = named_parameter("lastname", quotedString)
dob = named_parameter("dob", quotedString)
hobbies = named_parameter("hobbies", Suppress("[") + list_of_names + Suppress("]"))
is_minor = named_parameter("is_minor", boolean_value)

rawDescription: PyParsing a string representing a function


code:
super(Intermediary, Derived).foo
super(Intermediary, Derived).foo()
super(Intermediary, Derived).foo(d)

rawDescription: What the difference btween super(type, object) and super(supertype, type) in python?


code:
mylist1 = ['alpha', 'green']
mylist2 = ['blue', 'alpha', 'red']
sort_order = ['red', 'blue', 'green', 'alpha']
mylist1.sort(key=sort_order.index)
mylist1
mylist2.sort(key=sort_order.index)
mylist2

rawDescription: Custom sort order of list

description: Custom sort order of list


code:
#!/usr/bin/env python3

class team:
    def __init__(self, teamdata):
        self.name, self.wins, self.drawn, self.losses = teamdata
    def __repr__(self):
        return self.name.ljust(15) + '{} {} {}'.format(self.wins, self.drawn, self.losses)

lag = []
with open('30eapril.txt', 'rt') as file:
    for line in file:
        lag.append(team(line.split()))

#print("Number of teams: " + str(len(lag)))
for l in lag:
    print(l)

rawDescription: creating objects with attributes from a text file

description: Creating objects with attributes from a text file


code:
results = []
paths = []
for (k,v) in lines.items():
    if keywrd in k:
        results.append(k)
        paths.append(v)

rawDescription: return two lists from a list comprehension -- performance

description: Return two lists from a list comprehension -- performance


code:
def is_four_of_a_kind(hand):
    hand = sorted(hand)
    # assumes length >= 5
    return hand[0][0] == hand[3][0] or hand[1][0] == hand[4][0]

rawDescription: Test 5-card hand for four of a kind

description: Test 5-card hand for four of a kind


code: d.setdefault(day, []).append(activity)

rawDescription: Assign many values to an element of a list


code:
from datetime import timedelta
def diff(s, e):
    _diff = (end_date - start_date)
    while s < e:
        if s.weekday() in {5, 6}:
            _diff -= timedelta(days=1)
        s += timedelta(days=1)
    return timedelta(seconds=_diff.total_seconds())

rawDescription: Time between two dates except weekends

description: Time between two dates except weekends


code:
class RideViewSet(...):

    #...

    @detail_route(methods=['post'])
    def attach(self, request, pk=None):
        ride = self.get_object()
        ride.passengers.add(request.user.userprofile)
        return Response(self.get_serializer(ride).data)

rawDescription: django - Many To Many relationship issue

description: Django - Many To Many relationship issue


code:
next(iter({'name': 'value', 'name2': 'another value'}))
next(iter({}))  # <--  To handle empty case, pass default value
next(iter({}), 'default value')

rawDescription: How does the `for` loop work on dictionaries specifically


code:
from datetime import datetime

sorted(lst, key=lambda d: datetime.strptime(d, '%b %d'))

rawDescription: Python sort list of dates in [MMM dd, MMM dd...] format


code:
import matplotlib.pyplot as plt
plt.imshow(gkern(21), interpolation='none')

rawDescription: How to calculate a Gaussian kernel matrix efficiently in numpy?

description: Calculate a Gaussian kernel matrix efficiently in numpy


code: [i for i in a if not any(x in i for x in b)]

rawDescription: How to remove an array containing certain strings from another array in Python

description: Remove an array containing certain strings from another array in Python


rawDescription: Why isn't my Python 2.7 metaclass function getting invoked for subclasses?


code:
def moveon(event):
    pp.close()

cid = fig.canvas.mpl_connect('key_press_event', moveon)
pp.show()

rawDescription: python and update figure in matplotlib

description: Python and update figure in matplotlib


code: [y[1] for y in x]

rawDescription: Recursively defining an N-dimensional numpy array


code: [x + y for x, y in zip(string, string[i:])]

rawDescription: Grouping in a list with sequence re-read


rawDescription: Can I get JSON to load into an OrderedDict in Python?

description: Get JSON to load into an OrderedDict in Python


code:
data_file = open("task.txt")
block = ""
found = False

for line in data_file:
    if found:
        if line.strip() == "Finished Task:":
           break
        else:                # <--
           block += line     # <--
    else:
        if line.strip() == "Task:":  # <--
            found = True
            block = line

data_file.close()

rawDescription: How to print specific part of a file?

description: Print specific part of a file


code:
reobj = re.compile(r"Tata ([\w ]+\d+).*?$", re.IGNORECASE | re.MULTILINE)
result = reobj.sub(r"\1", subject)

rawDescription: Removing the unwanted substrings from a series of strings


code:
class MutableEfficientNamedList(object):
    __slots__ = ('field1', 'field2', 'field3')

    def __init__(self, *values):
        for k, v in zip(self.__slots__, values):
            setattr(self, k, v)

    def __getitem__(self, i):
        return getattr(self, self.__slots__[i])

    def __setitem__(self, i, v):
        return setattr(self, self.__slots__[i], v)

    def __repr__(self):
        return '{}({})'.format(type(self).__name__,
            ', '.join(repr(getattr(self, s)) for s in self.__slots__))

rawDescription: python - which data structure to use as an array of dicts?

description: Python - which data structure to use as an array of dicts


code:
trial_seq = [ i % 4 for i in xrange(36) ]
random.shuffle(trial_seq)

rawDescription: Generating random numbers in range until a max for that number has been met in python


code:
x = [['temp1_a','temp2_b', None, 'temp3_c'],['list1_a','list2_b','list3_c']]
y, z = [i if i is None else i.split('_')[0] for i in itertools.chain(*x)], [i if i is None else i.split('_')[1] for i in itertools.chain(*x) ]
y
z

rawDescription: How do I split items in a list (with delimiter) within a list?

description: Split items in a list (with delimiter) within a list


code:
s = 'test.zip.zyz'
s = s.split('.zip', 1)[0] + '.zip'

rawDescription: How to delete everything after a certain character in a string?

description: Delete everything after a certain character in a string


code:
l = []
for i in range(2, 11, 2):
    l.append(i)

rawDescription: Storing values from loop in a list or tuple in Python


code:
di={}
for pair in pairs(LoT):
   di[repr(list(pair))]=[theader[i] for i, t in enumerate(zip(*pair)) if t[0]!=t[1]]
di

rawDescription: Element by element comparison in tuple to return set of sets - python


code: last_true_loc = - N - 1

rawDescription: Filling next N rows in pandas with False when True found


code:
import sys
import time
from IPython.display import display,HTML,clear_output
for i in range(10):
    time.sleep(1)
    clear_output(wait=True)
    display(HTML('<b> Hello  ' + str(i) + '</b>'))

rawDescription: Is it possible to dynamically update a cell using HTML for ipython Notebook


code: axR.plot(0, 0, visible=False)

rawDescription: Matplotlib axes autoscale does not work with after twinx()


code:
for iframe in soup.find_all('iframe'):
    info = {
        "src":    iframe.get('src'),
        "height": iframe.get('height'),
        "width":  iframe.get('width'),
    }
    content.append(info)

rawDescription: Create List of Dictionary python

description: Create List of Dictionary python


code:
from sqlalchemy import create_engine
import os
import models

def db_create(conn_string):
    engine = create_engine(conn_string)
    models.Base.metadata.create_all(engine)

rawDescription: Trouble instantiating db SQLAlchemy when importing table class definitions


code:
import copy
def printtext(swefile):
    for row in swefile:
        print(row)
text = open("wordsv.txt","r",encoding='utf-8')
printtext(text)
text.seek(0)
printtext(text)

rawDescription: How to copy text file in python

description: Copy text file in python


code:
L1=[
'YYYYY', 'OPEN',  ' 111',   ' 222', 'CLOSE',
'XXXX','OPEN', '  333', '  444', 'OPEN', '    555', '    666', 'CLOSE','CLOSE'
]
def build_multilevel(entries):
    result = []
    stack = [result]
    for i, entry in enumerate(entries):
        if entry == 'OPEN':
            # convert last element of the top-most list on the stack
            # to a new, nested list, and push that new list on top
            stack[-1][-1] = [stack[-1][-1]]
            stack.append(stack[-1][-1])
        elif entry == 'CLOSE':
            stack.pop()
        else:
            stack[-1].append(entry)
    return result

build_multilevel(L1)

rawDescription: Python: flat delimited list to nested multilevel list


code:
def writerows(self, rowdicts):
    rows = []
    for rowdict in rowdicts:
        rows.append(self._dict_to_list(rowdict))
    return self.writer.writerows(rows)

rawDescription: python program gets KILLED with no errors during csv phare

description: Python program gets KILLED with no errors during csv phare


code:
def func(a,b,x):
    return [i for i,j in zip(a,b) if j == x]

func(a,b,2)

rawDescription: How to filter a list based on another list's values

description: Filter a list based on another list's values


rawDescription: removing pairs of elements from numpy arrays that are NaN (or another value) in Python

description: Removing pairs of elements from numpy arrays that are NaN (or another value) in Python


rawDescription: How can I change '>' to '>' and '>' to '>'?

description: Change '>' to '>' and '>' to '>'


rawDescription: How to discard part of function output in python?

description: Discard part of function output in python


rawDescription: Reduce the decimal points in Python

description: Reduce the decimal points in Python


code:
random.choice(a)
random.choice(a)
bts_a

rawDescription: Simple bootstrap with replacement of list


code: fn = fn[index+1 ::]

rawDescription: python string match time complexity

description: Python string match time complexity


code: myclass('some', 'argument', 'values')

rawDescription: Python27: Subclassing a class by using type


code: xx - yy

rawDescription: calculating distance between two numpy arrays

description: Calculating distance between two numpy arrays


code: subprocess.Popen("'C:\\Program Files\Microsoft Office\Office12\winword.exe' 'P:\\docs\\daily checks.doc' /mFilePrintDefault /mFileExit", shell=True).communicate()

rawDescription: Printing a word Document within Python

description: Printing a word Document within Python


code:
data = MyData(key_name=request_token, db_secret=request_secret)
data.put()

rawDescription: Easiest way to get a GAE datastore entry


code:
import operator
sorted(mainList, key=operator.attrgetter('name', 'level'))

rawDescription: Python: Sort a list of objects based on their attributes


code:
first = [0,1,2,3,4,5]
seen = set(first)
first += [x for x in second if x not in seen and not seen.add(x)]
first

rawDescription: Create a list of integer elements from list of objects


rawDescription: How can I compare two lists in python and return matches

description: Compare two lists in python and return matches


rawDescription: YAML parsing and Python?

description: YAML parsing and Python


code:
query_array = query[0].toarray()
result = map(lambda document: cosine(document.toarray(), query_array), tfidf_matrix)

rawDescription: Better way to map a function (cosine similarity) to each row in scipy.csr_matrix


code:
import urllib

def some_function_that_uses_urllib():
    ...
    urllib.urlopen()
    ...

rawDescription: How can one mock/stub python module like urllib


code:
event_form = EventForm(prefix="event")
event_time_form = EventTimeForm(prefix="eventtime")

rawDescription: Multiple models in one form

description: Multiple models in one form


code:
import functools

@functools.lru_cache()
def getSrc():
    return askdirectory()

rawDescription: Python Reuse a Variable in the Else Block of an If-Else Statement


code: dy = RK4(lambda t, y: t*sqrt(y))

rawDescription: Understanding Python lambdas

description: Understanding Python lambdas


code:
def nt_from_kws(cls, **kw):
    return cls(*(kw[k] for k in cls._fields))

rawDescription: Is it possible to specify attribute names when creating an instance of namedtuple?


code:
#! /usr/bin/env python
from __future__ import print_function
from itertools import product
from random import randint

width, height = 10, 10
known_env = [[0 for x in range(width)] for y in range(height)]
actual_env = [[0 for x in range(width)] for y in range(height)]

# Populate with obstacles
for i in xrange(10):
    x = randint(0, len(actual_env) - 1)
    y = randint(0, len(actual_env[x]) - 1)
    actual_env[x][y] += 1

# Run A* and get a path
path = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4),
        (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]  # dummy path

def effective_slices(i_w, j_h):
    """Note: Depends on globals width and height."""
    w, h = width - 1, height - 1
    i_w_p, j_h_p = max(0, i_w - 1), max(0, j_h - 1)
    i_w_s, j_h_s = min(w, i_w + 1), min(h, j_h + 1)
    return slice(i_w_p, i_w_s), slice(j_h_p, j_h_s)

# Traverse path, checking for "new" obstacles
for step in path:
    x, y = step[0], step[1]
    # check area around agent
    dim_w, dim_h = effective_slices(x, y)
    actual_set = set(map(tuple, actual_env[dim_w][dim_h]))
    known_set = set(map(tuple, known_env[dim_w][dim_h]))
    sym_diff = actual_set.symmetric_difference(known_set)
    if sym_diff:  # internal map doesn't match real world, update
        for (i, j) in product(range(dim_w.start, dim_w.stop + 1),
                              range(dim_h.start, dim_h.stop + 1)):
            if known_env[i][j] != actual_env[i][j]:
                known_env[i][j] = actual_env[i][j]
                # Re-run A*

rawDescription: Fastest method for comparing ranges of multidimensional lists


code:
def do_stuff_use():
    return (x for x in do_stuff() if x is not None)

rawDescription: python 2.7 - is there a more succint way to do this series of yield statements (in python 3, "yield from" would help)

description: Python 2.7 - is there a more succint way to do this series of yield statements (in python 3, "yield from" would help)


code: filter(lambda x: not x[0] in (4, 5, 7), [[a] for a in xrange(10)])

rawDescription: Reducing complexity of following code

description: Reducing complexity of following code


rawDescription: Separate lists of format M=[(a,x), (b,y)] into M1=[a,b] and M2=[x,y]


code:
with open(path + 'result.txt', 'w') as result, contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(path + 'file%d.txt' % (n+1))) for n in range(16)]
    form = ", ".join('{}' for f in files) + '\n'
    for lines in zip(*files):
        result.write(form.format(*map(str.rstrip, lines)))

rawDescription: Elegant way of combining files - Python

description: Elegant way of combining files - Python


rawDescription: Grouping values into lists based on parent list


code:
# change to your custom view
(r'^password_reset/$', 'your_app.views.password_reset'),

rawDescription: Django password reset email subject

description: Django password reset email subject


code:
for i, row in df.iterrows():
    df.loc[i, 'new'] = row['string'][:row['position']]

rawDescription: Python: In a dataframe, create a new column with a string sliced from a column with the value of another column


code:
string = "Will Ferrell (Nick Halsey), Rebecca Hall (Samantha), Michael Pena (Frank Garcia)"

import re
pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)')

lst = [(t[0].strip(), t[1].strip()) for t in pat.findall(string)]

rawDescription: Extracting contents of a string within parentheses


code: dir(dog)

rawDescription: While working on nltk, how to manipulate the nltk.corpus.reader.wordnet.Synset?


rawDescription: Summing across rows of Pandas Dataframe

description: Summing across rows of Pandas Dataframe


rawDescription: Python eig for generalized eigenvalue does not return correct eigenvectors


code:
import os
import tarfile

def make_tar(basename, files):
    tar = tarfile.open(basename + '.tar', 'w')
    for f in files:
        tar.add(f)
    tar.close()

map_reduce(os.listdir('.'),
           lambda x: (os.path.splitext(x)[0], x),
           make_tar)

rawDescription: Iterate within directory to zip files with python


code:
class Geometry(object):
    def __init__(self,id=0):
        self.id = id

rawDescription: Python 2.7, defining a base class with attributes, id with init constructor


rawDescription: Django: How to return all models associated with a ForeignKey including all attributes of those models?


code:
with open('result.txt', 'w') as outf:
    for i in diffs:
        outf.write('{0:12.5f}\n'.format(i))

rawDescription: Difference of consecutive float numbers in a column


code:
a, b, c, d = [], [], [], []

for var,data in zip([a,b,c,d], some_data_array):
    # call var.extend or var.append
    # var = some_value # don't do this. because it's just reference.
    var.extend(some_list)

rawDescription: Pythonic strategy to overwrite global variables in a for loop


code: res, tot_iter = newton(myffp, x, nits)

rawDescription: How can I check to see the number of iterations Newton's method takes to run?

description: Check to see the number of iterations Newton's method takes to run


rawDescription: What is the difference between these two (Python) code samples?


rawDescription: Django Query from given object instance

description: Django Query from given object instance


code:
import numpy as np

def pldist(x0, x1, x2):
    return np.divide(np.linalg.norm(np.linalg.det([x2 - x1, x1 - x0])),
                     np.linalg.norm(x2 - x1))

def rdp_index(M, epsilon=0, dist=pldist):

    dmax = 0.0
    index = -1

    for i in xrange(1, M.shape[0]):
        d = dist(M[i], M[0], M[-1])

        if d > dmax:
            index = i
            dmax = d

    if dmax > epsilon:
        r1 = rdp_index(M[:index + 1], epsilon, dist)
        r2 = rdp_index(M[index:], epsilon, dist)

        return np.vstack((r1[:-1], r2))
    else:
        part_mask = np.empty_like(M, dtype = bool)
        part_mask.fill(False)
        part_mask[0] = True
        part_mask[-1] = True
        return part_mask

rawDescription: Modify the Ramer–Douglas–Peucker (RDP) algorithm in numpy to return a mask instead of the values


code:
class bidict(dict):
    def __init__(self, *args, **kwargs):
        self.inverse = {}
        super(bidict, self).__init__(key, value)

    def __setitem__(self, key, value):
        super(bidict, self).__setitem__(key, value)
        self.inverse[value] = key

    def __delitem__(self, key):
        del self.inverse[self[key]]
        super(bidict, self).__delitem__(key)

rawDescription: Finding key from value in Python dictionary:


code:
def seq_op(obj_dict, obj):
    # equivalent to modify_object_dict
    # Lets assume it is as simple as this
    obj_dict.update((k, getattr(obj, k)) for k in ("x", "y", "z"))
    return obj_dict

def comb_op(obj_dict_1, obj_dict_2):
    # lets it is a simple union
    obj_dict_1.update(obj_dict_2)
    return obj_dict_1

dicts = pairs.aggregateByKey({}, seq_op, comb_op)

rawDescription: How to return a dictionary in parallel processing in spark?

description: Return a dictionary in parallel processing in spark


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

@register.simpletag
def i18ninclude(template_name, language):
    template_name, extension = os.path.splitext(template_name)
    template_name = '%s.%s%s' % (template_name, language, extension)
    return template.loader.render_to_string(template_name)

rawDescription: Technique for multi-language support of big static portions text in Django


rawDescription: Python variable interchange not working properly?