code:
from Tkinter import *
#

my_change = "No"

stateOpts = ['normal', 'disabled']

win_width = 610
win_height =866

# My frame for form
class simpleform_ap(Tk):

    #my_sel = ""
    global my_change

    # constructor
    def __init__(self,parent):
        Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
    #

    def initialize(self):
        #
        # Default Window Size
        self.geometry(str(win_width) + "x" + str(win_height))
        #
        self.grid_columnconfigure(0,weight=4)
        self.grid_rowconfigure(0,weight=1)
        #
        # Create a Canvas
        self.canvas=Canvas(self.parent)
        self.canvas.grid(row=0,column=0,sticky='nsew')
        #
        # Add a Frame inside my canvas
        self.frame1 = Frame(self.canvas)
        #
        # Create canvas window
        self.canvas.create_window(0,0,window=self.frame1,anchor='nw')
        #
        curr_row = 1
        text_height = 8
        text_width = 5*text_height
        # Label
        self.labelVariableChanges = StringVar()  # Label variable
        labelChanges=Label(self.frame1,textvariable=self.labelVariableChanges,
                           anchor="nw",
                           fg="Black")
        labelChanges.grid(column=0,row=curr_row,columnspan=1,sticky='EW')
        self.labelVariableChanges.set("Do your selection: ")
        # Selection
        optionList = ["Yes","No"]
        self.dropVarChanges=StringVar()
        self.dropVarChanges.set("Select")
        self.dropMenuChanges = OptionMenu(self.frame1 ,self.dropVarChanges,
                                          *optionList, command=self.get_Change_selection)
        self.dropMenuChanges.grid(column=2,row=curr_row)
        curr_row = curr_row+1
        # Text
        self.textStateChanges = stateOpts[1]
        self.TextVarChanges=StringVar()
        #
        self.textChanges=Text(self.frame1,state=self.textStateChanges,
                              height = text_height, width = text_width,
                              fg="black",bg="white") # ,textvariable=self.myTextVar)
        #
        self.textChanges.grid(column=1, row=curr_row+3, columnspan=2, sticky='EW')
        self.textChanges.insert('1.0',"If Yes, add changes here!")
        self.textChanges.config(state=stateOpts[1])
        #
        #
        # Update Geometry
        self.update()
        self.geometry(self.geometry() )
        self.frame1.update_idletasks()
        self.canvas.config(scrollregion=(0,0,self.frame1.winfo_width(),self.frame1.winfo_height()))
        #
        # end initialize()

    def get_Change_selection(self,value):
        global my_change
        my_change = value
        if value == 'Yes':
            self.textChanges.config(state=stateOpts[0])
        else:
            self.textChanges.config(state=stateOpts[1])
        self.dropVarChanges.set(value)

        return

def release_block(argv):
    # Create Form
    form = simpleform_ap(None)
    form.title('Release Information')
    #
    form.mainloop()

    print("Done")
    #

if __name__ == "__main__":
    release_block(sys.argv)

rawDescription: python tkinter: use a drop-down menu to enable a text field

description: Python tkinter: use a drop-down menu to enable a text field


code:
#!/usr/bin/env python
import os
os.system('which python')

rawDescription: execute os.system('python ') inside a virtualenv

description: Execute os.system('python ') inside a virtualenv


code:
class GraphicsView(QtWidgets.QGraphicsView):
    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.NoButton:
            print("Simple mouse motion")
        elif event.buttons() == QtCore.Qt.LeftButton:
            print("Left click drag")
        elif event.buttons() == QtCore.Qt.RightButton:
            print("Right click drag")
        super(GraphicsView, self).mouseMoveEvent(event)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            print("Press!")
        super(GraphicsView, self).mousePressEvent(event)

rawDescription: Why mouseMoveEvent does nothing in PyQt5


code:
from pyspark.mllib.linalg import VectorUDT

df = Vectors.sparse(
    document_frequency.shape[0], document_frequency.nonzero()[0],
    document_frequency[document_frequency.nonzero()]
)

def idf(df, d):
    values = ...  # Compute new values
    return Vectors.sparse(v.size, v.indices, values)

dataset.withColumn("idf_col", udf(idf, VectorUDT())(col("tf_col")))

rawDescription: Create a Python transformer on sparsevector data type column in Pyspark ML


rawDescription: How to test response contains a particular key and value

description: Test response contains a particular key and value


code:
for tag_type in dom.getElementsByTagName('tag_type'):
    while tag_type.hasChildNodes():
        tag_type.removeChild(tag_type.firstChild)
    tag_type.appendChild(dom.createTextNode("Replacement Word"))

rawDescription: Find replace Element using Python

description: Find replace Element using Python


code: fOWOO(fOWOO(num1, num2, op1), num3, op2)  # (num1 `op1` num2) `op2` num3

rawDescription: Python: Dealing with a second operator in calculator


code:
import re
block_re = re.compile(r'v_dims=\{(.*?)\}', re.S)

with open("C:\XXXX\nemo\Test.mrk") as f:
    doc = f.read()

block = block_re.search(doc)
[s.strip().strip('"') for s in block.group(1).split(',')]

rawDescription: Python Parse regex

description: Python Parse regex


code:
user = User.objects.all()[0]  # Get the first user

user.profile  # This would return the profile object
user.profile.type_user  # This would return the type_user of the profile related with this user

rawDescription: How do I define multiple user types in Django using the existing User model?

description: Define multiple user types in Django using the existing User model


rawDescription: Longest increasing subsequence in Python (For vs While loop)


code: sk_f = df.reindex(index).bfill()

rawDescription: To fill the missing data lines with pandas reindex function


rawDescription: How to: reduce number of ticks with matplotlib


code: data['new_parameter'] = [new_par1, new_par2]

rawDescription: Recommended way to represent my data with numpy


code:
Example
if __name__ == '__main__':
    import sys

    filename = sys.argv[1]
    if isinstance(filename, bytes):
        filename = filename.decode(sys.stdin.encoding)

    request = OWNER_SECURITY_INFORMATION
    sd = get_file_security(filename, request)
    sid = get_security_descriptor_owner(sd)
    name, domain, sid_type = look_up_account_sid(sid)
    if domain:
        name =  '{0}\\{1}'.format(domain, name)
    print("File : {0}".format(filename))
    print("Owner: {0} ({1})".format(name, sid_type))

rawDescription: Howto determine file owner on windows using python without pywin32


rawDescription: python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub

description: Python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub


code: import exampleModule

rawDescription: Using Python Functions in Terminal

description: Using Python Functions in Terminal


code:
import json
data = json.dumps(list(tracks))

rawDescription: Serializing attributes that are not model fields with Django JSON serializer


code:
import csv

def handleCSVfile(infilename, outfilename):
    with open(infilename, 'rb') as infile:
        with open(outfilename, 'wb') as outfile:
            reader = csv.reader(infile, lineterminator='\n')
            writer = csv.writer(outfile, lineterminator='\n')

            for row in reader:
                for field_index, field in enumerate(row):
                    if isWhatIWant(field):
                        row[field_index] = parse(field)
                writer.writerow(row)

rawDescription: Python: add column to CSV file based on existing column


code:
def test_some_function(monkeypatch):
    monkeypatch.setattr(time, 'sleep', lambda s: None)
    data = some_sleepy_function()
    assert data == expected_data

rawDescription: mocking sleep in a test

description: Mocking sleep in a test


code: scipy.sparse.vstack([X1, X2]).toarray()

rawDescription: Parallelize DictVectorizer Creation

description: Parallelize DictVectorizer Creation


