code:
a, b = "italic","ITALIC"
a.title(), b.title()

rawDescription: convert a string such that the first letter is uppercase and everythingelse is lower case

description: Convert a string such that the first letter is uppercase and everythingelse is lower case


code:
from xml.sax.saxutils import quoteattr

template = '<build><buildType id={id}/></build>'

url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/xml'}
build_id = 'MyTestBuild'
data = template.format(id=quoteattr(build_id))

r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)

rawDescription: How to use Python requests module and TeamCity API to trigger a build?

description: Use Python requests module and TeamCity API to trigger a build


code:
import itertools
toggle = itertools.cycle(['red', 'green', 'blue']).next
toggle()
toggle()
toggle()
toggle()
toggle()
toggle()

rawDescription: toggle a value in Python

description: Toggle a value in Python


code:
X = df.loc[df.Sales.notnull(), ['TV', 'Radio', 'Newspaper']]
X = sm2.add_constant(X)
Y = df[df.Sales.notnull()].Sales

model = sm.OLS(Y, X).fit()
new_x = df.loc[df.Sales.isnull(), ['TV', 'Radio', 'Newspaper']]
new_x = sm2.add_constant(new_x)  # sm2 = statsmodels.api

df.loc[df.Sales.isnull(), 'Sales'] = model.predict(new_x)

rawDescription: Predicting out future values using OLS regression (Python, StatsModels, Pandas)


rawDescription: number of values in a list greater than a certain number

description: Number of values in a list greater than a certain number


rawDescription: Convert datetime object to a String of date only in Python


code:
df = pd.read_csv(fake_file)
pd.to_datetime(df.opdate, format='%m/%d/%Y')
pd.to_datetime(df.opdate, format='%m/%d/%Y', coerce=True)
df['opdate'] = pd.to_datetime(df.opdate, format='%m/%d/%Y', coerce=True)

rawDescription: safest way to read missing dates with pandas read_csv--given blank space turns in today's date bug

description: Safest way to read missing dates with pandas read_csv--given blank space turns in today's date bug


code:
from django.test import TestCase
class ViewTest(TestCase):

    def test_view_returns_OK(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code,200)

class FunctionTest(TestCase):

    def test_function_returns_expected_result(self):
        response = time_encode(10)
        expected = "XYZ"
        self.assertEqual(response, expected)

rawDescription: How to write Unit Test in Django

description: Write Unit Test in Django


code:
# Reshape a to a 2D as required in few places later on
ar = a.reshape(a.shape[0],-1)

# Get dimension shape considering each block in axes(1,2) as an indexing tuple
dims = np.append(1,(ar[:,:-1].max(0)+1).cumprod())

# Finally get unique indexing tuples' indices that represent unique
# indices along first axis for indexing into input array and thus get
# the desired output of unique blocks along the axes(1,2)
out = a[np.unique(ar.dot(dims),return_index=True)[1]]

rawDescription: Finding duplicate matrices in Python?

description: Finding duplicate matrices in Python


code: [id(i) for i in g.vs['foo']]

rawDescription: How to assign values to individual elements of python igraph list attributes?

description: Assign values to individual elements of python igraph list attributes


rawDescription: What Can I do for sorting algorithm with my number language?


code:
for obj in browse_obj_list:
    id = obj.id

rawDescription: how to fetch a column in browse_record_list in orm browse method in openERP

description: Fetch a column in browse_record_list in orm browse method in openERP


rawDescription: Sorting in Python 3.3

description: Sorting in Python 3.3


code:
import collections
def top5_words(text):
    counts = collections.Counter(text.split())
    return counts.most_common(5)
top5_words("""As the title says, I need to write a code that returns a list of 5 words (from an input string) that have the highest frequency. This is what I have so far""")

rawDescription: Python - Return top 5 words with highest frequency


code:
class A:
  def __init__(self, b):
    self.b = b

class B:
  pass

import dill

b = B()
a = A(b)

f = open('_sed', 'wb')
dill.dump(({1:a},{2:b}), f)
f.close()

rawDescription: Pickling objects that refer to each other


code: clean_string = ''.join(c for c in s if c.isalnum() or c.isspace())

rawDescription: delete characters that are not letters, numbers, whitespace?

description: Delete characters that are not letters, numbers, whitespace


code:
for r in results:
    (okays if success_condition(r) else errors).append(r)

rawDescription: List splitting by predicate

description: List splitting by predicate


code: storage = [set()] * 35

rawDescription: List of sets, set.add() is adding to all sets in the list


code:
class Home(Edifice):
    def __init__(self, storeys, area, bedrooms):
        super().__init__(storeys, area)
        self.bedrooms = bedrooms
        self.message = "For human habitation: {} bedrooms".format(self.bedrooms)

    def show_info(self):
        super(Home, self).show_info()
        print(self.message)

rawDescription: Inheritance and classes

description: Inheritance and classes


code:
if len(s1) != len(s2):
    return False

rawDescription: Why does this Python Dict code work?

description: Why does this Python Dict code work


code:
def test_decorator(message, arg_name):
    @wrapt.decorator
    def wrapped_f(f, instance, args, kwargs):
        if arg_name in kwargs:
            print(message)
        return f(*args, **kwargs)
    return wrapped_f

rawDescription: How to allow parameters for a decorator while keep the function's signature at the same time?

description: Allow parameters for a decorator while keep the function's signature at the same time


rawDescription: Allocate items according to an approximate ratio in Python


code:
import pandas as pd
import numpy as np

dates = pd.date_range('2012-01-01', periods=24*3, freq='H')
values = np.random.randint(100, size=len(dates))
df = pd.DataFrame({'amount':values}, index=dates)

data = [grp['amount'].values.tolist() for key, grp in df.groupby([df.index.date])]

rawDescription: How to generate daily lists from pandas time series

description: Generate daily lists from pandas time series


code:
import timeit
def with_gens(l):
    return min(l), max(l)
timeit.timeit('with_gens(range(6000000))', 'from __main__ import with_gens', number=5)

rawDescription: List Comprehensions in Python to compute minimum and maximum values of a list


code:
from operator import add
map(add, list1, list2)

rawDescription: Add two lists of integers together into a 3rd list?


code:
import socket
import threading

class ChannelThread(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)

    self.clients = []
    self.chan_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    self.chan_sock.bind(('',0))
    _, self.port = self.chan_sock.getsockname()
    self.chan_sock.listen(5)
    self.daemon=True
    self.start()

  def run(self):
    while True:
      new_client = self.chan_sock.accept()
      if not new_client:
        break
      self.clients.append(new_client)

  def sendall(self, msg):
    for client in self.clients:
      client[0].sendall(msg)

class Channel(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)

    self.daemon = True
    self.channel_thread = ChannelThread()

  def public_address(self):
    return "tcp://%s:%d" % (socket.gethostname(), self.channel_thread.port)

  def register(self, channel_address, update_callback):
    host, s_port = channel_address.split("//")[-1].split(":")
    port = int(s_port)
    self.peer_chan_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    self.peer_chan_sock.connect((host, port))
    self._callback = update_callback
    self.start()

  def deal_with_message(self, msg):
    self._callback(msg)

  def run(self):
    data = ""
    while True:
      new_data = self.peer_chan_sock.recv(1024)
      if not new_data:
        # connection reset by peer
        break
      data += new_data
      msgs = data.split("\n\n")
      if msgs[-1]:
        data = msgs.pop()
      for msg in msgs:
        self.deal_with_message(msg)

  def send_value(self, channel_value):
    self.channel_thread.sendall("%s\n\n" % channel_value)

rawDescription: How to create channel with socket in Python

description: Create channel with socket in Python


code:
import time

def make_time_filter(start, end, time_format, file_format='index_{time_format:}.csv'):
    t_start = time.strptime(start, time_format)
    t_end = time.strptime(end, time_format)
    ft_fmt = file_format.format(time_format=time_format)

    def filt(fname):
        try:
            return t_start <= time.strptime(fname, ft_fmt) <= t_end
        except ValueError:
            return False

    return filt

rawDescription: python find all file names in folder that follows a pattern

description: Python find all file names in folder that follows a pattern


code:
word_list = ['hamburger', 'cow', 'meat']
with open('afile.html', encoding='utf-8-sig') as f:
    lines = f.readlines()
for line in lines:
    for word in word_list:
        if word in line:
            print(line)
            break

rawDescription: python remove info from readlines() that doesn't match a list

description: Python remove info from readlines() that doesn't match a list


code:
def scramble2(letters):
    for i in range(1, len(letters) + 1):
        for p in itertools.permutations(letters, i):
            words.add(''.join(p))

rawDescription: program takes long time to calculate........recursion(python)

description: Program takes long time to calculate........recursion(python)


code:
y = ["animal","zoo","potato"]
s =  ["The animal farm on the left","I had potatoes for lunch"]
s = list(set(s)) # But NOTE THAT this might change the order of your original list
for words in s:
    for char in y:
        if char in words:
            print (words)
            break

rawDescription: For loop with If not working as expected


code:
def longest_substr(lst):
    longest = None
    for word in lst:
        for i in range(len(word)):
            for j in range(i+1, len(word)+1):
                if ((longest is None or (j - i > len(longest))) and
                    sum(word[i:j] in w for w in lst) > 1):
                    longest = word[i:j]
    return longest

rawDescription: Longest repeated substring

description: Longest repeated substring


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

d = {'somestring': 'myfunction'} # in the real code this came from json.load
d = {k:globals()[v] for k,v in d.items()}
print(d) # {'somestring': <function myfunction at 0x7f36e69d8c20>}
print(d['somestring'](42)) # 84

rawDescription: Clean way to manage parse-dictionaries that contain function names


code:
F = A.ravel()
F

rawDescription: Efficent insertion of not aligned elements in a numpy array


code:
if ws.cell_value(6, cnum):
    wsHeaders[str(ws.cell_value(6, cnum))] = (cnum, ws.ncols)

rawDescription: Why is win32com so much slower than xlrd?


code:
for key, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, '{}/{}'.format(lat, long), count])

rawDescription: Python Counter results to csv file

description: Python Counter results to csv file


code: onlytxt = [x[:-4] for x in allfiles if x.endswith('.txt')]

rawDescription: Put names of .txt files into a list

description: Put names of .txt files into a list


code:
#To build the cython code in the .pyx file, type in the terminal:
#"python setup.py build_ext --inplace"
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy

extensions = [
    Extension("cython_finite_diff", ["cython_finite_diff.pyx"],
                include_dirs = [numpy.get_include()]),
]

setup(
    name = "my_cython_fd",
    ext_modules = cythonize(extensions, annotate=True),
)

rawDescription: Efficiently computing the 3D Laplacian using FFT and Python


code:
from sklearn import cross_validation

x_train, x_test, y_train, y_test = cross_validation.train_test_split(
    df, Y, test_size=0.8, random_state=0)

rawDescription: How to get the indices for randomly selected rows in a list (Python)

description: Get the indices for randomly selected rows in a list (Python)


code:
import base64
base64.b64encode('example')
base64.b64decode('ZXhhbXBsZQ==')

rawDescription: Sending text and binary using sockets in python


rawDescription: Python List To Dictionary - Without Value Overwrite


code: Cap_Austria.insert(0,  'default text')

rawDescription: How can I use the get() function to turn the answer in the entry() box into a string

description: Use the get() function to turn the answer in the entry() box into a string


code: d2 = {'edges' : map(lambda x: x.getDict(), d1['edges'])}

rawDescription: Recursive __dict__ call on python object?


code:
odd_count, even_count = GetOddEvenCount(10)
print("Odds:", odd_count, "Evens:", even_count)

rawDescription: Iterate through list of intervals in Python and return odd and even values?


code:
import bpy

