code:
scipy.io.wavfile.write('test.wav', rate, data_bis)
scipy.io.wavfile.read('test.wav')

rawDescription: Issues with scipy.io wave file processing after applying fourier transforms


code:
def _eval_power(self, expt):
    return self

rawDescription: Sympy classes Zero, One and NegativeOne, why they exist?


code:
import sys
sys.stdout.encoding

rawDescription: python: unicode in Windows terminal, encoding used?

description: Python: unicode in Windows terminal, encoding used


rawDescription: Regular expression find and replace multiple


code: os.path.join("path/to/base", Directory)

rawDescription: Assigning multiple variable values to a single variable in Python


code:
import re
myString = re.sub(r'\(.*\)', '', myString)

rawDescription: Strip a string if it contains a parnethesis


code:
url = "http://www.nalmls.com/SERetsHuntsville/Search.aspx?SearchType=Property&Class=RES&StandardNames=0&Format=COMPACT&Query=(DATE_MODIFIED=2012-09-28T00:00:00%2B)&Limit=10"
r = requests.get(url, auth=('user', 'pass'))
page = r.text

rawDescription: How to use Python to retrieve xml page that requires http login?

description: Use Python to retrieve xml page that requires http login


code:
from itertools import combinations
import difflib
li=['AAAAAAACDCBA', 'CCCCCCATATAT', 'CCCCCCAGAGAG', 'CCCCCTACACAC', 'AAAAAAACACAC']
d = defaultdict(list)
for i in li:
    d[i[:6]].append(i[6:])

keys=d.keys()
for i,j in combinations(keys,2):
     if difflib.SequenceMatcher(None,i, j).ratio()>0.8:
        d[i].extend(d[j])
        del d[j]

d

rawDescription: Use levenshtein distance for keys in defaultdict in python


code:
values['N_a'] # holds '2'
values['N_b'] # holds '5'
# etc...

rawDescription: Dynamically import file

description: Dynamically import file


code:
content = [7, 14, 23, 49, 191]
widths = [' '*len(str(c)) for c in content]
the_ones = [False, True, False, True, False] # or any other way to
                                             # signal which ones to tick
for i, t in enumerate(the_ones):
    if t == True:
        widths[i] = widths[i][:-1]+'|'

print(' '.join(widths))
print(' '.join(map(str, content)))

rawDescription: Python format print to evenly print numbers


code:
import csv
import urllib2

import BeautifulSoup