code:
from bs4 import BeautifulSoup
tt = BeautifulSoup('

')

new = BeautifulSoup('
aaaaaaa<aaaaa>
')
tt.p.replace_with(new.p)

rawDescription: how to avoid replace_with escape my '<' and '>'?

description: Avoid replace_with escape my '<' and '>'


code: [x | y for x,y in zip(list_1, list_2)]

rawDescription: Combining Lists in python with common elements


code: logger = logging.getLogger(__name__)

rawDescription: No handler found for library with logging configured


code:
from functools import partial

map(partial(urljoin, response.url), url_list)

rawDescription: How to use map with urljoin?

description: Use map with urljoin


code: f_out.writelines(line for line in f_in if "timeout of" in line)

rawDescription: How do I search a file, count the number of hits and write the number to column B in a .csv?

description: Search a file, count the number of hits and write the number to column B in a .csv


code:
from xml.etree.ElementTree import parse
et = parse(xmlfile)

rawDescription: How to prevent "billion laughs" DoS attack in Python's xlrd?

description: Prevent "billion laughs" DoS attack in Python's xlrd


code:
plt.plot(x1,x2,'g--^', label='regional')
plt.plot(y1,y2,'b-o', label='local')

rawDescription: Python plot legend : markers appear twice


code:
cypher = {}
for i in range(len(english)): # for each english character
    c = english[i]
    secrets = []
    for j in range(len(secret)): # for each corresponding secret character
        secrets.append(secret[j][i])
        cypher[c] = secrets # make a mapping of english character to list-of-secret-characters
    secrets = [] # clear out list of secret characters for the next english character

rawDescription: Reading and writing to files in python, translating text in one file to another


code:
temp = {}
for d in data:
    temp[d['id1']] = temp.get(d['id1'], 0) + int(d['price'])

temp

rawDescription: Merge values of same key, in list of dicts


rawDescription: Split on space but not if there is a colon followed by space or if there is a space in quotes


code:
operators = []

class Operator:
    def __init__(self, precedence):
        self.precedence = precedence
        operators.append(self)

PLUS = Operator(0)
UPLUS = Operator(10)
MIN = Operator(0)
UMIN = Operator(10)
MULT = Operator(20)

# Freeze the collection of Operators
operators = tuple(operators)

rawDescription: Python: Grouping objects together

description: Python: Grouping objects together


rawDescription: Determine the cluster for a new document with Scikit


code:
import functools
import nose

def expected_failure(test):
    @functools.wraps(test)
    def inner(*args, **kwargs):
        try:
            test(*args, **kwargs)
        except Exception:
            raise nose.SkipTest
        else:
            raise AssertionError('Failure expected')
    return inner

rawDescription: nose plugin for expected-failures

description: Nose plugin for expected-failures


code:
result = pd.merge(df, counts, left_on=['Protein', 'Peptide'], right_index=True,
                  how='inner')

#   Protein Peptide  Mean intensity  counts
# 0      A1     AAB            4.54       2
# 3      A1     AAB            5.67       2
# 1      A1     ABB            5.56       2
# 2      A1     ABB            4.67       2
# 5      A2     ABB            4.64       2
# 7      A2     ABB            5.56       2
# 8      A2     ABC            4.67       2
# 9      A2     ABC            5.67       2

rawDescription: Grouping and filtering data

description: Grouping and filtering data


rawDescription: Assigning int values to each dictionary entry as well as having reference numbers?


code:
sub_list = [0] * 10
a_list = [sub_list] * 10

rawDescription: Python list confusion

description: Python list confusion


code:
class PollForm(forms.ModelForm):
    class Meta:
        model = Poll
        fields = ('question_text', )

class ChoiceForm(forms.ModelForm):
    class Meta:
        model = Choice
        fields = ('choice_text',)

rawDescription: Combining two forms in one Django view

description: Combining two forms in one Django view


rawDescription: Import binary data using a different scanning direction


code:
def get_selection_manual(self, event):
    span = matplotlib.widgets.SpanSelector(self.ax, \
        self.process_selection_manual, "horizontal", useblit=True, \
        rectprops=dict(alpha=0.5, facecolor="red"))

rawDescription: wxPython and matplotlib.widgets

description: WxPython and matplotlib.widgets


code:
import re
s = "javascript:GetApplyClickCount('https://careers-virtua.icims.com/jobs/5587/1024245/job?apply=yes&hashed=58168622', 'http://virtuacareers.com/list.aspx?state=voorhees&category=staff+nurse&jobtitle=registered+nurse+(rn)&jobid=3025458&dmaid=1286&dmaname=voorhees', 'SameWindow', 'scrollbars=1, toolbar=1, resizable=1, location=1, directories=1, status=1, menubar=1, copyhistory=1, fullscreen=1', 'true', '0', '0', 'virtuacareers.com', '', '', '3025458', 'Registered Nurse (RN)','212','True','','False');"
re.search("\'(?P<url>https?://[^\s]+)\'", s).group("url")

rawDescription: scrapy scraped data contains javascript

description: Scrapy scraped data contains javascript


code:
def foo():
    ...
    logger.info("message")
    ...

rawDescription: How do I make better use of logging module in my program?

description: Make better use of logging module in my program


code: C[d,e,f + b[:, np.newaxis]].shape

rawDescription: Speed up for loop with numpy

description: Speed up for loop with numpy


code:
key = ('node1', 'node2', 'node3')
'__tuple__({})'.format(','.join(key))
mapped_key = '__tuple__({})'.format(','.join(key))
tuple(mapped_key[10:-1].split(','))

rawDescription: JSON encoding for dict of dicts

description: JSON encoding for dict of dicts


rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code: ['hattrick', 'google', 'wampum', 'newcom', 'smithsonian']

rawDescription: removing first four and last four characters of strings in list, OR removing specific character patterns

description: Removing first four and last four characters of strings in list, OR removing specific character patterns


code:
import struct

def floatToBits(f):
    s = struct.pack('>f', f)
    return struct.unpack('>l', s)[0]

floatToBits(173.3125)
hex(_)

rawDescription: Get the "bits" of a float in Python?

description: Get the "bits" of a float in Python


code:
df1 = orig(output_summary)
df2 = alt(output_summary)
df1.equals(df2)

rawDescription: Python Pandas, translating start-end events into single consolidated Dataframe


code:
# if python 2.x
#from itertools import tee, izip
# if python 3
from itertols import tee
# http://docs.python.org/2/library/itertools.html#recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    # if python 2.x
    #return izip(a, b)
    return zip(a, b)

new_data = []
with open('temp100.txt', 'r') as sqFile:
    for sLine, edit_line  in pairwise(seqFile):
        # I think this is just new_line = tempLine
        #tempLine = edit_line[:20]
        #new_line = editLine.replace(editLine, tempLine)
        new_data.append(sLine + editLine[:20])
        if len(sLine) > 20:
            new_data.append('\n')

with open("new_temp100.txt", "w") as new:
    new.write(''.join(new_data))

rawDescription: performance - python text file edit 2GB files

description: Performance - python text file edit 2GB files


rawDescription: Renaming multiple files in python

description: Renaming multiple files in python


code:
total = sum(count for count in collections.Counter(
    elem.tag for elem in ET.XML(refdoc)).values()
    if count > 1)

rawDescription: How to detect number of xml nodes?

description: Detect number of xml nodes


code:
class A:
    def __init__(self, a):
        self.a = a
    def __reduce__(self):
        raise GoAwayError()

rawDescription: How to add a custom type to dill's pickleable types

description: Add a custom type to dill's pickleable types


rawDescription: How to filter out subarrays which contain NaN's?

description: Filter out subarrays which contain NaN's


rawDescription: Splitting dataframe and saving to txt files


rawDescription: python - modify a list of strings via regex

description: Python - modify a list of strings via regex


code:
from itertools import combinations
[ i[0] & i[1] for i in combinations(s,2) ]

rawDescription: Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists


rawDescription: Passing arguments to fsolve

description: Passing arguments to fsolve


code:
from Tkinter import *
root = Tk()
topframe=Frame(root)
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM,fill=X)
topframe.pack(side=TOP,fill=BOTH)
scrollbar = Scrollbar(topframe)
scrollbar.pack(side=RIGHT,fill=Y)
text = Text(topframe,yscrollcommand=scrollbar.set)
text.pack(side=LEFT,fill=BOTH)
scrollbar.config(command=text.yview)
text.config(state=DISABLED)
v = StringVar()
e = Entry(bottomframe,textvariable=v)
def submit():
    command = v.get()
    v.set('')
    #your input handling code goes here.
    wprint(command)
    #end your input handling
e.bind('<Return>',submit)
button=Button(bottomframe,text='RUN',command=submit)
button.pack(side=RIGHT)
e.pack(expand=True,side=LEFT,fill=X)
def wprint(obj):
    text.config(state=NORMAL)
    text.insert(END,str(obj)+'\n')
    text.config(state=DISABLED)
root.mainloop()

rawDescription: Terminating raw_input() if other text displays


code:
kwargs['client_flag'] = CLIENT.FOUND_ROWS
kwargs.update(settings_dict['OPTIONS'])

rawDescription: change CLIENT_FOUND_ROWS flag in django for mysql-python (MySQLdb)?

description: Change CLIENT_FOUND_ROWS flag in django for mysql-python (MySQLdb)


code:
import chardet

your_str = "Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb"
detected_encoding = chardet.detect(your_str)["encoding"]

try:
    correct_str = your_str.decode(detected_encoding)
except UnicodeDecodeError:
    print("Could not estimate encoding")

rawDescription: Unmunging munged unicode

description: Unmunging munged unicode


code:
class Stream(object):
        """A lazily computed recursive list."""
        def __init__(self, first, compute_rest, empty=False):
            self.first = first
            self._compute_rest = compute_rest
            self.empty = empty
            self._rest = None
            self._computed = False
        @property
        def rest(self):
            """Return the rest of the stream, computing it if necessary."""
            assert not self.empty, 'Empty streams have no rest.'
            if not self._computed:
                self._rest = self._compute_rest()
                self._computed = True
            return self._rest
        def __repr__(self):
            if self.empty:
                return '<empty stream>'
            return 'Stream({0}, <compute_rest>)'.format(repr(self.first))

Stream.empty = Stream(None, None, True)

def cons_stream(a,b):
    return Stream(a,lambda : b)

def add_streams(a,b):
    if a.empty or b.empty:
            return Stream.empty
    def compute_rest():
        return add_streams(a.rest,b.rest)
    return Stream(a.first+b.first,compute_rest)

def scale_stream(a,scale):
    if a.empty:
            return Stream.empty
    def compute_rest():
        return scale_stream(a.rest,scale)
    return Stream(a.first*scale,compute_rest)

def make_integer_stream(first=1):
      def compute_rest():
        return make_integer_stream(first+1)
      return Stream(first, compute_rest)

def truncate_stream(s, k):
        if s.empty or k == 0:
            return Stream.empty
        def compute_rest():
            return truncate_stream(s.rest, k-1)
        return Stream(s.first, compute_rest)

def stream_to_list(s):
        r = []
        while not s.empty:
            r.append(s.first)
            s = s.rest
        return r

def integral(integrand,initial_value,dt):
    placeholder = Stream(initial_value,lambda : None)
    int_rec = cons_stream(initial_value,
                          add_streams(scale_stream(integrand,dt),
                                      placeholder))
    placeholder._compute_rest = lambda:int_rec
    return int_rec

a = truncate_stream(make_integer_stream(),5)
print(stream_to_list(integral(a,8,.5)))

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


rawDescription: RIGHT() function in sqlalchemy

description: RIGHT() function in sqlalchemy


rawDescription: the .set() method is not in the xml.etree library for Python?

description: The .set() method is not in the xml.etree library for Python


code:
from lxml import etree

html = etree.HTML("""

        <title>History of Roundish Stones in the Paleozoic Era</title>

        Andrew S. Johnson
        E. Idle

""")

print(html.xpath('//@data-email'))

rawDescription: Regexing an email from HTML

description: Regexing an email from HTML


rawDescription: Python - Extract folder path from file path


rawDescription: Formatting JSON from a Pandas data frame for Highcharts within a Django template


rawDescription: How to make a histogram from this nc file?

description: Make a histogram from this nc file


code:
def myFunc(x, y):
    for i in range(x,y) if x<y else range(y,x):
        ...

rawDescription: Best way to find max and min of two values

description: Find max and min of two values


code:
math.sin(x)
np.sin(x)

rawDescription: Python: What is the difference between math.exp and numpy.exp and why do numpy creators choose to introduce exp again


code:
class DateTimeForm(Form):
    datetime = TextField()
    timezone = SelectField(choices=..., validators=[RequiredIf('datetime')])

rawDescription: How to make a field conditionally optional in WTForms?

description: Make a field conditionally optional in WTForms


rawDescription: Can I generate a private key with pyOpenSSL with a passphrase

description: Generate a private key with pyOpenSSL with a passphrase


code: values = [option.get('value') for select in playVal for option in select.find_all('option')]

rawDescription: Option Value in loop

description: Option Value in loop


code:
def parse(self, response):
    cat = json.loads(response.body_as_unicode())
    for c in cat:
        if self.seen_404:
            break

        url = 'http://www.url.com/'+str(c)+'/'+str(page)+'.json'
        page += 1
        yield Request(url, callback=self.parse_cats)

def parse_cats(self, response):
    if response.status == '404':
        self.seen_404 = True

rawDescription: Scrapy - Break out of loop if response.status == 404


code:
b = type('', (), {})()
b.this_works = 'cool'

rawDescription: Creating an empty object in Python

description: Creating an empty object in Python


code:
from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as NavigationToolbar

class MatplotPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent,-1,size=(50,50))

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.toolbar = NavigationToolbar(self.canvas)

        self.button = wx.Button(self, -1, "Change plot")
        self.button.Bind(wx.EVT_BUTTON, self.changePlot)

        self.sizer.Add(self.toolbar, 0, wx.EXPAND)
        self.sizer.Add(self.button, 0, wx.EXPAND)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)

        self.drawSin()
        self.current_draw = 'sin'

#       self.drawLines()

    def changePlot(self, event):

        if self.current_draw == 'sin' :
            self.drawLines()
            self.current_draw = 'lines'
        else:
            self.drawSin()
            self.current_draw = 'sin'

        self.Layout()

    def drawLines(self):

        x = numpy.arange(0.0,10,1.0)
        y = [0,1,0,1,0,2,1,2,1,0]

        self.axes.clear()
        self.axes.plot(x, y)

    def drawSin(self):

        x = numpy.arange(0.0,10,0.1)
        y = numpy.sin(x)

        self.axes.clear()
        self.axes.plot(x, y)

rawDescription: WXPython with MatPlotLib

description: WXPython with MatPlotLib


code: minimize(tmp,[0,3], args=(n,cons),tol =1e-15)#where args is (2,True)

rawDescription: Minimizing a function while keeping some of the variables constant


rawDescription: How to compute weighted sum of all elements in a row in pandas?

description: Compute weighted sum of all elements in a row in pandas


rawDescription: Minimizing a Tk Window