class A(bpy.types.Operator):
    bl_idname = "object.simple_operator_a"
    bl_label = "Simple Object Operator A"

    def execute(self,context):
        self.some_function()
        return {'FINISHED'}

    @classmethod
    def some_function(cls, some_parameter='not woop'):
        print('some_parameter', some_parameter)

class B(bpy.types.Operator):
    bl_idname = "object.simple_operator_b"
    bl_label = "Simple Object Operator B"

    def execute(self,context):
        A.some_function('woooop')
        return {'FINISHED'}

def register():
    bpy.utils.register_module(__name__)

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()

rawDescription: Call a function in a class from different class


code:
class Crono(QtCore.QThread):
    tick = QtCore.pyqtSignal(int, name="changed") #New style signal

    def __init__(self, parent):
        QtCore.QThread.__init__(self,parent)

    def checkStatus(self):
        for x in range(1,101):
            self.tick.emit(x)
            time.sleep(1)

rawDescription: Progress bar with pyqt

description: Progress bar with pyqt


code:
fontProperties = {'family':'sans-serif', 'weight': 'normal', 'size': 12}
ax1.set_xticklabels(ax1.get_xticks(), fontProperties)
ax1.set_yticklabels(ax1.get_yticks(), fontProperties)

rawDescription: Latex font style issues using amsmath and sfmath for plot labeling


code:
def get_row(dict):
    ...
    for t in range(3):
         ...
         # a = dict.popitem()
         a = dict[t]

rawDescription: How not to change outer values?

description: How not to change outer values


rawDescription: Extracting selected feature names from scikit pipeline


code:
text = "Áno"
count = sum(c.isupper() for c in text)
count
text = u"Áno"
count = sum(c.isupper() for c in text)
count
text = "Áno".decode("utf-8")
count = sum(c.isupper() for c in text)
count

rawDescription: Method isupper unicode friendly

description: Method isupper unicode friendly


code:
f.seek(0)
f.read()

rawDescription: Python: TemporaryFile returns empty string when read


code:
import pprint
pprint.pprint(puzzle)

rawDescription: How to add CSV file to dictionary using specific keys in python?

description: Add CSV file to dictionary using specific keys in python


code:
def emptyline(self):
        """Called when an empty line is entered in response to the prompt.

        If this method is not overridden, it repeats the last nonempty
        command entered.

        """
        if self.lastcmd:
            return self.onecmd(self.lastcmd)

rawDescription: Python: cmd execute last command while prompt and empty line


code:
with open("settings.conf","w") as settings_file:
    config.write(settings_file)

rawDescription: python configparser writes configuration file to one line

description: Python configparser writes configuration file to one line


code:
from django import forms

class CountryForm(forms.Form):
        OPTIONS = (
                ("AUT", "Austria"),
                ("DEU", "Germany"),
                ("NLD", "Neitherlands"),
                )
        Countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                             choices=OPTIONS)

rawDescription: Django: How can i create a multiple select form?


code: [v for k,v in myclass.__dict__.items() if isinstance(v,int)]

rawDescription: Python 2.7: How to get the list of static variables in a class?


rawDescription: How to match multiple characters 'n' times using Python RE module?

description: Match multiple characters 'n' times using Python RE module


code:
## create labels from breakpoints
breaks=[0,20,25,30,pd.np.inf]
diff=np.diff(breaks).tolist()

## make tuples of *breaks* and length of intervals
joint = list(zip(breaks,diff))

## format label
s1 = "{left:,.0f} to {right:,.0f}"
labels = [s1.format(left=yr[0], right=yr[0]+yr[1]-1) for yr in joint]
labels

['0 to 19', '20 to 24', '25 to 29', '30 to inf']

rawDescription: Python: How to find properties of items in a series


code:
charts = group_obj.chartgroup.values_list('chart_info_id', 'orderg').order_by('orderg', '-id')
context['assigned_charts'] = charts

rawDescription: How to include nested for loop in Django framework?

description: Include nested for loop in Django framework


code: import twisted

rawDescription: Force python to use an older version of module (than what I have installed now)


code:
def get_names(input_dictionary):
    return input_dictionary.keys()

rawDescription: Get a list of a dictionary's key names

description: Get a list of a dictionary's key names


code:
import IPython
import inspect
inspect.getsourcefile(IPython)

rawDescription: Launching ipython notebook via the api (script)


code:
from collections import Counter

dataDict = {}

# Read the csv file, line by line
with open('data.csv', 'r') as dataFile:
    for line in dataFile:

        # split the line by ',' since it is a csv file...
        entry = line.split(',')

        # Check to make sure that there is data in the line
        if entry and len(entry[0])>0:

            # if the customer_id is not in dataDict, add it
            if entry[0] not in dataDict:
                dataDict[entry[0]] = {'month':[entry[1]],
                                   'time':[entry[2]],
                                   'ABC':[''.join(entry[3:])],
                                   }
            # customer_id is already in dataDict, add values
            else:
                dataDict[entry[0]]['month'].append(entry[1])
                dataDict[entry[0]]['time'].append(entry[2])
                dataDict[entry[0]]['ABC'].append(''.join(entry[3:]))

# Now write the output file
with open('out.csv','w') as f:

    # Loop through sorted customers
    for customer in sorted(dataDict.keys()):

        # use Counter to find the most common entries
        commonMonth = Counter(dataDict[customer]['month']).most_common()[0][0]
        commonTime = Counter(dataDict[customer]['time']).most_common()[0][0]
        commonABC = Counter(dataDict[customer]['ABC']).most_common()[0][0]

        # Write the line to the csv file
        f.write(','.join([customer, commonMonth, commonTime, commonABC, '\n']))

rawDescription: Python CSV - Check if index is equal on different rows


code: dict(v.split(':') for v in lst)

rawDescription: Splitting lists to make dictionary python


rawDescription: representing large number in python

description: Representing large number in python


code: noun_patt = r'\b(' + '|'.join(nouns) + r')\b'

rawDescription: Find Pattern in Textfile From Several Elements In Several Lists?


code:
def get_page_data(page_number):
    # Fetch page data
    ...
    # Parse page data
    ...
    for linked_page in parsed_links:
        # Fetch page source and save to file
        ...

rawDescription: Distributing a python workload across multiple processes


code: new_file.write('this is some content')

rawDescription: creating a tmp file in python

description: Creating a tmp file in python


code:
with open("numberlist.txt") as f: # this auto closes the file after reading. It's good practice
    numbers = f.readlines() # numbers is a list of all the numbers(a list of lines in the file)

rawDescription: Python, reading lines from a file one by one


rawDescription: How to find the column index of the value of a given row in numpy?

description: Find the column index of the value of a given row in numpy


code: np.concatenate((a1, b1))

rawDescription: append 2dim arrays to one array

description: Append 2dim arrays to one array


code:
with open(fileout,'w',encoding='utf-8') as fout:
    fout.write("\\begin{enumerate}[1.]\n")

rawDescription: How do you write special characters ("\n","\b",...) to a file in Python?

description: Write special characters ("\n","\b",...) to a file in Python


code:
tagged_words = nltk.word_tokenize(text)
tagged_words = nltk.pos_tag(tagged_words)
lemmatizer = nltk.stem.WordNetLemmatizer()
words = []
for tagged_word in tagged_words:
    pos = wordnet_pos_code(tagged_word[1])

    if pos is not None:
        words.append((lemmatizer.lemmatize(tagged_word[0], pos=pos), tagged_word[1]))

fdist = nltk.FreqDist(words)

rawDescription: How to get frequency of words in text depends of they part of speech?

description: Get frequency of words in text depends of they part of speech


code:
def randomNumber():
    number = random.randint(1,10)
    print(number)
    return number

def main():
    number = randomNumber()
    print(number)

if __name__=='__main__':
    main()

rawDescription: python doesn't update int in main method

description: Python doesn't update int in main method


code:
import filecmp
filecmp.cmp('file1.txt', 'file1.txt')
filecmp.cmp('file1.txt', 'file2.txt')

rawDescription: see if two files have the same content in python

description: See if two files have the same content in python


code: table(ax, df, rowLabels=['']*df.shape[0], loc='center')

rawDescription: How to save a pandas DataFrame table as a png

description: Save a pandas DataFrame table as a png


rawDescription: Interpolate between rows or columns of a Numpy array


code:
z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for i in z.keys(): #reaching the keys of dict
    for x in z[i]: #reaching every element in tuples
        if x=="CI": #if match found..
            print ("{} holding {}.".format(i,x)) #printing it..

rawDescription: Iterating over dict values

description: Iterating over dict values


code:
nodes = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
edges = [('a','b'), ('a','e'), ('f', 'a'), ('k','l')]
nodesRDD = sc.parallelize(nodes).map(lambda n: (n, ''))
edgesRDD = sc.parallelize(edges)
joinedRDD = nodesRDD.join(edgesRDD).map(lambda tup: (tup[0], tup[1][1]))
groupedRDD = joinedRDD.groupByKey()

groupedRDD.map(lambda x : (x[0], list(x[1]))).collect()

rawDescription: join two rdds to make an adjacency list

description: Join two rdds to make an adjacency list


code: ''.join(chr(c) for c in recv_buffer)

rawDescription: How to access C structs from a python array

description: Access C structs from a python array


code:
import os
import yaml

def logmaker():
    path = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(path, 'bot.log')
    return logging.FileHandler(path)

def main():
    # The file's path
    path = os.path.dirname(os.path.realpath(__file__))

    # Config file relative to this file
    loggingConf = open('{0}/logging.yml'.format(path), 'r')
    logging.config.dictConfig(yaml.load(loggingConf))
    loggingConf.close()
    logger = logging.getLogger('cloaked_chatter')
    logger.debug('Hello, world!')

if __name__ == '__main__':
    main()

rawDescription: How to specify in YAML to always create log file in the project's folder using dictConfig?

description: Specify in YAML to always create log file in the project's folder using dictConfig


code:
def tokenizer(l):
    prev_i = 0
    for (i, c) in enumerate(l):
        if c in ',.?!- ':
            if prev_i != i:
                yield l[prev_i: i]
            yield c
            prev_i = i + 1
    if prev_i != 0:
        yield l[prev_i: ]

rawDescription: Python Tokenization

description: Python Tokenization


code:
mylist = list()

while True:
    line = raw_input()
    if not line: break
    mylist.append(line)

for line in mylist:
    print(line)

rawDescription: Python how to read lines and how to output the new lines


code:
content = [];
with open("input.txt") as f:
  content = f.readline().split()

ismallest = int(content[0])

for i in range(0,len(content),1):
  if (int(content[i]) < ismallest):
    ismallest = int(content[i])

print ("the smallest number is", ismallest)

rawDescription: Using a Scanner Loop

description: Using a Scanner Loop


rawDescription: Group DataFrame by entries X amount of time from each other


code:
from mlabwrap import mlab as matlab
a = [[1, 2], [3, 4]]
cell = matlab.mat2cell(array(a), [1, 1], [2])
matlab.display(cell)

rawDescription: How do I use mlabwrap to call a matlab function with cell arguments from python?

description: Use mlabwrap to call a matlab function with cell arguments from python


code:
def fill_range(initial_range, fill_vallue):
    result = []
    smallest = initial_range[0]
    biggest = initial_range[-1]
    items = set(initial_range)
    for i in range(smallest, biggest+1):
        if i in items:
            result.append(i)
        else:
            result.append(fill_value)
    return result

rawDescription: Insert value in Incremental List not working


rawDescription: Fermat Factorisation with Python

description: Fermat Factorisation with Python


code:
import maya.cmds as cmds
import maya.OpenMayaUI as apiUI
from PySide import QtCore, QtGui
import shiboken