def getPageText(url, filename):
    data = urllib2.urlopen(url).read()
    bs = BeautifulSoup.BeautifulSoup(data, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
    with open(filename, 'w') as f:
        writer = csv.writer(f)
        for li in bs.findAll('li', attrs={'class':'g'}):
            sLink = li.find('a')
            sSpan = li.find('span', attrs={'class':'st'})
            writer.writerow([sLink['href'], sSpan])

def main():
    urls = [
        'http://192.168.1.200/coimbatore/3BHK_flats_inCoimbatore.html_%94201308110608%94.html',
        'http://192.168.1.200/coimbatore/3BHK_flats_inCoimbatore.html_%94201308110608%94.html.html',
    ]
    for i, url in enumerate(urls, 1):
        getPageText(url, '{}.csv'.format(i))

if __name__=="__main__":
    main()

rawDescription: Scrape html files stored in remote directory


code: sub[random.randint(0,9)] = 1

rawDescription: Very simple Python script, puzzling behaviour


code:
#!/usr/bin/python3

import os
import argparse
import sys

def safe_remove(dirs, exclude, verbose, dry_run):
    for directory in dirs:
        if verbose or dry_run:
            print("Checking directory '%s'" % (directory,))
        for filename in os.listdir(directory):
            if filename not in exclude:
                filename = os.path.join(directory, filename)
                if verbose or dry_run:
                    print('rm %s'%filename)
                if not dry_run:
                    os.remove(filename)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Remove files, with exceptions')
    parser.add_argument('-x', '--exclude',
                        metavar='FILE',
                        default=[],
                        nargs='+',
                        help='files to exclude')
    parser.add_argument('dirs',
                        metavar='DIR',
                        nargs='+',
                        help='directories to clean')
    parser.add_argument('-v', '--verbose',
                        action='store_true',
                        help='Print actions')
    parser.add_argument('-n', '--dry-run',
                        action='store_true',
                        help='Print, but do not perform, actions')
    args = parser.parse_args()
    safe_remove(**vars(args))

rawDescription: Why does shopt fail when called from python?


code:
def main(args=None):
    if args is None:
        args = sys.argv[1:]

rawDescription: Use Python's `timeit` from a program but functioning the same way as the command line?


code:
def find_neighbors(m, i, j, dist=1):
    neighbors = []
    i_min = max(0, i-dist)
    i_max = i+dist+1
    j_low = max(0, j-dist)
    j_max = j+dist+1
    for row in m[i_min:i_max]:
        neighbors.append(row[j_min:j_max])
    return neighbors

rawDescription: python find all neighbours of a given node in a list of lists

description: Python find all neighbours of a given node in a list of lists


rawDescription: How do I sort a numerical list with names attached?

description: Sort a numerical list with names attached


code: items = [[a, b] for a in items for b in items if x != a or y != b]

rawDescription: Creating a list with two different numbers


code:
import numpy as np
import pandas as pd

##############################
# generate sample DF
##############################
rows = 2*10**7
chr_lst = ['chr{}'.format(i) for i in range(1,10)]

df = pd.DataFrame({'SNP': np.random.randint(10**6, 10**7, rows).astype(str)})
df['CHR'] = np.random.choice(chr_lst, rows)
df['BP'] = np.random.randint(10**6, 10**9, rows)
df['P'] = np.random.rand(rows)
df.SNP = 'rs' + df.SNP

"""
# NOTE: sometimes it gives me MemoryError !!!
# because of that i did it "column-by-column" before
df = pd.DataFrame({
    'SNP': np.random.randint(10**6, 10**7, rows).astype(str),
    'CHR': np.random.choice(chr_lst, rows),
    'BP':  np.random.randint(10**6, 10**9, rows),
    'P':   np.random.rand(rows)
}, columns=['SNP','CHR','BP','P'])

df.SNP = 'rs' + df.SNP
"""

# make 8 columns out of 4 ...
df = pd.concat([df]*2, axis=1)
df.columns = ['SNP', 'CHR', 'BP', 'P', 'SNP2', 'CHR2', 'BP2', 'P2']

##############################
# store DF as CSV file
##############################
csv_path = r'c:/tmp/file_8_cols.csv'
df.to_csv(csv_path, index=False)

##############################
# read CSV file (only needed cols) in chunks
##############################
csv_path = r'c:/tmp/file_8_cols.csv'
cols = ['SNP', 'CHR', 'BP', 'P']
chunksize = 10**6

df = pd.concat([x for x in pd.read_csv(csv_path, usecols=cols,
                                       chunksize=chunksize)],
               ignore_index=True )

##############################
# sort DF and save it as .h5 file
##############################
store_path = r'c:/tmp/file_sorted.h5'
store_key = 'test'
(df.sort_values(['CHR','BP'])
   .to_hdf(store_path, store_key, format='t', mode='w', data_columns=True)
)

##############################
# read HDF5 file in chunks
##############################
store_path = r'c:/tmp/file_sorted.h5'
store_key = 'test'
chunksize = 10**6

store = pd.HDFStore(store_path)

threshold = 0.001
store_condition = 'P < %s' % threshold

i = store.select(key=store_key, where=store_condition)

# select all rows between `min(SNP) - 500K` and `max(SNP) + 500K`
window_size = 5*10**5
start = max(0, i.index.min() - window_size)
stop = min(store.get_storer(store_key).nrows, i.index.max() + window_size)
df = pd.concat([
        x for x in store.select(store_key, chunksize=chunksize,
                                start=start, stop=stop, )
               ])

# close the store before exiting...
store.close()

rawDescription: Efficient way to subset a huge delimited file


code: t = [[0] * (max_length - len(item)) + item for _, item in sorted(a.items())]

rawDescription: How to convert a python dictionary to an 2D array and pad wherever there is mismatch in length?

description: Convert a python dictionary to an 2D array and pad wherever there is mismatch in length


rawDescription: Python single character clean

description: Python single character clean


rawDescription: Closing a QWidget opened from a QMainWindow


code: xx = get_integral(tt)

rawDescription: python - scipy.integrate.odeint returning wrong results

description: Python - scipy.integrate.odeint returning wrong results


code:
df
slice_consc(df,3)

rawDescription: slice pandas df based on n consecutive instances of element

description: Slice pandas df based on n consecutive instances of element


code:
C = name()
a, b = C.solve(np.arange(5, dtype=np.float64), 3.0)

rawDescription: Python numba.jit types

description: Python numba.jit types


code:
import pygame

pygame.init()
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                print('this DOES work! :)')

rawDescription: pygame: pygame.KEYDOWN not working

description: Pygame: pygame.KEYDOWN not working


code:
if cv2.contourArea(contours[i]) < 100:
  continue

rawDescription: OpenCV get centers of multiple objects

description: OpenCV get centers of multiple objects


code:
class User(Base):
    ...

rawDescription: Application Layout with Groups of single items in Python


code:
import itertools
groups = itertools.groupby(lst, lambda i: i[0])
for key, value in groups:
    print [key] + map(sum, zip(*value)[1:])

rawDescription: Get all elements in a list where the value is equal to certain value


code:
import sys
dir(sys)

rawDescription: Regarding dir()

description: Regarding dir()


code:
import types
if not isinstance(obj, types.StringTypes) and hasattr(obj, "__iter__"):
    obj = list(obj)
return obj

rawDescription: python, wrap and object into a list if not is an iterable

description: Python, wrap and object into a list if not is an iterable


rawDescription: Changing python indexes in a string

description: Changing python indexes in a string


code:
from test import *
proc = MyProcessor()
holder = DataHolder()

proc.process(holder)

data = holder.BinaryData
print(repr(data))
print(data.tobytes())

rawDescription: Fill char* with binary data in a c++ Python wrapped class with SWIG


code:
import re
def as_list(time):
    """
    >>> as_list('1:38:11.50r')
    [1, 38, 11, 50]
    >>> as_list('2.23')
    [0, 0, 2, 23]
    """
    # Extract times and convert to integers
    times = [int(x) for x in re.split(r"[:.]", re.sub("[a-z]$", "", time))]
    # If needed pad from the left side with zeros and return
    return times if len(times) == 4 else [0] * (4 - len(times)) + times

[k for k, t in sorted(times.items(), key = lambda x: as_list(x[1]))]

rawDescription: How to sort a dictionary by a value passed through a function?

description: Sort a dictionary by a value passed through a function


rawDescription: Scraping for bottom row of table

description: Scraping for bottom row of table


code: print(word, end='')

rawDescription: I need to make the output be in one line


code: labelurl = tk.Button(window, text=url[2], height = 2, command = urlOpen(url[1]), width = 10)

rawDescription: Python creating dynamic button

description: Python creating dynamic button


code:
def longitudinal_parity(data, total_bits, word_bits, expected_parity):
    """
    Performs longitudinal parity check
    """
    for nbits in (total_bits, word_bits):
        if nbits & (nbits - 1):
            raise ValueError("bit size must be power of two")

    mask = (1 << total_bits) - 1

    while total_bits > word_bits:
        total_bits >>= 1
        data ^= (data >> total_bits)
        mask >>= total_bits
        data &= mask
    return data == expected_parity

rawDescription: Python - How to break word into 64bit chunks


code:
from myproject.mymodules import myfunctions
myfunctions.add(1, 2)

rawDescription: python local modules

description: Python local modules


code:
if condition:
   arg3 = "some value",
else:
   arg3 = ()
func("arg", "arg2", *arg3)

rawDescription: Conditionally passing arbitrary number of default named arguments to a function


code:
import re
patt = re.compile("([0-9]{2}/[0-9]{2}/[0-9]{4})")
m = patt.search(ami_image.description)
m.groups(0)

rawDescription: I want to find the date in the description of AMI image


code: result/days

rawDescription: Applying cell wise function in a dataframe


code: final_dict = {k:(NO_dict[k], EN_dict[k]) for k in NO_dict}

rawDescription: Python: Compare lists and combine in common fields


code:
for x in print_progress(my_list):
    # processing
    ...

rawDescription: Python/Django print loop progress along the way


code:
with app.test_client() as c:
    response = c.get('/some/path/that/exists')
    self.assertEquals(response.status_code, 200)

rawDescription: Testing Flask routes do and don't exist

description: Testing Flask routes do and don't exist


code:
for i,d in enumerate(m):

    # Using np.cov :
    org_cov = np.cov(d, ddof=0, rowvar=False)

    # Using earlier 2D array hacked version :
    nC = m[i].shape[0]
    X = m[i] - m[i].mean(0,keepdims=True)
    hacked_cov = np.dot(X.T, X)/nC

rawDescription: Quickly compute eigenvectors for each element of an array in python


code: [[left, op] + [sum(rights) // len(rights)] for (left, op), rights in expressions.items()]

rawDescription: Combining lists in python with unique elements but changing the third


code:
templatetags/my_tags.py
...
@register.filter
def where_id(users,user_id):
    return filter(lambda u:u.pk==user_id,users)
...

rawDescription: Django Templates: Is there a way to query a specific object based on its property (instead of iterating over all)?


code: df['Diff']

rawDescription: Column Differences in Python Pivot-Table


code:
from fabric.api import run
from fabric.context_managers import settings

def serv_foo():
    return 'bla@example.com'

def serv_bar():
    return 'bla@example2.com'

def get_all_servers():
    return {(k, v) for k, v in globals().items() if k.startswith("serv_")}

def get_hostnames():
    for serv_name, serv_fptr in get_all_servers():
        with settings(host_string=serv_fptr()):
            hostname = run("hostname")
            print(hostname)

rawDescription: Update hosts within fabric script

description: Update hosts within fabric script


code:
ip = '192.168.1.1'
ip_as_bytes = bytes(map(int, ip.split('.')))

rawDescription: Converting IP address into bytes in python


code:
import os
import math
os.path.abspath(math.__file__)

rawDescription: Python: Find the absolute path of an imported module


code:
# a method to check all sub squares starting at row and column 0 through 2
def checkgrid():
    # row 0 through 2
    for r in xrange(3):
        # column 0 through 2
        for c in xrange(3):
            # sum up all entries of grid matrix
            if grid[r:r+3, c:c+3].sum() != 4:
                return False
    return True

rawDescription: 5*5 grid, in every 3*3 square of the grid must be 4 "lights"


code:
import sys

from myprogram import main, parse_args

def modify_args(args):
    """Modify the arguments."""
    parsed_args = parse_args(args)  # reuse the original parser
    ...  # add your own changes
    return modified_args

if __name__ == "__main__":
    main(modify_args(sys.argv))

rawDescription: How to "hijack" and modify command line parameters


code:
def time_between(a, b):
    minutes, seconds = divmod((b-a).total_seconds(), 60)
    hours, minutes = divmod(minutes, 60)
    return hours, minutes, seconds

rawDescription: How to see when a point in time has passed in Python

description: See when a point in time has passed in Python


code: vbox.Add(topLabel, 0, wx.ALL, 5)

rawDescription: wxPython control spacing

description: WxPython control spacing


code:
teststring = 'newstring'
teststring == 'newstring' # True

nextstring = 'new-string'
nextstring == 'new-string' # True

rawDescription: compare two python strings with hypen/dash

description: Compare two python strings with hypen/dash


code:
import os
path = os.environ.get('path')
pathlist = path.split(';')
matlabpath = min([s for s in pathlist if 'MATLAB' in s], key=len)
print(matlabpath)

rawDescription: What is the Matlab install directory on 64bit or how to get it in Python?


code:
itemIDs = map(int, itemIDs)
itemNames = map(unicode, itemNames)

rawDescription: How to use a .NET method which modifies in place in Python?

description: Use a .NET method which modifies in place in Python


code: from utils import *

rawDescription: update fct in python constructors

description: Update fct in python constructors


code:
@staticmethod
def getData(parent = None):
    dialog = Widget(parent)
    dialog.exec_()
    return dialog.returnAnswer1()

rawDescription: How to use QtGui in PyQt4 to collect input variables to a python program?

description: Use QtGui in PyQt4 to collect input variables to a python program


rawDescription: White lines in confusion matrix?

description: White lines in confusion matrix


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

rawDescription: How to run all tests in a python file from a python script?

description: Run all tests in a python file from a python script


rawDescription: how do i test subprocess's stdout, stderr in python on windows

description: Test subprocess's stdout, stderr in python on windows


code:
d = dict((v,k) for (k,v) in enumerate('dacg'))
sorted('abdcdfs', key = lambda c:d.get(c, len(d)))

rawDescription: String Sort based on some Format

description: String Sort based on some Format


code:
pointArray = [1, 2, 3]
output = ["XYZ"] + pointArray
output

rawDescription: How to transform a list to a sequence of its comma-separated elements?

description: Transform a list to a sequence of its comma-separated elements


code: conditions = (and_(c1=x, c2=y, c3=z) for (x, y, z) in items)

rawDescription: How to get rows which match a list of 3-tuples conditions with SQLAlchemy

description: Get rows which match a list of 3-tuples conditions with SQLAlchemy


code: Board = copy.deepcopy(startBoard)

rawDescription: (Python) adding a list to another without the brackets


code:
name = tkinter.filedialog.asksaveasfilename()
file = open(name,'w')

rawDescription: How to save as a file but get its name at the same time?

description: Save as a file but get its name at the same time


rawDescription: Conditions in Find, Mongo

description: Conditions in Find, Mongo


rawDescription: building a parser in python

description: Building a parser in python


code: filename = os.path.join('./out', fn)

rawDescription: Python - Open file in Append Mode. Write Never Happens


code:
comm = [[k,v] for k,v in main_c]
make_a_frame = pd.DataFrame(comm)
make_a_frame.columns = ['Words', 'Frequency']
print(make_a_frame).sort("Frequency",ascending=False)

rawDescription: How to Crawl Multiple Websites to find common Words (BeautifulSoup,Requests,Python3)


code:
rex= re.compile("(?s).*?(cat|dog|rat)")
result= rex.sub("\\1", input_text, 1)

rawDescription: Delete all characters in a multline string up to a given pattern


code: intervalcount <- apply(resultmatrix, 2, sum)

rawDescription: Code for determining number of 15 minute periods


code: df['ingredients'] = [[item.strip().lower() for item in lst] for lst in df['ingredients']]

rawDescription: How to normalize text in a list that is itself in a column of Pandas dataframe?

description: Normalize text in a list that is itself in a column of Pandas dataframe


code: {file_field: (name, content, content_type, additional_file_headers)}

rawDescription: Mime type for Requests post file

description: Mime type for Requests post file


rawDescription: How can I format a float to separate by thousands, inverting dot and commas?

description: Format a float to separate by thousands, inverting dot and commas


rawDescription: Python - Remove "tagged" item from list only if another item with greater "tag" exists


rawDescription: How do I get the index of each item in a groupby object in Pandas?

description: Get the index of each item in a groupby object in Pandas


code:
class Handle:
    def __init__(self, pid=-1):
        if isinstance(pid, str):
            self.procname = pid
            self.pid = -1
        else:
            self.procname = None
            self.pid = pid

rawDescription: Python overload __init__

description: Python overload __init__


code:
if randomNumber in (One,Uno):
    randomNumber = 1
else:
    randomNumber = 2

rawDescription: If statement for multiple values

description: If statement for multiple values


rawDescription: How to check if a number is within a group of non-consecutive ranges?

description: Check if a number is within a group of non-consecutive ranges


code:
# moduleb.py
import json  # for instance

rawDescription: How to import appropriately

description: Import appropriately


code:
l = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
from itertools import groupby
groupby(l, lambda x: x == "")
[list(group) for k, group in groupby(l, lambda x: x == "") if not k]

rawDescription: Python split for lists

description: Python split for lists


rawDescription: Merging CSV data and counting cell values in python pandas


code:
def setUp(self):
    self.patcher1 = patch(
        "projectname.common.credential."
        "CredentialCache.mymethodname")

rawDescription: how to handle long path name for pep8 compliance?

description: Handle long path name for pep8 compliance


code: "Hello %s" % ', '.join(my_args)

rawDescription: python - How to format variable number of arguments into a string?

description: Python - How to format variable number of arguments into a string


code:
names = {"Spiderman":1, "Dr. House":2, "Jon Skeet":1}

resulting_keys = [k for k, v in names.iteritems() if v == 1]
# returns ['Spiderman', 'Jon Skeet']

rawDescription: Is there a dictionary-like datastructure that would allow searches for 'key' and for 'value'


code: Two Three

rawDescription: Python save arbitrarily nested list to CSV


code:
import datetime
dt = datetime.datetime.strptime('3/5/14', '%m/%d/%y')
dt

rawDescription: Required format for month-day-year plot in matplotlib


code:
def remove_nan(a, split=True):
    cols = [i[0] for i in eval(str(a.dtype))]
    col = cols[0]
    test = ~np.isnan(a[col])
    if not split:
        new_len = len(a[col][test])
        new = np.empty((new_len,), dtype=a.dtype)
        for col in cols:
            new[col] = a[col][~np.isnan(a[col])]
        return new
    else:
        indices = [i for i in xrange(len(a)-1) if test[i+1]!=test[i]]
        return [i for i in np.split(a, indices) if not np.isnan(i[col][0])]

rawDescription: Slicing numpy recarray at "empty" rows

description: Slicing numpy recarray at "empty" rows


code:
import itertools as IT
somedata = [1,12,123,1234,12345]
list(map(int, IT.chain.from_iterable(map(str, somedata))))

rawDescription: python map/reduce: emit multiple keys values from single map lambda

description: Python map/reduce: emit multiple keys values from single map lambda


code:
os.system('java '
          '-jar /path/to/selenium-server-standalone-2.0b3.jar '
          '-firefoxProfileTemplate /path/to/profile')

rawDescription: Sending stdin to subprocess in python script


rawDescription: how to calculate a 2D array with numpy mask

description: Calculate a 2D array with numpy mask


code:
def set_widget_value(widget,value):
    if hasattr(widget,"SetWidgetValue"):
        return widget.SetWidgetValue(value)
    if isinstance(widget,wx.Choice):
       return widget.SetStringSelection(value)
    if hasattr(widget,"SetValue"):
        return widget.SetValue(value)
    if hasattr(widget,"SetLabel"):
        return widget.SetLabel(value)
    else:
       raise Exception("Unknown Widget Type : %r"%widget)

def get_widget_value(widget):
     if hasattr(widget,"GetWidgetValue"):
        return widget.GetWidgetValue()
     if isinstance(widget,wx.Choice):
        return widget.GetStringSelection()
     if hasattr(widget,"GetValue"):
        return widget.GetValue()
     if hasattr(widget,"GetLabel"):
        return  widget.GetLabel()
     else:
       raise Exception("Unknown Widget Type : %r"%widget)

class WidgetManager(wx.Panel):
      def __init__(self,parent):
         self._parent = parent
         wx.Panel.__init__(self,parent,-1)
         self.CreateWidgets()
      def CreateWidgets(self):
         #create all your widgets here
         self.widgets = {}
      def SetWidgetValue(self,value):
         if isinstance(value,dict):
            for k,v in value.items():
               set_widget_value(self.widgets.get(k),v)
         else:
            raise Exception("Expected a dictionary but got %r"%value)
      def GetWidgetValue(self):
          return dict([(k,get_widget_value(v))for k,v in self.widgets])

rawDescription: Is there an analog to tk.IntVar() in wxPython?


code:
def sum_digits2(n):
    if n < 10:
        return n
    else:
        return sum_digits2(sum(int(c) for c in str(n))) # this one returns an int

rawDescription: How can I Keep the following program running until it becomes a single digit number?


code:
SWAGGER_SETTINGS = {
    "exclude_namespaces": ["internal_apis"],    #  List URL namespaces to ignore
}

rawDescription: Exclude URLs from Django REST Swagger

description: Exclude URLs from Django REST Swagger


code:
def pixel(surface, color, pos):
    pygame.draw.line(surface, color, pos, pos)

rawDescription: Pygame: Draw single pixel

description: Pygame: Draw single pixel


code:
def constructor(loader, node):
    return node.value
yaml.SafeLoader.add_constructor("tag:yaml.org,2002:python/unicode", constructor)
yaml.safe_load(y)

rawDescription: How can I get pyyaml.safe_load() to handle python/unicode tag?

description: Get pyyaml.safe_load() to handle python/unicode tag


code:
def main():
    infile = open("module3.txt","r")
    uppercasecount = 0
    lowercasecount = 0
    digitcount = 0
    spacecount = 0
    lines = infile.readlines()
    for line in lines:
        for character in line:
            if character.isupper() == True:
                uppercasecount += 1
            if character.islower() == True:
                lowercasecount += 1
            if character.isdigit() == True:
                digitcount += 1
            if character.isspace() == True:
                spacecount += 1
    print ("Total count is %d Upper case, %d Lower case, %d Digit(s) and %d spaces." %(uppercasecount, lowercasecount, digitcount, spacecount))

main()

rawDescription: Reading multiple lines from an external text file in Python


rawDescription: Average positive numbers in a row

description: Average positive numbers in a row


code:
def class_for_method(cls, method):
    return next((c for c in inspect.getmro(cls)
                 if method.__func__ in vars(c).values()), None)

rawDescription: In Python, class from which a given instance is inheriting a particular method


code:
words = s.lower().split()
words
words.sort()
words

rawDescription: Finding letters in a string

description: Finding letters in a string


code:
(d + datetime.timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S')
'{:%Y-%m-%d %H:%M:%S}'.format(d + datetime.timedelta(hours=3))

rawDescription: time function in Python for add an interval to a datetime object

description: Time function in Python for add an interval to a datetime object


code: map(partial(reduce, lambda x, y: x.replace(y[0], y[1]), replacements), mylist)

rawDescription: itertools or functools for find-replace list in python

description: Itertools or functools for find-replace list in python


code:
class OrderAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(ActiveOfferAdmin, self).queryset(request)
        if request.GET.get('pop'):
            return qs.order_by(...)
        return qs

rawDescription: Displaying "info" by selecting foreign key in django admin


code:
import operator
ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div}

rawDescription: python random arithmetic game

description: Python random arithmetic game


code: df['Diff'] = df['End_Time'] - df['Start_Time']

rawDescription: How to convert the time from 00:00 to 24:00 in python

description: Convert the time from 00:00 to 24:00 in python


rawDescription: Creating a matrix of joint number of hits from two columns using numpy/pandas


code:
import locale
_locale_radix = locale.localeconv()['decimal_point']

def read_float_with_comma(num):
    if _locale_radix != '.':
        num = num.replace(_locale_radix, ".")
    return float(num)

rawDescription: Convert Python strings into floats explicitly using the comma or the point as separators


rawDescription: Django-models: use field from foreign key


code:
# will only work if studetName is a string
# if it's an int for a really weird reason it will throw a TypeError

print("Thanks " + studentName + " for participating in the quiz." )

rawDescription: Text after variable print command

description: Text after variable print command


code:
foo = [1,2,3]
bar = foo[:]
bar.append(4)
foo
bar

rawDescription: Why does Python modify the list which is out of the loop?


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# display result
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(F, T, Z,
    rstride=1, cstride=1, cmap=cm.RdPu, antialiased=True, linewidth=0.2)
ax.view_init(elev=35, azim=160)
ax.dist = 10
plt.show()

rawDescription: how test all the possible outcomes of a formula in Python?

description: How test all the possible outcomes of a formula in Python


code:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rawDescription: Django Rest get file from FileField url

description: Django Rest get file from FileField url


code:
import math

class Shape:
    """Shape class: has methods move(), location(), and __init__()."""
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def move(self, deltaX, deltaY):
        self.x = self.x + deltaX
        self.y = self.y + deltaY
    def location(self):
        return "Circle at coordinates (%d, %d)" % (self.x, self.y)

class Circle(Shape):
    """Circle is a sub-class of shape and inherits the move() and location() methods."""
    pi = 3.14159
    def __init__(self, x=0, y=0, r=1):
        Shape.__init__(self, x, y)
        self.radius = r
    def area(self):
        return self.radius * self.radius * self.pi
    def __str__(self):
        return "Circle of radius %s at coordinates (%d, %d)" % (self.radius, self.x, self.y)

    # Class methods
    @classmethod
    def is_collision(Circle, c1, c2):
        '''Return True or False'''
        return c1.radius + c2.radius >= Circle.distance(c1, c2)
    @classmethod
    def distance(Circle, c1, c2):
        """calculate distance between two circles"""
        return math.sqrt(((c1.x-c2.x)**2)+((c1.y-c2.y)**2))

rawDescription: Python Circle Shape Collison Class

description: Python Circle Shape Collison Class


rawDescription: List of list increment if exists otherwise extend


rawDescription: __repr__ for an attribute that can be a string or None?


code:
"""
Problem:
    Generate a string of N characters that only contains alphanumerical
    characters. The following restrictions apply:
        * 0-9 must come before a-z, which must come before A-Z
        * it's valid to not have any digits or letters in a sequence
        * no neighbouring characters can be the same
        * the sequences must be in an order as if the string is base62, e.g.,
          01010...01019, 0101a...0101z, 0101A...0101Z, 01020...etc

Solution:
    Implement a recursive approach which discards invalid trees. For example,
    for "---" start with "0--" and recurse. Try "00-", but discard it for
    "01-". The first and last sequences would then be "010" and "ZYZ".

    If the previous character in the sequence is a lowercase letter, such as
    in "02f-", shrink the pool of available characters to a-zA-Z. Similarly,
    for "9gB-", we should only be working with A-Z.

    The input also allows to define a specific sequence to start from. For
    example, for "abGH", each character will have access to a limited set of
    its pool. In this case, the last letter can iterate from H to Z, at which
    point it'll be free to iterate its whole character pool next time around.

    When specifying a starting sequence, if it doesn't have enough characters
    compared to `length`, it will be padded to the right with characters free
    to explore their character pool. For example, for length 4, the starting
    sequence "29" will be transformed to "29  ", where we will deal with two
    restricted characters temporarily.

    For long lengths the function internally calls a routine which relies on
    fewer recursions and cached results. Length 4 has been chosen as optimal
    in terms of precomputing time and memory demands. Briefly, the sequence is
    broken into a remainder and chunks of 4. For each preceeding valid
    subsequence, all valid following subsequences are fetched. For example, a
    sequence of six would be split into "--|----" and for "fB|----" all
    subsequences of 4 starting A, C, D, etc would be produced.

Examples:
    >>> for i, x in enumerate(generate_sequences(7)):
    ...    print i, x
    0, 0101010
    1, 0101012
    etc

    >>> for i, x in enumerate(generate_sequences(7, '012abcAB')):
    ...    print i, x
    0, 012abcAB
    1, 012abcAC
    etc

    >>> for i, x in enumerate(generate_sequences(7, 'aB')):
    ...    print i, x
    0, aBABABA
    1, aBABABC
    etc
"""

import string

ALLOWED_CHARS = (string.digits + string.ascii_letters,
                 string.ascii_letters,
                 string.ascii_uppercase,
                 )
CACHE_LEN = 4

def _generate_sequences(length, sequence, previous=''):
    char_set = ALLOWED_CHARS[previous.isalpha() * (2 - previous.islower())]
    if sequence[-length] != ' ':
        char_set = char_set[char_set.find(sequence[-length]):]
        sequence[-length] = ' '
    char_set = char_set.replace(previous, '')

    if length == 1:
        for char in char_set:
            yield char
    else:
        for char in char_set:
            for seq in _generate_sequences(length-1, sequence, char):
                yield char + seq

def _generate_sequences_cache(length, sequence, cache, previous=''):
    sublength = length if length == CACHE_LEN else min(CACHE_LEN, length-CACHE_LEN)
    subseq = cache[sublength != CACHE_LEN]
    char_set = ALLOWED_CHARS[previous.isalpha() * (2 - previous.islower())]
    if sequence[-length] != ' ':
        char_set = char_set[char_set.find(sequence[-length]):]
        index = len(sequence) - length
        subseq0 = ''.join(sequence[index:index+sublength]).strip()
        sequence[index:index+sublength] = [' '] * sublength
        if len(subseq0) > 1:
            subseq[char_set[0]] = tuple(
                    s for s in subseq[char_set[0]] if s.startswith(subseq0))
    char_set = char_set.replace(previous, '')

    if length == CACHE_LEN:
        for char in char_set:
            for seq in subseq[char]:
                yield seq
    else:
        for char in char_set:
            for seq1 in subseq[char]:
                for seq2 in _generate_sequences_cache(
                                length-sublength, sequence, cache, seq1[-1]):
                    yield seq1 + seq2

def precompute(length):
    char_set = ALLOWED_CHARS[0]
    if length > 1:
        sequence = [' '] * length
        result = {}
        for char in char_set:
            result[char] = tuple(char + seq for seq in  _generate_sequences(
                                                     length-1, sequence, char))
    else:
        result = {char: tuple(char) for char in ALLOWED_CHARS[0]}
    return result

def generate_sequences(length, sequence=''):
    # -------------------------------------------------------------------------
    # Error checking: consistency of the value/type of the arguments
    if not isinstance(length, int):
        msg = 'The sequence length must be an integer: {}'
        raise TypeError(msg.format(type(length)))
    if length < 0:
        msg = 'The sequence length must be greater or equal than 0: {}'
        raise ValueError(msg.format(length))
    if not isinstance(sequence, str):
        msg = 'The sequence must be a string: {}'
        raise TypeError(msg.format(type(sequence)))
    if len(sequence) > length:
        msg = 'The sequence has length greater than {}'
        raise ValueError(msg.format(length))
    # -------------------------------------------------------------------------
    if not length:
        yield ''
    else:
        # ---------------------------------------------------------------------
        # Error checking: the starting sequence, if provided, must be valid
        if any(s not in ALLOWED_CHARS[0]+' ' for s in sequence):
            msg = 'The sequence contains invalid characters: {}'
            raise ValueError(msg.format(sequence))
        if sequence.strip() != sequence.replace(' ', ''):
            msg = 'Uninitiated characters in the middle of the sequence: {}'
            raise ValueError(msg.format(sequence.strip()))
        sequence = sequence.strip()
        if any(a == b for a, b in zip(sequence[:-1], sequence[1:])):
            msg = 'No neighbours must be the same character: {}'
            raise ValueError(msg.format(sequence))
        char_type = [s.isalpha() * (2 - s.islower()) for s in sequence]
        if char_type != sorted(char_type):
            msg = '0-9 must come before a-z, which must come before A-Z: {}'
            raise ValueError(msg.format(sequence))
        # ---------------------------------------------------------------------
        sequence = list(sequence.ljust(length))
        if length <= CACHE_LEN:
            for s in _generate_sequences(length, sequence):
                yield s
        else:
            remainder = length % CACHE_LEN
            if not remainder:
                cache = tuple((precompute(CACHE_LEN),))
            else:
                cache = tuple((precompute(CACHE_LEN), precompute(remainder)))
            for s in _generate_sequences_cache(length, sequence, cache):
                yield s

rawDescription: How to generate this custom alpha-numeric sequence?

description: Generate this custom alpha-numeric sequence


code:
import os
os.getcwd()

rawDescription: What's the working directory when using IDLE?


code:
import sys
import time
import win32api

forever = True
handled_ctrl_type = None

def handler(ctrl_type):
    global forever, handled_ctrl_type
    forever = False
    handled_ctrl_type = ctrl_type
    print("HANDLER")
    return True

def main(args = None):
    win32api.SetConsoleCtrlHandler(handler, True)
    n = 0
    while forever:
        time.sleep(1)
        print(n)
        n = n + 1
    print("exiting...", handled_ctrl_type)
    return 0

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

rawDescription: How do I change what the X button does on the Windows console window?

description: Change what the X button does on the Windows console window


code: neworig, newtarget = path.vertices

rawDescription: How to get the exact shrink value when customizing arrow styles in annotate

description: Get the exact shrink value when customizing arrow styles in annotate


code: values = ','.join(item['value'] for item in lst)

rawDescription: Python: comma-delimited list from a list of sets


code:
with open("input") as f:
    print(''.join(replace_line(f, 'some pattern\n', ['foo\n', 'bar\n'])))

rawDescription: How can I keep the indentation between lines?

description: Keep the indentation between lines


code:
hex_string = '0e0010000001020c93b2'
decimal_int = int(hex_string, 16)
decimal_int
decimal_string = str(decimal_int)
decimal_string
digits = [int(c) for c in decimal_string]
digits
zero_padded_BCD_digits = [format(d, '04b') for d in digits]
zero_padded_BCD_digits
''.join(zero_padded_BCD_digits)

rawDescription: Convert hex to BCD in python

description: Convert hex to BCD in python


rawDescription: Is there a way to find out if A is a submatrix of B?


code:
def a():
    print("Hello!")

def b(fun):
    print("running fun")
    fun()
    print("all done")

b(a) # prints "running fun", then "Hello!", then "all done".

rawDescription: function as constructor parameter in python

description: Function as constructor parameter in python


rawDescription: Different Column values not displayed in PYGTK TreeView


code:
import ast
ast.literal_eval(myString)

rawDescription: How do I convert this string to an array with all the proper formatting?

description: Convert this string to an array with all the proper formatting


code: nhat = get_coords() # leave coords in tuple

rawDescription: create python list of exactly three elements

description: Create python list of exactly three elements


rawDescription: Partitioning a file for parallel download


code:
import functools
try:
    import builtins
except ImportError:
    import __builtin__ as builtins
import mako.filters

def lookup_escape(name):
    path_parts = mako.filters.DEFAULT_ESCAPES[name].split('.')
    for module in (mako, builtins):
        try:
            return functools.reduce(getattr, path_parts, module)
        except AttributeError:
            pass
    raise LookupError(name)

rawDescription: Lookup escape filter method

description: Lookup escape filter method


code:
points = tDict['Example']['points']
p1 = points[0]
p2 = points[1]

rawDescription: Splitting one dictionary item into 2 variables


code:
from django import forms
from myapp.models import FooModel

class FooForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        self.fields['field1'].widget.attrs = { 'class': 'fooclass' }

    class Meta:
        model = FooModel
        fields = ['field1', 'field2']

rawDescription: Specifying a css class for a field of a generic form


code:
def SQLQueryDaily(currency,start,end):
    sql = '''
        SELECT buy, AVG(sell)
        FROM {t}
        WHERE (datetime > ? AND datetime < ?)
        GROUP BY strftime('%Y-%m-%d %H',date)
        '''.format(t = currency)
    c.execute(sql, [start, end])
    for row in c:
        print (row)

rawDescription: Regroup time list in python from sql query


code:
with open('this.txt') as f:
    text = f.read()
matches = re.findall('', text) # do some re matching here
with open('that.txt', 'w') as g:
    g.write("\n".join(i[0] for i in matches))

rawDescription: Writing items to file on separate lines without blank line at the end


code: new_class = type("NewClassName", (BaseClass), {"new_method": lambda self: ...})

rawDescription: How can I dynamically create derived classes from a base class

description: Dynamically create derived classes from a base class


code:
def max_alt_sum(n,d):
  number = list(map(int,str(n)))
  negatedEven = []
  negatedOdd = []
  for i,v in enumerate(number):
    if i%2==0:
      negatedOdd.append(v)
      negatedEven.append(-v)
    else:
      negatedOdd.append(-v)
      negatedEven.append(v)
  maximum = sum(negatedEven[:d])
  for i in range(0, len(str(n))-d+1):
    if i%2==0:
      current = sum(negatedOdd[i:i+d])
    else:
      current = sum(negatedEven[i:i+d])
    if current > maximum:
      maximum = current
  return maximum

rawDescription: Finding maximum alternating sum of digits (python 3)


code:
for key, cycle in cycles.items():
    cycles['rows'].sort(key=itemgetter('test_time'))

rawDescription: Need help to sort processed mdb file in Python on Linux machine


code:
for (i, j, k), v in np.ndenumerate(b):
    assert v == a[ind[i, j, k], j, k]

rawDescription: Numpy fancy indexing suggestion needed

description: Numpy fancy indexing suggestion needed


rawDescription: Pandas Split DataFrame

description: Pandas Split DataFrame


code:
def add_abilities(abilities_m_l):
    jobs_dict = OrderedDict()
    for data_dict in abilities_m_l:
        o_code = data_dict['O*NET-SOC Code']
        activity = data_dict['Element Name']
        activities_so_far = jobs_dict.setdefault(o_code, set)
        activities_so_far.add(activity)
    return [{o_code: list(activities)} for o_code, activities in jobs_dict.iteritems()]

rawDescription: Not appending to list

description: Not appending to list


code:
data = urllib2.urlopen(apacheLog)
with open('C:\LogCopy.txt','a') as f: # probably need a double backslash
    for line in data.splitlines():
        f.write(line) # might need a newline character
        # f.write(line + '\n')

rawDescription: Parse Apache log with Python 2.7

description: Parse Apache log with Python 2.7


code: d.groupby(['Month', 'Item']).size().unstack().loc[['January', 'February', 'March', 'July']].fillna(0).plot(kind='line')

rawDescription: Python3 MatPlotLib : How can I get Multiple Line Plots


rawDescription: Python: command line argument not passing the same way as hard coded lines


code:
seen = set()
repeated = set()
for l in list_of_lists:
  for i in set(l):
    if i in seen:
      repeated.add(i)
    else:
      seen.add(i)

rawDescription: Python: Find identical items in multiple lists


rawDescription: Trying to create a stacked bar chart of the top 10 issues per month


code: diffs = [0] + [j - data[i] for i,j in enumerate(data[1:])]

rawDescription: Difference of consecutive float numbers in a column


code:
import example
example.f1()
example.f2(3.14)

rawDescription: Template argument inference by constructor arguments


code:
from collections import OrderedDict
from itertools import product

d = OrderedDict()
for k, v in records:
    d.setdefault(k, []).append(v)

d
['_'.join(k+v for k,v in zip(d, v)) for v in product(*d.values())]

rawDescription: Efficient way to create strings from a list


code:
import re
import random

animals = ['bird','monkey','dog','fox']

def callback(matchobj):
    return random.choice(animals)

teststr = 'test test test test'
ret = re.sub(r'test', callback, teststr)
print(ret)

rawDescription: Python string replacement with random items


code:
minloc = dist.argmin(0)
other[dist.argmin(0), np.arange(dist.shape[1])[:, None], np.arange(dist.shape[2])]

rawDescription: Finding minimum value element-wise in three 2d submatrices


code: [i.text.replace('\n', ' ').strip() for i in soup.find_all('p')]

rawDescription: Python: parsing only text from HTML using bs4 and RegEx


code:
import csv
import io
next(csv.reader(io.StringIO(u"'a','b'"), quotechar="'"))

rawDescription: Coverting a string to an array in python


rawDescription: find peaks location in a spectrum numpy

description: Find peaks location in a spectrum numpy


code:
def compare(word):
    res = 0
    for letter in word:
        if letter in score:
            res += score[letter]
    return res

rawDescription: python - how to compare a key of the dictionary with a string character

description: Python - how to compare a key of the dictionary with a string character


code:
'http://{username}:{password}@{server}:{port}'.format(
    username=username,
    password=password,
    server=server,
    port=port
)

rawDescription: Python 3 Print Variables

description: Python 3 Print Variables


rawDescription: Erase whole array Python

description: Erase whole array Python


code:
if lec_id in lecturers:
    thelec = lecturers[lec_id]
else:
    thelec = lecturers[lec_id] = Lecturer(lec_id, lec_name)
thelec.offered_proj.add(proj_id)

rawDescription: How do I create a list or set object in a class in Python?

description: Create a list or set object in a class in Python


code:
target = (target + dm).fillna(0)
target

rawDescription: Pandas Dataframe - How To Convert Date to Boolean Columns?


code: max(len(x) for x in re.findall(r'[%s]+' % ch_, str_))

rawDescription: Number of the same characters in a row - python


code:
lookup = dict(zip(cs.collections, cs.levels))
z = lookup[line_collection_artist]

rawDescription: matplotlib - extracting values from contour lines

description: Matplotlib - extracting values from contour lines


code: totaluniqueimp = db.alpha2.map_reduce(map, reduce, "myresults", query={'ts': {'$gt': 1345840456, '$lt': 2345762454}, 'cid': '2636518'})

rawDescription: map_reduce() *and* find() in same query

description: Map_reduce() *and* find() in same query


rawDescription: Sorting a list of tuples in python according to an element index


code:
# Assuming something like:  /quiz/69/ with "69" being the quiz PK.
def render_quiz(request, quiz_id):
    quiz = get_object_or_404(Quiz, quiz_id)
    form = QuizForm(questions=quiz.question_set.all())
    if request.method == "POST":
        form = QuizForm(request.POST, questions=quiz.question_set.all())
        if form.is_valid(): ## Will only ensure the option exists, not correctness.
            attempt = form.save()
            return redirect(attempt)
    return render_to_response('quiz.html', {"form": form})

rawDescription: DJango How to build a formset for a Quiz?


code:
import pandas as pd
import numpy as np

a = np.random.rand(26*10+3)
r = pd.qcut(a, 10)
np.bincount(r.labels)

rawDescription: Python Pandas qcut behavior with # of observations not divisible by # of bins


rawDescription: Python: from a text file to dictionary with keys


code: ''.join(random.choice(y) for _ in xrange(x))

rawDescription: "for in" with unused variable

description: "for in" with unused variable


code:
SharedExamplePackage1
SharedExamplePackage2
SharedExamplePackage3
SharedExamplePackage4
SharedExamplePackage5

rawDescription: Maintaining different requirements files for virtualenv and pip


code:
import math
mylist = [0 if math.isnan(x) else x for x in mylist]

rawDescription: replace the NaN value zero after an operation with arrays

description: Replace the NaN value zero after an operation with arrays


rawDescription: how can I asynchronously map/filter an asynchronous iterable?

description: Asynchronously map/filter an asynchronous iterable


code:
class NestedDialog(object):
    def __init__(self, dialog):
        self.dialog = dialog
        self.response_var = None

    def run(self):
        self._run()
        return self.response_var

    def _run(self):
        self.dialog.show()
        self.dialog.connect("response", self._response)
        Gtk.main()

    def _response(self, dialog, response):
        self.response_var = response
        self.dialog.destroy()
        Gtk.main_quit()

rawDescription: gtk MessageDialog not closing until enclosing method finishes

description: Gtk MessageDialog not closing until enclosing method finishes


code: parent = elt.getparent()

rawDescription: XML Library Suggestions

description: XML Library Suggestions


code: np.in1d(b, a).nonzero()[0]

rawDescription: Getting the indices of several elements in a NumPy array at once


rawDescription: cPickle.load() doesnt accept non-.gz files, what can I use for .pkl files?

description: CPickle.load() doesnt accept non-.gz files, what can I use for .pkl files


code: wchild.wolf = not wchild.wolf

rawDescription: Python: Parent and Child responding to child-specific changes in boolean values. Why is this happening?


code: sorted(listofLines, key=extract_time)

rawDescription: Sort list by given order of indices -Python


code:
all_commands = ['search', 'quit', 'quaff']

def find_command(string, allowed_commands=None):
    if allowed_commands is None:
        # if there is no restrictions, look for all commands
        allowed_commands = all_commands

    matching_commands = []

    for command in commands:
        if command.startswith(string):
            matching_commands.append(command)

    if len(matching_commands) == 1:
        # found a match
        return matching_commands[0]

    # found either no match or more than one
    return None

rawDescription: Example of a Sufficient MUD-Style and working Text Parser for Python


rawDescription: Efficient way to create list of same numbers?


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

dpi = 80 # Arbitrary. The number of pixels in the image will always be identical
data = np.random.random((10, 10))

height, width = np.array(data.shape, dtype=float) / dpi

fig = plt.figure(figsize=(width, height), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.imshow(data, interpolation='none')
fig.savefig('test.tif', dpi=dpi)

rawDescription: Save raw data as tif

description: Save raw data as tif


rawDescription: regex to parse tables wrapped into xml

description: Regex to parse tables wrapped into xml


code: angle = np.tan(pi * 0.25)

rawDescription: Angle between intersecting planes drawn with matplotlib


code:
from scipy.stats import expon
loc, scale = expon.fit(x, floc=0)
scale

rawDescription: Generating random numbers given required distribution and empirical sampling


code:
output = {}
with open('input') as fin:
    for line in fin:
        length = len(line.split())
        output.setdefault(length, TemporaryFile()).write(line)

rawDescription: Sorting csv by number of columns in each row


rawDescription: Mock CSV DictReader

description: Mock CSV DictReader


rawDescription: How can I convert a SHA256 hash from integer to string and back?

description: Convert a SHA256 hash from integer to string and back


code:
m = 20
index = np.random.randint(a, size=m)

rawDescription: Translating Matlab (Octave) group coloring code into python (numpy, pyplot)


code:
def splitName(fileName):
    return re.split("[ ._-]+", fileName)

rawDescription: My first Python program! Anyone care to review it an help me improve?


rawDescription: Python webcrawling BeautifulSoup: getting both text and links


code:
from collections import Counter
with open('invoice_dates') as f:
    invoice_count = Counter(line.strip() for line in f)

rawDescription: After counting occurrences, how to make entries for each day in list


code: data: 4

rawDescription: Correct usage of multithreading and Queue module in data collection application written in Python


code:
from itertools import cycle
mySmallSquareIterator = cycle(i*i for i in range(10))
# Will yield 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, ...

rawDescription: Python: How to toggle between two values


code:
def getinput():
    return input("What do you want to do? ").lower()

x = getinput()
print(x)

rawDescription: Python - function setting external variable to user input as side effect


code:
def newErrInfo(self):
  newString = str(self.runner.readAllStandardError())
  print(newString, end=" ")

rawDescription: How do I get the output of a command run by QProcess in PySide?

description: Get the output of a command run by QProcess in PySide


code:
# main.py
import foo_level
while True:
    key = raw_input()
    if key == "foo":
        foo_level.do_stuff()
    # and so on.

rawDescription: Import same python module more than once


code:
from PySide.QtCore import *
from PySide.QtGui import *
from PySide import QtCore
import sys

class WorkThread(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)

    def run(self):
        print("From thread")
        self.emit(QtCore.SIGNAL("trying()"))

class Foo(QObject):
    def handle_trigger(self):
        print ("trigger signal received")
        self.get_thread.quit()
        self.get_thread.wait()
        QApplication.quit()

    def new_thread(self):
        self.get_thread = WorkThread()
        self.connect(self.get_thread, QtCore.SIGNAL("trying()"), self.handle_trigger)
        self.get_thread.start()

a = Foo()
a.new_thread()

app = QApplication(sys.argv)
app.exec_()

rawDescription: Custom signals and multithreading

description: Custom signals and multithreading


code:
from itertools import groupby

def indexed_date_groups(it):
    for key, group in groupby(enumerate(it), lambda v: v[1] is not None):
        if key:
           indices, elems = zip(*group)
           yield indices[0], elems

rawDescription: Split list on None and record index

description: Split list on None and record index


code: filter(lambda x: x not in secnd_list, first_list) + filter(lambda x: x not in first_list, secnd_list)

rawDescription: How to compare a list of lists/sets in python?

description: Compare a list of lists/sets in python


rawDescription: Most efficient way to find mode in numpy array


code:
wordlist = [':)', ':(', 'happy', 'sad']
tweets = ['I find python cool, it makes me happy :)', 'today is a sad day :(']
for tweet in tweets:
    print(' '.join(['1' if word in tweet else '0' for word in wordlist]))

rawDescription: Changing lines of text into binary type pattern


code:
u = uf_node('a')
u

rawDescription: python class output at the interpreter

description: Python class output at the interpreter


code:
class MyForm(forms.Form):
    my_choices = forms.ModelMultipleChoiceField(
                      queryset=SomeModel.objects.all(),
                      widget=forms.CheckboxSelectMultiple)

rawDescription: Construct form from queryset

description: Construct form from queryset


code:
df = pd.concat([df, dates.apply(lambda x: pd.Series(json.loads(x)))], axis=1, ignore_index=True)
df
df.dtypes

rawDescription: Python pandas.read_csv split column into multiple new columns using comma to separate


code:
import string

def clean_string(input_string):
    result = ""
    for char in input_string:
        if char in string.letters: # string.letters contains a...zA...Z
            result += char
    return result

rawDescription: String with non-letters

description: String with non-letters


code:
childbr = lxml.etree.SubElement(root, "br")
childbr
lxml.etree.tostring(root)

rawDescription: Replace text with HTML tag in LXML text element


code:
@view_incrememter
@cache_page(timeout=60)
def show_board(request, pk):
    ...

rawDescription: Counting "page views" or "hits" when using cache


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

    def _get_state():
        return self.cast().get_state()

    state = property(_get_state)

rawDescription: "Annotating" querysets with model function returns


code:
with open('yourfile') as f:
    lst = [ map(int,x.replace('.','0')) for x in f ]

rawDescription: Building a List from a text file in python


rawDescription: Selenium and Python 3 – unable to find element


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


rawDescription: return value from listWidget in pyqt4

description: Return value from listWidget in pyqt4


code:
import requests
url = 'http://www.transfermarkt.com/'
requests.get(url).raise_for_status()

rawDescription: Python requests package returning different HTTP status than browser


code:
from urlparse import urlparse, parse_qs
s = "https://xx.com/question/index?qid=2ss2830AA38Wng"
parse_qs(urlparse(s).query)['qid'][0]

rawDescription: Parsing query string using regular expression in python


code:
test_cols = data[['a1', 'a4']]
test_vals = np.array(('a1v1', 'a4v1'), test_cols.dtype)
data[test_cols == test_vals]

rawDescription: Create a new array from numpy array based on the conditions from a list


code:
d = dict()
d.update(re.findall(r'([a-zA-Z]+)(\d+)',"english100"))

rawDescription: how to split numbers and characters in python

description: Split numbers and characters in python


code: fig.savefig('Pics2/forcing' + str(forcing) + 'damping' + str(damping) + 'omega' + str(omega) + 'set2.png')

rawDescription: Python: how do I save a file in a different directory?


code: list(combinations('ABCD', 2))

rawDescription: How to get all combinations of list groupings of at least a certain size?

description: Get all combinations of list groupings of at least a certain size


rawDescription: replace some part of a word with regex

description: Replace some part of a word with regex


code:
maxlen = np.max(pairs,axis=(0,1))
dims = np.append(maxlen[::-1][:-1].cumprod()[::-1],1)

pairs1D = np.dot(pairs.reshape(-1,3),dims)
positions1D = np.dot(positions,dims)
mask_idx = ~(np.in1d(pairs1D,positions1D).reshape(-1,2).all(1))
out = pairs[mask_idx]

rawDescription: Efficient Python implementation of numpy array comparisons


code:
import re

test_lines = """
~   VERSION   11 11 11.1  222 22 22.222
$   VERSION 11 11 11.1      222 22 22.222
@      VERSION    11 11 11.1          222 22 22.222
"""

version_pattern = re.compile(r"""
[~!@#$%^&*()]               # Starting symbol
\s+                         # Some amount of whitespace
VERSION                     # the specific word "VERSION"
\s+                         # Some amount of whitespace
(\d+\s+\d+\s+\d+\.\d+)      # First capture group
\s+                         # Some amount of whitespace
(\d+\s+\d+\s+\d+\.\d+)      # Second capture group
""", re.VERBOSE)

lines = test_lines.split('\n')

for line in lines:
    m = re.match(version_pattern, line)
    if (m):
        print (line)
        print (m.groups())

rawDescription: How to match this regular expression in python?

description: Match this regular expression in python


code: e, f, g = map(list, zip(*x))

rawDescription: How to arrange three lists in such a way that the sum of corresponding elements if greater then appear first?

description: Arrange three lists in such a way that the sum of corresponding elements if greater then appear first


code:
[list(permutations(grp.index)) for (name, grp) in age]
list(product(*[(permutations(grp.index)) for (name, grp) in age]))

rawDescription: Quick way to find all permutations of a pandas DataFrame that preserves a sort?


code:
for i in xrange(20, len(arr)):
    arr[i] = 0

rawDescription: In python how can I set multiple values of a list to zero simultaneously?


rawDescription: django haystack module search with whoosh

description: Django haystack module search with whoosh


code:
class User(models.Model):
   first_name = models.CharField(max_length=255)

   def get_username(self):
       return self.username

   class Meta:
       abstract = True

class Employee(User):
   title = models.CharField(max_length=255)

rawDescription: django abstract models versus regular inheritance

description: Django abstract models versus regular inheritance


code: u'doesn\u2019t' in mystr

rawDescription: python convert unicode into it's "print" form

description: Python convert unicode into it's "print" form


code:
def cartesian_exponent(li, e=1):
    pools = [li] * e
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    return result

rawDescription: how to permute n elements from list recursively in python?

description: Permute n elements from list recursively in python


code: itertools.product(list1, list2, list3)

rawDescription: how do I concatenate 3 lists using a list comprehension?

description: Concatenate 3 lists using a list comprehension


rawDescription: What is the simplest way to remove phase angle discontinuities


code:
sum([int(i) for i in str(123)])
sum([int(i) for i in str(2048)])

rawDescription: Sum of digits of a number using While

description: Sum of digits of a number using While


code:
d = np.random.random((16,3,90,144))
e = np.random.random((16,3))
f = e[:,:,None,None]
scl = f.sum(axis = 1)
avg = np.multiply(d,f).sum(axis = 1)/scl

rawDescription: Numpy weighted average of 4D array with 2D array of weights without list comprehension


rawDescription: Append a 1d array to a 2d array in Numpy Python


code:
import inspect
import sys

def _force_locals(old_frame, new_locals):
    ''' Force a new set of locals on a given frame.

    :param old_frame: The frame to which locals will be applied.
    :type old_frame: frame.
    :param new_locals: What locals() should return for old_frame.
    :type new_locals: dict.

    .. note:: This function will force a custom trace function onto
              the old_frame.  Within the context of a trace function
              (often used for debugging), a frame's f_locals is
              modifiable.  In most execution paths, f_locals is
              writable but not modifiable.

    '''
    # Force tracing by setting the global tracing function to
    # any non-None function.
    if not sys.gettrace():
        sys.settrace(lambda *args, **keys: None)

    # Custom trace function that will force locals.
    def trace(frame, event, arg):
        # Update the frame's locals.
        frame.f_locals.update(new_locals)
        # Set frame to use default trace, preventing this trace
        # function from resetting the locals on each trace call.
        del frame.f_trace

    # Set the old frame's trace function to the custom trace.
    old_frame.f_trace = trace

def update_locals(frame, *refs):
    ''' Modifies a frame's locals based on the provided references.

    :param frame: The frame from which a locals will be updated.
    :type frame: frame.
    :param refs: Iterable pair of (old_ref, new_ref) tuples.
    :type refs: Iterable type of pairs.

    '''
    new_locals = frame.f_locals.copy()
    has_changes = False

    # If a frame's local has an identity patch with a provided
    # reference, then update new_locals with the new reference.
    for key, ref in new_locals.iteritems():
        for old_ref, new_ref in refs:
            if ref is old_ref:
                new_locals[key] = new_ref
                has_changes = True

    # If new_locals has changes, then force them onto the frame.
    if has_changes:
        _force_locals(frame, new_locals)

rawDescription: Boost.python automatically convert parameter


code: list.sort(Action._registry, key=lambda item: item.__dict__['date'].get())

rawDescription: Python3 & Tkinter, list.sort list of objects made of StringVar


code:
def returnJSONQuestion(id):

    if minuteMod(3): # current minute is a factor of 3
        return jsonFromCache # open a file and output cached contents
    else:
        url = 'http://...'
        storeJSONToFile(url)
        return json

rawDescription: Python: Check the url request per hour

description: Python: Check the url request per hour


code:
print(df.groupby([d.strftime('%Y-%m') for d in df['Idx']]).sum())
#          A  B  C
# 2004-04  2  2  0
# 2004-05  0  0  0

# [2 rows x 3 columns]

rawDescription: Pandas Python: Merging every two rows in one dataframe


code:
with open('data.json', 'r') as f:
  data = json.load(f)
type(data)

rawDescription: What is recommended way to store dictionaries and json file type in python


code: question = [a, b, c]

rawDescription: Python 3.5 Bracket and Speech Mark Removal from Lists


code: array = list(cursor)

rawDescription: Improve loop efficiency

description: Improve loop efficiency


code:
txt='''\
commit 34343asdfasdf343434asdfasdfas
Author: John Doe <john@doe.com>
Date:   Wed Jun 25 09:51:49 2014 +0800'''
json.dumps({k:v for k,v in re.findall(r'^([^\s]+)\s+(.+?)$', txt, re.M)})

rawDescription: how to convert a string into json in python?

description: Convert a string into json in python


code:
start = array[0].searchsorted(lower_x_limit, 'right')
end = array[0].searchsorted(upper_x_limit, 'left')
temp = array[1, start:end]
start = temp.searchsorted(lower_y_limit, 'right')
end = temp.searchsorted(upper_y_limit, 'left')
count = end - start

rawDescription: Numpy: Comparison within Multidimensional array values


code:
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
weekdays[0]
weekdays[5]

rawDescription: In Python i need a day_name function

description: In Python i need a day_name function


code:
re.search(r'fund.{1,7}assets', 'fund assets')
re.search(r'fund.{1,7}assets', 'fund total assets')
re.search(r'fund.{1,7}assets', 'fund seeks to achieve its investment objective by investing at least 80% of its total assets')

rawDescription: How to limit certain char appearing in regex

description: Limit certain char appearing in regex


code:
count = 0
dfs = []
for my_str in strings:
    str_split = my_str.split()
    data = dict(zip(cols,str_split))
    panda_frame = pandas.DataFrame(data,index=[count],columns = cols)
    dfs.append(panda_frame)
    count += 1
df = pandas.concat(dfs)

rawDescription: Append String Split to Pandas DataFrame

description: Append String Split to Pandas DataFrame


rawDescription: Selecting columns from pandas.HDFStore table


code:
def rgba1(s, unpack=struct.unpack):
    return unpack("BBBB", s.decode("hex"))

def rgba2(s, int=int, xrange=xrange):
    return [int(s[i:i+2], 16) for i in xrange(0, 8, 2)]

def rgba3(s, int=int, xrange=xrange):
    x = int(s, 16)
    return [(x >> i) & 255 for i in xrange(0, 32, 8)]

rawDescription: Split a string "aabbcc" -> ["aa", "bb", "cc"] without re.split


code:
def add(x, y):
    return x + y

def multiply(a, b):
    product = 0
    for i in range(a):
        # I call add with parameters, and use the return value
        product = add(product, b)
    return product

rawDescription: Passing a variable between functions

description: Passing a variable between functions


code:
def get_object_list(self, request):
    return super(UserResource, self).get_object_list(request).filter(username=request.user)

rawDescription: limiting data using tasty pie authorization

description: Limiting data using tasty pie authorization


code:
img.putdata(pix)
photo.paste(img)

rawDescription: How do I save an image in python 3 using PIL?

description: Save an image in python 3 using PIL


code:
from datetime import datetime, timedelta, time

today = datetime.now().date()
tomorrow = today + timedelta(1)
today_start = datetime.combine(today, time())
today_end = datetime.combine(tomorrow, time())

rawDescription: Django filter events occurring today

description: Django filter events occurring today


code:
np.savetxt('x.txt', x.ravel())
np.savetxt('gz.txt', gz.ravel())

rawDescription: Assistance with numpy savetext function

description: Assistance with numpy savetext function


code: OK

rawDescription: python print one line same space

description: Python print one line same space


code:
a = [1, 2, 3]
b = [4, 5, 6]
result = [x - y for x in a for y in b]

rawDescription: Pythonic way to write a loop

description: Pythonic way to write a loop


code:
x=[]
for i in range(50,151): x.append(i/100)

rawDescription: iPython: Create variables that depend on the loop index

description: IPython: Create variables that depend on the loop index


rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


rawDescription: How to create a list while avoiding duplicate?

description: Create a list while avoiding duplicate


code: [line[:-(line[-1] == '\n') or len(line)+1] for line in file]

rawDescription: Reading a file without newlines

description: Reading a file without newlines


code: ord(c) > 0x1f and ord(c) != 0x7f and not (0x80 <= ord(c) <= 0x9f)

rawDescription: How to detect undecoded characters in python?

description: Detect undecoded characters in python


code: list(map(lambda x: [x[0]] + list(map(lambda y: y[1]*y[2], x[1:])), orders))

rawDescription: How can I rewrite this map() example using list comprehension?

description: Rewrite this map() example using list comprehension


rawDescription: get escaped unicode code from string

description: Get escaped unicode code from string


code:
def f(x, *args):
    if x not in f.all_intermediates:
        f.all_intermediates[x] = computationally_expensive_fct(x)
    intermediate = f.all_intermediates[x]
    return do_stuff(intermediate,*args)
f.all_intermediates = {}

rawDescription: Alternative for non existing global dictionary


code:
amount = int(input("How many dollars? "))

print("Bill list:")
for denom in [500, 200, 100, 50, 20, 10]:
    num_bills = amount // denom     # integer division
    amount %= denom                 # get remainder
    if num_bills:
        print("{} USD x {}".format(denom, num_bills))

if amount:
    print("Remainder: {} dollars".format(amount))

rawDescription: All cash change is only for one bill

description: All cash change is only for one bill


code:
names = ["Utku", "Onur"]
c.setName(*names)

rawDescription: Best way to apply function to element or to list of elements in python

description: Apply function to element or to list of elements in python


code:
def make_mask(s):
    if np.unique(s).size == 2: # If binary, return all-false mask
        return np.zeros_like(s, dtype=bool)
    else: # Otherwise, identify outliers
        return s >= np.percentile(s, 99)

rawDescription: Pandas DataFrame apply function doubling size of DataFrame


code:
iterable = ['aaa','bbb','ccc','ddd']
zip(*iterable) == ['abcd','abcd','abcd'] # kind of...

rawDescription: Converting string to float

description: Converting string to float


code:
result.set_index( 'Name', inplace=True)
#     Value2       Value
#Name
#A         x  [8.8, 6.6]
#B         y       [6.6]

rawDescription: Pandas DataFrame - Combining one column's values with same index into list


code:
if keyword.lower() == 'last5':
    cursor.execute('SELECT income_Ref, income_Amount FROM model_income WHERE company_MobileNumber = %s ORDER BY income_Datetime DESC LIMIT 5', [sender])
    result = cursor.fetchall()
    result = [list(row) for row in result]
    self.respond("\n".join("Ref:{} Amount:{}".format(ref, amt) for ref, amt in result))
    return ()

rawDescription: Python: Formatting lists of lists

description: Python: Formatting lists of lists


rawDescription: Slice subarray from numpy array by list of indices


code:
img = LoadImage("images/test1.jpg").load()
img.shape()

rawDescription: Python class return

description: Python class return


code:
def clean_table(self,tableName):
    cleanTableQuery = """TRUNCATE TABLE %s;""" % (tableName,)
    self.cursorMySQL.execute(cleanTableQuery)

    setIndexQuery = """ALTER TABLE %s AUTO_INCREMENT = 1;""" % (tableName,)
    self.cursorMySQL.execute(setIndexQuery)

rawDescription: Python - automating MySQL query: passing parameter


code:
d = {}
for i in xrange(1, MAXNUM+1):
    d[i] = dsums[i]
def memo_s(n):
    if n in d:
        return d[n]
    else:
        t = s(n)
        d[n] = t
        return t

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


rawDescription: What do you call an iterator with two different "done" states?


code:
string.whitespace
string.punctuation

rawDescription: Writing a counting program in python

description: Writing a counting program in python


code: newfoo = foo.resize(100, 100).cutoff(55)

rawDescription: Handling arguments in order for preprocessing in Python, when order matters


code:
mask = im == 0
all_white = mask.sum(axis=2) == 0
rows = np.flatnonzero((~all_white).sum(axis=1))
cols = np.flatnonzero((~all_white).sum(axis=0))

crop = im[rows.min():rows.max()+1, cols.min():cols.max()+1, :]

rawDescription: Remove empty 'rows' and 'columns' from 3D numpy pixel array


code:
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^dogs/(?P<slug>[-\w]+)/$', views.dog_view, name='profile'),
    url(r'^mating/', views.mating_list, name='mating'),
    url(r'^admin/', admin.site.urls),
]

rawDescription: Django – create pages along with the objects using the same template


code:
from requests.utils import cookiejar_from_dict as jar
cookies = jar(sess.cookies)

rawDescription: Python how to preserve HTTP cookies

description: Python how to preserve HTTP cookies


code:
def getConfidenceInterval():
    responseModel = mc.Model([samples_to_average, list_of_samples, sample_average])
    mapRes = mc.MAP(responseModel)
    mapRes.fit()
    mcmc = mc.MCMC(responseModel)
    mcmc.sample( 10000, 5000)
    average = np.vstack((t for t in mcmc.trace('sample_average')))
    upper = np.percentile(average, 95, axis = 0)
    lower = np.percentile(average, 5, axis = 0)
    return (lower, upper)

rawDescription: Passing parameters to deterministic variables, pymc


code:
cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls()

rawDescription: Improve current implementation of a setInterval python


code:
class MapToolEmitPoint(QgsMapToolEmitPoint):
    canvasDoubleClicked = QtCore.pyqtSignal(object, object)

    def canvasDoubleClickEvent(self, event):
        point = self.toMapCoordinates(event.pos())
        self.canvasDoubleClicked.emit(point, event.button())
        super(MapToolEmitPoint, self).canvasDoubleClickEvent(event)

rawDescription: Emit and catch double-click signals from QgsMapCanvas


code:
df
df["Date"] = pd.to_datetime(df["Date"])
df["Order"] = df["Order"].str.split().str[-1]
df_p = df.pivot(index="Date", columns="Client", values="Order")
df_p = df_p.reindex(pd.date_range(df_p.index.min(), df_p.index.max()))

rawDescription: Pivoting a Pandas dataframe with a gapless daterange as index


code:
import re
regexp = r'ATG(?:(?!TAA|TAG|TGA)...){9,}?(?:TAA|TAG|TGA)'
re.findall(regexp, 'ATGAAAAAAAAAAAAAAAAAAAAAAAAAAATAG')
re.findall(regexp, 'ATGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATAG')
re.findall(regexp, 'ATGAAATAGAAAAAAAAAAAAAAAAAAAAATAG')

rawDescription: Why is re.findall not being specific in finding triplet items in string. Python


rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


rawDescription: How to split list of (X,Y) coordinates of path into seperate list of X and Y coordinates?

description: Split list of (X,Y) coordinates of path into seperate list of X and Y coordinates


code:
import pandas as pd

df = pd.DataFrame({'name':users, 'pred':pred})

print(df.groupby('name').mean())
#            pred
# name
# User0  0.450000
# User1  0.550000
# User2  0.550000
# User3  0.435000
# User4  0.816667

rawDescription: Average using grouping value in another vector (numpy / Python)


code:
flagged = df[df.IndepFlag == 1]
flagged
flagged.to_excel("flagged.xlsx")

rawDescription: Pandas if statements

description: Pandas if statements


code:
from win32com.client import Dispatch
from tkinter import *
from tkinter import ttk
import tkinter

class applicazione(object):

    def __init__(self, root):
        self.root = root

        # Top-level frame
        self.root.title('Controllo dati per fatturazione elettronica - Manticle - Smith & Nephew Italia')

        self.frame = ttk.Frame(self.root, width=300, height=250)

        # Canvas creation with double scrollbar
        hscrollbar = ttk.Scrollbar(self.frame, orient = tkinter.HORIZONTAL)
        vscrollbar = ttk.Scrollbar(self.frame, orient = tkinter.VERTICAL)
        sizegrip = ttk.Sizegrip(self.frame)
        self.canvas = tkinter.Canvas(self.frame, bd=0, highlightthickness=0, yscrollcommand = vscrollbar.set, xscrollcommand = hscrollbar.set)
        vscrollbar.config(command = self.canvas.yview)
        hscrollbar.config(command = self.canvas.xview)

        # Add controls here
        self.subframe = ttk.Frame(self.canvas)

        #### Titles
        self.titoli_HFT = ["Dest_Cod_FIS_P_Iva", "Cod_Cli", "Dest_RagSoc1", "Dest_RagSoc2",
                           "Dest_Indirizzo", "Dest_CAP", "Dest_Localita", "Dest_Provincia", "Cli_Cod_Fis_P_Iva",
                            "Cod_Dest", "Cli_RagSoc1", "Cli_RagSoc2", "Cli_Indirizzo", "Cli_CAP",
                           "Cli_Localita", "Cli_Provincia", "Tipo_Doc", "pre_Num_Doc", "Num_Doc",
                            "Data_Doc", "Vs_Rif", "Data_Rif", "Blank", "Blank2", "CPT", "Scad_Pagamento",
                           "Descr", "Num_Ord", "Tot_Imp", "Tot_IVA", "Tot_Doc", "Nazione", "IPA", "Reg_Fiscale"]

        self.inizializza_widgets()

        #Packing everything
        self.subframe.pack(fill = tkinter.BOTH, expand = tkinter.TRUE)
        hscrollbar.pack( fill=tkinter.X, side=tkinter.BOTTOM, expand=tkinter.FALSE)
        vscrollbar.pack( fill=tkinter.Y, side=tkinter.RIGHT, expand=tkinter.FALSE)
        sizegrip.pack(in_= hscrollbar, side = BOTTOM, anchor = "se")
        self.canvas.pack(side = tkinter.LEFT, padx  = 5, pady  = 5, fill = tkinter.BOTH, expand= tkinter.TRUE)
        self.frame.pack( padx   = 5, pady  = 5, expand = True, fill = tkinter.BOTH)

        self.canvas.create_window(0,0, window = self.subframe)
        self.root.update_idletasks() # update geometry
        self.canvas.config(scrollregion = self.canvas.bbox("all"))
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def inizializza_widgets(self):

        self.LabelFrame = ttk.Frame(self.subframe)
        self.lblins = tkinter.Label(self.LabelFrame, text="Controllo dati per fatturazione elettronica", font=("Helvetica", 12))
        self.lblins.pack()

        for i in range (0,len(self.titoli_HFT)):
            j = 80*i
            self.lblnome=tkinter.Label(self.LabelFrame, text= self.titoli_HFT[i], font=("Helvetica", 8))
            self.lblnome.pack(side = LEFT)#place(x=85+j, y=50)

        self.ContentFrame = ttk.Frame(self.subframe, width = 600, height = 600)

        self.ButtonsFrame = ttk.Frame(self.subframe)
        ttk.Frame(self.ButtonsFrame).pack(side=LEFT, fill = X, expand=TRUE)
        ttk.Button(self.ButtonsFrame, text='Inserisci', width='10').pack(side = LEFT)
        ttk.Button(self.ButtonsFrame, text='Modifica', width='10').pack(side = LEFT)
        ttk.Button(self.ButtonsFrame,  text='Indietro', width='10').pack(side = LEFT)
        ttk.Button(self.ButtonsFrame,  text='Avanti', width='10').pack(side = LEFT)
        ttk.Frame(self.ButtonsFrame).pack(side=RIGHT, fill = X, expand=TRUE)

        self.LabelFrame.pack(side = TOP, fill = X, expand=TRUE)
        self.ContentFrame.pack(fill = BOTH, expand = TRUE)
        self.ButtonsFrame.pack(side = BOTTOM, fill = X, expand = TRUE)

if __name__ == '__main__':
    root = tkinter.Tk()
    root.title( "Double scrollbar with tkinter" )
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (0.99*w, 0.9*h))
    applicazione(root)

    root.mainloop()

rawDescription: How to add 2 scrollbars with tkinter in python 3.4?

description: Add 2 scrollbars with tkinter in python 3.4


code:
class classthing: # This represents your class
    def __init__(self, name):
        self.name = name
listofstuff = ['Joe', 'Bob', 'Mary']
dct = {name: classthing(name) for name in listofstuff}
dct  # dct now holds all the data you need
# Each value in dct is an individual instance of your class
dct['Joe'].name
dct['Bob'].name
dct['Mary'].name

rawDescription: Convert list of strings into objects

description: Convert list of strings into objects


code:
def test():
  print("Hello from a Python file!", end=" ")
  print("Welcome to Python!")
test()

rawDescription: comma does not separate lines of print in python34 on windows8?

description: Comma does not separate lines of print in python34 on windows8


code:
def validate_ip(s):
    a = s.split('.')
    if len(a) != 4:
        return False
    for x in a:
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255:
            return False
    return True

rawDescription: How to check if a string matches an IP adress pattern in python?

description: Check if a string matches an IP adress pattern in python


code: multilist = [colNum*[0] for x in xrange(rowNum)]

rawDescription: Cannot understand a python code

description: Cannot understand a python code


code:
ind=[[0,1,2],[3]]
[allrays[i] for i in ind]

rawDescription: Efficient way of appending / extracting list elements


rawDescription: replace with regular expression python

description: Replace with regular expression python


code:
# tlsclient.py
from twisted.python.filepath import FilePath
from twisted.internet.endpoints import SSL4ClientEndpoint
from twisted.internet.ssl import (
    PrivateCertificate, Certificate, optionsForClientTLS)
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.task import react
from twisted.internet.protocol import Protocol, Factory

class SendAnyData(Protocol):
    def connectionMade(self):
        self.deferred = Deferred()
        self.transport.write(b"HELLO\r\n")
    def connectionLost(self, reason):
        self.deferred.callback(None)

@inlineCallbacks
def main(reactor, name):
    pem = FilePath(name.encode("utf-8") + b".client.private.pem").getContent()
    caPem = FilePath(b"ca-private-cert.pem").getContent()
    clientEndpoint = SSL4ClientEndpoint(
        reactor, u"localhost", 4321,
        optionsForClientTLS(u"the-authority", Certificate.loadPEM(caPem),
                            PrivateCertificate.loadPEM(pem)),
    )
    proto = yield clientEndpoint.connect(Factory.forProtocol(SendAnyData))
    yield proto.deferred

import sys
react(main, sys.argv[1:])

rawDescription: Use TLS and Python for authentication

description: Use TLS and Python for authentication


rawDescription: How to unit test view_func in url rule?

description: Unit test view_func in url rule


code:
a
(a.reshape(-1,1) & np.array([0xF, 0xF0], dtype=np.uint8)) >> np.array([0, 4], dtype=np.uint8)

rawDescription: numpy parse int into bit groupings

description: Numpy parse int into bit groupings


code:
def item_insertion_window(self):
        """ Display the stars to add to the database
        Group the stars using radio buttons
        """
        self.new_window=Tkinter.Toplevel(self)
        self.new_window.wm_title("Add my favorite stars")
        self.new_window.grid_rowconfigure(0, weight=1)
        self.new_window.grid_columnconfigure(0, weight=1)

        self.exitb=Tkinter.Button(self.new_window,text="Exit",command=self.new_window.quit)
        self.submitb=Tkinter.Button(self.new_window,text="Submit",command=self.increment_db)
        self.exitb.grid(row=8,column=1)
        self.submitb.grid(row=8,column=0,sticky=Tkinter.W)

        self.v=IntVar()
        self.tvstars=[('YOWERI KAGUTA MUSEVENI', 1), ('KIIZA BESIGYE', 2),
                      ('AMAAMA JOHN MBABAZI ', 3), ('KARUNGI SHARON', 4),
                      ('BYAMUKAMA OSCAR', 5), ('MATILDA MOREEN', 6),
                      ('DUNCANS', 7)]
        self.i=0
        for self.txt, star in self.tvstars:
            self.i=self.i+1
            self.rb=Tkinter.Radiobutton(self.new_window,text=self.txt,variable=self.v,value=star)
            self.rb.grid(row=self.i,column=0,sticky=Tkinter.W)

rawDescription: how to connect to mysql database from gui made in python

description: Connect to mysql database from gui made in python


code:
import re
s = "The quick  brown fox"
re.findall(r'\S+\s*(?=\s\S|$)', s)

rawDescription: Removing empty entries and adding them as a whitespace in the previous entry of a list


code:
import pandas as pd
def elasticToDataframe(elasticResult,aggStructure,record={},fulllist=[]):
    for agg in aggStructure:
        buckets = elasticResult[agg['key']]['buckets']
        for bucket in buckets:
            record = record.copy()
            record[agg['key']] = bucket['key']
            if 'aggs' in agg:
                elasticToDataframe(bucket,agg['aggs'],record,fulllist)
            else:
                for var in agg['variables']:
                    record[var['dfName']] = bucket[var['elasticName']]

                fulllist.append(record)

    df = pd.DataFrame(fulllist)
    return df

rawDescription: pandas dataframe from a nested dictionary (elasticsearch result)

description: Pandas dataframe from a nested dictionary (elasticsearch result)


code:
import itertools

class Comment(object):
    def __iter__(self):
        return _iter_helper(self, 0)

    def _iter_helper(self, depth):
        item = {'indent_level': depth, 'comment': self}
        return itertools.chain([item],
                               *[comment._iter_helper(depth+1)
                                 for comment
                                 in self.all_comments
                                 if comment.parent == self])

rawDescription: A complex ordering algorithm for a Python list?


code:
tmp = pd.merge(test, data, how='inner', sort=False, copy=False,
               on=['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7'])

rawDescription: Pandas Merge vs. Boolean Indexing

description: Pandas Merge vs. Boolean Indexing


rawDescription: Python auto define variables

description: Python auto define variables


rawDescription: apply a function to a pandas Dataframe whose retuned value is based on other rows

description: Apply a function to a pandas Dataframe whose retuned value is based on other rows


code:
[{'number': 0, 'other_number': 3},
 {'number': 1, 'other_number': 4},
 {'number': 2, 'other_number': 5}]

rawDescription: Update dictionary from two yield functions


code:
g['data1'].rank(method='min')
df['RN'] = g['data1'].rank(method='min')

rawDescription: SQL-like window functions in PANDAS: Row Numbering in Python Pandas Dataframe


code:
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.all = []
        self.path = ""
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("SomeName")
        self.style = Style()
        self.style.theme_use("default")

        self.frame2 = Frame(self, relief=FLAT, borderwidth=2)
        self.frame2.pack(side=TOP, fill=BOTH, expand=False)

        self.usrLable = Label(self.frame2, text="Username: ")
        self.usrLable.pack(side=LEFT, padx=5, pady=1)

        self.frame6 = Frame(self, relief=FLAT, borderwidth=2)
        self.frame6.pack(fill=BOTH, expand=True)

        stopButton = Button(self.frame6, text="Stop", command=self.stopButtonClick)
        stopButton.pack(side=LEFT)

    def stopButtonClick(self):
        self.usrLable.configure(text="hello")

rawDescription: How do I access a label to change its text in Tkinter

description: Access a label to change its text in Tkinter


rawDescription: i am trying send email using web2py with gmail and using smtp setting i have attached all code

description: I am trying send email using web2py with gmail and using smtp setting i have attached all code


code: data = json.load(open('config.json'), object_pairs_hook=OrderedDict)

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

description: Get JSON to load into an OrderedDict in Python


code:
from operator import itemgetter
from itertools import groupby

shoesizes    = [ 2 ,  5 ,  6 , 1 , 3 , 2 ,  4 ,  5 , 2 , 3 , 1 ]
quantities   = [ 50, 100, 120, 20, 40, 10, 90 , 10 ,30 , 20, 80]

# For convenience, short names for itemgetters
getsize, getcnt = itemgetter(0), itemgetter(1)

# Sort to bins of same size next to each other
sorted_bins = sorted(zip(shoesizes, quantities), key=getsize)

# Group and sum bins of same size
summed_sizes = [(k, sum(map(getcnt, g))) for k, g in groupby(sorted_bins, key=getsize)]

# Convert back to separate lists
orderedsizes, totalquant = map(list, zip(*summed_sizes))

print(orderedsizes)
print(totalquant)

rawDescription: sorting integers in lists into bins

description: Sorting integers in lists into bins


code:
# (Python 3)
class Type1:
    def __eq__(self, other):
        if isinstance(other, Type1):
            return True
        return super().__eq__(other)

    def __hash__(self):
        return 1329916036    # anything constant

rawDescription: Make Counter consider two objects of the same class the same


code: world2 = world[:]

rawDescription: List being altered while working on copy in Python 2.7


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

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', labelspacing=2)
plt.show()

rawDescription: How to adjust the size of matplotlib legend box?

description: Adjust the size of matplotlib legend box


rawDescription: Finding round figure

description: Finding round figure


code:
def f(maybe_list):
    if not isinstance(maybe_list, list):
        maybe_list = [maybe_list]
    # carry on, you have a list.

rawDescription: Convert a string to a list of length one


code:
# Duplicates in row:  ['A' 'A' 'B']
# Duplicates in column:  ['A' 'A' 'B']

rawDescription: Finding duplicates in each row and column


code:
from itertools import starmap
from operator import or_ #bitwise or for the function passed to starmap
list(starmap(or_, zip_longest(l1,l2, fillvalue=0)))

rawDescription: Combining Lists in python with common elements


code:
root = 'MonthlyDataSplit'
for gp in g:
    filename = gp[0] + '.csv'
    print(filename)
    gp[1].to_csv(root + '/' + filename)

rawDescription: Save pandas csv to sub-directory

description: Save pandas csv to sub-directory


code:
## client side
# get file size here, for example:
# filesize = os.path.getfilesize(filepath)
sock.sendall("FILE %s %d\n" % (filename, filesize))
sock.sendall(fd.read())

...
## server side
# error handling is left out
header = ""
while True:
    d = sock.recv(1)
    if d == '\n':
        break
    header += d

filesize = int(header.split()[-1])
# or search for the last space in header
# and get a substring of header as filename
filename = "".join(header.split()[1:-1])
data = ""
while filesize > 0:
    chunk = sock.recv(1024) # or any amount of data
    filesize -= chunk
    data += chunk

rawDescription: Unable to separate file names with file contents in Python socket programming


code:
from datetime import combine

class MyModel(models.Model):
    start_date = models.DateField()
    start_time = models.TimeField()

    class Meta:
        ordering = ['start_date', 'start_time']

    def start_datetime(self):
        return combine(self.date, self.time)

rawDescription: Django filter datetime field by time, irrespective of date


code:
# pick out months from time array using filtering with np.diff
months = time.month[:-1][np.diff(time.month) != 0]
months = np.append(months, time.month[-1])
# months = array([11, 12, 1]) corresponding to Nov, Dec, Jan

rawDescription: Plotting colormap graph for each day side by side


code:
config = Configurator(registry=request.registry)
config.add_route(...)
config.commit()

rawDescription: Adding routes dynamically to pyramid

description: Adding routes dynamically to pyramid


code:
from collections import namedtuple

class Quarter(namedtuple('Quarter', 'year quarter')):
    __slots__ = ()

    @classmethod
    def from_string(cls, text):
        """Convert 'NQM' into Quarter(year=2000+N, quarter=M)."""
        year, quarter = map(int, text.split('Q'))
        return cls(year + 2000, quarter)

    @classmethod
    def from_date(cls, date):
        """Create Quarter from datetime.date instance."""
        return cls(date.year, (date.month - 1) // 3 + 1)

    def increment(self):
        """Return the next quarter."""
        if self.quarter < 4:
            return self.__class__(self.year, self.quarter + 1)
        else:
            assert self.quarter == 4
            return self.__class__(self.year + 1, 1)

    def __str__(self):
        """Convert to "NQM" text representation."""
        return "{year}Q{quarter}".format(year=self.year-2000, quarter=self.quarter)

rawDescription: generate time series by quarter, increment by one quarter

description: Generate time series by quarter, increment by one quarter


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

def P(x):
        return 924*x**6 - 2772*x**5 + 3150*x**4 - 1680*x**3 + 420*x**2 - 42*x + 1
def dPdx(x):
        return 5544*x**5 - 13860*x**4 + 12600*x**3 - 5040*x**2 + 840*x - 42

accuracy = 1e-10

roots = []
for k in range(6):
    x = 1.0
    xlast = float("inf")

    x_points = np.linspace(0.0, 1.0, 200)
    y_points = P(x_points)
    for rt in roots:
        y_points /= (x_points - rt)
    y_points = np.array([ max(-1.0,min(1.0,np.real(y))) for y in y_points ])

    plt.plot(x_points,y_points,x_points,0*y_points)
    plt.show()
    while np.abs(x - xlast) > accuracy:
        xlast = x
        corr = 1e-8j
        for rt in roots:
            corr += 1/(xlast-rt)
        Px = P(xlast)
        dPx = dPdx(xlast)
        x = xlast - Px/(dPx - Px*corr)
    print(x)
    roots.append(x)

rawDescription: Solve for the positions of all six roots PYTHON


code: size = fields.IntegerRangeField(range(1, 50))

rawDescription: How to limit the maximum value of a numeric field in a Django model?

description: Limit the maximum value of a numeric field in a Django model


code:
n = 5
plt.plot([x + n - 1 for x in range(0, len(plotted_values), n)], nth_value_plot, "o")

rawDescription: matplotlib plotting a dot every nth x

description: Matplotlib plotting a dot every nth x


code: func = dec(func)

rawDescription: Is it possible to apply my own decorators to builtin methods in Python?


code: clear_keys = True

rawDescription: Make text appear based on key press (give user real time feedback) in psychopy


code:
import sys
import subprocess

if 'darwin' in sys.platform:
    print('Running \'caffeinate\' on MacOSX to prevent the system from sleeping')
    subprocess.Popen('caffeinate')

rawDescription: Prevent OS X from going to sleep with Python?


code:
#AllText.txt
Hello
How
Are
You

rawDescription: Read text file as a whole

description: Read text file as a whole


code:
# Update: sort stop words so that words prefixing
# other stop words don't cause issues
stopwords.sort(key=lambda x: len(x), reverse=True)
pattern = re.compile('|'.join('(?=(%s))' % word for word in stopwords))
matches = pattern.finditer(orig_str)

rawDescription: Python regex for quickly removing any possible instances of substrings?


code: x = ''.join(i if i != 'a' or random.randint(0, 1) else 'b' for i in x)

rawDescription: Replace 50% of characters (randomly) in a String


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, (-1, -1), wx.Size(300, 200))
        self.panel1 = wx.Panel(self)
        self.Author = wx.HyperlinkCtrl(self.panel1, -1, "", "http://127.0.0.1/some_directory/",pos=(30,50))
        self.Button = wx.Button(self.panel1, -1, "Click Me", pos=(80,100))
        self.Button.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Show()

    def OnButton(self,event):
        self.Author.Hide()
        if self.Author.IsEnabled():
            self.Author = wx.StaticText(self.panel1, -1, "http://127.0.0.1/some_directory/", pos=(30,50))
            self.Author.Disable()
        else:
            self.Author = wx.HyperlinkCtrl(self.panel1, -1, "", "http://127.0.0.1/some_directory/", pos=(30,50))
            self.Author.Enable()
        self.Author.Show()
        self.Update()

if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame(None, -1, 'Hyperlink')
    app.MainLoop()

rawDescription: How to unset or disable hyperlinkctrl in wxpython only on some conditions

description: Unset or disable hyperlinkctrl in wxpython only on some conditions


rawDescription: Reduce array over ranges

description: Reduce array over ranges


code:
name.split(', ')
first, last = name.split(', ')
first
last
[last, first]
', '.join([last, first])
last + ', ' + first

rawDescription: Swapping first and last name positions

description: Swapping first and last name positions