description: Minimizing a Tk Window


code:
ds = ts.resample('5min', how=np.any)
ds

rawDescription: Downsize series containing boolean data with resample


code:
def do_work(wid, value):
    time.sleep(random.randint(0,2))
    info("%d Task %s done" % (wid, value))

def worker(wid, q):
    while True:
        item = q.get()
        try:
            info("%d Got item %s" % (wid, item))
            do_work(wid, item)
        finally:
            q.task_done()
            info("%d Done item %s" % (wid, item))

def producer(pid, q):
    for item in iter(lambda: random.randint(1, 11), 10):
        time.sleep(.1) # simulate a green blocking call that yields control
        info("%d Added item %s" % (pid, item))
        q.put(item)
    info("%d Signal Received" % (pid,))

rawDescription: Throughput differences when using coroutines vs threading


rawDescription: How to use regex with optional characters in python?

description: Use regex with optional characters in python


code:
s1 = 'fly,dream'
s2 = 'dream,fly'
s1 = s1.split(',')
s1
s2 = s2.split(',')
s2
s1.sort()
s1
s2.sort()
s2
s1 == s2

rawDescription: python return equal where the string is not actually equal?

description: Python return equal where the string is not actually equal


code:
sentinel = object()     #a new object, guaranteed not in dictionary
all( d1.get(x, sentinel) == d2.get(x, sentinel) for x in l )

rawDescription: Equality of dictionaries

description: Equality of dictionaries


code:
from itertools import groupby, chain

def get_sections(fle):
    with open(fle) as f:
        grps = groupby(f)
        for k, v in grps:
            if k:
                yield chain([next(v)], (next(grps)[1]))  # all lines up to next #TYPE

rawDescription: How to split file into chunks by string delimiter in Python

description: Split file into chunks by string delimiter in Python


code:
points.shape
points.size   # number of elements
len(points)  # size of the 1st dimension

rawDescription: What is faster: Python3's 'len' or numpys shape?


code: comb = [x for i in range(1, len(data)+1) for c in combinations(data, i) for x in negations(c)]

rawDescription: all combination of a complicated list

description: All combination of a complicated list


rawDescription: How to coarse grain xy coordinates

description: Coarse grain xy coordinates


code:
v = setup_view(MyClassedBasedView(), request)
v.method_name()

rawDescription: How to unit test methods inside django's class based views?

description: Unit test methods inside django's class based views


rawDescription: Python reversing slice of a list

description: Python reversing slice of a list


code:
import re

map_lat_long = re.compile(r'google\.maps\.LatLng\(([\d.-]+),\s*([\d.-]+)\)')
lat, long = map_lat_long.search(page_source).groups()

rawDescription: Python extract text after keywords and brackets


code:
import MySQLdb
MySQLdb.paramstyle

rawDescription: String formatting on SQL insert using dict


rawDescription: pandas object indexes can be either string or int, how can I tell them apart?

description: Pandas object indexes can be either string or int, how can I tell them apart


rawDescription: vectors in python structs

description: Vectors in python structs


code:
def foo(x):
    return x*x

bar = lambda x: x*x

rawDescription: Create numerous unique events

description: Create numerous unique events


code: b[mask]

rawDescription: Filter an array in Python3 / Numpy and return indices


rawDescription: Draggable point in matplotlib - How to retrieve point coordinates