def wrapinstance(ptr, base=None):
    """
    Utility to convert a pointer to a Qt class instance (PySide/PyQt compatible)
    :param ptr: Pointer to QObject in memory
    :type ptr: long or Swig instance
    :param base: (Optional) Base class to wrap with (Defaults to QObject, which should handle anything)
    :type base: QtGui.QWidget
    :return: QWidget or subclass instance
    :rtype: QtGui.QWidget
    """
    if not globals().has_key('QtCore') or not globals().has_key('QtGui'):
        return None

    if ptr is None:
        return None
    ptr = long(ptr)  # Ensure type
    if globals().has_key('shiboken'):
        if base is None:
            qObj = shiboken.wrapInstance(long(ptr), QtCore.QObject)
            metaObj = qObj.metaObject()
            cls = metaObj.className()
            superCls = metaObj.superClass().className()
            if hasattr(QtGui, cls):
                base = getattr(QtGui, cls)
            elif hasattr(QtGui, superCls):
                base = getattr(QtGui, superCls)
            else:
                base = QtGui.QWidget
        return shiboken.wrapInstance(long(ptr), base)
    elif globals().has_key('sip'):
        base = QtCore.QObject
        return sip.wrapinstance(long(ptr), base)
    else:
        return None

def getMayaWindow():
    ptr = apiUI.MQtUtil.mainWindow()
    return wrapinstance(long(ptr), QtCore.QObject)

def toQtObject(mayaName):
    '''
    Given the name of a Maya UI element of any type,
    return the corresponding QWidget or QAction.
    If the object does not exist, returns None
    '''
    ptr = apiUI.MQtUtil.findControl(mayaName)
    if ptr is None:
        ptr = apiUI.MQtUtil.findLayout(mayaName)
    if ptr is None:
        ptr = apiUI.MQtUtil.findMenuItem(mayaName)
    if ptr is not None:
        return wrapinstance(long(ptr), QtCore.QObject)

class MayaSubWindow(QtGui.QMainWindow):
    def __init__(self, parent=getMayaWindow()):
        super(MayaSubWindow, self).__init__(parent)
        qtObj = toQtObject(cmds.animCurveEditor())
        #Fill the window, could use qtObj.setParent
        #and then add it to a layout.
        self.setCentralWidget(qtObj)

myWindow = MayaSubWindow()
myWindow.show()

rawDescription: How can I create a new Graph Editor in Maya using Python?

description: Create a new Graph Editor in Maya using Python


code:
#!/usr/bin/env python
import ctypes
import functools
import os

_environ = None

def get_libc_environb_items():
    """Get envvars from C environ as bytestrings (unsplit on b'=')."""
    global _environ
    if _environ is None:
        libc = ctypes.CDLL(None)
        _environ = ctypes.POINTER(ctypes.c_char_p).in_dll(libc, 'environ')
    return iter(functools.partial(next, iter(_environ)), None)

def get_libc_environb():
    """Get a copy of C environ as a key,value mapping of bytestrings."""
    return dict(k_v.split(b'=', 1) for k_v in get_libc_environb_items()
                if b'=' in k_v)  # like CPython

def get_libc_environ():
    """Get a copy of C environ as a key,value mapping of strings."""
    environb = get_libc_environb()
    # XXX sys.getfilesystemencoding()+'surrogateescape'
    fsdecode = getattr(os, 'fsdecode', None)
    if fsdecode is None:  # Python 2
        return environb  # keep bytestrings as is (`str` type)
    else:  # Python 3, decode to Unicode
        return {fsdecode(k): fsdecode(v) for k, v in environb.items()}

def synchronize_environ():
    """Synchronize os.environ with C environ."""
    libc_environ = get_libc_environ()
    os.environ.clear()
    os.environ.update(libc_environ)

def test():
    assert 'SPAM' not in os.environ
    assert 'SPAM' not in get_libc_environ()
    os.putenv('SPAM', 'egg')
    assert 'SPAM' not in os.environ
    assert os.getenv('SPAM') is None
    assert get_libc_environ()['SPAM'] == 'egg'
    assert os.popen('echo $SPAM').read().strip() == 'egg'
    synchronize_environ()
    assert os.environ['SPAM'] == 'egg'

if __name__ == "__main__":
    test()
    from pprint import pprint
    pprint(get_libc_environ())

rawDescription: python: getting actual environment variables to modify and pass to subprocess

description: Python: getting actual environment variables to modify and pass to subprocess


code:
# \xe2\x80\x93 represents a long dash (or long minus)
s = 'hello – world'
s
import re
re.split("\xe2\x80\x93", s)

rawDescription: How to split line at non-printing ascii character in Python

description: Split line at non-printing ascii character in Python


rawDescription: Python parsing list of string

description: Python parsing list of string


code:
class MyLinkExtractor(LxmlLinkExtractor):
    def __init__(self, allow=(), deny=(), allow_domains=(), deny_domains=(), restrict_xpaths=(),
                 tags=('a', 'area'), attrs=('href',), canonicalize=True,
                 unique=True, process_value=None, deny_extensions=None, restrict_css=()):
        tags, attrs = set(arg_to_iter(tags)), set(arg_to_iter(attrs))
        tag_func = lambda x: x in tags
        attr_func = lambda x: x in attrs
        lx = MyParserLinkExtractor(tag=tag_func, attr=attr_func,
            unique=unique, process=process_value)

        super(LxmlLinkExtractor, self).__init__(lx, allow=allow, deny=deny,
            allow_domains=allow_domains, deny_domains=deny_domains,
            restrict_xpaths=restrict_xpaths, restrict_css=restrict_css,
            canonicalize=canonicalize, deny_extensions=deny_extensions)

rawDescription: Scrapy - get multiple urls from one link


code:
if request.user == lyric.user:
    lyric.delete() # or save edits
else:
    raise PermissionDenied # import it from django.core.exceptions

rawDescription: How can I enable the users delete and edit the objects they create in Django?

description: Enable the users delete and edit the objects they create in Django


code: sum(nums)/len(nums)

rawDescription: Create a random array with a particular average


code:
def transform(inputt, outputt):
    with open(inputt) as f, open(outputt, "w") as f1:
        f1.write(f.read().split("***")[0])

rawDescription: Python copy all lines before string in another text file


code: row = ','.join([str(dict1.get(c + str(r), '')) for c in cols])

rawDescription: Using dictionary keys as coordinates when writing to csv


code: wins = stats[0]['wins']

rawDescription: Python 3: Iterating over a dictionary

description: Python 3: Iterating over a dictionary


code: user = find_or_add(User, mysession, email="bob@localhost.com")

rawDescription: Proxy pattern idiom

description: Proxy pattern idiom


code:
from ctypes import *

LIBRARY_NAME = 'libjox.so'
c = cdll.LoadLibrary(LIBRARY_NAME)

WIDTH = 20
HEIGHT = 20

class JoxColor(Structure):
    _fields_ = [("r", c_float), ("g", c_float), ("b", c_float), ("a", c_float)]

ColorBlock = JoxColor * (WIDTH * HEIGHT)

data_array = ColorBlock()

color = JoxColor(0, 0, 1, 0)
for i in range(WIDTH * HEIGHT):
    data_array[i] = color

c._Z15writePixelsRectP8JoxColoriiii(data_array, 0, 0, WIDTH, HEIGHT)

rawDescription: Array allocation of SWIG C++ type from Python


code:
EDIT
text2 = ''.join(m.groups())  # is better

rawDescription: Python Regex Problems

description: Python Regex Problems


code:
RegionIDArray = [7236, 7665]
dict = {7236: 2, 7665: 3} #{'Rome': 3, 'Paris': 2}
for RegionID in RegionIDArray:
    for page in range(1,2):
        url = "http://www.isango.de/affiliatesearch.aspx?&regionid=" + str(RegionID) + "&pid=" + str(page)
        html = urllib.request.urlopen(url).read()
        soup = BeautifulSoup(html)

        g_data = soup.find_all("div", {"class": "gridHeadOuter productInfoOuter"})
        for item in g_data:
            Header = item.find_all("div", {"class": "offerInto"})
            Header_final = (Header[0].contents[0].text.strip())

        print("Header: " + Header_final + " | " + "PartnerID: " + str(dict[RegionID]))

rawDescription: Crawling output - connecting two variables


code: item = response.meta['item']

rawDescription: Scrapy: Passing item between methods

description: Scrapy: Passing item between methods


code:
from math import sqrt

point_b = (point_a[0]+dx(distance,m), point_a[1]+dy(distance,m))
other_possible_point_b = (point_a[0]-dx(distance,m), point_a[1]-dy(distance,m)) # going the other way

def dy(distance, m):
    return m*dx(distance, m)

def dx(distance, m):
    return sqrt(distance/(m**2+1))

rawDescription: python find point-B on line by distance from point-A

description: Python find point-B on line by distance from point-A


code:
def findLine(prog,target):
    return next(i for i,line in enumerate(prog) if line.split()[0] == target)

rawDescription: Python 3 - Finding which index of a list contains a particular string as a substring


rawDescription: Pandas compare next row

description: Pandas compare next row


code:
def log(msg):
    ...

class LoggingDict(dict):
    def __setitem__(self, key, value):
        super(LoggingDict, self).__setitem__(key, value)
        log('Updated: {}={}'.format(key, value))

rawDescription: why types/class unification majorly in python

description: Why types/class unification majorly in python


code:
#!/usr/bin/python

import re

data = [[]]

for line in open('in'):
    line = line.strip()
    line = re.match(r'\[?(.*)\]', line).group(1)

    res = re.split(r', (?=\[)', line)

    data[0].append(res[0])
    string = res[1] + res[2]
    data.append([string])

for i, v in enumerate(data):
    print("{}\n".format(data[i]))

rawDescription: Reading in lines of numeric strings into separate lists in python


code: df2_lagged = df2.shift(365)

rawDescription: Use Python/Pandas to Match Sample Pairs Yearly Data


code:
def product(request):
    if request.method=='GET':
        sku = request.GET.get('sku')
        if not sku:
            return render(request, 'inventory/product.html')
        else:
            # now you have the value of sku
            # so you can continue with the rest
            return render(request, 'some_other.html')

rawDescription: how to Pass variable in link to the django view


rawDescription: Different way to create an instance method object in Python


code:
now = datetime.now()
previous_midnight = datetime.datetime( now.year, now.month, now.day )

rawDescription: get unix time from yesterday 0000 hrs to today 0000 hours using python

description: Get unix time from yesterday 0000 hrs to today 0000 hours using python


code:
from bs4 import BeautifulSoup

html = """

test1

test2

test3

"""

soup = BeautifulSoup(html, "lxml")

def filter_function(elm):
    return elm and "class" in elm.attrs and "A" in elm["class"] and "Y" not in elm["class"]

for div in soup.find_all(filter_function):
    print(div.text)

rawDescription: Selecting Tags With Multiple Part Class in BeautifulSoup


code: s = requests.session()

rawDescription: Python Requests and persistent sessions

description: Python Requests and persistent sessions


code:
dataset = SonarFile('input.dat')

for frame in dataset:
    im = frame.data
    # Do something...

rawDescription: Writing to numpy array from dictionary

description: Writing to numpy array from dictionary


code:
import pandas as pd

data = [['Tokyo','London', 'New York', 'Manchester'],
['Japan','UK','US','UK'],
['Asia','Europe','North America','Europe']]

df = pd.DataFrame(data).transpose()
df.columns = ['City','Country','Continent']
df2 = df.set_index('City')

rawDescription: Create series from one row of dataframe

description: Create series from one row of dataframe


code: socket.setsockopt(zmq.SUBSCRIBE, "")

rawDescription: ZeroMQ Pub/Sub simplest example is not working - What am I doing wrong?


code:
from collections import Counter, defaultdict
from itertools import count

def tmatrix(self, lst):
    # defaultdict that'll produce a unique index for each unique character
    # encountered in lst
    indices = defaultdict(count().next)
    unique_count = len(set(lst))
    b = [[0 for _ in xrange(unique_count)] for _ in xrange(unique_count)]
    for (x, y), c in Counter(zip(lst, lst[1:])).iteritems():
        b[indices[x]][indices[y]] = c
    return b

rawDescription: Calculate transition matrix of letters

description: Calculate transition matrix of letters


code:
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.setGeometry(0, 0, 400, 200)
pic = QtGui.QLabel(window)
pic.setGeometry(10, 10, 400, 200)
pixmap = QtGui.QPixmap(FILENAME)
pixmap = pixmap.scaledToHeight(200)
pic.setPixmap(pixmap)

window.show()
sys.exit(app.exec_())

rawDescription: How to load and show a rescaled image with pyqt4

description: Load and show a rescaled image with pyqt4


code:
# import the package
import antigravity

# import the antigravity module
from antigravity import antigravity

# or an object inside the antigravity module
from antigravity.antigravity import my_object

rawDescription: Running unittest with typical test directory structure


rawDescription: column max with list of matrices

description: Column max with list of matrices


rawDescription: Getting TypeError when trying to concatenate 'str' and 'NoneType' objects


code:
@app.context_processor
def add_user():
    # Get user
    return {"user": user}

rawDescription: Do I have partial view/code behind in Flask?


code:
a = Test()
a._test   # The property hasn't been called so there is no result saved yet.
a.test    # First property access will evaluate the code you have in your property
a.test    # Accessing the property again will give you the saved result
a._test   # Or access the saved result directly

rawDescription: Declaring class attributes in __init__ vs with @property


code:
for spine_loc in ('top', 'right'):
    ax.spines[spine_loc].set_visible(False)

rawDescription: Graphs: contours, arrow and naming

description: Graphs: contours, arrow and naming


rawDescription: How to calculate a short fixed length obfuscated ID similar to YouTube (e.g. 2WNrx2jq184)

description: Calculate a short fixed length obfuscated ID similar to YouTube (e.g. 2WNrx2jq184)


code:
import re
s = 'she said he was a nice girl'
re.sub('s?he', lambda m: 'he' if m.group() == 'she' else 'she', s)

rawDescription: Regular Expressions in Python - combining two operations in re.sub


code:
from tempfile import NamedTemporaryFile
from itertools import islice
from shutil import move