code:
a2 = c[:, :a.size//len(a)].reshape(a.shape)
b2 = c[:, a.size//len(a):].reshape(b.shape)

rawDescription: Better way to shuffle two numpy arrays in unison


code:
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
        outfile.write(line)

rawDescription: Python concatenate text files

description: Python concatenate text files


rawDescription: Python Pandas get one text value

description: Python Pandas get one text value


code:
arrays = [[1, 2]*3, ['A', 'B', 'C']*2]
columns = pd.MultiIndex.from_arrays(arrays, names=['foo', 'bar'])

df = pd.DataFrame(np.random.randn(2,6),
                  columns=columns,
                  index= pd.date_range('20000103',periods=2))

rawDescription: How to apply hierarchy or multi-index to panda columns

description: Apply hierarchy or multi-index to panda columns


rawDescription: Transform comma separated string into a list but ignore comma in quotes


code: {'user': '<user1>', 'negative': 8, 'positive': 32, 'rating': 80.0}

rawDescription: flask/jinja: creating a leaderboard out of an unordered dict object

description: Flask/jinja: creating a leaderboard out of an unordered dict object


code:
import importlib
identifier = 'collections.defaultdict'
modulename, _, classname = identifier.rpartition('.')
modulename, classname
args = (int,)
kw = {}
module = importlib.import_module(modulename)
klass = getattr(module, classname)
klass
instance = klass(*args, **kw)
instance

rawDescription: Instantiating object of a class using the name of the class


rawDescription: Python create an event to an ObjectListView check box


rawDescription: Combine date column and time column into index in pandas data frame


rawDescription: Matching all links, except the ones at the beginning in parentheses


rawDescription: Flask: Creating objects that remain over multiple requests


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

rawDescription: Web (weird)wrapped text to plain text string


code:
import sys
from io import StringIO

def decorator_that_makes_func_into_generator(func):
    def wrapper(*a, **ka):
        # Temporarily redirect all output to StringIO instance (intr)
        ts, intr = sys.stdout, StringIO()
        sys.stdout = intr
        func(*a, **ka)
        # Restore normal stdout from backup (ts)
        sys.stdout = ts
        # Get output from intr, split it by whitespace and use it as generator
        yield from intr.getvalue().split()

    return wrapper

@decorator_that_makes_func_into_generator
def countdown(n):
    while n > 0:
        print(n)
        n = n - 1

print(countdown(5), list(countdown(5)))
# <generator object wrapper at 0x01E09058> ['5', '4', '3', '2', '1']

rawDescription: Using decorator to turn function into generator in python


rawDescription: Finding minumum element in a stack in constant time


code: [(l, l.parent.get('id')) for l in links]

rawDescription: Grab the parent id tag with beautiful soup?


code:
length=22
slope=45
newstring='length {}, slope {}'.format(length, slope)
newstring

rawDescription: python3.4.2 how to assign a string with texts and variables

description: Python3.4.2 how to assign a string with texts and variables


code:
import glob
indir, outdir = '/home/directory/', '/home/directory/out/'
files = glob.glob1(indir, '*.sam')
infiles  = [indir  + f              for f in files]
outfiles = [outdir + f[:-3] + "out" for f in files]
for infile, outfile in zip(infiles, outfiles):
    do_stuff_with_files(infile, outfile)

rawDescription: python multiple inputs and multiple outputs

description: Python multiple inputs and multiple outputs


rawDescription: Python sort a JSON list by two key values


code: square = 77 if any(value in list1 for value in list2) else 55

rawDescription: How to search for items in a list in python

description: Search for items in a list in python


rawDescription: Making a function wich argument is a list and return a tuple with the number of 'twos' in it. EG:


code: formset = RoleFormSet(prefix='roles')

rawDescription: Multiple linked Django forms, one submit


code:
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

rawDescription: Writing header with DictWriter from Python's csv module


code:
if 'session_key' in request.session and 'uid' in request.session:
    fb.session_key = request.session['session_key']
    fb.uid = request.session['uid']
else:

    try:
        fb.auth_token = request.GET['auth_token']
    except KeyError:
        # Send user to the Facebook to login
        return HttpResponseRedirect(fb.get_login_url())

    # getSession sets the session_key and uid
    # Store these in the cookie so we don't have to get them again
    fb.auth.getSession()
    request.session['session_key'] = fb.session_key
    request.session['uid'] = fb.uid

rawDescription: Accessing Facebook Connect FBML cookie via PyFacebook?


code: chili = my_dict[2][:]

rawDescription: Behaviour of DEL with list taken from a dict


code:
def junuxx(a) :
    b = np.array([], dtype=np.uint8)
    for x in a:
        b = np.append(b, np.arange(x))
    return b

def mr_e(a) :
    return reduce(lambda x, y: x + range(y), a, [])

rawDescription: repeat arange with numpy

description: Repeat arange with numpy


code:
import threading

def printit():
  threading.Timer(1.0, printit).start()
  #do your work here

printit()

rawDescription: Run a command every one second using threads in python


rawDescription: Create a list (of tuples?) from two lists of different sizes


code:
def popular(letter):
    '''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int}
    '''
    my_dictionary = {}
    for alphabet, picks in letter.items():
        if alphabet[0] in my_dictionary:
            my_dictionary[alphabet[0]] += picks
        else:
            my_dictionary[alphabet[0]] = picks
    return my_dictionary

rawDescription: How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x

description: Add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x


code:
from tkinter import *

class Application(object):
    def __init__(self, parent):
        self.parent = parent
        self.canvas =  Canvas(self.parent, bg='black', width = 200, height = 500)
        self.mainFrame = Frame(self.canvas)
        self.scroll = Scrollbar(self.parent, orient = VERTICAL, command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.scroll.set)
        self.scroll.pack(side='right', fill='y')
        self.canvas.pack(side='left', fill='both')
        self.canvas.create_window((4,4), window=self.mainFrame, anchor="nw", tags="frame")

        self.canvas.configure(yscrollcommand = self.scroll.set)
        self.mainFrame.bind("<Configure>", self.update)
        self.x = []
        for i in range(1000):
            self.x.append(Label(self.mainFrame, text=str(i)))
            self.x[i].grid()

    def update(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

if __name__ == '__main__':
    root = Tk()
    app = Application(root)
    root.mainloop()

rawDescription: Display of a large amount of data in a Canvas with a Scrollbar


code:
t.value1 = 1
t.value2 = 2
t.save()

rawDescription: Django how to update more than a row field at once


code:
import re
test_f = open('test.txt')
result_f = open('result.txt', 'a')
for line in test_f:
    new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
    result_f.write(new_str)

# also, this too, please:
test_f.close()
result_f.close()

rawDescription: write a text file in Python, line by line

description: Write a text file in Python, line by line


rawDescription: Append a column to a 2 dimensional array


rawDescription: Splitting a file with multiple but not all delimiters in Python


code:
def my_method(self,*args,**kwargs):
    App.get_running_app().prefix = str(random.randint(0,9))
    self.my_label1.indice = str(int(self.my_label1.indice) + 1)
    if int(self.my_label1.indice) == 2:
        self.my_label2.prefix = 'changed'

rawDescription: Kivy: is it possible to trigger events with class level (not instance) Properties?


rawDescription: different encrypted versions on encrypting the same string using the same key

description: Different encrypted versions on encrypting the same string using the same key


code:
data = {}
def test():
    while True:
        variable = input("Please enter the name of variable: ")
        new_list = []
        while True:
            unit = input("Enter unit: ")
            if unit == "":break
            new_list.append(unit)

rawDescription: Compare length of list in dictionary

description: Compare length of list in dictionary


code:
from collections import defaultdict

words = 'dog god steer reste trees dog fred steer'.split() # or words from a file

unique_words = set(words)
anagram_dict = defaultdict(list)
for word in unique_words:
    key = "".join(sorted(word))
    anagram_dict[key].append(word)

for anagram_list in anagram_dict.values():
    if len(anagram_list) > 1:
        print(*anagram_list)

rawDescription: How can I get the value of multiple elements while searching a dict efficiently? (python)

description: Get the value of multiple elements while searching a dict efficiently? (python)


code: L = [child.attrib for child in root]

rawDescription: How to keep adding values at end of dictionary

description: Keep adding values at end of dictionary


code:
import struct
struct.pack('>i', 257)
struct.pack('<i', 257)
struct.unpack('<i', '\x01\x01\x00\x00')
struct.unpack('>i', '\x00\x00\x01\x01')

rawDescription: int to binary python

description: Int to binary python


rawDescription: python recursive yield to reduce memory footprint

description: Python recursive yield to reduce memory footprint


code:
#! /usr/bin/python3

from random import randrange

class Operator:
    def __init__ (self, argc, f):
        self.argc = argc
        self.f = f

    def __call__ (self, *args):
        return self.f (*args)

def parse (s):
    s = s.replace ('(', ' ').replace (')', ' ').replace (',', ' ')
    return s.split () [::-1]

def evaluate (ops):
    stack = []
    while ops:
        op = ops [0]
        ops = ops [1:]
        try:
            stack.append (int (op) )
            continue
        except: pass
        try:
            stack.append (float (op) )
            continue
        except: pass
        try:
            operator = operators [op]
        except:
            raise Exception ('Unkown operator {}'.format (op) )
        args = [stack.pop () for _ in range (operator.argc) ]
        stack.append (operator (*args) )
    return stack [0]

operators = {
    'add': Operator (2, lambda a, b: a + b),
    'sub': Operator (2, lambda a, b: a - b),
    'mul': Operator (2, lambda a, b: a * b),
    'div': Operator (2, lambda a, b: a / b),
    'pow': Operator (2, lambda a, b: a ** b),
    'floor': Operator (1, lambda a: int (a) ),
    'abs': Operator (1, lambda a: abs (a) ),
    }

n = int (input ('Which fibonacci number do you want: ') )
fib = 'floor add div pow div add 1 pow 5 .5 2 {} pow 5 .5 .5'.format (n)
#or if you like parentheses: 'floor(add(div(pow(div(add(1,pow(5,.5)),2),{}),pow(5,.5)),.5))'
ops = parse (fib)
print ('F({}) = {}'.format (n, evaluate (ops) ) )

rawDescription: recursively computing expression python

description: Recursively computing expression python


code: 'nsubj(are-5, Robots-1)\nxsubj(remind-8, Robots-1)\namod(culture-4, popular-3)\nprep_in(Robots-1, culture-4)\nroot(ROOT-0, are-5)\nadvmod(are-5, there-6)\naux(remind-8, to-7)\nxcomp(are-5, remind-8)\ndobj(remind-8, us-9)\ndet(awesomeness-12, the-11)\nprep_of(remind-8, awesomeness-12)\namod(agency-16, unbound-14)\namod(agency-16, human-15)\nprep_of(awesomeness-12, agency-16)'

rawDescription: How to find the shortest dependency path between two words in Python?

description: Find the shortest dependency path between two words in Python


code:
table
table[0]
table[1][2]

rawDescription: Loading a file into a numpy array with python


code:
dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT)

rawDescription: Python calling method in class

description: Python calling method in class


code: np.clip(a, 0, 255, out=a)

rawDescription: numpy element transformation with lambda?

description: Numpy element transformation with lambda


rawDescription: Function which is similar to numpy's diff


code:
import Tkinter as tk
class SimpleApp(object):
    def __init__(self, master, **kwargs):
        self.master = master
        self.params = (1,2,3)
        self.button = tk.Button(master, text='Boink', command=self.boink)
        self.button.pack()
    def boink(self):
        print(self.params)

root = tk.Tk()
app = SimpleApp(root)
root.mainloop()

rawDescription: access to top level widget in Tkinter

description: Access to top level widget in Tkinter


code:
def repeat_count(x):
    if x==x.shift():
        return x.cumsum()

rawDescription: python Pandas calling a complex function in groupby.agg

description: Python Pandas calling a complex function in groupby.agg


rawDescription: unique count in (list of smaller lists)

description: Unique count in (list of smaller lists)


rawDescription: Sikuli Random - function that randomly click one of the location


rawDescription: How fill a regex string with parameters

description: How fill a regex string with parameters


code:
for m in OldModel.objects.all():
    aDict = { 'col1':m.col1, 'old_at_fk':m.fktoanothertable.id, 'old_id':id }
    csvwriter.writerow( aDict )

rawDescription: Fill Django application with data using very large Python script


rawDescription: Passing multiple value_list in Django

description: Passing multiple value_list in Django


code:
import fileinput

def f():
    for line in fileinput.input():
        for i in range(10):
            y = int(line.strip()) + int(line.strip())
f()

rawDescription: Python getting meaningful results from cProfile


code:
import os
import csv

with open('hosts.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

hosts = [row['host'] for row in rows]
statuses = [row['status'] for row in rows]

print('[DEBUG]', hosts)
print('[DEBUG] 1st host is', hosts[0])
print('[DEBUG]', statuses)

for row in rows:
    #ping hosts
    hostname = row['host']
    response = os.system("ping -n 1 " + hostname)
    print ("[DEBUG]", response)
    if response == 0:
        print (hostname, 'is up')
        row['status'] = 'Up'
    else:
        print (hostname, 'is down')
        row['status'] = 'Down'

#write results
with open("hosts.csv", "wb") as f:
    writer = csv.DictWriter(f, reader.fieldnames)
    # to maintain the same structure from the original file, rewrite header in original position
    writer.writeheader()
    print("[DEBUG] just before write rows")
    writer.writerows(rows)
    print("[DEBUG] after write rows")

rawDescription: Unable to write list back to CSV

description: Unable to write list back to CSV


code:
def encode(msg,code):
    code = {ord(k):v for k,v in code.items()}
    return msg.translate(code)

print(encode("blagh", {"a":"e","h":"r"}))
print(encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'}))

rawDescription: Encoder for a string - Python

description: Encoder for a string - Python


code:
from django.shortcuts import redirect

def enter_view(request):
    if request.user.has_perm('app_label.permission_codename'):
        return redirect('/page-A')
    elif request.user.has_perm('app_label.another_permission'):
        return redirect('/page-B')
    else:
        return redirect('/page-C')

rawDescription: How to have specific users see different webpages? Django

description: Have specific users see different webpages? Django


code:
from django.http import StreamingHttpResponse

def my_streaming_view(request):
    return StreamingHttpResponse(
         content_generator(['cat', '/tmp/some_large_file.txt'])
    )

rawDescription: send live console data back from server to client using django

description: Send live console data back from server to client using django


code:
from itertools import islice

for row in islice(cr, 4, None):
    print(row)

rawDescription: I can't read a csv file in Python. The result has many rows instead of cells


code:
import numba as nb
import numpy as np

@nb.njit
def nb_replace_values(array, old_new_array):
    res = np.zeros(array.shape, dtype=np.float64)

    rows = array.shape[0]
    columns = array.shape[1]
    rows_replace_array = old_new_array.shape[0]

    for row in range(rows):
        for column in range(columns):
            val = array[row, column]
            # only replace values that are not zero
            if val != 0:
                # Find the value to replace the element with
                for ind_replace in range(rows_replace_array):
                    if old_new_array[ind_replace, 0] == val:
                        # Match found. Replace and break the innermost loop
                        res[row, column] = old_new_array[ind_replace, 2]
                        break

    return res

nb_replace_values(array1, array2)
array([[  0.,  62.,  62.,  88.],
       [  0.,  73.,  64.,  95.],
       [  0.,  59.,  67.,  65.]])

rawDescription: Replacing entries of an array with those of different array


code:
"vanilla" and ""
"" and "vanilla"

rawDescription: Need help understanding Booleans?

description: Need help understanding Booleans


code: from xmldoc import bigxml

rawDescription: How to Include xml file as .py source file

description: Include xml file as .py source file


code:
args = parser.parse_args()
filters = decode(args.filter)

rawDescription: Handling string with delimiters in argparse


code:
@property
def spam(self):
    """I'm the 'spam' property."""
    return self._spam

@spam.setter
def spam(self, value):
    if not value.endswith("!"):
        raise ValueError("spam must end with !")
    # Store the value in "private" _spam attribute
    self._spam = value

@spam.deleter
def spam(self):
    del self._spam

rawDescription: Initializing object variables - a Java approach, a Python approach?


code:
import os
import requests

dump_directory = os.path.join(os.getcwd(), 'mp3')
if not os.path.exists(dump_directory):
    os.makedirs(dump_directory)

def dump_mp3_for(resource):
    payload = {
        'api': 'advanced',
        'format': 'JSON',
        'video': resource
    }
    initial_request = requests.get('http://youtubeinmp3.com/fetch/', params=payload)
    if initial_request.status_code == 200:  # good to go
        download_mp3_at(initial_request)

def download_mp3_at(initial_request):
    j = initial_request.json()
    filename = '{0}.mp3'.format(j['title'])
    r = requests.get(j['link'], stream=True)
    with open(os.path.join(dump_directory, filename), 'wb') as f:
        print('Dumping "{0}"...'.format(filename))
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()

rawDescription: Make a request to download a video in Python


code: data.loc[data.index != "Colorado"]

rawDescription: Most efficient way to exclude indexed rows in pandas dataframe


rawDescription: efficient method for merging 2 sorted files with duplicate coordinates in python

description: Efficient method for merging 2 sorted files with duplicate coordinates in python


code:
from collections import *
d = defaultdict(list)

for item in items:
    d[tuple(item[1:])].append(item[0])

rawDescription: Make a dictionary on matching values

description: Make a dictionary on matching values


code:
whitelist = set('abcdefghijklmnopqrstuvwxy ABCDEFGHIJKLMNOPQRSTUVWXYZ')
myStr = "happy t00 go 129.129"
answer = ''.join(filter(whitelist.__contains__, myStr))

rawDescription: Removing everything except letters and spaces from string in Python3.3


code:
class JobListing(Base):
    __tablename__ = 'joblist'
    id = Column(Integer, primary_key=True)
    jobname = Column(String(80), unique=True)
    biddate = Column(DateTime)

obj = JobListing(jobname="Test Job", biddate=datetime.now())

rawDescription: ORM Design using Pyramid and SQL Alchemy


rawDescription: How to get value from a html table?

description: Get value from a html table


code:
class DBAccessor(Resource):
    def put(self, ques_no, i):
        ...
        return 'ok'

rawDescription: flask restful: how to give multiple arguments to get methhod of any Api using flask restful?

description: Flask restful: how to give multiple arguments to get methhod of any Api using flask restful


code:
def get2(x):
    return x[2]

rawDescription: python 2.4 sorting a text file by specific column

description: Python 2.4 sorting a text file by specific column


rawDescription: What is the different between these two ways for declaring variables in python?


code:
for i in date_list:
    data[i+"InDays"] = data[i].apply(lambda x: (current_date - x).days if x is not pd.NaT else np.NaN)

rawDescription: pandas error creating TimeDeltas from Datetime operation

description: Pandas error creating TimeDeltas from Datetime operation


code:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def ode_rhs(y, t, p, t1):
    ydot[0] = -p[0]*y[0]*y[1] + p[1]*y[2] + p[2]*y[2]
    if t < t1:
        ydot[1] = 0.0
    else:
        ydot[1] = -p[0]*y[0]*y[1] + p[1]*y[2]
    ydot[2] = p[0]*y[0]*y[1] - p[1]*y[2] - p[2]*y[2]
    return ydot

ydot = np.zeros(3)
p = np.array([0.01, 0.25, 0.1])
y0 = [20.0, 100.0, 0.0]
t = np.linspace(0, 200, 2001)
t1 = 20.0

sol = odeint(ode_rhs, y0, t, args=(p, t1))

plt.figure(1)
plt.clf()

plt.subplot(3, 1, 1)
plt.plot(t, sol[:, 0])
plt.axvline(t1, color='r')
plt.grid(True)
plt.ylabel('y[0]')

plt.subplot(3, 1, 2)
plt.plot(t, sol[:, 1])
plt.axvline(t1, color='r')
plt.grid(True)
plt.ylabel('y[1]')
plt.ylim(0, 110)

plt.subplot(3, 1, 3)
plt.plot(t, sol[:, 2])
plt.axvline(t1, color='r')
plt.grid(True)
plt.ylabel('y[2]')
plt.xlabel('t')

plt.show()

rawDescription: Update initial condition in ODE solver each time step


rawDescription: Get content of tags with empty id in BeautifulSoup


code: arts = d['artist'].lower

rawDescription: Put dict into new list based on a key value in Python


code:
rules = [
    Rule(LinkExtractor(allow=r"/q/hp\?s=\w+\.\w+"), follow=True)
]

rawDescription: Scrapy: Scraping very select URLs

description: Scrapy: Scraping very select URLs


rawDescription: Difference between different hex types/representations in Python


code:
def a(df):
    df1 = df.Foo.str.split(expand=True).stack().reset_index(level=1, drop=True).reset_index(name='Foo')
    for k, v in terms.items():
        df1[k] = df1.Foo.str.contains('|'.join(terms[k]))
    return df1.groupby('index').sum().astype(int)

def b(df):
    from collections import Counter

    df1 = pd.DataFrame(terms)

    res = []
    for i,r in df.iterrows():
        s = df1.replace(Counter(r['Foo'].split())).replace('\w',0,regex=True).sum()
        res.append(pd.DataFrame(s).T)
    return pd.concat(res)

rawDescription: Python pandas count number of Regex matches in a string


code: prd = map(''.join, itertools.product(bS, repeat=len(bS)-1))

rawDescription: python: chain elements of a tuple in a list of tuples

description: Python: chain elements of a tuple in a list of tuples


code:
from lxml import html

source = """html posted in the question here"""
tree = html.fromstring(source)
tds = tree.xpath('//table//td[@class="plaintext"]/text()[normalize-space()]')
description = ' '.join(tds)
print(description)

rawDescription: How to find a specific xpath td class from a table with lxml and python

description: Find a specific xpath td class from a table with lxml and python


code: bin_middles = (edges[:-1] + edges[1:]) / 2

rawDescription: Weighted mean in numpy/python

description: Weighted mean in numpy/python


code:
import re

#if its fixed:  [  Key ( Value1 , Value2 , Value3 )  ]
regex = re.compile(r'([A-Za-z0-9]+) \( (.+?) , (.+?) , (.+?) \)')
s = "stringOfAlphaNumeric1 ( stringOfAnyCharacter1 , stringOfAnyCharacter2 , stringOfAnyCharacter3 ) stringOfAlphaNumeric2 ( stringOfAnyCharacter4 , stringOfAnyCharacter5 , stringOfAnyCharacter6 )"

d = dict((i[0], i[1:]) for i in regex.findall(s))

rawDescription: Again, regular expression matching in python


code:
def f3(x=x,y=y,n=n,z=z):
    rows = [[0]*y for i in range(x)]
    rr = random.randrange
    inc = (1).__add__
    sat = (0xff).__and__

    for i in range(n):
        inputX, inputY = rr(x), rr(y)
        b = max(0, inputX - z)
        t = min(inputX + z, x)
        l = max(0, inputY - z)
        r = min(inputY + z, y)
        for i in range(b, t):
            rows[i][l:r] = map(inc, rows[i][l:r])
    for i in range(x):
      rows[i] = map(sat, rows[i])

rawDescription: Python performance: iteration and operations on nested lists


code:
l_max=[1,2,3]
a=l_max[:] # create copy
b=a[:]
c=b[:]
s=c[:]
s.insert(0, 0) # insert only into s

rawDescription: python: list.insert: Insert an item at a given position

description: Python: list.insert: Insert an item at a given position


code: MAP_BTW_REGIME_KLANT_TOPACCOUNT = {1: 'L3', 2: 'C', 3: 'I', 4: 'E'}

rawDescription: Using a map to return something specific


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

x = np.arange(10)
y = np.arange(10) * 0.1

mask1 = y < 0.5
mask2 = y >= 0.5

plt.bar(x[mask1], y[mask1], color = 'red')
plt.bar(x[mask2], y[mask2], color = 'blue')
plt.show()

rawDescription: Color matplotlib bar chart based on value


code:
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)

rawDescription: python 3 directed graph with labels from file

description: Python 3 directed graph with labels from file


rawDescription: Search in a python list

description: Search in a python list


code: cleaned = filter(None, map(str.strip, words))

rawDescription: Python - are there other ways to apply a function and filter in a list comprehension?


code:
users = df.groupby('buyer_id').apply(lambda r: r['item_id'].unique().shape[0] > 1 and
                                               r['date'].unique().shape[0] > 1 )*1
df.set_index('buyer_id', inplace=True)
df['good_user'] = users

rawDescription: how to groupby pandas dataframe on some condition

description: Groupby pandas dataframe on some condition


code: df = pd.DataFrame([flatten(t) for t in tweets])

rawDescription: Manipulate Pandas DataFrame containing dictionaries from Twitter API


code:
def checkclas(x):
    while x not in ("A", "B", "C"):
        x = raw_input("You have to choose one of the three classes: ").upper()
    return x

clas = raw_input("which class are you in? ").upper()
clas = checkclas(clas)
print (clas)

rawDescription: How to use a shortcut for the (or) statement in python

description: Use a shortcut for the (or) statement in python


code:
def trigger(df):

    def min_y(d):
        return d[d['bool'] == 'y'].date.min()

    dt = df.groupby('Group').apply(min_y)
    dt = DataFrame(dt, columns=['trigger_date']).reset_index()
    ix = df.index.copy(deep=True)
    df = df.merge(dt, how='left', on='Group')
    ser = df['trigger_date']
    ser.index = ix
    return ser

rawDescription: Assigning a column for a modified dataframe back to original dataframe in pandas


code:
from operator import attrgetter

srt = sorted(twitter_users.values(), key=attrgetter('mentioned'))

rawDescription: Why is my list not sorted as expected?

description: Why is my list not sorted as expected


code:
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Visible = True
Path = "C:\\Program Files\\Microsoft Office\\Office14\\XLSTART\\perso.xlsm"
xl.Workbooks.Open(Filename=Path)
param1 = "Jeremy"
param2 = 3
xl.Application.Run("Proc", param1, param2)

rawDescription: Call a macro with parameters : Python win32com API


code:
np.atleast_2d(b).T
A = np.arange(25).reshape(5,5)
np.atleast_2d(A).T

rawDescription: Is it possible to use einsum to transpose everything?


code:
def try_match(m, re_match=re.compile(r'sldkjlsdjf').match):
    return re_match(m)

rawDescription: How to maintain state in Python without classes?

description: Maintain state in Python without classes


code: diff = [left-right for left, right in zip(angles, angles[1:]+angles[:1])]

rawDescription: How to compare the last index to the first in a list whilst iterating, or looping

description: Compare the last index to the first in a list whilst iterating, or looping


code:
n_rows = len(x)
n_cols = max(map(len, x))

new_array = np.empty((n_rows, n_cols))
new_array.fill(-1)
for i, row in enumerate(x):
    for j, ele in enumerate(row):
        new_array[i, j] = ele

rawDescription: 2D list to numpy array, and fill remaining values of shorter sublists with -1


rawDescription: Convert String of Hex and Ints to List in Python


code:
def my_function(my_dict, name):
    return next((value[1] for value in my_dict.values() if value[0]==name), None)

my_function(names_dict, 'Temperature')
my_function(names_dict, 'SP')

rawDescription: Retrieving value from this dictionary of tuples


code:
#!/usr/bin/python
from twisted.scripts.twistd import run
from sys import argv
argv[1:] = [
    '-y', 'myapp.py',
    '--pidfile', '/var/run/myapp.pid',
    '--logfile', '/var/run/myapp.log'
]
run()

rawDescription: Twisted application without twistd

description: Twisted application without twistd


rawDescription: Regex - Replacing a matching subgroup

description: Regex - Replacing a matching subgroup


code:
class User(ndb.Model):
    username = ndb.StringProperty(required = True)
    password = ndb.StringProperty(required = True)
    email = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add = True)

class Blog(ndb.Model):
    title = ndb.StringProperty(required = True)
    body = ndb.TextProperty(required = True)
    created = ndb.DateTimeProperty(auto_now_add = True)
    author = ndb.KeyProperty(required = True)

def new_blog(author):
    """Creates a new blog post for the given author, which may be a ndb.Key or User instance"""
    if isinstance(author, User):
        author_key = author.key
    elif isinstance(author, ndb.Key):
        assert author.kind() == User._get_kind()  # verifies the provided ndb.Key is the correct kind.
        author_key = author

    blog = Blog(title="title", body="body", author=author_key)
    return blog

rawDescription: Assigning an author to an entity during its creation


code:
from matplotlib.dates import AutoDateFormatter, AutoDateLocator

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)
xtick_formatter.scaled[30.] = '%d %b'
xtick_formatter.scaled[1.] = '%d %b'
xtick_formatter.scaled[1/24.] = '%d/%m %H:%M'
xtick_formatter.scaled[1/(24.*60.)] = '%d/%m %H:%M'
xtick_formatter.scaled[1/(24.*60.*60.)] = '%d/%m %H:%M:%S'
ax_av.xaxis.set_major_locator(xtick_locator)
ax_av.xaxis.set_major_formatter(xtick_formatter)

rawDescription: How to reduce xticks label resolution when showing clock time

description: Reduce xticks label resolution when showing clock time


code:
reader = csv.DictReader(open('MyFile.csv'))
#you might want to get rid of the intermediate list if the file is really big.
data = numpy.array(list(d.values() for d in pre_process(reader)))

rawDescription: How to convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics?

description: Convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics


code:
myId1 = wx.NewId()
myId2 = wx.NewId()
wx.StaticText(self.panel, id=myId1, label='test', pos=(10, 30))
wx.StaticText(self.panel, id=myId2, label='test', pos=(10, 60))

rawDescription: How can I change label of statictext without naming it

description: Change label of statictext without naming it


rawDescription: Python decimal range() step value

description: Python decimal range() step value


code:
with open(file_name) as f:
    lines_list = [line.strip() for line in f]

rawDescription: Python: list items are not changed in for loop


code:
parser = et.XMLParser(remove_blank_text=True)
xml = et.parse("test.xml",parser)

xml.find(".//attributes/transpose").append(et.fromstring('<octave-change>-1</octave-change>'))
xml.write('test.xml', pretty_print=True)

rawDescription: How to add a new Element to a musicXML tree in Python (elementtree)?

description: Add a new Element to a musicXML tree in Python (elementtree)


code:
class DLVRAdmin(admin.ModelAdmin):
    list_display = ['sett_type', 'sett_num']
    search_fields=['sett_num','sett_type__stt_typ_name']

rawDescription: How can implement foreign key in admin and model


code:
input_args = inspect.getargvalues(inspect.currentframe())[3]
logging.debug('Input to this function = %s', repr(input_args).replace('\n', ''))

rawDescription: How to print numpy objects without line breaks

description: Print numpy objects without line breaks


code:
list_of_lists = []
for sublist in L:
    list_of_lists.append(list(sublist))

iterator = iter(L)
for i in range(0,iterator.__length_hint__()):
    return list(iterator.next())
    # Or yield list(iterator.next()) if you want lazy evaluation

rawDescription: Python list index splitting and manipulation


code:
class Television: #all python3 classes inherit from object
        def __init__(self, volume = 0, channel = 0):
                self.volume = volume
                self.channel = channel

        def setVolume(self, volume): #reference to instance as first arg
                if not 0 <= volume <= 100:
                        print('Volume out of bounds.')
                        return #return without setting member
                self.volume = volume #setting member

        def setChannel(self, channel):
                if not 0 <= channel<= 100:
                        print('Channel out of bounds.')
                        return
                self.channel = channel

        def __str__(self): #for printing it
                return 'Volume is {} and channel is {}.'.format(self.volume, self.channel)

tv = Television() #calling init

while True:
        choice = input('''YO TV

0 - Turn off TV
1 - TV status
2 - Change channel
3 - Change volume
''')
        if choice == '0': break
        if choice == '1':
                print(tv) #calling __str__
                continue
        if choice == '2':
                tv.setChannel(int(input('New channel: ')))
                continue
        if choice == '3':
                tv.setVolume(int(input('New volume: ')))
                continue
        print('Unkown command.')

rawDescription: how to make a proper object?

description: Make a proper object


code:
import urlparse
parsed_url = urlparse.urlparse(url)
number1 = parsed_url.path.split("/")[-1]
number2, number3 = urlparse.parse_qs(parsed_url.query)["t:ac"][0].split("/")
number1, number2, number3

rawDescription: split url by python

description: Split url by python


code: 'Let/NNP the/DT sizes/NNS be/VB denoted/VBN by/IN $s(n)$/NNP and/CC $t(n)$/NNP respectively./NNP'

rawDescription: chunk NP and VP using nltk

description: Chunk NP and VP using nltk


code:
import numpy as np
import visvis as vv
app = vv.use()

f = vv.clf()
a = vv.cla()

angle = np.linspace(0, 6*np.pi, 1000)
x = np.sin(angle)
y = np.cos(angle)
z = angle / 6.0
vv.plot(x, y, z, lw=10)

angle += np.pi*2/3.0
x = np.sin(angle)
y = np.cos(angle)
z = angle / 6.0 - 0.5
vv.plot(x, y, z, lc ="r", lw=10)

app.Run()

rawDescription: Is there something like a depth buffer in matplotlib?


code: char, value  = line.split()[:2]

rawDescription: Writing tabs in a specific way (Not from lists) in python


code:
s = "7A"
firstHex, secondHex = list(s)

rawDescription: Python string splitting

description: Python string splitting


code: new = old.rstrip('\n').rsplit('\n', 1)[0] + '\nNew line to be added with line break included.'

rawDescription: How do I efficiently replace the last line in a string?

description: Efficiently replace the last line in a string


code:
from myapp.views import CreateReport
url(r'^create_report/(?P<some_param_if_needed>[-\w]+)',
                       CreateReport.as_view(),
                       name='create_report'),

rawDescription: Download SQL data in xlsx format with Django


code:
import os
import signal

pid = '123'
name = 'pfinder'

pid_path = os.path.join('/proc', pid)
if os.path.exists(pid_path):
    with open(os.join(pid_path, 'comm')) as f:
        content = f.read().rstrip('\n')

    if name == content:
         os.kill(pid, signal.SIGTERM)

rawDescription: Get the process name by pid

description: Get the process name by pid


code:
foo = IndexingList([{ 'id': 1, 'name': 'cat' }, { 'id': 2, 'name': 'dog' }])
foo[0]
foo.find_all("id", 2)
foo += [{'id': 3, 'name': 'dog'}]
foo.find_all('name', 'dog')

rawDescription: Python list class that indexes its object-elements' properties


code:
df['tick'] = np.where(df.vols < .05, df.index, pd.tslib.NaT)
df

rawDescription: In python/pandas how to search for nearest value?


code:
class StudentDetail(generics.RetrieveAPIView):
    serializer_class = PersonSerializer

    def get_object(self):
        student_id = self.kwargs.get('pk', None)
        return Student.objects.get(pk=student_id)

rawDescription: Consuming api from django rest framework


code:
import pandas
dt = pandas.DatetimeIndex(periods=10, start='2014-02-01', freq='10T')
dt.format(formatter=lambda x: x.strftime('%Y    %m    %d  %H:%M.%S'))

rawDescription: How to "pretty print" a python pandas DatetimeIndex


code:
def drawBar(t, height):
    if height >= 50:
        t.fillcolor("blue")
    elif height < 50 and height >= 30:
        t.fillcolor("yellow")
    else:
        t.fillcolor("red")

    t.begin_fill()
    t.left(90)
    t.forward(height)
    t.write('  '+ str(height))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height)
    t.left(90)
    t.end_fill()