with open("test.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    for line in f:
        if '"domain2.com"' in line:
            list(islice(f, 7))
        else:
            temp.write(line)

move(temp.name,"test.txt")

rawDescription: python3.4 how to delete a section of text following pattern string match

description: Python3.4 how to delete a section of text following pattern string match


code: jmeter_md5_list.sort(key=lambda val: list(map(int, re.compile('(\d+(?!$))').findall(val))))

rawDescription: Python3 Make tie-breaking lambda sort more pythonic?


rawDescription: Pandas multiindex dataframe set first row in a column to 0


code:
import pandas as pd
df = pd.DataFrame.from_csv( 'test.csv', index_col=None )

rawDescription: Calculating previous chance figure for use in chi square test


code:
df_asint = df.astype(int)
coocc = df_asint.T.dot(df_asint)
coocc

rawDescription: Constructing a co-occurrence matrix in python pandas


code:
class Location(models.Model):
    locationname = models.CharField(max_length=100)

    def __unicode__(self):
        return self.locationname

    def latest(self):
        return Rating.objects.values('rating').filter(von_location=self).order_by('-id')[0]

class Rating(models.Model):
   von_location = models.ForeignKey(Location,related_name="locations_rate")
   rating = models.IntegerField()

   def __unicode__(self):
        return "{0}".format(self.rating)

rawDescription: django related manager - in template

description: Django related manager - in template


code: zip(colours, map(lambda x: len(filter(lambda y: y==x, c)), colours))

rawDescription: Use map over a list of 50 generated colours to count, using filter, and reduce, or len, the frequency of occurence


code:
import pexpect # $ pip install pexpect

def every_second(d, last=[None]):
    current = d['child'].before
    if last[0] == current: # "settled down"
        raise pexpect.TIMEOUT(None) # exit run
    last[0] = current

output, status =  pexpect.run('top', timeout=1, withexitstatus=1,
                              events={pexpect.TIMEOUT: every_second})

rawDescription: How do I obtain the output from a program that uses screen redrawing for use in a terminal screen scraper?

description: Obtain the output from a program that uses screen redrawing for use in a terminal screen scraper


rawDescription: I cannot seem to find a string in a subarray in an array of arrays


code:
pw = Patchwork(a=1, b=2, c=3)
pw.get("b")
pw.get(["a", "c"])

rawDescription: How can I use functools.singledispatch with instance methods?

description: Use functools.singledispatch with instance methods


code:
if key(left[left_counter]) < key(right[right_counter]):
    seq[master_counter] = left[left_counter]
    left_counter += 1
else:
    seq[master_counter] = right[right_counter]
    right_counter += 1

rawDescription: Merge sort a list of words

description: Merge sort a list of words


code:
# just row- and column-wise traversals of the grid
# I believe these correspond exactly to your hData and vData tables
rows = [ "bac", "def", "hig" ]
cols = [ "dag", "hbe", "cfi" ]

res = [ [ set(r) & set(c) for c in cols ] for r in rows ]
print(res)

rawDescription: How to cross 2 two-dimensional arrays in python?

description: Cross 2 two-dimensional arrays in python


rawDescription: Numpy - summing up a list of vectors

description: Numpy - summing up a list of vectors


code:
import pandas as pd
left = pd.DataFrame({'url': ['foo.com', 'foo.com', 'bar.com'], 'action': [0, 1, 0]})
left["class"] = NaN
right1 = pd.DataFrame({'url': ['foo.com'], 'class': [0]})
right2 = pd.DataFrame({'url': ['bar.com'], 'class': [ 1]})

pd.merge(left.drop("class", axis=1), pd.concat([right1, right2]), on="url")

rawDescription: What is the equivalent to R's match() for python Pandas/numpy?


code:
def stupidFacebookPost():
    integerValues = []
    productValues = []
    commonValue = []
    while True:
        try:
            integer = input("Enter a Integer Value ")
            if integer == '': break
            Product = input("Enter a Product Value ")
            if Product == '': break
            integerValues.append(int(integer))
            productValues.append(int(Product))
            print(integerValues) #testing
            print(productValues) #testing
        except ValueError:
            break

    for integers in  integerValues:
        for products in productValues:
            commonValue.append(int(products) // int(integers))
            print(commonValue) #test
            integerValues.pop([0])
            productValues.pop([0])
    print('the Common Value is {}'.format((commonValue)))

stupidFacebookPost()

rawDescription: first user input being ignored python

description: First user input being ignored python


rawDescription: Split string multiple times in Python

description: Split string multiple times in Python


rawDescription: Trying to remove nan from csv file in python pandas


code:
import re
data = re.findall("(.*?) CiteSeerX.*(\d{4})$", col4)
if data:
    # we have a match extract the first capturing group
    title, year = data[0]
    print(title, year)
else:
    print("Unable to parse the string")

# Output: May god bless our families studied. 2004

rawDescription: How to extract text before a specific keyword in python?

description: Extract text before a specific keyword in python


code: translated = [i.upper().strip().translate(str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "LFWOAYUISVKMNXPBDCRJTQEGHZ")) for i in list_of_words]

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


code:
moviedata = [("one","two"), ("two","one"), ("two","three")]
moviedata[1]
moviedata[1][1]
moviedata[1][1][:2]

rawDescription: Errors with obtaining and reading data from a file


rawDescription: Python- add to dictionary based on an incrementing value in 2 lists


code:
traindir = '/home/alvas/my_movie_reviews'
mr = CategorizedPlaintextCorpusReader(traindir, r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*', encoding='ascii')

rawDescription: Testing the NLTK classifier on specific file


code: selected_keys = [i for i in g.keys() if i[1] == True and i[2] != block]

rawDescription: How to remove large numbers of dictionary entries in python

description: Remove large numbers of dictionary entries in python


code:
syllables = re.compile("[.,:;!?]? |/").split
text = "Hi! I do/n'/t know how ma/ny sy/lla/bu/s a/re  the/re i/n thi/s te/x/te, who kno/w."

print(syllables(text))

rawDescription: How to split a poem in python

description: Split a poem in python


rawDescription: Gridding a numpy array

description: Gridding a numpy array


code:
env = Environment()

dirname = 'build'
VariantDir(dirname, 'src', duplicate=0)

Export('env')

SConscript(dirname+'/SConscript')

rawDescription: SCons to generate variable number of targets


rawDescription: Python equivalent of PHP Mcrypt

description: Python equivalent of PHP Mcrypt


code: table = soup.find('tr', {'class': 'zone-dedicated-availability'})

rawDescription: Python BeautifulSoup find span inside class


code:
result = {
    'mary': [1, 2, 3, ''],
    'anna': [7, 9, 8],
    'liz': [2, 1, '', ''],
}
{key: [v for v in value if v != ''] for key, value in result.items()}

rawDescription: Iterate an operation on a dictionary in python


rawDescription: python pandas beginner: multi-dimensional data-analysis workflow (groupby+agg+plot)

description: Python pandas beginner: multi-dimensional data-analysis workflow (groupby+agg+plot)


code:
C = []
for i in range(min(len(A), len(B))):
    a_item = A[i]
    b_item = B[i]
    for _ in range(a_item):
        C.append(b_item)

rawDescription: How to get one number specific times in an array python

description: Get one number specific times in an array python


code:
import seaborn as sns; sns.set()
import numpy as np; np.random.seed(0)
from matplotlib import pyplot as plt

fig, ax = plt.subplots()
fig.set_size_inches(14, 7)
uniform_data = np.random.rand(10, 12)
cbar_ax = fig.add_axes([.92, .3, .02, .4])
sns.heatmap(uniform_data, ax=ax, cbar_ax=cbar_ax)

rawDescription: Python - Seaborn: Modifying the heatmap legend


code:
class SomeEntity(Base):
    __tablename__ = 'some_entity'
    id = Column(Integer, primary_key=True)
    attributes = Column(PickleType)

# Just set the attribute to save it
s = SomeEntity(attributes={'baked': 'beans', 'spam': 'ham'})
session.add(s)
session.commit()

# If mutable=True on PickleType (the default) SQLAlchemy automatically
# notices modifications.
s.attributes['parrot'] = 'dead'
session.commit()

rawDescription: Python dicts in sqlalchemy

description: Python dicts in sqlalchemy


code:
import subprocess
import sys
p = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(100)'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT); print('finished')

rawDescription: Run background process in Python and do NOT wait - no suggestions work


code: isItA = '*' in x and not  '**' in x

rawDescription: In python, test for 1 or 3 consecutive instances of a string, but not 2 (without regex)


code: topiclist = [topic for (topic, tlist) in dictionary.items() if word in tlist]

rawDescription: Find which dictionaries from a list contain word


rawDescription: Modifying a list while iterating when programming with python


code: df = pd.DataFrame([(k, s) for k, v in mydict.items() for s in v.split()], columns=['key_val','splitted_words'])

rawDescription: How to efficiently convert the entries of a dictionary into a dataframe

description: Efficiently convert the entries of a dictionary into a dataframe


code:
import main
...
exit(main.main())

rawDescription: Run python script from another python script but not as an child process


code: H = H * H_coeff

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code: val = ~key_equal + P.Word(P.alphanums+', ')

rawDescription: Non greedy parsing with pyparsing

description: Non greedy parsing with pyparsing


code: unique = str(unique) + i + " " + str(newWords.count(i)) + "\n"

rawDescription: Unique words save to text file as a word per line


code:
import pyaudio

chunk = 1024

p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=44100,
                input=True,
                frames_per_buffer=chunk)

data = stream.read(chunk)

rawDescription: Detecting system sound on Windows using Python


code: counts = [lettercount(t) for t in zip(seq1, seq2, seq3)]

rawDescription: frequency of letters in column python

description: Frequency of letters in column python


code:
levels = {'DEBUG':0,'INFO':1,'WARNING':2,'ERROR':3}
LL.sort(key = lambda x: levels[x.split(':')[0]])

rawDescription: Python - Sort Log Messages By Level before Printing


code:
import pyximport
pyximport.install()

import cobject_api

for i in cobject_api.take_list():
    print("{} has id {}".format(i, i.id))

rawDescription: Using data in python code from cpp using cython


code:
x = rdpcap("myfile")
len_x = len(x)

for i in x:
   if TCP in i:
      i.show()

rawDescription: Scapy - how to get the statistics?

description: Scapy - how to get the statistics


code: list(izip_longest(*([iter(li)] * n)))

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


code:
def init():
    print('myplugin1')

rawDescription: Telling __import__ where to look - am I stuck with sys.path?


code:
firsts = ['ph', 'sd', 'nn', 'mm', 'gh']
seconds = fourths = ['a', 'e', 'i', 'o', 'u', 'y', 'rc']
thirds = 'b'
fifths = 'a'

rawDescription: Python script to generate words from letters and two letter combination


code: row[0] = REV(flip(row[n]))

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


code:
class WantFixup(object):
    def new_instance(self, name, derived_name):
        cls = type(self)
        if name is None:
            name = derived_name.replace('_', ' ')
        return cls(name)

class Container(WantFixup):
    def __init__(self, name=None):
        self.name = name
    def __repr__(self):
        return "Container('%s')" % str(self.name)

class WillFixup(object):
    def __init__(self):
        cls = type(self)
        for name in cls.__dict__:
            o = cls.__dict__[name] # look up object from name
            if not isinstance(o, WantFixup):
                continue
            print("calling %s.new_instance('%s', '%s')" % (o, o.name, name))
            self.__dict__[name] = o.new_instance(o.name, name)

class Name(WillFixup):
    first_name = Container("given name")
    last_name = Container()

rawDescription: Extract assigned variable name

description: Extract assigned variable name


rawDescription: What is the Matlab equivalent to Python's `not in`?


code:
def f(matrix, vector, input_vector):
    return np.dot(matrix, input_vector) + vector

results = {}
for type_ in types:
    func = partial(f, matrices[type_], vectors[type_])
    results[type_] = p.map(func, input_vectors)

rawDescription: Global variables in python's multiprocessing.Pool class


code:
mapping = {"encode_b64": base64.encodestring,
           "encode_url": urllib.quote_plus}
process = mapping.get(item, default_encode)

rawDescription: Building commands from variables in Python and Tkinter


code:
from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

rawDescription: Timeout function if it takes too long to finish


rawDescription: Setting all dictionary elements to 0 python


code:
df.reset_index(level='date', inplace=True)
df = df.join(repository, rsuffix='_threshold')

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


code:
a = [boundaries]
p = [p]# this can be anything
for i in p:
    for bound in a:
        if i > bound:
            pass
        else:
            p1.append(bound)

rawDescription: Python: putting elements into proper interval


code:
YY, XX = numpy.mgrid[10:40:10, 1:4]
ZZ = XX + YY # These are equivalent to the output of meshgrid

YY, XX = numpy.ogrid[10:40:10, 1:4]
ZZ = XX + YY # These are equivalent to the atleast_2d example

rawDescription: Mesh grid functions in Python (meshgrid mgrid ogrid ndgrid)


code:
dic = {}
for line in text.splitlines():
    arr = line.split(' ')
    dic[arr[0].rstrip(':')] = ' '.join(arr[1:])

rawDescription: How to convert string to dictionary or some sort (from websocket client)

description: Convert string to dictionary or some sort (from websocket client)


code:
def extract_times(times,is_start):
   return [(times[i],i,is_start) for i in range(len(times))]

rawDescription: python find intersection timeranges in array

description: Python find intersection timeranges in array


code: y_axis += [int(i) / float(summ)]

rawDescription: Divide list elements by list sum and place back into list


code: concatenate([MyFunct(X).reshape((-1,2,3)) for X in values])

rawDescription: Build an ever growing 3D numpy array

description: Build an ever growing 3D numpy array


code:
data = np.column_stack((np.random.normal(scale=10, size=1000),
                        np.random.normal(scale=20, size=1000)))
x, y = data.T
hist, x_bins, y_bins = np.histogram2d(x, y, bins=(50, 50))
x_bin_midpoints = x_bins[:-1] + np.diff(x_bins)/2
y_bin_midpoints = y_bins[:-1] + np.diff(y_bins)/2
cdf = np.cumsum(hist.ravel())
cdf = cdf / cdf[-1]

values = np.random.rand(10000)
value_bins = np.searchsorted(cdf, values)
x_idx, y_idx = np.unravel_index(value_bins,
                                (len(x_bin_midpoints),
                                 len(y_bin_midpoints)))
random_from_cdf = np.column_stack((x_bin_midpoints[x_idx],
                                   y_bin_midpoints[y_idx]))
new_x, new_y = random_from_cdf.T

plt.subplot(121, aspect='equal')
plt.hist2d(x, y, bins=(50, 50))
plt.subplot(122, aspect='equal')
plt.hist2d(new_x, new_y, bins=(50, 50))
plt.show()

rawDescription: Random Number from Histogram

description: Random Number from Histogram


code: thelist = next(reader)

rawDescription: Strip outside quotes from text when writing to list in Python


code:
bar = iter(foo)
val = next(bar, "default")

rawDescription: Using iter on a list with a default value


code:
[defaults]
python=2

rawDescription: The Python Windows launcher isn't reading `py.ini`


code:
from wand.color import Color
from wand.compat import nested
from wand.drawing import Drawing
from wand.image import Image

dimensions = {'width': 450,
              'height': 100}

with nested(Image(background=Color('skyblue'), **dimensions),
            Image(background=Color('transparent'), **dimensions)) as (bg, shadow):
    # Draw the drop shadow
    with Drawing() as ctx:
        ctx.fill_color = Color('rgba(3, 3, 3, 0.6)')
        ctx.font_size = 64
        ctx.text(50, 75, 'Hello Wand!')
        ctx(shadow)
    # Apply filter
    shadow.gaussian_blur(4, 2)
    # Draw text
    with Drawing() as ctx:
        ctx.fill_color = Color('firebrick')
        ctx.font_size = 64
        ctx.text(48, 73, 'Hello Wand!')
        ctx(shadow)
    bg.composite(shadow, 0, 0)
    bg.save(filename='/tmp/out.png')

rawDescription: python wand: creating text dropshadow

description: Python wand: creating text dropshadow


code:
def filepath(filename, foldername=None, envar='MYAPPDIR'):
  default = '~/myFolder'
  if foldername:
    default = os.path.join(default, foldername)
  dirpath = os.path.expanduser(os.environ.get(envar, default))

  try:
    os.makedirs(dirpath)
  except OSError as e:
    if e.errno != errno.EEXIST:
      raise
  return os.path.join(dirpath, filename)

rawDescription: Python Creating Unwanted Folder in Directory


code:
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

rawDescription: Scatter plot and Color mapping in Python


rawDescription: Python: modify element in a nested dict

description: Python: modify element in a nested dict


code:
x = iter([ xrange(0,5), xrange(5,10)])
a = (i for subiter in x for i in subiter)
list(a)

rawDescription: If a python iterator returns iterable objects, how can I chain those objects into one big iterator?


code:
a_list = [1,2,3,4,5]
another_list = []

for i in range(5):
    another_list.append(a_list)
    a_list[0] = i + 10

print(another_list)

rawDescription: Python Creating a nested list with random module


code:
from billiard import Process, forking_enable
import cv2 #does matter where this happens when you don't use fork

def cam():
    vc = cv2.VideoCapture(0) #modify 0/1 to toggle between USB and internal camera
    while True:
        junk,image = vc.read()

forking_enable(0) # Is all you need!
camProcess = Process( target=cam )
camProcess.start()

while True:
    pass

rawDescription: OpenCV crash on OS X when reading USB cam in separate process


code:
#!/usr/bin/python2
import codecs
with codecs.open('y.py', 'w', 'utf-8-sig') as outputFile:
    outputFile.write(u'#!/usr/bin/python2\n')
    outputFile.write(u'\n')
    outputFile.write(u'# ' + u'Syst\xe9m' + u'\n')
    outputFile.write(u'print \'Hello, World!\'\n')

rawDescription: Cannot execute auto-generated Python script encoded in UTF8-sig


rawDescription: Delete rest of string after n-th occurence


code: [name for name in dir(a) if isinstance(getattr(a, name), types.MethodType)]

rawDescription: Differentiating methods from variables of an object


rawDescription: Pandas selecting data with specific conditions


code:
filename = "myFile.txt"
outputFile = open(filename, "w")
string = "WWWW 2 77777 54 M 888 90 6.7 100 No yyy kk 888 zz F too yy 8.8 123 xxx yyy pp"
outputFile.write("\n".join(item for item in string.split(" ")))
outputFile.close()

rawDescription: How do I align data vertically in python?

description: Align data vertically in python


code: from sqlalchemy import desc

rawDescription: Python SqlAlchemy order_by DateTime?

description: Python SqlAlchemy order_by DateTime


code: lookup = {1:0}

rawDescription: finding the lowest collatz sequence that gives more that 65 primes

description: Finding the lowest collatz sequence that gives more that 65 primes


code:
def lgCeil(x):
    startNum = 0
    numOfTimes = 0 # why two values to keep count?
    base = 2
    integer = base * 2 # what about numbers <= 2?
    while not(integer >= x): # why not 'integer < x'?
        startNum = 2 # always resets to 2 - why?
        numOfTimes = numOfTimes + 1 # could just be '+= 1'
        integer = integer * base # could just be '*= base'
    numOfTimes = numOfTimes + startNum # always adding on a fixed 2
    if (integer <= x):
        base**(numOfTimes+1) # this line doesn't actually contribute to output
    return numOfTimes

rawDescription: LgCeil - My professor says my code does not work for 1<n<=4


code:
smaller_things = {}
for k, v in things.items():
    if v == 3:
        smaller_things[k] = v

rawDescription: extracting dictionary pairs based on value

description: Extracting dictionary pairs based on value


code:
def checker(data, char_checked):
    opened, result = 0, []
    for idx, char in enumerate(data):
        if char == char_checked and opened == 0 and char != "(":
            result.append(idx)
        if char == "(":
            opened += 1
        elif char == ")":
            opened -= 1
    return result

assert checker('(A.(B|A)).A', '.')  == [9]
assert checker('(A.(B|A)).A', 'A')  == [10]
assert checker('(A.(B|A)).A', 'C')  == []

rawDescription: Determine whether a character is not in a set of paranthesis at an index?


code: search_terms = ['a','b','c'] #User's search query, split into a list of strings

rawDescription: GAE text search with secondary sorting

description: GAE text search with secondary sorting


code:
from curses import ascii
bytearray(filter(ascii.isprint, b'123'))

rawDescription: Python - How can I change bytes in a file


code:
my_list = [(2, 3), (3, None), (None, None), (3, 4), (None, 2)]
[t for t in my_list if None not in t]
[t for t in my_list if t != (None, None)]

rawDescription: Filtering a list of tuples filled with None in python


code:
class Car:
    def __init__(self, brand, model, hp):
        self.brand = brand
        self.model = model
        self.hp = hp

rawDescription: Python collections of non-base type?

description: Python collections of non-base type


code:
dte = "2002-08-22T07:00:00Z"
print( datetime.strptime(dte, "%Y-%m-%dT%H:%M:%SZ"))
utc = datetime.strptime(dte, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_utc)
for tz in pytz.all_timezones:
    tz = timezone(tz)
    dt = (utc.astimezone(tz))
    if str(dt.time()) == "00:00:00":
        print(tz)
        print(dt)

rawDescription: Translating timestamp to Human Readable format


code: headerdict = parseHeader(headerbytes)

rawDescription: Read large file header (~9GB) inside tarfile without full extraction


code:
from itertools import chain
with open('file.txt') as f:
    lines = chain.from_iterable([l.replace(r'"','').rstrip('\n').split('\t',1) for l in f])

rawDescription: Python: What's a fast way to read and split a file?


code: age = models.IntegerField()

rawDescription: How to set NULL for IntegerField instead of setting 0?

description: Set NULL for IntegerField instead of setting 0


code:
board = {}
board[ 3, 6 ] = "black queen"
board[ 0, 0 ] = "white king"

rawDescription: Rubyist in Pythonland: what is a real world example of a tuple?


code:
with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
         file_2.write(file_1.read())

rawDescription: What does it means to not exceeding 80 characters in a line in Python?


code:
class CustomJSONDecoder(JSONDecoder):
    def __init__(self, *args, **kwargs):
        self.orig_obj_hook = kwargs.pop("object_hook", None)
        super(CustomJSONDecoder, self).__init__(*args,
            object_hook=self.custom_obj_hook, **kwargs)

    def custom_obj_hook(self, dct):
        # Calling custom decode function:
        dct = HelperFunctions.jsonDecodeHandler(dct)
        if (self.orig_obj_hook):  # Do we have another hook to call?
            return self.orig_obj_hook(dct)  # Yes: then do it
        return dct  # No: just return the decoded dict

rawDescription: Proper overloading of json encoding and decoding with Flask


code:
to_call = [function1, function2, function3]
random.shuffle(to_call)
for f in to_call:
    f()

rawDescription: Do things in random order?

description: Do things in random order


code:
def main():
    C1 = DNPClass()
    C1.method1(arg1, arg2, arg3, arg4, arg5)

    # subscribing to event
    C1.method2.RequestEvent += handleResponseEvent  # will call C1.method3

    C2 = DNPClass()

    C2.method2.RequestEvent += handleResponseEvent  # will call C2.method3

def handleResponseEvent(request, response):
    #code to execute when event handler is called
    #code references additional method from current DNPClass instance
    request.dnp.method3()
    ...

rawDescription: Function inside a function best approach?


rawDescription: delete empty rows from a python list

description: Delete empty rows from a python list


code: zip(aindex, lindex)

rawDescription: Python : creating an array from list with given indices


code:
def strip_n_chars(s, n, char):
    """Remove at most n of char from the start of s."""
    for _ in range(n):
        if s[0] == char:
            s = s[1:]
        else:
            break
    return s

rawDescription: How to strip() out a maximum of two white spaces from the front of a string

description: Strip() out a maximum of two white spaces from the front of a string


rawDescription: Generating products of lists that sum to a parameter N


code:
class ModelB(ndb.Model):
    msg_id = ndb.StringProperty(indexed=False)
    cat_ids = ndb.StringProperty(repeated=True, indexed=False)
    list_ids = ndb.StringProperty(repeated=True, indexed=False)
    default_list_id_index = ndb.IntegerProperty(indexed=False)

class ModelA(ndb.Model):
    date_join = ndb.DateTimeProperty(auto_now_add=True)
    name = ndb.StringProperty()
    owner_salutation = ndb.StringProperty(indexed=False)
    owner_email_address = ndb.StringProperty()
    logo_url = ndb.StringProperty(indexed=False)
    ...
    messages = ndb.LocalStructuredProperty(ModelB, name='bm', repeated=True, keep_keys=True)

rawDescription: Loading datastore entities from Python project in Go leads to nested structs slices of slices error


code:
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from werkzeug.security import generate_password_hash, check_password_hash

engine = sa.create_engine('sqlite://', echo=True)
session = Session(engine)
Base = declarative_base(engine)

class User(Base):
    __tablename__ = 'user'

    id = sa.Column(sa.Integer, primary_key=True)
    username = sa.Column(sa.String, nullable=False, unique=True)
    password = sa.Column('password', sa.String)

    def set_password(self, secret):
        self.password = generate_password_hash(secret)

    def check_password(self, secret):
        return check_password_hash(self.password, secret)

Base.metadata.create_all()

u = User(username='davidism')
u.set_password('cabbage')
session.add(u)
session.commit()

u = session.query(User).filter_by(username='davidism').one()
print(u.password)
# pbkdf2:sha1:1000$w9jx4Egp$b420d784ac6ad0575e4a9a908bb4679826e56f5f
print(u.check_password('cabbage'))
# True

rawDescription: Why is check_password_hash always returning False in this login view?


code: navigated_pages = re.findall(r'EVENT\(X(.*?)\) ',data,re.DOTALL|re.MULTILINE)

rawDescription: Getting strings in between two keywords from a file in python


code:
import datetime
for record in records:
    datepart, _ = record.split("T")
    date = datetime.datetime.strptime(datepart, "%Y-%m-%d")

rawDescription: How to categorize and count imported data

description: Categorize and count imported data


rawDescription: Order multiple sorted arrays

description: Order multiple sorted arrays


code: self.memory[index:index + 4] = p.process_id, p.state, p.priority, p.urgency

rawDescription: unpacking class variables as a list

description: Unpacking class variables as a list


code:
with open(r"c:\temp\data1.csv") as r:
    for l in r:
        c[l.rstrip('\n')] += 1

rawDescription: Finding word co-occurrences

description: Finding word co-occurrences


code:
import urlparse
import posixpath

def resolveComponents(url):
    """
    >>> resolveComponents('http://www.example.com/foo/bar/../../baz/bux/')
    'http://www.example.com/baz/bux/'
    >>> resolveComponents('http://www.example.com/some/path/../file.ext')
    'http://www.example.com/some/file.ext'
    """

    parsed = urlparse.urlparse(url)
    new_path = posixpath.normpath(parsed.path)
    if parsed.path.endswith('/'):
        # Compensate for issue1707768
        new_path += '/'
    cleaned = parsed._replace(path=new_path)
    return cleaned.geturl()

rawDescription: Python: How to resolve URLs containing '..'


code:
if GO_TO_MAX_SPEED and NOT_AT_MAX_SPEED:
    ACCELERATE

rawDescription: Need help detecting a change in a variable outside of a while loop


code:
it = iter(dct['time'] for dct in a)
tot = sum(it, next(it))

for dct in a:
   dct['time'] = tot

rawDescription: Python list Comprehension inside dictionaries


code:
class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):
    def _row_to_python(self, rowdata, desc=None):
        row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
        if row:
            return dict(zip(self.column_names, row))
        return None