rawDescription: Conditional if statements based on items in a list with python 3.x


code:
import pygame
pygame.init()

RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)
colors = (RED, BLACK, BLUE) # tho allow you to iterate over the colors

for c in colors:
    pygame.draw.circle(screen,c,(500,500),200)
    pygame.display.flip()
    pygame.time.wait(1000)
pygame.quit()

rawDescription: Basic Pygame Graphics

description: Basic Pygame Graphics


rawDescription: Python date parsing from Amazon EC2 EBS

description: Python date parsing from Amazon EC2 EBS


code:
import numpy as np
np.random.seed(2015)

m, n = 10, 5
A = np.random.randint(10, size=(m,3))
B = A[np.random.choice(m, n, replace=False)]
print(A)
# [[2 2 9]
#  [6 8 5]
#  [7 8 0]
#  [6 7 8]
#  [3 8 6]
#  [9 2 3]
#  [1 2 6]
#  [2 9 8]
#  [5 8 4]
#  [8 9 1]]

print(B)
# [[2 2 9]
#  [1 2 6]
#  [2 9 8]
#  [3 8 6]
#  [9 2 3]]

def using_view(A, B, assume_unique=False):
    Ad = np.ascontiguousarray(A).view([('', A.dtype)] * A.shape[1])
    Bd = np.ascontiguousarray(B).view([('', B.dtype)] * B.shape[1])
    return ~np.in1d(Ad, Bd, assume_unique=assume_unique)

print(using_view(A, B, assume_unique=True))

rawDescription: Matrix row difference, output a boolean vector


code:
import time
while True:
    putMessageToScreen()
    time.sleep(25*60)

rawDescription: Automatically update stored value of datetime.datetime.now()


code:
li = ['0', ['1', '2'], ['3', ['4', '5'], '6', ['7'], '8'], '9']
def to_int(lst, path=[]):
    for i, j in enumerate(lst):
        if isinstance(j, list):
            yield list(to_int(j, path+[i]))
        else:
            yield int(j), path+[i]

print(list(to_int(li)))

rawDescription: Working on multilevel list (2)

description: Working on multilevel list (2)


code:
Larr = np.array(L)
Larr[:,None]
Larr[None, :]

rawDescription: Python - list of same columns / rows from matrix


rawDescription: "Group By" multiple columns on Large Data in HDFStore


rawDescription: Grouping elements according to a single value


code:
def get_unused_chars(mystring):
    # Generate the list of every valid ASCII character
    all_chars = set(chr(i) for i in range(256))

    # Determine which characters are unused
    unused_chars = all_chars - set(mystring)

    return unused_chars

rawDescription: Get all chars not in string python

description: Get all chars not in string python


code: uniqueList = list(set(myList))

rawDescription: How to count similar domains in emails and print every domain only once[python]?

description: Count similar domains in emails and print every domain only once[python]


code: x = [wr.take(setSize) for j in range(numSets)]

rawDescription: Unique value in nested list - random

description: Unique value in nested list - random


code:
@app.route('/profile/<username>')
def profile(username):
    twitter_api = oauth_login()
    profiles = get_user_profile(twitter_api, screen_names=(username,))
    profile = profiles.get(username)

    if profile is None:
        abort(404)

    return render_template('profile.html', profile=profile)

rawDescription: Get Twitter profile to display in template


code:
class Employee(models.Model):
    # some fields and relationships
    objects = CurrentCompanyManager("section__company")

class Accounts(models.Model):
    # some fields and relationships
    objects = CurrentCompanyManager("customer__company")

rawDescription: Django: limiting model data

description: Django: limiting model data


rawDescription: Create unique ID from the existing two columns, python


code:
import theano
import theano.tensor as T

AA = T.tensor3()
BB = T.imatrix()

CC = AA[T.arange(AA.shape[0]).reshape((-1, 1)), T.arange(AA.shape[1]), BB]

f = theano.function([AA, BB], CC)

f(A.astype(theano.config.floatX), B)

rawDescription: Indexing tensor with index matrix in theano?


rawDescription: python getting weekday from an input date

description: Python getting weekday from an input date


code:
import itertools
import bisect

def sub_helper(cur_i, combo, all_options):
    #cur_i is the index of the letter in the subsequence
    #cur_idx is the index of the sequence which contains that letter
    if cur_i>0:
        prev_i = combo[cur_i-1]
    else:
        prev_i = -1
    cur_options = all_options[cur_i]
    start_i = bisect.bisect(cur_options,prev_i)
    cur_i_gen = itertools.islice(cur_options,start_i,None)
    if cur_i+1 == len(all_options): #last one:
        for cur_idx in cur_i_gen:
            combo[cur_i] = cur_idx
            yield tuple(combo)
    else:
        for cur_idx in cur_i_gen:
            combo[cur_i] = cur_idx
            yield from sub_helper(cur_i+1, combo, all_options)

def sub_sequence_generator(sequence,sub_seq):
    indices_map = {c:[] for c in set(sub_seq)} #create a list for each character
    for i,c in enumerate(sequence):
        try:
            indices_map[c].append(i,) #the helper is simpler if they are all stored as single element tuples
        except KeyError:
            pass

    # now we have indices for each character of the sub_sequence
    # we just need to put them in a sequence that corelates to the subsequence
    chr_indices = tuple(indices_map[c] for c in sub_seq)

    return sub_helper(0,[None]*len(chr_indices), chr_indices)

sequence = "abccabac"
subsequence = "abc"

for idxs in sub_sequence_generator(sequence,subsequence):
    print(idxs)

rawDescription: Python: Sub sequence search

description: Python: Sub sequence search


code:
for game in (x for x in list_of_games if x.name=='stuff'):
    print_score(game)

rawDescription: SQLAlchemy Query Possible?

description: SQLAlchemy Query Possible


code:
import matplotlib.pyplot as plt
d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1}

plt.bar(range(len(d)), d.values(), align='center')
plt.xticks(range(len(d)), d.keys(), rotation=25)

rawDescription: ipython pylab: print histogram from dictionary

description: Ipython pylab: print histogram from dictionary


code:
def by_three(n): return False if n % 3 else cube(n)