db = mysql.connector.connect(user='root', database='test')

cursor = db.cursor(cursor_class=MySQLCursorDict)

rawDescription: python mysql.connector DictCursor?

description: Python mysql.connector DictCursor


rawDescription: How to convert a string into a constant tuple in Python

description: Convert a string into a constant tuple in Python


code:
array = map(int, array)
prod = 1
for x in array:
    prod *= x
    prod %= n2

rawDescription: How to boost efficiency for large number modulus multiplications in Python

description: Boost efficiency for large number modulus multiplications in Python


code:
def test_it():
    dct = {str(i): i for i in xrange(100)}
    assert dct == "Hi"

def test_it2():
    dct = {str(i): i for i in xrange(100)}
    assert dct == "Hi", str(dct) + " shall sound friendly"

rawDescription: py.test printing out full data in stack trace

description: Py.test printing out full data in stack trace


rawDescription: Rotate pandas DataFrame 90 degrees

description: Rotate pandas DataFrame 90 degrees


code:
import numpy as np

def nan_helper(y):
    """Helper to handle indices and logical indices of NaNs.

    Input:
        - y, 1d numpy array with possible NaNs
    Output:
        - nans, logical indices of NaNs
        - index, a function, with signature indices= index(logical_indices),
          to convert logical indices of NaNs to 'equivalent' indices
    Example:
        >>> # linear interpolation of NaNs
        >>> nans, x= nan_helper(y)
        >>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])
    """

    return np.isnan(y), lambda z: z.nonzero()[0]

rawDescription: Interpolate NaN values in a numpy array

description: Interpolate NaN values in a numpy array


code:
import pandas as pd
df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])
df
s = pd.Series([5,6],index=['A','B'])
s
df.append(s,ignore_index=True)

rawDescription: Is it possible to append Series to rows of DataFrame without making a list first?


code:
start = "AAT"
end = ["ATG", "TTT", "ATC"]
regex = "%s.*?(?:%s)" % (start, '|'.join(end))

rawDescription: How to: From one string to another in a long list of strings


code:
def __iadd__(self, n):
    self.count += n
    return self

rawDescription: Reinserting set element creates holes

description: Reinserting set element creates holes


code:
def read_by_tokens(fileobj):
    for line in fileobj:
        for token in line.split():
            yield token

rawDescription: Python: Read whitespace separated strings from file similar to readline


rawDescription: Conditional counting within groups

description: Conditional counting within groups


code:
for root, dirs, files in os.walk('root path'):
    for dir in dirs:
        if dir.endswith(' ') or dir.endswith('.'):
            os.rename(...)

rawDescription: recursive script to rename folders ending with a space or period

description: Recursive script to rename folders ending with a space or period


code: print(dfrwg)

rawDescription: Grouping pandas data frame by time intervals


rawDescription: Dealing with missing data in an one column text file


rawDescription: Flask: How to manage different environment databases?


code:
i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)

rawDescription: Issues with the labels in image in matplotlib


code: listA = [a + [b] for a, b in zip(listA, listB)]

rawDescription: Appending in lists of list

description: Appending in lists of list


code:
dict1 = {'topkey1': {'datetimes': [9,8], 'values': [7,6]}, 'topkey2': {'datetimes': [5,4], 'values': [3,2]}}
dict2 = {'topkey1': {'datetimes': [29,28], 'values': [17,16]}, 'topkey2': {'datetimes': [35,34], 'values': [43,42]}}
for key, value in dict2.items():
    for subkey, subvalue in value.items():
        dict1[key][subkey] = dict1[key][subkey] + subvalue

dict1

rawDescription: How to create a Python nested dictionary from 2 pkl files/combine 2 nested dictionaries into one?

description: Create a Python nested dictionary from 2 pkl files/combine 2 nested dictionaries into one


code:
import re

re.split(r'^\n\n', paragraphs, flags=re.MULTILINE)

rawDescription: Splitting paragraphs that begin as indents


rawDescription: Difference between numpy.array shape (R, 1) and (R,)


code:
from markdown import blockprocessors as bp
def build_block_parser(md_instance, **kwargs):
    """ Build the default block parser used by Markdown. """
    parser = bp.BlockParser(md_instance)
    parser.blockprocessors['empty'] = bp.EmptyBlockProcessor(parser)
    parser.blockprocessors['indent'] = bp.ListIndentProcessor(parser)
    # parser.blockprocessors['code'] = bp.CodeBlockProcessor(parser)
    parser.blockprocessors['hashheader'] = bp.HashHeaderProcessor(parser)
    parser.blockprocessors['setextheader'] = bp.SetextHeaderProcessor(parser)
    parser.blockprocessors['hr'] = bp.HRProcessor(parser)
    parser.blockprocessors['olist'] = bp.OListProcessor(parser)
    parser.blockprocessors['ulist'] = bp.UListProcessor(parser)
    parser.blockprocessors['quote'] = bp.BlockQuoteProcessor(parser)
    parser.blockprocessors['paragraph'] = bp.ParagraphProcessor(parser)
    return parser