def cube(n): return n**3

by_three(11)
by_three(12)
by_three(13)

rawDescription: Strange multiple return values in Python


rawDescription: Python, transposing a list and writing to a CSV file


rawDescription: Rounding a number in python but keeping ending zeros


code:
while running:
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

rawDescription: python to arduino serial read & write

description: Python to arduino serial read & write


code:
class A(object):
    pass

rawDescription: how does django set up object method before it was defined

description: How does django set up object method before it was defined


code:
seq_iter= iter( something.get() )
head = seq_iter.next()
root.copy( head )
foo( head )
for member in seq_iter:
    somewhereElse.copy( member )
    foo( member )

rawDescription: "For" loop first iteration

description: "For" loop first iteration


code:
url = 'https://raw.githubusercontent.com/108michael/ms_thesis/master/SIC2CRPCats.csv'
df = pd.read_csv(url, engine='python', sep=r'\s{2,}', encoding='utf-8_sig')

url='https://raw.githubusercontent.com/108michael/ms_thesis/master/test.merge'
merged = pd.read_csv(url, index_col=0)

# clearing data
merged.SICcode = pd.to_numeric(merged.SICcode, errors='coerce')

mrg = df.merge(merged, on='SICcode', how='left')

mrg.head()

rawDescription: Pandas: dataframes won't merge

description: Pandas: dataframes won't merge


code:
F = np.array([[33, 250, 196, 136, 32], [55, 293, 190, 71, 13]])
chi2, p, dof, expected = chi2_contingency(F)
residuals(F, expected)
stdres(F, expected)

rawDescription: What is the equivalent of R data.chisq$residuals in python?


code: out = resp.split(';')

rawDescription: Python splitting values from urllib in string


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

# create a bit more realistic-looking data
# - looks complicated, but just has a constant switch-off and switch-on probabilities
#   per column
# - the result is a 20 x 500 array of booleans
p_switchon = 0.02
p_switchoff = 0.05
data = np.empty((20,500), dtype='bool')
data[:,0] = np.random.random(20) < .2
for c in range(1, 500):
    r = np.random.random(20)
    data[data[:,c-1],c] = (r > p_switchoff)[data[:,c-1]]
    data[-data[:,c-1],c] = (r < p_switchon)[-data[:,c-1]]

# create some labels
labels = [ "label_{0:d}".format(i) for i in range(20) ]

# this is the real plotting part
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data, aspect='auto', cmap=plt.cm.gray)
ax.set_yticks(np.arange(len(labels)))
ax.set_yticklabels(labels)

rawDescription: Matplot: How to plot true/false or active/deactive data?


code:
def tag_last(iterable):
    """Given some iterable, returns (last, item), where last is only
    true if you are on the final iteration.
    """
    iterator = iter(iterable)
    gotone = False
    try:
        lookback = next(iterator)
        gotone = True
        while True:
            cur = next(iterator)
            yield False, lookback
            lookback = cur
    except StopIteration:
        if gotone:
            yield True, lookback
        raise StopIteration()

rawDescription: How to check if an item is the last one of iteration in python

description: Check if an item is the last one of iteration in python


code:
param1 = ""
param2 = ""
def addparams():
    global param1
    global param2
    typeans = ['parameter 1', 'param 1']
    typeansa = ['parameter 2', 'param 2']
    while True:
        again = raw_input('Would you like to add another parameter? Enter y/n: ')
        if again == "n":
            break
        if again == "y":
            additionalparams = raw_input("Would you like to add any other parameters? (Parameter 1, Parameter 2): ")
            if additionalparams.lower() in typeans:
                param1 = raw_input('Please enter the first search criteria: ')
                param1 = param1+"one"
            elif additionalparams.lower() in typeansa:
                param2 = raw_input('Please enter the second search criteria: ')
                param2 = param2+"two"

rawDescription: Updating empty variables outside a function


code:
from nltk.corpus import wordnet as wn
wn.synsets('car')[0].root_hypernyms()
wn.synsets('love')[0].root_hypernyms()
wn.synsets('love', 'v')[0].root_hypernyms()

rawDescription: NLTK WordNet verb hierarchy

description: NLTK WordNet verb hierarchy


rawDescription: how can I covert this to a matrix

description: Covert this to a matrix


code: csv.reader(..., escapechar='\\')

rawDescription: python csv reader not handling quotes

description: Python csv reader not handling quotes


code:
ctags -R
ctags --append -R /path/to/python-source/Lib

rawDescription: ctags info for built-in functions in PHP/Python/Etc

description: Ctags info for built-in functions in PHP/Python/Etc


code:
class Person:
    def PersonWalk(self):
        ...

rawDescription: What are the character limitations to Django model's related_name in a relationship?


code:
from __future__ import print_function

import random as r

UPTO = 100

def main():
    # use a step of 10
    for i in range(0, UPTO, 10):
        # sep="" will leave no spaces between, end="" removes newline
        print(*(r.randint(0, 9) for _ in range(10)), end="", sep="")
        print()

rawDescription: python line break by 10 elements

description: Python line break by 10 elements


code: myfunc(*['abc']*n)

rawDescription: Inputing an identical string multiple times to a function


code:
df
fn = r'D:\temp\.data\out.csv'
df.to_csv(fn, index=False, sep='\t', float_format='%.6f')

rawDescription: convert scientific notation to decimal pandas python

description: Convert scientific notation to decimal pandas python


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

R=input('enter the rate of rainfall in mm/hr ')
#D=np.linspace(0.2,6,30)
D = np.arange(0.2,6,0.5)

n=0.08
l=41*pow(R,(-0.21))
N=n*np.exp(-l*D)

plt.plot(D,N)
plt.xlim(0.2,6)
plt.gca().set_xticks(D) # This

plt.show()

rawDescription: Unable to handle linspace properly

description: Unable to handle linspace properly


code:
import datetime as DT
text = '07/20-10:38:04.360700'
date = DT.datetime.strptime('2014/'+text, '%Y/%m/%d-%H:%M:%S.%f')
(date - DT.datetime(1970,1,1)).total_seconds()

rawDescription: DateTime Conversion to Epoch Time

description: DateTime Conversion to Epoch Time


code:
flow
flow
flow

rawDescription: Dynamically creating a menu in Tkinter. (lambda expressions?)


code:
a = {}

for row in reader:
    a.setdefault(row[0], {}).setdefault(row[1], 0)
    a[row[0]][row[1]] += 1

rawDescription: Update dictionary while parsing CSV file


code:
for student in student_list:
    print_gender(student)

rawDescription: Is this code simplified? Should I use more functions?


code: decision = df["condition"] | (np.sign(df["x1"]) != np.sign(df["y1"]))

rawDescription: Applying function to each row of pandas data frame - with speed


rawDescription: Python Type Conversion

description: Python Type Conversion


code: del A

rawDescription: Understanding reference count of class variable


code:
for i, j in zip(long_str[::2], long_str[1::2]):
  print (i+j)

rawDescription: Getting two characters from string in python


rawDescription: Sorting all rows in numpy matrix by target-column


code:
with open('abc') as f, open('out.txt','w') as f2:
    seen = False                         #initialize `seen` to False
    for line in f:        #iterate over each line in f
        spl = line.split()               #split the line at  whitespaces
        if seen:                         #if seen is True then :
            spl[1] = '10'                   #set spl[1] to '10'
            seen = False                    #set seen to False
            line = " ".join(spl) + '\n'     #join the list using `str.join`
        elif not seen and spl[1] == '2': #else if seen is False and spl[1] is '2', then
            seen = True                     #set seen to True
        f2.write(line)                   #write the line to file

rawDescription: modifying a text file containing array with python

description: Modifying a text file containing array with python


rawDescription: How would I run numbers through a list in python?


code:
import operator
import itertools
import re
import math
import functools
import logging
logger = logging.getLogger(__name__)

zip_longest = itertools.izip_longest

def tableinfo(rows,
              sep = u'─',
              corner = u'·',
              delim = None,
              corner_delim = None,
              prefix = u'│ ',
              postfix = u' │',
              colsep = u' │ ',
              has_header = False,
              header = None,
              separate_rows = False,
              framed = (True, True),
              separate_empty_lines = True,
              justify = 'right',
              wrapfunc = lambda x:x,
              width = None,
              phantom = None,
              **kw):
    # Based on: http://code.activestate.com/recipes/267662-table-indentation/
    # Author: http://code.activestate.com/recipes/users/2591466/ (George Sakkis)
    def row_wrapper(row):
        try:
            new_rows = [wrapper(item).split('\n') for (item, wrapper)
                        in zip(row, wrapfunc)]
        except TypeError:
            # This happens if wrapfunc is not an iterator
            # TypeError: zip argument #2 must support iteration
            new_rows = [wrapfunc(item).split('\n') for item in row]
        return list(zip_longest(*new_rows, fillvalue = u''))
    if header:
        has_header = True
        rows = itertools.chain(normalize([header]), rows)
    logical_rows = [row_wrapper(row) for row in rows]
    columns = zip(*functools.reduce(operator.add, logical_rows))
    max_width = (
        [max(len(item) for item in column) for column in columns]
        if width is None else width )
    if phantom is not None:
        max_width = [max(x) for x in zip(phantom, max_width)]
    lcorner = corner + sep*(len(prefix)-1) if len(prefix) >= 1 else u''
    rcorner = sep*(len(postfix)-1) + corner if len(postfix) >= 1 else u''

    delim = itertools.repeat(colsep) if delim is None else itertools.cycle(delim)
    corner_delim = (delim_to_corner(delim, sep, corner)
                  if corner_delim is None else itertools.cycle(corner_delim))
    row_separator = (sep*w for w in max_width)
    row_separator = (lcorner
                     +''.join(list(iterjoin(corner_delim, row_separator)))
                     +rcorner)
    dispatch = {'center':unicode.center, 'right':unicode.rjust, 'left':unicode.ljust}
    try: justify = itertools.cycle([dispatch[item] for item in justify])
    except KeyError: justify = itertools.repeat(dispatch[justify.lower()])
    result = []
    for physical_rows in logical_rows:
        row_result = []
        for row in physical_rows:
            if separate_empty_lines and not ''.join(row).strip():
                row_result.append(row_separator)
            else:
                pieces = [justifier(item, w) for (item, w, justifier)
                        in zip(row, max_width, justify)]
                row_result.append(
                    prefix
                    + u''.join(list(iterjoin(delim, pieces)))
                    + postfix )
        result.append(u'\n'.join(row_result))
        if has_header and not separate_rows:
            result.insert(1, row_separator)
            has_header = False
    joiner = u'\n'+row_separator+u'\n' if separate_rows else u'\n'
    result = joiner.join(result)
    top_framed, bottom_framed = framed
    if top_framed: result = row_separator+u'\n'+result
    if bottom_framed: result = result+u'\n'+row_separator
    return result, max_width

def iterjoin(sep, it):
    sep = itertools.cycle(sep)
    it = iter(it)
    yield next(it)
    for a, b in zip(it, sep):
        yield b
        yield a

def normalize(rows):
    new_rows = []
    for row in rows:
        new_rows.append([unicode(elt).expandtabs() for elt in row])
    return new_rows

def delim_to_corner(delim, sep, corner):
    for d in delim:
        d = d.replace(u'│', corner).replace(u'|', corner)
        for c in '< >': d = d.replace(c, sep)
        yield d