bp.build_block_parser = build_block_parser

rawDescription: Reducing capabilities of markdown in python


code:
field_names = [field.name for field in opts.fields]
if fields:
    field_names = filter(lambda field: field in fields, field_names)
elif exclude:
    field_names = filter(lambda field: field not in exclude, field_names)

rawDescription: Sorting model fields in set

description: Sorting model fields in set


code:
from scipy.optimize import leastsq
res = leastsq(f2,initial_guess,args = [x,y,r])

rawDescription: How to perform non-linear optimization with scipy/numpy or sympy?

description: Perform non-linear optimization with scipy/numpy or sympy


code:
def recur(n, ds=None):
    if ds is None: ds = {}
    x=do_foo(n)
    if foo(n):
        ds[n] = recur(x, ds)
    else:
        return x

rawDescription: Python: Recursion: Passing some value down through the calls


code: my_text = my_button['text']

rawDescription: Get the text of a button widget

description: Get the text of a button widget


code: return self.year and (self.year == date.year)

rawDescription: Logical operator "and" in python

description: Logical operator "and" in python


code:
import pprint
import psycopg2
conn = psycopg2.connect('');
curs = conn.cursor()
curs.execute("SELECT 1 as col1, 2 as col2, 'text' as colblah");
pprint.pprint(curs.description)

rawDescription: How to get column attributes from a query using PostgreSQL?

description: Get column attributes from a query using PostgreSQL


code:
class User(object):

    @classmethod
    def get_by_username(cls, dbsession, username):
        return dbsession.query(cls).filter(cls.username==username).scalar()

mapper(User, tables.auth_user,
    properties={
        ...
        }
    )

rawDescription: The pythonic way to handle sqlalchemy models


code: ul = soup.find(attrs={"id": "mgioLangList"})

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


code: c2.bogus = 42  # AttributeError: Can not add field 'bogus' to instance of 'SWF_RGBA'

rawDescription: Does this Python class look stupid?

description: Does this Python class look stupid


code:
class Table(object):
    def __init__(self):
        self.chain = None
        self.rule = None
        self.match = None

    def setInput(self):
        self.chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')

    def setOutput(self):
        self.chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT')

    ...

table = Table()
table.setInput()
...

rawDescription: Python-iptables how to optimize code

description: Python-iptables how to optimize code


code:
fname="gencode.v19.annotation.gtf"
with open('results.txt','w') as datafile:

    results = []
    for line in open(fname,'r'):
        if not line.startswith('##'):
            col1=line.split()[0]
            col3=line.split()[2]
            col4=line.split()[3]
            col5=line.split()[4]
            if "protein_coding" in line and col3=="exon":
                data = col1,col4,col5
                dataFile.write(str(data)) # Fix this: I dont know what formatting you want
                print(data)

rawDescription: Write three columns of file to new text file using python


code:
for index, data in enumerate(sentence):
    for key, value in word_list.iteritems():
        if key in data:
            sentence[index]=data.replace(key, word_list[key])

rawDescription: Replace strings in list from dictionary

description: Replace strings in list from dictionary


code:
import feedparser as fp

feed = fp.parse("http://www.dn.se/rss/senaste-nytt/")
for entry in feed["entries"]:
    print(entry["link"])

rawDescription: Python3 XML get text between tags

description: Python3 XML get text between tags


code: [len(set(i)) for i in data.reshape(data.shape[0],-1)]

rawDescription: vectorize numpy unique for subarrays

description: Vectorize numpy unique for subarrays


code:
import csv

irTable = {}
with open("devices.txt", newline='') as file:
    for label, freq, state in csv.reader(file, skipinitialspace=True):
        irTable[label] = int(freq), state

rawDescription: Python reading \n on the end of a line

description: Python reading \n on the end of a line


code:
def main(reactor):
    """makes a collection of deffered calls and then fires them. Stops reactor at end"""
    deferred_calls = [getDummyData(r) for r in range(0,100)]
    d = defer.gatherResults(deferred_calls, consumeErrors = True)
    d.addCallback(printData)
    return d

if __name__ == "__main__":
    from twisted.internet import task
    task.react(main, [])

rawDescription: stop a twisted reactor after a gatherResults has finished

description: Stop a twisted reactor after a gatherResults has finished


code:
if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()

rawDescription: Get the path of "static" folder in django automatically


code:
Mike: Plane
Car
Paula: Plane
Train
Boat
Car
Bill: Boat
Train
Scott: Car

rawDescription: Group and Check-mark using Python

description: Group and Check-mark using Python


code:
data = "Att education is secondary,primary,unknown"
first, _, last = data.rpartition(" ")
for item in last.split(","):
    print("{} {}".format(first, item))

rawDescription: Python 3.3: Split string and create all combinations


code:
def read(from_filename, buffer, process_queue):
  file = open(from_filename, 'r')
  slice = islice(file, buffer)
  while slice:
    to_process = []
    for line in slice:
      to_process.append(line)
    process_queue.put(to_process)
  process_queue.put('kill')

rawDescription: Process not ending in python

description: Process not ending in python


code:
tr = soup.find(class_='RESULTS').find(text='AUD/AED').parent.parent

import re

tr.find(text=re.compile(r'\w+ \d{1,2} \w+ \d{4}'))
Out[66]: 'Wednesday 23 APR 2014'

rawDescription: Python Beautiful Soup Print exact TD tag


rawDescription: Returning 0 for a value that doesn't exist


code:
from django.contrib.auth.models import User

class UserProfile(models.Model):
    # This field is required.
    user = models.OneToOneField(User)

    # Other fields here
    accepted_eula = models.BooleanField()
    favorite_animal = models.CharField(max_length=20, default="Dragons.")

rawDescription: get user profile in django

description: Get user profile in django


code:
d1 = {'local': {'count': 7, 'dining-and-nightlife': {'count': 1, 'bar-clubs': {'count': 1}}, 'activities-events': {'count': 6, 'outdoor-adventures': {'count': 4}, 'life-skill-classes': {'count': 2}}}}
keep_most_relevant(d1)
pprint.pprint(d1)
d2 = {'local': {'count': 11, 'dining-and-nightlife': {'count': 4, 'bar-clubs': {'count': 4}}, 'activities-events': {'count': 6, 'outdoor-adventures': {'count': 4}, 'life-skill-classes': {'count': 2}}}}
keep_most_relevant(d2)
pprint.pprint(d2)

rawDescription: Find Most Relevant Child in Dictionary

description: Find Most Relevant Child in Dictionary


code:
import random

#lists you want to shuffle
s1 = [1, 2, 3, 4]
s2 = [1, 2, 3, 4]
s3 = [1, 2, 3, 4]
s4 = [1, 2, 3, 4]

def mid_generator():

    while True:
        random.shuffle(s1)
        random.shuffle(s2)
        random.shuffle(s3)
        random.shuffle(s4)

        test0 = {s1[0], s2[0], s3[0], s4[0]}
        test1 = {s1[1], s2[1], s3[1], s4[1]}
        test2 = {s1[2], s2[2], s3[2], s4[2]}
        test3 = {s1[3], s2[3], s3[3], s4[3]}

        if len(test0) == len(test1) == len(test2) == len(test3) == 4:
            break

    return s1, s2, s3, s4

rawDescription: python, shuffle until lists are completely different

description: Python, shuffle until lists are completely different


code: sourceout.write (str(readfile))

rawDescription: Python - glob.glob doesn't find *.txt in specified filepath within Unix OS


code:
# To run the program foo that takes an option and two arguments
# Equivalent to "foo -d bar baz" directly in the shell
call(['foo', '-d', 'bar', 'baz'])

rawDescription: Need to write python script to execute linux commands in cygwin


rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


code:
import re
re.search(r'itunes(\d+)', 'itunes20140618.tbz').group(1)

rawDescription: Capture contents in regular expression

description: Capture contents in regular expression


rawDescription: Remove Rows Based on User-Input Conditions (Pandas,Python 3)


code:
for it in range(num_fills):
    data_a.insert(i+1+it+shift, float(nan))

rawDescription: How to improve my performance in filling gaps in time series and data lists with Python

description: Improve my performance in filling gaps in time series and data lists with Python


rawDescription: Read each entire Column of CSV file using python (preferably by help of pandas )


code:
print('
{0}	{1}	{2}
'.format(index, col1, col2))

rawDescription: Python formatting of strings with line breaks


code:
# rank 2 structure with full connectivity
struct = ndimage.generate_binary_structure(2, 2)
erode = ndimage.binary_erosion(mask, struct)
edges = mask ^ erode

rawDescription: border/edge operations on numpy arrays

description: Border/edge operations on numpy arrays


code:
from scrapy import project, signals
from scrapy.conf import settings
from scrapy.crawler import CrawlerProcess
from scrapy.xlib.pydispatch import dispatcher
from multiprocessing.queues import Queue
import multiprocessing

class CrawlerWorker(multiprocessing.Process):

    def __init__(self, spider, result_queue):
        multiprocessing.Process.__init__(self)
        self.result_queue = result_queue

        self.crawler = CrawlerProcess(settings)
        if not hasattr(project, 'crawler'):
            self.crawler.install()
        self.crawler.configure()

        self.items = []
        self.spider = spider
        dispatcher.connect(self._item_passed, signals.item_passed)

    def _item_passed(self, item):
        self.items.append(item)

    def run(self):
        self.crawler.crawl(self.spider)
        self.crawler.start()
        self.crawler.stop()
        self.result_queue.put(self.items)

rawDescription: building scrapy spiders into my own program, i don't want to call scrapy from command line)

description: Building scrapy spiders into my own program, i don't want to call scrapy from command line)


code:
from datetime import datetime
import pandas.io.data as web
import pandas as pd

class MonthlyChange(object):
    months = { 0:'JAN', 1:'FEB', 2:'MAR', 3:'APR', 4:'MAY',5:'JUN', 6:'JUL', 7:'AUG', 8:'SEP', 9:'OCT',10:'NOV', 11:'DEC' }

    def __init__(self,month):
        self.month = MonthlyChange.months[month-1]
        self.sum_of_pos_changes=0
        self.sum_of_neg_changes=0
        self.total_neg=0
        self.total_pos=0
    def add_change(self,change):
        if change < 0:
            self.sum_of_neg_changes+=change
            self.total_neg+=1
        elif change > 0:
            self.sum_of_pos_changes+=change
            self.total_pos+=1
    def get_data(self):
        if self.total_pos == 0:
            return (self.month,0.0,0,self.sum_of_neg_changes/self.total_neg,self.total_neg)
        elif self.total_neg == 0:
            return (self.month,self.sum_of_pos_changes/self.total_pos,self.total_pos,0.0,0)
        else:
            return (self.month,self.sum_of_pos_changes/self.total_pos,self.total_pos,self.sum_of_neg_changes/self.total_neg,self.total_neg)

for ticker in ['MSFT'] :

    data = web.DataReader(ticker, "yahoo", datetime(2014,1,1), datetime(2015,12,31))
    data['ymd'] = data.index
    year_month = data.index.to_period('M')
    data['year_month'] = year_month
    first_day_of_months = data.groupby(["year_month"])["ymd"].min()
    first_day_of_months = first_day_of_months.to_frame().reset_index(level=0)
    last_day_of_months = data.groupby(["year_month"])["ymd"].max()
    last_day_of_months = last_day_of_months.to_frame().reset_index(level=0)
    fday_open = data.merge(first_day_of_months,on=['ymd'])
    fday_open = fday_open[['year_month_x','Open']]
    lday_open = data.merge(last_day_of_months,on=['ymd'])
    lday_open = lday_open[['year_month_x','Open']]

    fday_lday = fday_open.merge(lday_open,on=['year_month_x'])
    monthly_changes = {i:MonthlyChange(i) for i in range(1,13)}
    for index,ym, openf,openl in fday_lday.itertuples():
        month = ym.strftime('%m')
        month = int(month)
        diff = (openf-openl)/openf
        monthly_changes[month].add_change(diff)
    changes_df = pd.DataFrame([monthly_changes[i].get_data() for i in monthly_changes],columns=["Month","Avg Inc.","#Inc","Avg.Dec","#Dec"])
    print(changes_df)

rawDescription: Isolating/manipulating data in a pandas Dataframe


code:
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=25)

    def __repr__(self):
        return '<User: %s>' % self.name

class Job(models.Model):
    name = models.CharField(max_length=25)

    def __repr__(self):
        return '<Job: %s>' % self.name

class UserJob(models.Model):
    user = models.ForeignKey(User)
    job = models.ForeignKey(Job)

    def __repr__(self):
        return '<UserJob: %s %s>' % (self.user.name, self.job.name)

rawDescription: Django search multiple filters

description: Django search multiple filters


code:
import numpy as np
mydata = np.genfromtext(filename, delimiter=",")

rawDescription: Loading a dataset from file, to use with sklearn


code: df['new_column'] = my_fxn(df['col1'], df['col2'])

rawDescription: What is the `pandas` way to create a column in a dataframe by operating on each row?


code:
import lxml.html as LH
import lxml.etree as ET

content='<root>
....Page Break....
</root>'
doc=LH.fromstring(content)
# print(LH.tostring(doc))
for div in doc.xpath('//div[@id="pgbrk"]'):
    parent=div.getparent()
    parent.replace(div,ET.Comment("page break"))
print(LH.tostring(doc))

rawDescription: How do I replace a HTML element with some new format in Python

description: Replace a HTML element with some new format in Python


code: call_later = MyClass.as_view

rawDescription: How to present a class as a function?

description: Present a class as a function


code:
for content in sort_list:
    flag = True
    content = content.lower()
    for thing in list1:
        thing = thing.lower()
        if thing in content:
            flag = False
            break
    if flag:
        print ("\n\n",outcome,"\n\n",content)

rawDescription: Can't successfully compare strings with python


code:
timeit('from __main__ import np, A_list, B_list; np.linalg.solve(A_list, B_list)', number = 100)
timeit('from __main__ import np, A_list, B_list; np.array([np.linalg.solve(A,B) for A, B in zip(A_list, B_list)])', number = 100)
timeit('from __main__ import np, A, B; np.linalg.solve(A,B)', number = 100)

rawDescription: How to map np.linalg.solve to an array of matrice and keep speed?

description: Map np.linalg.solve to an array of matrice and keep speed


rawDescription: How should I organise my functions with pyparsing?


code:
name = asksaveasfilename(defaultextension=".txt",
                         filetypes=[("Text files",".txt"),
                                    ("Word files",".doc")],
                         initialdir="dir",
                         title="Save as")

rawDescription: How to save text from a Text-widget Tkinter to a .doc using asksaveasfile?

description: Save text from a Text-widget Tkinter to a .doc using asksaveasfile


code:
raw_data='''
82   68   86   94   89   63   77   76   84    89
75   78   81   82   76   99   80   84   89    88
60   83   72   83   85   56   86   68   75   100
90   84   75   86   74   77   95   63   80    76
100   43  76   81   79   74   96   52   69    86'''
tu = [0,60,70,80,90,100]
print( 'raw_data :%s\n\ntu :\n%s' % (raw_data,tu),'\n' )

tu0, tuLast = tu[0], tu[-1]
tu_from1 = tu[1:]
from collections import OrderedDict
d = OrderedDict( (two[1],[two]) for two in zip(tu, tu_from1) )

print ('OrderedDictionary , before:\n%s'
       % '\n'.join('key:%3s   value:%s'  % item for item in d.items()))

# the core of the code is here:
for x in (x for x in map(int,raw_data.split()) if x>=tu0):
    d[next(lim for lim in tu_from1
           if x<lim or x==tuLast==lim)].append(x)

print ('\nOrderedDictionary , after:\n%s'
       % '\n'.join('key:%3s   value:%s'  % item for item in d.items()),'\n')

print( '\n'.join('%-15s%s' % (v[0],len(v)-1) for v in d.values()) )

rawDescription: how to cut a serial numbers into intervals in python code?

description: Cut a serial numbers into intervals in python code


code:
mylist = ["important", "comment"]
c = len(mylist) == 2 and mylist[1] == "comment"
c
mylist = ["important"]
c = len(mylist) == 2 and mylist[1] == "comment"
c

rawDescription: Check if a key exists in a Python list

description: Check if a key exists in a Python list


code:
def check(): #Will go through the list and print out any values greater than 100
    plist = price()
    for p in plist:
        if p > 100:
            print("{} needs to be recorded".format(p))

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


code:
def add_nodes(root, nodes):
    if nodes:
        node = nodes.pop(0)
        root.setdefault(node, {})
        add_nodes(root[node], nodes)

rawDescription: Pathname to a tree structure

description: Pathname to a tree structure


code:
url(r'^show/(?P<show_name>.+)/episodes', ShowDetail.as_view(), name='show-detail'),
url(r'^show/(?P<show_name>.+)-(?P<episode_season>\d+)-(?P<episode_number>\d+)',
    ShowDetail.as_view(), name='show-detail-update')

rawDescription: Django - a form input field doesn't get posted


code: all_data[i,j] = all_files[i]

rawDescription: Variable dimension array

description: Variable dimension array


code: b

rawDescription: Create new list with copied and averaged items from old list


code:
import io

class AlphaPeekReader(io.BufferedReader):
    def readalpha(self, count):
        "Read one character, and peek ahead (count - 1) *extra* characters"
        val = [self.read1(1)]

        # Find first alpha character
        while not val[0].isalpha():
            if val == ['']:
                return ''  # EOF
            val = [self.read1(1)]

        require = count - len(val)
        peek = self.peek(require * 3)  # Account for a lot of garbage
        if peek == '':  # EOF
               return val[0]

        for c in peek:
            if c.isalpha():
               require -= 1
               val.append(c)
               if not require:
                   break

        # There is a chance here that there were not 'require' alpha chars in peek
        # Return anyway.
        return ''.join(val)

rawDescription: character reading in a variety way

description: Character reading in a variety way


code:
matrix_1 = tf.Variable([[1, 2], [2, 3]], name="v1")
matrix_2 = tf.Variable([[3, 4], [5, 6]], name="v2")
init = tf.initialize_all_variables()

saver = tf.train.Saver()

sess = tf.Session()
sess.run(init)
save_path = saver.save(sess, "/model.ckpt")
sess.close()

rawDescription: Why do we use name parameter when creating a variable in Tensorflow?


code: l.sort(key=lambda p:(p.lastname, p.firstname, p.dob))

rawDescription: Pythonic Comparison Functions

description: Pythonic Comparison Functions


code:
aspan = self.axes.axvspan(x0,event.xdata, facecolor='y', alpha=0.5)
# do stuff
aspan.remove()
plt.draw()

rawDescription: How can I delet an axvspan line?

description: Delet an axvspan line


code: float(value.strip(' \t\n\r%'))

rawDescription: How to compare two percentages in python?

description: Compare two percentages in python


code:
import numpy as np
t12 = 3.1*60.
dt = 0.01
ln2 = np.log(2)

s = 98765

def parallel(nsims):  # your code, unaltered, except removed inaccurate timing method
    decay_time = np.zeros(nsims)
    t = dt
    np.random.seed(s) # also had to add a seed to get comparable results
    while 0 in decay_time:
        inot_decayed = np.where(decay_time == 0)[0]
        idecay_check = np.random.random(len(inot_decayed)) > np.exp(-ln2*dt/t12)
        decay_time[inot_decayed[np.where(idecay_check==True)[0]]] = t
        t += dt
    return decay_time

def parallel_micro(nsims): # micromanaged code
    decay_time = np.zeros(nsims)
    t = dt
    half_time = np.exp(-ln2*dt/t12)  # there was no need to calculate this again in every loop iteration
    np.random.seed(s)  # fixed seed to get comparable results
    while 0 in decay_time:
        inot_decayed = np.where(decay_time == 0)[0]  # only here you need the call to np.where
        # to my own surprise, len(some_array) is quicker than some_array.size (function lookup vs attribute lookup)
        idecay_check = np.random.random(len(inot_decayed)) > half_time
        decay_time[inot_decayed[idecay_check]] = t # no need for another np.where and certainly not for another boolean comparison
        t += dt
    return decay_time

rawDescription: Python/Numpy - Speeding up Monte Carlo method for radioactive decay


code:
import functools

def batchify(batch_size=200):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(d):
            assert isinstance(d, list), "data has to be in list form."
            N = len(d)
            results = []
            for i in xrange(N / batch_size + 1):
                low = i * batch_size
                high = min((i + 1) * batch_size, N)
                result = f(d[low:high])
                results.append(result)
            return [r for result in results for r in result]
        return wrapper
    return decorator

rawDescription: A decorator function for batching computations for large data in Python


code: {{ expense.vendor.get().friendlyName }}

rawDescription: Google App Engine Datastore modeling issue


code:
d = {A:['asdasd',2,3], B:['asdasd',4,5], C:['rgerg',9,10]}
from functools import reduce    # Py3
x,y = reduce(lambda t, e: (t[0]+e[0], t[1]+e[1]), ((a*b, a) for _,a,b in d.values()))
x/y   # float(y) in Py2

rawDescription: Using dictionary values to calculate sum of weighted values without explicitly defined weights


code:
boxes = (box1, box2, box3, box4)
data = [example(box) for box in boxes]

rawDescription: How to repeat a function with change some variables inside of the function? PYTHON 3.4

description: Repeat a function with change some variables inside of the function? PYTHON 3.4


code:
self.splitter = QtGui.QSplitter()
self.listA = QtGui.QListWidget()
self.listB = QtGui.QListWidget()
self.splitter.addWidget(self.listA)
self.splitter.addWidget(self.listB)
self.mainLayout.addWidget(self.splitter)

rawDescription: How to change QListWidget size interactively

description: Change QListWidget size interactively


code:
a=imread("sorNB.png")
h,l=a.shape
dl=50
b=numpy.zeros((h,l+dl),dtype=a.dtype)
for y in range(h):
    dec=(dl*(h-y))//h
    b[y,dec:dec+l]=a[y,:]

rawDescription: Skewing an array in Python

description: Skewing an array in Python


code:
for x in arg:
    lines = words = chars = 0
    with open("{}{}".format(folder, x), "r") as inp:
        ...

rawDescription: Python: counter in a function with multiple args


code:
def sumNumbers(n):
    i = 0
    sum = 0
    while i <= n:
       sum += i
       i += 1
    return sum

rawDescription: How can I Improve this Code, using While Loop?

description: Improve this Code, using While Loop


rawDescription: How to check if an array contains multiple specific elements

description: Check if an array contains multiple specific elements


code:
#! /usr/bin/python3

import sys, io

BINARY=True ## either way works

if BINARY: istream = sys.stdin.buffer
else:      istream = io.TextIOWrapper(sys.stdin.buffer,encoding='latin-1')

header = istream.readline()
if BINARY: header = header.decode('ASCII')
print("header=["+header.strip()+"]")

payload = istream.read()
print("len="+str(len(payload)))
for i in payload: print( i if BINARY else ord(i) )

rawDescription: binary input with an ASCII text header, read from stdin

description: Binary input with an ASCII text header, read from stdin