def wrap_onspace(text, width):
    # written by Mike Brown
    # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
    '''
    A word-wrap function that preserves existing line breaks
    and most spaces in the text. Expects that existing line
    breaks are posix newlines (\n).
    '''
    words = iter(text.split(' '))
    line = next(words)
    for word in words:
        contemplated_width = (len(line[line.rfind('\n')+1:]) +
                              len(word.split('\n', 1)[0]))
        if contemplated_width >= width:
            line += '\n'+word
        else:
            line += ' '+word
    return line

def wrap_onspace_strict(text, width):
    '''Similar to wrap_onspace, but enforces the width constraint:
       words longer than width are split.'''
    word_pat = re.compile(r'\S{'+unicode(width)+r',}')
    return wrap_onspace(word_pat.sub(lambda m: wrap_always(m.group(), width), text),
                        width)

def wrap_always(text, width):
    '''A simple word-wrap function that wraps text on exactly width characters.
       It doesn\'t split the text in words.'''
    return '\n'.join( text[width*i:width*(i+1)]
                       for i in xrange(int(math.ceil(1.*len(text)/width))) )

def onspace(width):
    return functools.partial(wrap_onspace, width = width)

def strict(width):
    return functools.partial(wrap_onspace_strict, width = width)

def always(width):
    return functools.partial(wrap_always, width = width)

def table(rows,
          sep = u'─',
          corner = u'·',
          delim = None,
          corner_delim = None,
          prefix = u'│ ',
          postfix = u' │',
          has_header = False,
          header = None,
          separate_rows = False,
          framed = (True, True),
          separate_empty_lines = True,
          justify = 'right',
          wrapfunc = lambda x:x,
          width = None,
          **kw):
    '''
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │                 rows │ A sequence of sequences of items, one sequence per row. │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │               framed │ row separator on top and bottom                         │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │                  sep │ Character to be used for the row separator line (if     │
    │                      │ has_header==True or separate_rows==True).               │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │                delim │ A sequence of column delimiters. The delimiters are     │
    │                      │ repeated in a cycle                                     │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │         corner_delim │ A sequence of column delimiters used in row separators, │
    │                      │ repeated in a cycle.                                    │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │               prefix │ A string prepended to each printed row.                 │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │              postfix │ A string appended to each printed row.                  │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │           has_header │ True if there is a row separator between the first and  │
    │                      │ second row                                              │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │        separate_rows │ True if all rows are to be separated                    │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │               framed │ True if top (and/or bottom) have a row separator        │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │ separate_empty_lines │ replace empty lines with a row separator                │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │              justify │ Determines how the data is justified in each column.    │
    │                      │ Valid values are 'left','right' and 'center', or a list │
    │                      │ of such values (one element per column).                │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │             wrapfunc │ A function f(text), or list of functions, for wrapping  │
    │                      │ text; each element in the table is first wrapped by     │
    │                      │ this function. If wrapfunc is a list of functions, then │
    │                      │ table will apply one function per column.               │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    │               width  │ A list of column widths. If None, the widths will be    │
    │                      │ calculated.                                             │
    ·──────────────────────·─────────────────────────────────────────────────────────·
    '''
    result, max_width = tableinfo(
        normalize(rows), sep = sep, corner = corner, delim = delim,
        corner_delim = corner_delim,
        prefix = prefix, postfix = postfix, has_header = has_header, header = header,
        separate_rows = separate_rows, framed = framed,
        separate_empty_lines = separate_empty_lines, justify = justify,
        wrapfunc = wrapfunc, width = width)
    return result

def ascii_table(rows,
          sep = '-',
          corner = '+',
          delim = [' | '],
          corner_delim = None,
          prefix = u'| ',
          postfix = u' |',
          has_header = False,
          header = None,
          separate_rows = False,
          framed = (True, True),
          separate_empty_lines = True,
          justify = 'right',
          wrapfunc = lambda x:x,
          width = None,
          **kw):
    result, max_width = tableinfo(
        normalize(rows), sep = sep, corner = corner, delim = delim,
        corner_delim = corner_delim,
        prefix = prefix, postfix = postfix, has_header = has_header, header = header,
        separate_rows = separate_rows, framed = framed,
        separate_empty_lines = separate_empty_lines, justify = justify,
        wrapfunc = wrapfunc, width = width)
    return result

rawDescription: How to print a MySQLdb unicode result in human readable way

description: Print a MySQLdb unicode result in human readable way


code:
class MyConnectionPlugin(object):
  def __init__(self, *args, **kw):
    super(MyConnectionPlugin, self).__init__(*args, **kw)
    # etc etc -- rest of initiatizations, other methods

class SecureConnection(MyConnectionPlugin,
                       httplib.HTTPSConnection, object):
  pass

class PlainConnection(MyConnectionPlugin,
                      httplib.HTTPConnection, object):
  pass

def ConnectionClass(secure):
  if secure:
    return SecureConnection
  else:
    return PlainConnection

conn = ConnectionClass(whatever_expression())()

rawDescription: Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection


code:
list4sets = [set(L) for L in list4]
list4flat = [el for lst in list4sets for el in lst]
term = {el: list4flat.count(el) for el in list4flat}
term['apples']
term['oranges']

rawDescription: Counting the number of lists that contain an element in Python


code:
bool("False")
bool("")
print(json.dumps(u'\u0411', ensure_ascii="False"))
print(json.dumps(u'\u0411', ensure_ascii=False))

rawDescription: Output utf-8 characters in django as json


code: print("Randy's phone # is {}".format(people['Randy']['phone']))

rawDescription: Accessing nested dictionary items in Python


code:
big_keys = dct.keys()
small_keys = (dct[big_key].keys() for big_key in big_keys)
list(itertools.product(*small_keys))

rawDescription: Concatenation of a variant number of keys of a dictionary Python (recursion?)


rawDescription: Schedule a repeating event in Python 3

description: Schedule a repeating event in Python 3


code:
user = db.get('aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM')
que = user.Portfolio_Owners_set

rawDescription: Gql Query on ReferenceProperty()

description: Gql Query on ReferenceProperty()


code:
import test
test.putAll(b"hello world")
assert test.getAll() == b"hello world"
test.putAll(bytearray(b"another string"))
test.putAll([1, 2, 3, 255])

rawDescription: How to pass Python list to C function using Cython

description: Pass Python list to C function using Cython


code:
def a(a, b, c):
    z = 5
    print(len(locals()))

rawDescription: Check the number of parameters passed in Python function


rawDescription: plotting & formatting seaborn chart from pandas dataframe

description: Plotting & formatting seaborn chart from pandas dataframe


code:
class pick(models.Model):
    id_hash = models.TextField(default="")
    symbol = models.CharField(max_length=5)
    buy_datetime = models.DateTimeField()
    buy_price = models.DecimalField(max_digits=8, decimal_places=2)
    sell_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
    buy_quantity = models.IntegerField()
    current_price = models.DecimalField(max_digits=8, decimal_places=2)
    def hash(self):
        return hashlib.md5(str(self.id)).hexdigest()
    def __str__(self):
        return "{} {} {} {} {} {}".format(self.symbol,self.buy_datetime,self.buy_price,self.sell_price,self.buy_quantity, self.current_price)

    def save(self, *args, **kwargs):
        with transaction.atomic():
            super().save(*args, **kwargs)
            # for python < 3.0 super(pick, self).save(*args, **kwargs)
            self.id_hash = self.hash()
            super().save(*args, **kwargs)
            # for python < 3.0 super(pick, self).save(*args, **kwargs)

rawDescription: How do you access the id of a Django model inside the model object?

description: Access the id of a Django model inside the model object


code:
class InterpolatedArray(object):
    """ An array-like object that provides interpolated values between set points.
    """
    points = None
    wrap_value = None
    offset = None

    def _mod_delta(self, a, b):
        """ Perform a difference within a modular domain.
            Return a value in the range +/- wrap_value/2.
        """
        limit = self.wrap_value / 2.
        val = a - b
        if val < -limit: val += self.wrap_value
        elif val > limit: val -= self.wrap_value
        return val

    def __init__(self, points, wrap_value=None):
        """Initialization of InterpolatedArray instance.

        Parameter 'points' is a list of two-element tuples, each of which maps
        an input value to an output value.  The list does not need to be sorted.

        Optional parameter 'wrap_value' is used when the domain is closed, to
        indicate that both the input and output domains wrap.  For example, a
        table of degree values would provide a 'wrap_value' of 360.0.

        After sorting, a wrapped domain's output values must all be monotonic
        in either the positive or negative direction.

        For tables that don't wrap, attempts to interpolate values outside the
        input range cause a ValueError exception.
        """
        if wrap_value is None:
            points.sort()   # Sort in-place on first element of each tuple
        else:   # Force values to positive modular range
            points = sorted([(p[0]%wrap_value, p[1]%wrap_value) for p in points])
            # Wrapped domains must be monotonic, positive or negative
            monotonic = [points[x][1] < points[x+1][1] for x in xrange(0,len(points)-1)]
            num_pos_steps = monotonic.count(True)
            num_neg_steps = monotonic.count(False)
            if num_pos_steps > 1 and num_neg_steps > 1: # Allow 1 wrap point
                raise ValueError("Table for wrapped domains must be monotonic.")
        self.wrap_value = wrap_value
        # Pre-compute inter-value slopes
        self.x_list, self.y_list = zip(*points)
        if wrap_value is None:
            intervals = zip(self.x_list, self.x_list[1:], self.y_list, self.y_list[1:])
            self.slopes = [(y2 - y1)/(x2 - x1) for x1, x2, y1, y2 in intervals]
        else:   # Create modular slopes, including wrap element
            x_rot = list(self.x_list[1:]); x_rot.append(self.x_list[0])
            y_rot = list(self.y_list[1:]); y_rot.append(self.y_list[0])
            intervals = zip(self.x_list, x_rot, self.y_list, y_rot)
            self.slopes = [self._mod_delta(y2, y1)/self._mod_delta(x2, x1) for x1, x2, y1, y2 in intervals]

    def __getitem__(self, x):       # Works with indexing operator []
        result = None
        if self.wrap_value is None:
            if x < self.x_list[0] or x > self.x_list[-1]:
                raise ValueError('Input value out-of-range: %s'%str(x))
            i = bisect.bisect_left(self.x_list, x) - 1
            result = self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
        else:
            x %= self.wrap_value
            i = bisect.bisect_left(self.x_list, x) - 1
            result = self.y_list[i] + self.slopes[i] * self._mod_delta(x, self.x_list[i])
            result %= self.wrap_value
        return result

rawDescription: Circular interpolation in Python

description: Circular interpolation in Python


code:
from collections import Counter
cnt = Counter({3: 1575, 2: 1462, 6: 1359, 4: 1161, 5: 1159, 1: 868})
[cnt.keys(), cnt.values()]

rawDescription: Split the result of 'counter'

description: Split the result of 'counter'


code:
time.tzset()
time.tzname

rawDescription: Time issues in Python

description: Time issues in Python


code:
import json

def convert_to_bool(bstring):
    return True if bstring == b'\x00' else False

rawDescription: Jsonifying bits from MySQLdb in Python

description: Jsonifying bits from MySQLdb in Python


rawDescription: python- finding total number of items of certain range in a list

description: Python- finding total number of items of certain range in a list