code:
import sys

# Python 2/3 compatibility shim
if sys.hexversion >= 0x3000000:
    inp = input
    rng = range
else:
    inp = raw_input
    rng = xrange

def get_int(prompt):
    while True:
        try:
            return int(inp(prompt))
        except ValueError:
            pass

class Book:
    @classmethod
    def from_prompt(cls):
        title  = inp('Enter title: ').strip()
        author = inp('Enter author: ').strip()
        pages  = get_int('Page count: ')
        date   = inp('Publication date: ').strip()
        return cls(title, author, pages, date)

    def __init__(self, title, author, pages, date):
        self.title  = title
        self.author = author
        self.pages  = pages
        self.date   = date

    def __str__(self):
        return "Book: {title}\nAuthor: {author}\nPage count: {pages}\nPublish Date: {date}".format(
            title=self.title, author=self.author, pages=self.pages, date=self.date
        )

class Library:
    def __init__(self, books=None):
        self.books = []
        self.title_index = {}
        if books:
            for book in books:
                self.add(book)

    def add(self, book):
        self.books.append(book)
        self.title_index[book.title] = book

    def find_title(self, title):
        return self.title_index.get(title, None)

    def __str__(self):
        return '\n\n'.join(str(book) for book in self.books)

def main():
    #
    # You get to write this part,
    # but here are some code examples:
    #
    lib = Library()

    book1 = Book('Fun with Dick and Jane', 'May Hill Arbuthnot', 160, '1951')
    lib.add(book1)

    book2 = Book('The Adventures of Pinocchio', 'Carlo Collodi', 171, '1911')
    lib.add(book2)

    # prompt for book 3 information
    book3 = Book.from_prompt()
    lib.add(book3)

    # find a book and display its information
    print('='*30)
    print(lib.find_title('The Adventures of Pinocchio'))

    # display the whole library contents
    print('='*30)
    print(lib)

if __name__=="__main__":
    main()

rawDescription: Beginner-level virtual library program troubles, how do I let the user create an array or 'def'?


code:
lst = [123, 32, 434]
data = [{'a': k, 'b': v} for k, v in enumerate(lst, 1)]
data

rawDescription: convert simple list of numbers to JSON array

description: Convert simple list of numbers to JSON array


code:
con = mdb.connect('localhost', 'rsnape', '<my_password>', 'testdb');
with con:
    cur = con.cursor()
    cur.execute("SELECT * FROM Writers")
    rows = cur.fetchall()
    for row in rows:
        print(row)
with con:
    cur = con.cursor()
    cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s",
        ("Guy de Matis", "4"))
    print("number of rows",cur.rowcount)
with con:
    cur = con.cursor()
    cur.execute("SELECT * FROM Writers")
    rows = cur.fetchall()
    for row in rows:
        print(row)

rawDescription: Simple MYSQL Update in Python

description: Simple MYSQL Update in Python


code:
@task
@hosts('controller')
def run_script():
    run('/test/launch_process.sh')
    execute(check_ps, hosts=['client'])

rawDescription: Python Fabric : tricky ssh issue

description: Python Fabric : tricky ssh issue


code:
class Anaconda:

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

    def wriggle(self):
        self.python.wriggle()

    def devourCrocodile(self, croc):
        ...

    def __getattr__(self, name):
        return getattr(self.python, name)

rawDescription: Python: Should I use delegation or inheritance here?


code:
re.search('\s*\S+\s*', '   foo   ').group(0)
re.search('\s*\S+\s*', 'foo   ').group(0)
re.search('\s*\S+\s*', 'foo').group(0)

rawDescription: simple python regex

description: Simple python regex


code:
plt.plot(range(10), range(10))
plt.xlabel('To change it', fontsize=20)
plt.ylabel('To keep it', fontsize=20)
plt.gca().xaxis.get_label().set_fontsize(50)

rawDescription: Updating the fontsize only of title, xlabel or ylabel


code: df1.apply(lambda x: x.asof(df2.index))

rawDescription: KDB+ like asof join for timeseries data in pandas?


code:
username = name.split("_")[0]
description = name.split("_")[1]

rawDescription: Python-way of getting a substring with a specified delimiter?


code:
import sys, os
from collections import defaultdict

filenames = sys.argv[1:]

# collect like-named files
groups = defaultdict(set)
for filename in filenames:
    key = filename.split('.')[0].split("-")[0]
    groups[key].add(filename)

# work on each group
for names in groups.values():
    target_name = sorted(names)[0] # or min(names, key=len), or whatever
    largest_file = max(names, key=os.path.getsize)

    os.rename(largest_file, target_name)

    to_remove = names.difference((largest_file, target_name))
    for name in to_remove:
        os.remove(name)

rawDescription: batch delete smaller of two files

description: Batch delete smaller of two files


code:
worksheet.merge_range('B4:D4',    'Merged Range', merge_format)
worksheet.merge_range(3, 1, 3, 3, 'Merged Range', merge_format)

rawDescription: Merging Excel cells using Xlsxwriter in Python


code:
df = pd.DataFrame({"A": [1,1,2,3,2,4]})
df
df_a, df_b= df[~df.duplicated()], df[df.duplicated()]
df_a
df_b

rawDescription: separating data frames instead of dropping in pandas

description: Separating data frames instead of dropping in pandas


code:
elements = ['elem1','elem2','elem3']
output = ['prefix_{}'.format(i) for i, elem in enumerate(elements, 1)]
output

rawDescription: Create list of strings with fixed prefix based on size of a list


code:
from django.contrib import admin

class CommentAdmin(admin.ModelAdmin):
    # define which columns displayed in changelist
    list_display = ('text', 'name', 'date', 'article')
    # add filtering by date
    list_filter = ('date',)
    # add search field
    search_fields = ['text', 'article']

admin.site.register(Comment, CommentAdmin)

rawDescription: Django: show useful database data in admin interface?


rawDescription: PEP440 compliant AND git describe info available from deployed package


code:
def factor(a, b, c):
    low_value = min(a, b, c)
    high_value = max(a, b, c)
    for i in range(low_value, high_value):
        for j in range(low_value, high_value):
            for k in range(low_value, high_value):
                if i*k != a:
                    # check this clause earlier to improve speed a bit
                    continue
                for l in range(low_value, high_value):
                    if j*l != c:
                        continue
                    if (i*l) + (j*k) != b:
                        continue
                    return (i, j, k, l)
    return None

print("Factoring...")
solution = factor(1, 2, 4)
if solution:
    (i, j, k, l) = solution
    print("Your factored Equation is: (" + i + "x + " + j + ")" +
          "(" + k + "x + " + l + ")")
else:
    print("No solution can be found.")

rawDescription: Multiple for loops in Python

description: Multiple for loops in Python


code:
class WindowsBalloonTip:
    def __init__(self):
        message_map = {
                win32con.WM_DESTROY: self.OnDestroy,
        }
        # Register the Window class.
        wc = WNDCLASS()
        self.hinst = wc.hInstance = GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbar"
        wc.lpfnWndProc = message_map # could also specify a wndproc.
        self.classAtom = RegisterClass(wc)

    def ShowWindow(self,title, msg):
        # Create the Window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = CreateWindow( self.classAtom, "Taskbar", style, \
                0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
                0, 0, self.hinst, None)
        UpdateWindow(self.hwnd)
        iconPathName = os.path.abspath(os.path.join( sys.path[0], "balloontip.ico" ))
        icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
        try:
           hicon = LoadImage(self.hinst, iconPathName, \
                    win32con.IMAGE_ICON, 0, 0, icon_flags)
        except:
          hicon = LoadIcon(0, win32con.IDI_APPLICATION)
        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "tooltip")
        Shell_NotifyIcon(NIM_ADD, nid)
        Shell_NotifyIcon(NIM_MODIFY, \
                         (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\
                          hicon, "Balloon  tooltip",msg,200,title))
        # self.show_balloon(title, msg)
        DestroyWindow(self.hwnd)

    def OnDestroy(self, hwnd, msg, wparam, lparam):
        nid = (self.hwnd, 0)
        Shell_NotifyIcon(NIM_DELETE, nid)
        PostQuitMessage(0) # Terminate the app.

w = WindowsBalloonTip()
w.ShowWindow("Title1","Message One!")
time.sleep(1) # some time later
w.ShowWindow("Title2","Message Two!")

rawDescription: Error when trying to reuse Windows Notification class in Python


code: VALIDVALUES = list(filter(...))

rawDescription: Python 3 filter - Bug or Feature?

description: Python 3 filter - Bug or Feature


code:
import heapq
import operator
import math

y = [10.5,10,12,13,10,11,16,10,9,13,10]
x= np.linspace(1, len(y), len(y), endpoint=True)

y1,y2 = heapq.nsmallest(2, enumerate(y), key=operator.itemgetter(1))
x1,y1 = y1
x1 = x[x1]

x2,y2 = y2
x2 = x[x2]

m = (y2-y1)/(x2-x1)
print("Equation of line: y = {}(x-{}) + {}".format(m, x1, y1))

apexPoint = (5,4)  # or wherever the apex point is
X,Y = apexPoint
M = 1/m
print("Equation of perpendicular line: y = {}(x-{}) + {}".format(M, X, Y))

intersect_x = ((M*X)+Y-(m*x1)-y1)/(M-m)
intersect_y = m*(intersect_x - x1) + y1

dist = math.sqrt((X - intersect_x)**2 + (Y - intersect_y)**2)  # this is your answer

rawDescription: How to calculate distance between a point and an intersection line in python?

description: Calculate distance between a point and an intersection line in python


code:
foo = np.random.uniform(0,1,20).reshape(10,2)
bar = foo[foo[:,1]<0.5]

rawDescription: Creating a smaller array from a larger array in python, based on values in one column


code:
class A: pass
isinstance(A, type)
isinstance(A(), type)

rawDescription: is there a way to check if a param contains a class or a class instance?

description: Is there a way to check if a param contains a class or a class instance


code:
import datetime
...
logConfig['filename'] = 'error.log_%s' % datetime.datetime.now().strftime('%d.%m.%Y')
...
log.dictConfig(logConfig)

rawDescription: Rotating logger in python

description: Rotating logger in python


code:
def func(list1):
    list1 = list1[2:]
    print(list1)   # prints [2, 3]
    return list1

list1=func(list1)

rawDescription: Python modifying list within function

description: Python modifying list within function


code:
segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
sentence = "this is a foobar in a barbar withoutspace"
" ".join( [ segmenter.get(word,word) for word in sentence.split()] )

rawDescription: Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python


code:
import re
insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')

rawDescription: Python Case Insensitive Replace

description: Python Case Insensitive Replace


code:
import re
s = "sampleStringWithNumber/obj3453andBlabla"
re.search(r'/(.*?\d+)', s).group(1)

rawDescription: String between string and the next char that is not a number


code:
def rk2a( f, x0, t ):
    """Second-order Runge-Kutta method to solve x' = f(x,t) with x(t[0]) = x0.

    USAGE:
        x = rk2a(f, x0, t)

    INPUT:
        f     - function of x and t equal to dx/dt.  x may be multivalued,
                in which case it should a list or a NumPy array.  In this
                case f must return a NumPy array with the same dimension
                as x.
        x0    - the initial condition(s).  Specifies the value of x when
                t = t[0].  Can be either a scalar or a list or NumPy array
                if a system of equations is being solved.
        t     - list or NumPy array of t values to compute solution at.
                t[0] is the the initial condition point, and the difference
                h=t[i+1]-t[i] determines the step size h.

    OUTPUT:
        x     - NumPy array containing solution values corresponding to each
                entry in t array.  If a system is being solved, x will be
                an array of arrays.

    NOTES:
        This version is based on the algorithm presented in "Numerical
        Analysis", 6th Edition, by Burden and Faires, Brooks-Cole, 1997.
    """

    n = len( t )
    x = numpy.array( [ x0 ] * n )
    for i in xrange( n - 1 ):
        h = t[i+1] - t[i]
        k1 = h * f( x[i], t[i] ) / 2.0
        x[i+1] = x[i] + h * f( x[i] + k1, t[i] + h / 2.0 )

    return x

rawDescription: what will be python code for runge kutta second method?

description: What will be python code for runge kutta second method


code:
from itertools import islice
import os

files = sorted(os.listdir(os.curdir))  # get directory listing

desired_cols = 2
whole_rows, partial_rows = divmod(len(files), desired_cols)
num_rows = whole_rows + (1 if partial_rows > 0 else 0)

iterators = islice(files, None), islice(files, num_rows, None)

for i, f1 in enumerate(iterators[0], start=1):
    j = i + num_rows
    try:
        f2 = next(iterators[1])
    except StopIteration:
        print('{:2d}: {:38}'.format(i, f1[:38]))  # second column empty
        break
    print('{:2d}: {:38}  {:2d}: {:38}'.format(i, f1[:38], j, f2[:38]))

num = int(raw_input('\nEnter no. of file: '))  # have user select file by no.
index = num - 1
print ('\n{0}\n'.format(files[index]))  # print out corresp. filename

rawDescription: Listing contents of a dictionary in two columns


code:
dg = DependencyGraph(conll_data1)
tree = dg.tree()
tree.pprint()

rawDescription: How can I generate a bracketed tree string in NLTK from a list of nodes and their children

description: Generate a bracketed tree string in NLTK from a list of nodes and their children


code: Immutable = collections.namedtuple("Immutable", ["a", "b"])

rawDescription: How to make an immutable object in Python?

description: Make an immutable object in Python


code:
# references:
#   https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/TpFeWxEE9nsJ
#   https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/eEHYAl4dH9YJ
#
#   Here's a module to show stderr output from console-less Python
#   apps, and stay out of the way otherwise. I plan to make a ASPN
#   recipe of it, but I thought I'd run it by this group first.
#
#   To use it, import the module. That's it. Upon import it will
#   assign sys.stderr.
#
#   In the normal case, your code is perfect so nothing ever gets
#   written to stderr, and the module won't do much of anything.
#   Upon the first write to stderr, if any, the module will launch a
#   new process, and that process will show the stderr output in a
#   window. The window will live until dismissed; I hate, hate, hate
#   those vanishing-consoles-with-critical-information.
#
#   The code shows some arguably-cool tricks. To fit everthing in
#   one file, the module runs the Python interpreter on itself; it
#   uses the "if __name__ == '__main__'" idiom to behave radically
#   differently upon import versus direct execution. It uses TkInter
#   for the window, but that's in a new process; it does not import
#   TkInter into your application.
#
#   To try it out, save it to a file -- I call it "errorwindow.py" -
#   - and import it into some subsequently-incorrect code. For
#   example:
#
#        import errorwindow
#
#        a = 3 + 1 + nonesuchdefined
#
#   should cause a window to appear, showing the traceback of a
#   Python NameError.
#
#   --
#   --Bryan
#   ----------------------------------------------------------------
#
#   martineau - Modified to use subprocess.Popen instead of the os.popen
#               which has been deprecated since Py 2.6. Changed so it
#               redirects both stdout and stderr. Added numerous
#               comments, and also inserted double quotes around paths
#               in case they have embedded space characters in them, as
#               they did on my Windows system.

"""
    Import this module into graphical Python apps to provide a
    sys.stderr. No functions to call, just import it. It uses
    only facilities in the Python standard distribution.

    If nothing is ever written to stderr, then the module just
    sits there and stays out of your face. Upon write to stderr,
    it launches a new process, piping it error stream. The new
    process throws up a window showing the error messages.
"""
import subprocess
import sys
import thread
import os

if __name__ == '__main__':  # when spawned as separate process
    # create window in which to display output
    # then copy stdin to the window until EOF
    # will happen when output is sent to each OutputPipe created
    from Tkinter import BOTH, END, Frame, Text, TOP, YES
    import tkFont
    import Queue

    queue = Queue.Queue(100)

    def read_stdin(app, bufsize=4096):
        fd = sys.stdin.fileno()  # gets file descriptor
        read = os.read
        put = queue.put
        while True:
            put(read(fd, bufsize))

    class Application(Frame):
        def __init__(self, master=None, font_size=8, text_color='#0000AA', rows=25, cols=100):
            Frame.__init__(self, master)
            # argv[0]: name of this script (not used)
            # argv[1]: name of script that imported this module
            # argv[2]: name of redirected stream (optional)
            if len(sys.argv) < 3:
                title = "Output Stream from %s" % (sys.argv[1],)
            else:
                title = "Output Stream '%s' from %s" % (sys.argv[2], sys.argv[1])
            self.master.title(title)
            self.pack(fill=BOTH, expand=YES)
            font = tkFont.Font(family='Courier', size=font_size)
            width = font.measure(' '*(cols+1))
            height = font.metrics('linespace')*(rows+1)
            self.configure(width=width, height=height)
            self.pack_propagate(0)  # force frame to be configured size
            self.logwidget = Text(self, font=font)
            self.logwidget.pack(side=TOP, fill=BOTH, expand=YES)
            # Disallow key entry, but allow copy with <Control-c>
            self.logwidget.bind('<Key>', lambda x: 'break')
            self.logwidget.bind('<Control-c>', lambda x: None)
            self.logwidget.configure(foreground=text_color)
            #self.logwidget.insert(END, '==== Start of Output Stream ====\n\n')
            #self.logwidget.see(END)
            self.after(200, self.start_thread, ())

        def start_thread(self, _):
            thread.start_new_thread(read_stdin, (self,))
            self.after(200, self.check_q, ())

        def check_q(self, _):
            log = self.logwidget
            log_insert = log.insert
            log_see = log.see
            queue_get_nowait = queue.get_nowait
            go = True
            while go:
                try:
                    data = queue_get_nowait()
                    if not data:
                        data = '[EOF]'
                        go = False
                    log_insert(END, data)
                    log_see(END)
                except Queue.Empty:
                    self.after(200, self.check_q, ())
                    go = False

    app = Application()
    app.mainloop()

else: # when module is first imported
    import traceback
    class OutputPipe(object):
        def __init__(self, name=''):
            self.lock = thread.allocate_lock()
            self.name = name

        def __getattr__(self, attr):
            if attr == 'pipe':  # pipe attribute hasn't been created yet
                # launch this module as a separate process to display any output
                # it receives.
                # Note: It's important to put double quotes around everything in case
                # they have embedded space characters.
                command = '"%s" "%s" "%s" "%s"' % (sys.executable,                # command
                                                   __file__,                      # argv[0]
                                                   os.path.basename(sys.argv[0]), # argv[1]
                                                   self.name)                     # argv[2]

                # sample command and arg values on receiving end:
                #   E:\Program Files\Python\python[w].exe                         # command
                #   H:\PythonLib\TestScripts\PyRemindWrk\errorwindow.py           # argv[0]
                #   errorwindow.py                                                # argv[1]
                #   stderr                                                        # argv[2]

                # execute this script as __main__ with a stdin PIPE for sending output to it
                try:
                    # had to make stdout and stderr PIPEs too, to make it work with pythonw.exe
                    self.pipe = subprocess.Popen(command, bufsize=0,
                                                 stdin=subprocess.PIPE,
                                                 stdout=subprocess.PIPE,
                                                 stderr=subprocess.PIPE).stdin
                except Exception:
                    # output exception info to a file since this module isn't working
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    msg = ('%r exception in %s\n' %
                            (exc_type.__name__, os.path.basename(__file__)))
                    with open('exc_info.txt', 'wt') as info:
                        info.write('msg:' + msg)
                        traceback.print_exc(file=info)
                    sys.exit('fatal error occurred spawning output process')

            return super(OutputPipe, self).__getattribute__(attr)

        def write(self, data):
            with self.lock:
                self.pipe.write(data)  # 1st reference to pipe attr will cause it to be created

    # redirect standard output streams in the process importing the module
    sys.stderr = OutputPipe('stderr')
    sys.stdout = OutputPipe('stdout')

rawDescription: Writing to easygui textbox as function is running, Python


code:
import wx

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.frame = parent

        sizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        for num in range(4):
            label = "Button %s" % num
            btn = wx.Button(self, label=label)
            sizer.Add(btn, 0, wx.ALL, 5)
        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(sizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75)
        self.SetSizer(hSizer)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    #----------------------------------------------------------------------
    def OnEraseBackground(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()

        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("butterfly.jpg")
        dc.DrawBitmap(bmp, 0, 0)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, size=(600,450))
        panel = MainPanel(self)
        self.Center()

########################################################################
class Main(wx.App):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, redirect=False, filename=None):
        """Constructor"""
        wx.App.__init__(self, redirect, filename)
        dlg = MainFrame()
        dlg.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = Main()
    app.MainLoop()

rawDescription: set picture as background

description: Set picture as background


code:
XMLSchemaNamespace = '{http://www.w3.org/2001/XMLSchema-instance}'
document = lxml.parse(xmlfile)
schemaLink = document.get(XMLSchemaNamespace + 'schemaLocation')
if schemaLink is None:
    schemaLink = document.get(XMLSchemaNamespace + 'noNamespaceSchemaLocation')

rawDescription: Python lxml: how to validate file using xml schema file defined in the xml file


code: (i for i,v in enumerate(l) if MyString in i).next()

rawDescription: Finding the index of a string within another string in a list in Python


code:
def setup_django_env(path):
    import imp, os
    from django.core.management import setup_environ

    f, filename, desc = imp.find_module('settings', [path])
    project = imp.load_module('settings', f, filename, desc)

    setup_environ(project)

setup_django_env('/path/to/django/project/')

rawDescription: Access django models inside of Scrapy

description: Access django models inside of Scrapy


code:
from IPython.display import display
import sympy as sy

sy.init_printing()  # LaTeX-like pretty printing for IPython

t = sy.Symbol("t", real=True)
m, k = sy.symbols('m k', real=True)  # gives C_1 Exp() + C_2 Exp() solution
# m, k = sy.symbols('m k', positive=True)  # gives C_1 sin() + C_2 cos() sol.
a0, b0 = sy.symbols('a0, b0', real=True)
y = sy.Function('y')

Eq1 = sy.Eq(m*sy.diff(y(t), t, 2) + k*y(t))
print("ODE:")
display(Eq1)

print("Generic solution:")
y_sl0 = sy.dsolve(Eq1, y(t)).rhs  # take only right hand side
display(sy.Eq(y(t), y_sl0))

# Initial conditions:
cnd0 = sy.Eq(y_sl0.subs(t, 0), a0)  # y(0) = a0
cnd1 = sy.Eq(y_sl0.diff(t).subs(t, 0), b0)  # y'(0) = b0

#  Solve for C1, C2:
C1, C2 = sy.symbols("C1, C2")  # generic constants
C1C2_sl = sy.solve([cnd0, cnd1], (C1, C2))

# Substitute back into solution:
y_sl1 = sy.simplify(y_sl0.subs(C1C2_sl))
print("Solution with initial conditions:")
display(sy.Eq(y(t), y_sl1))

rawDescription: Sympy second order ode

description: Sympy second order ode


code:
import numpy as np
import pymc as pm
aRange = 3
bRange = 4

aCPT = pm.Dirichlet('aCPT', np.ones(aRange))

#make variable a
a = pm.Categorical('a', aCPT)

#make a CPT table as an array of
CPTLines = [pm.Dirichlet('CPTLine%i' %i, np.ones(bRange)) for i in range(aRange)]

#make a node for variable b
@pm.stochastic(dtype=int)
def b(value=0, CPT=CPTLines, a=a):
    return pm.categorical_like(value, p=pm.extend_dirichlet(CPT[a]))

model = pm.MCMC([a, b, CPTLines])

rawDescription: How to make Conditional Probability Tables (CPTs) for Bayesian networks with pymc

description: Make Conditional Probability Tables (CPTs) for Bayesian networks with pymc


code:
from turtle import *
#we make an object from class Turtle
alex=Turtle()
def parallel_lines(number):
    #number is number of lines
    with_s=alex.window_width()
    height_s=alex.window_height()
    alex.setheading(90)
    alex.pu()
    #for fill all screen and equall distance below line needed
    alex.setposition(with_s/-2,height_s/-2)
    for i in range(1,number+1):
        alex.pd()
        alex.fd(height_s)
        alex.pu()
        alex.setposition(with_s/-2+i*(with_s/(number-1)),height_s/-2)

parallel_lines(5)

rawDescription: How to use Turtle graphics to draw a series of parallel lines in python?

description: Use Turtle graphics to draw a series of parallel lines in python


code:
locs = aframe.index.indexer_at_time('7:00:00')
aframe.iloc[locs]

rawDescription: Query same time value every day in Pandas timeseries


code:
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')

#then load it later, remember to import joblib of course

clf = joblib.load('filename.pk1')

rawDescription: How to output sklearn standardscaler

description: Output sklearn standardscaler


code:
def getLine(data, line_no):
    index = -1
    for _ in range(line_no):index = data.index('\n',index+1)
    return data[index+1:data.index('\n',index+1)]

rawDescription: get nth line of string in python

description: Get nth line of string in python


code: self.collection.update({'date' : 2}, { '$set': {'result': record['result']} }, True)

rawDescription: insert and update list of dictionary in pymongo

description: Insert and update list of dictionary in pymongo


code:
int_string = '1558662:10306104:11038113:7883355'
hex_string = ':'.join(format(int(i), 'X') for i in int_string.split(':'))
hex_string

rawDescription: how to convert delimited string of integers into hex in python

description: Convert delimited string of integers into hex in python


code:
class Match(models.Model):
    player_1 = models.ForeignKey(auth.User)
    score_1 = models.PositiveIntegerField(null=True, blank=True)
    player_2 = models.ForeignKey(auth.USer)
    score_2 = models.PositiveIntegerField(null=True, blank=True)
    court = models.ForeignKey(Court)
    date = models.DateField()

    @property
    def winner(self):
        "None means not played yet, or a draw."
        if self.score_1 > self.score_2:
            return self.player_1
        if self.score_1 < self.score_2:
            return self.player_2

    @property
    def is_draw(self):
        return self.score_1 == self.score_2 and self.score_1 is not None

class Location(models.Model):
    name = models.CharField()

class Court(models.Model):
    location = models.ForeignKey(Location)
    number = models.PositiveIntegerField()

rawDescription: Aggregate data using the ORM

description: Aggregate data using the ORM


code:
def weapon_fact(weptype, dmg_type):
    class SpecificWeapon(weapon):
        def __init__(self, name, dmg_mod):
            weapon.__init__(self, name, weptype, dmg_mod, dam_type)
            self.name = name
    return SpecificWeapon

rawDescription: Python Metaclasses with Class Inheritance


code:
result_list = my_list[:]
for l in my_list:
    tmp = '_'.join(map(str,l))
    for pattern in pattern_list:
        if pattern in tmp:
            result_list.remove(l)
            break

rawDescription: python list matching for multiple patterns

description: Python list matching for multiple patterns


code:
subprocess.Popen('$HOME/.virtualenvs/supervisor/bin/' \
                     'supervisorctl restart {0}'.format(projname),
                     shell=True, close_fds=True, stdout=open('/dev/null', 'w'))

rawDescription: TextMate Python bundle non-blocking

description: TextMate Python bundle non-blocking


rawDescription: How should I extract % delimited tags

description: How should I extract % delimited tags


code:
class MyItem(Item):
    value = Field()

class MySpider(BaseSpider):
    ...

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        items = hxs.select('//table[@class="tablehd"]/td')

        for item in items:
            my_item = MyItem()
            my_item['value'] = item.select('.//text()').extract()
            yield my_item

rawDescription: Scrape data from a table with scrapy

description: Scrape data from a table with scrapy


code:
from matplotlib import rc
import matplotlib.pylab as plt

rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)

x = plt.linspace(0,5)
plt.plot(x,plt.sin(x))
plt.ylabel(r"This is $\sin(x)$", size=20)
plt.show()

rawDescription: Matplotlib not using latex font while text.usetex==True


code:
def int_or_str(value):
    try:
        return int(value)
    except:
        return value

rawDescription: Argument parser with mixed type of args input in Python's argparse module


code:
s = "THE SMASH-HIT, CRITICALLY ACCLAIMED SERIES RETURNS! Now that you've read the first two bestselling collections of SAGA , you're all caught up and ready to jump on the ongoing train with Chapter Thirteen, beginning an all-new monthly sci-fi/fantasy adventure, as Hazel and her parents head to the planet Quietus in search of cult romance novelist D. Oswald Heist."
import HTMLParser
HTMLParser.HTMLParser().unescape(s)

rawDescription: Encoding a string with ASCII Characters (Find and replace?)


code:
def hit_test(x, y, xsize, ysize):
    xmin = (x - xsize//2) // tile_size
    xmax = (x + xsize//2) // tile_size
    ymin = (y - ysize//2) // tile_size
    ymax = (y + ysize//2) // tile_size
    for xtile in range(xmin, xmax):
        for ytile in range(xmin, xmax):
            if tiles[xtile][ytile] != 0:
                COLLISION

rawDescription: How do I Get Faster Collisions From A List?

description: Get Faster Collisions From A List


code:
import datetime
from dateutil import relativedelta

today = datetime.date.today()
past = today + relativedelta.relativedelta(years=-25)
print(today, past, sep='\t')

rawDescription: How to Date deduction with Python?

description: Date deduction with Python


code:
from pylab import *
NUM_COLORS = 22

cm = get_cmap('gist_rainbow')
for i in range(NUM_COLORS):
    color = cm(1.*i/NUM_COLORS)  # color will now be an RGBA tuple

# or if you really want a generator:
cgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))

rawDescription: Create a color generator from given colormap in matplotlib


code: ordering = ['-date_joined']

rawDescription: How can I order the native django users in the django admin page based on creation time?

description: Order the native django users in the django admin page based on creation time


rawDescription: How to delete the very last character from every string in a list of strings

description: Delete the very last character from every string in a list of strings


code:
canvas = FigureCanvasAgg(figure)
manager = FigureManagerBase(canvas, num)
return manager

rawDescription: matplotlib pyplot show capture image

description: Matplotlib pyplot show capture image


code:
def ok_command(self):
        file = self.get_selection()
        if os.path.exists(file):
            if os.path.isdir(file):
                self.master.bell()
                return
            d = Dialog(self.top,
                       title="Overwrite Existing File",
                       text="You can't overwrite an existing file %r. Please select a new name." % (file,),
                       bitmap='error',
                       default=0,
                       strings=("OK",))
            return
        else:
            head, tail = os.path.split(file)
            if not os.path.isdir(head):
                self.master.bell()
                return
        self.quit(file)

rawDescription: save as file dialog - how to not allow overwrite

description: Save as file dialog - how to not allow overwrite


code: from other_file import *

rawDescription: Define global variables in one line Python


code:
primes = [2, 3]
upto = 1000
for num in range(4, upto+1):
    if all(num % p for p in primes):
        primes.append(num)

print(primes)

rawDescription: Run a loop again

description: Run a loop again


code:
import analytic_wfm as AW
AW.ACV_A6( ... )

import peakdetect as PK
PK.peakdetect_parabola( ... )

rawDescription: How do I install a package from GitHub gist?

description: Install a package from GitHub gist


code:
import datetime
today = datetime.date.today()
print(today.strftime('%x'))

rawDescription: CPython - Making the date show up using the date on your computer


code:
from itertools import product
characters = [['a','b','c'],['d'],['e','f']]
[''.join(item) for item in product(*characters)]

rawDescription: Generate wordlist by List of List of character


code:
import inspect

print(inspect.getfullargspec(os_chdir))
# Prints FullArgSpec(args=['dir'], varargs=None, varkw=None, defaults=None,
#                    kwonlyargs=[], kwonlydefaults=None, annotations={})

print(inspect.getfullargspec(os.chdir))
# Raises ValueError: no signature found for builtin <built-in function chdir>

rawDescription: Python: mock.create_autospec() does not perform argument checking for builtin functions


code:
class Data(object):
    def __init__(self, data):
        self.data = data
        self.valid = False
        #Analyze and validate data
        self._preprocess_data()
        self.validate_data()
    def _preprocess_data(self):
        if self.preprocess_data.im_func != Data.preprocess_data.im_func:
            self.data = self.data.copy()
        return self.preprocess_data()

rawDescription: Perform a copy() of a class attribute if an only if a subclass overrides a method


code:
lines = []

with open('file.txt', 'r') as f:
    lines = f.readlines()

with open('file.txt', 'w') as f:
    f.writelines(lines[:1] + lines[2:]) # This will skip the second line

rawDescription: Removing the second line from a text file


code:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.get_active_sheet()
ws.cell('A1').value = 1
wb.save('test.xslx')
wb2 = openpyxl.load_workbook('test.xlsx')
ws2 = wb2.get_active_sheet()
ws2.cell('A2').value = 2
wb2.save('test2.xlsx')

rawDescription: (Python - openpyxl) Can't import the exported xlsx file


code:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('create table t (c);')
conn.executemany("insert into t values (?);", ('a','b','c',))
conn.execute('select c from t;').fetchall()
# -> [(u'a',), (u'b',), (u'c',)]
conn.executemany('delete from t where c = ?;', ('a','b',))
conn.execute('select c from t;').fetchall()
# -> [(u'c',)]
conn.close()

rawDescription: cx_oracle deleting with executemany?

description: Cx_oracle deleting with executemany


rawDescription: Why a function called `main` doesn't have any special significance?


code:
from scipy.io.wavfile import read
a = read("adios.wav")
numpy.array(a[1],dtype=float)

rawDescription: Python: write a wav file into numpy float array


code:
i = 1
while i < len(sub_meta):
    if sub_meta[i][1] < sub_meta[i-1][1]:
        dict_meta[sub_meta[i-1][0]]= sub_meta[i][0]
    elif sub_meta[i][1] == sub_meta[i-1][1]:
        dict_meta[sub_meta[i-1][0]]= ''
        i += 1
    i += 2

rawDescription: Increment on certain condition with xrange()


code:
from collections import defaultdict

def get_file_type(filename):
    base, ext = os.path.splitext(filename)
    return base.rsplit('_', 1)[1] + ext

files_by_type = defaultdict(list)
for filename in os.listdir(input_path):
    filetype = get_file_type(filename)
    files_by_type[filetype].append(filename)

rawDescription: Filter files based on file name

description: Filter files based on file name


code: collection = getattr(db, screen_name)

rawDescription: How to make functions for my pymongo/twitter script?

description: Make functions for my pymongo/twitter script


code:
while not self.stopped.wait(10):
    if self.stopped.isSet():
        return
    ser.write("{0},{1}\r".format(self.name,"PING"))

rawDescription: Python thread continuously executes when setting stop flag


code:
import numpy as np
from bokeh.plotting import figure, show, output_file
from bokeh.models import Circle

N = 100
max = 100
x = np.random.random(size=N) * max
y = np.random.random(size=N) * max

p = figure(tools="box_select", width=400, height=400, x_range=(0,100), y_range=(0,100))
r = p.circle(x, y, size=10, fill_color="black", line_color=None)
r.selection_glyph = Circle(fill_color="orange", line_color=None)
r.nonselection_glyph = Circle(fill_color="black", line_color=None)

output_file("scatter.html")
show(p)

rawDescription: Change the highlighting behaviour of the box select tool in Bokeh?


code:
data = [('b','..','o','b'),('t','s','..','t')]
newData = [tuple(s if s != ".." else " " for s in tup) for tup in data]
newData

rawDescription: Replace String From Tuple Inside List

description: Replace String From Tuple Inside List


rawDescription: Pyserial bluetooth working only at 9600 baud rate


code:
s = raw_input("Please enter your numbers: ")

mynums = [int(i) for i in s.split()]
# OR
mynums = map(int, s.split())

rawDescription: accepting multiple user inputs seperated by a space in python and append them to a list

description: Accepting multiple user inputs seperated by a space in python and append them to a list


rawDescription: Comparing/testing two list of tuples

description: Comparing/testing two list of tuples


code:
import gzip
content = "Lots of content here"
f = gzip.open('/home/joe/file.txt.gz', 'wb')
f.write(content)
f.close()

rawDescription: python how to append to file in zip archive

description: Python how to append to file in zip archive


code:
b=[]
a = Board_status.objects.values('board_id').distinct()
for i in range(a.count()):
 b.append(Board_status.objects.filter(board_id=a[i]['board_id']).latest('time'))

rawDescription: Django group by id then select max timestamp


rawDescription: Marking query in particular case

description: Marking query in particular case


code:
import re

regex = r'\d-\d{4}-\d{4}-\d'

preg = re.compile(regex)

s1 = '9-9715-0210-0'
s2 = '997-150-210-0'

m1 = preg.match(s1)
m2 = preg.match(s2)

if m1:
    print('String s1 is valid')
else:
    print('String s1 is invalid')

if m2:
    print('String s2 is valid')
else:
    print('String s2 is invalid')

rawDescription: Determine whether the input matches a specified format


code:
import subprocess
variable = 'thevariable'
subprocess.call("echo "+variable +" | thecommand", shell=True)

rawDescription: Importing OS Commands into Python; how to pipe with a variable in the middle?


code:
import pkgutil

def usable_modules(package_name):
    modules = pkgutil.iter_modules([package_name])
    usable = []
    for importer, name, ispkg in modules:
        module = pkgutil.find_loader('{0}.{1}'.format(package_name, name)).\
                                                             load_module(name)
        if hasattr(module, 'CAN_USE') and module.CAN_USE:
            usable.append(module)
    return usable

print(usable_modules('functions'))

rawDescription: Check variable of modules in package

description: Check variable of modules in package


code:
import itertools

file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3)
for variations in variations:
    variation_string = ""
    for letter in variations:
        variation_string += letter
    file.write(variation_string)
file.close()

rawDescription: how to direct output into a txt file in python in windows

description: Direct output into a txt file in python in windows


code:
x = np.zeros((100,9))
y = x[:,:,np.newaxis,np.newaxis]

rawDescription: Correct way to broadcast a 100x9 to a 100x9x1x1 numpy array for computation in Caffe


code:
from collections import Counter
A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})
A + B

rawDescription: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?


code: im_new = im_old[:,:,np.newaxis]

rawDescription: Polymorphic treating of 2D and 3D numpy array


code:
x,y,z = zip(*MWpos1)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(x, y, z, '.')
ax.legend()
plt.show()

rawDescription: Python - Plotting a 3 dimensional array

description: Python - Plotting a 3 dimensional array


code:
key = ('*', '<A>')
if key[0] in RJECNIK and key[1] in RJECNIK[key[0]]:
    pass

rawDescription: How to check if dictionary has certain key (Python)

description: Check if dictionary has certain key (Python)


code:
l
[ filter(None, a) for a in l]

rawDescription: Data transformation - Python

description: Data transformation - Python


code:
from datetime import datetime
dt = datetime.fromordinal(733828)
dt
dt.strftime('%Y%m%d')

rawDescription: How to convert the integer date format into YYYYMMDD?

description: Convert the integer date format into YYYYMMDD


code:
from rest_framework import generics
from rest_framework.parsers import FormParser, MultiPartParser
from .serializer import MyModelSerializer

class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FormParser, MultiPartParser)

    def post(self, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: source
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return super(MyModelView, self).post(self, *args, **kwargs)

rawDescription: Django REST Framework + Django REST Swagger + ImageField


code:
class Tee(object):
    def __init__(self, f1, f2):
        self.f1, self.f2 = f1, f2
    def write(self, msg):
        self.f1.write(msg)
        self.f2.write(msg)

outfile = open('outfile', 'w')

sys.stdout = outfile
sys.stderr = Tee(sys.stderr, outfile)

rawDescription: Redirecting stdout, stderror to file while stderr still prints to screen


rawDescription: I want to isolate the IP and the port from a string in a python script


code:
import string
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))

with open('data10.txt', 'r') as f:
    for line in f:
        for word in line.split():
            word = word.translate(remove)
            print(word.lower())

rawDescription: Python parsing to lower case and removing punctuation not functioning properly


code:
import Image

old_im = Image.open('someimage.jpg')
old_size = old_im.size

new_size = (800, 800)
new_im = Image.new("RGB", new_size)   ## luckily, this is already black!
new_im.paste(old_im, ((new_size[0]-old_size[0])/2,
                      (new_size[1]-old_size[1])/2))

new_im.show()
# new_im.save('someimage.jpg')

rawDescription: Adding borders to an image using python

description: Adding borders to an image using python


code:
targets_with_args = [
    (target1, arg1),
    (target2, arg2),
    (target3, arg3),
    ...
]

with concurrent.futures.ProcessPoolExecutor(max_workers=20) as executor:
    futures = [executor.submit(target, arg) for target, arg in targets_with_args]
    results = [future.result() for future in concurrent.futures.as_completed(futures)]

rawDescription: Execute a list of process without multiprocessing pool map


code:
import errno
import os
import subprocess

def assert_remote_dir_is_mounted(remote_dir, local_dir):
    # Make sure the directory exists.
    try:
        # Try it first. This avoids race conditions where two processes check
        # for its existence at the same time.
        os.makedirs(local_dir)
    except OSError as exc:
        # The "already exists" error is OK. Only report other error conditions.
        if exc.errno != errno.EEXIST:
            raise

    retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir])

    # The call succeeded
    if not retcode:
        return True

    # If it didn't succeed, see if the directory is on a different device
    # from its parent. If it is, then the directory was already mounted,
    # and hopefully on `remote_dir`. If that's sufficient, then you're done
    # here. If you really need to verify that it's mounted on `remote_dir`,
    # shell out to `mount` or otherwise check it.
    local_parent = os.path.abspath(os.path.join(local_dir, os.pardir))
    if os.stat(local_parent).st_dev != os.stat(local_dir).st_dev:
        return True

    return False
    # or raise SomeException("couldn't mount"), etc.

rawDescription: Mount OS X volume only if it is not only mounted - how?


code:
sentence = ['this','is','a','sentence']
'-'.join(sentence)

rawDescription: Concatenate item in list to strings

description: Concatenate item in list to strings


rawDescription: Python OR operator and parenthesis

description: Python OR operator and parenthesis


code:
courses = []
comp_course = []
for payment in transactions:
    if payment.payment_type == "1":
        unit = Units.objects.get(webducate_id=str(payment.course))

        comp_course.append(str(unit.course.webducate_id))

        units = Units.objects.filter(course=unit.course)
        unit_list = []
        for unit in units:
            if unit.webducate_id == payment.course and payment.successfull == "1":
                courses.append([str(unit.course.webducate_id),'1',str(unit.webducate_id)])
            else:
                courses.append([str(unit.course.webducate_id),'0',str(unit.webducate_id)])
comp_course = list(set(comp_course))
return render_to_response('student-account.html', {'Courses': courses, 'Comp_Course': comp_course,'Message': "", 'Transactions': transactions}, context_instance=RequestContext(request))

rawDescription: Django template not iterating through list


code:
def string_to_num(in_str):
    try:
        translationdict = str.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")
    except AttributeError:
        import string
        translationdict = string.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")

    out_str = in_str.lower().translate(translationdict)
    return out_str

rawDescription: How to convert Strings to into a phone number

description: Convert Strings to into a phone number


code:
import numpy as np
df['col']
np.bitwise_and(df['col'], 0b101010)

rawDescription: Performing bitwise operations on a dataframe


code:
# Read all lines of the file into a list of strings
with open("config.php", "r") as file:
  lines = list(file)
  file.close()

# This gets the line number for the first line containing '//cats'
# Note that it will throw an StopIteration exception, if no such line exists...
linenum = (num for (num, line) in enumerate(lines) if '//cats' in line).next()

# insert a line after the line containing '//cats'
lines.insert(linenum+1, 'This is a new line...')

# You could also replace the line following '//cats' like
lines[linenum+1] = 'New line content...'

# Write back the file  (in fact this creates a new file with new content)
# Note that you need to append the line delimiter '\n' to every line explicitely
with open("config.php", "w") as file:
  file.writelines(line + '\n' for line in lines)
  file.close()

rawDescription: how to Use python to find a line number in a document and insert data underneath it


rawDescription: How to ensure two line breaks between each paragraph in python

description: Ensure two line breaks between each paragraph in python


code: class BackupSomeModel(SomeModel): pass

rawDescription: Dynamically create new kind with all the same properties of existing model class


code:
from collections import Counter

freq = Counter()
for x in data:
    freq[(x - 1) // 10] += 1

rawDescription: What is the cleanest way to count frequencies in python


code:
import pandas as pd

Dict = {'Image': [1,2,3],
    'color1': ['red','blue','white'],
    'color2': ['blue','blue','red'],
    'color3': ['yellow','red','pink']}

df = pd.DataFrame(Dict)
df.set_index('Image',inplace=True)

Color_Counts = df.stack().value_counts()
Color_Counts.to_csv('Color_Counts.csv')

rawDescription: Python: Pandas Create new csv with contents counted


code:
import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame()
df['Distance']=[5,100,200,300,350,370,400]
df['Elevation']=[0,5,10,5,10,15,20]

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.plot(df['Distance'],df['Elevation'])
ax.set_ylim(-5,25)

rawDescription: Matplotlib pyplot set axis limits after rescaling equal


code:
import requests

def lastfm_artist_search(request, artist_name):
    api_url = 'http://ws.audioscrobbler.com/2.0/'
    api_key = 'YOUR_LASTFM_API_KEY'
    url = api_url+'?method=artist.search&format=json&artist='+artist_name+'&api_key='+api_key
    data = requests.get(url)
    return HttpResponse(data.text)

rawDescription: Lastfm artist searcher in python with django


code:
non_negative_w = np.abs(w)
sum_w = np.sum(non_negative_w)
normalized_non_negative_w = non_negative_w / sum_w

rawDescription: How do a make sure an arbitrary number of weights sum to 1 (Python)?


code:
from google.appengine.ext.ndb import model

class Unique(model.Model):
    @classmethod
    def create_multi(cls, values):
        keys = [model.Key(cls, value) for value in values]
        entities = [cls(key=key) for key in keys]
        func = lambda e: e.put() if not e.key.get() else None
        created = [model.transaction(lambda: func(e)) for e in entities]

        if created != keys:
            # A poor man's "rollback": delete all recently created records.
            model.delete_multi(k for k in created if k)
            return False, [k.id() for k in keys if k not in created]

        return True, []

    @classmethod
    def delete_multi(cls, values):
        return model.delete_multi(model.Key(cls, v) for v in values)

# Assemble the unique values for a given class and attribute scope.
uniques = [
    'User.username.%s' % username,
    'User.auth_id.%s' % auth_id,
    'User.email.%s' % email,
]

# Create the unique username, auth_id and email.
success, existing = Unique.create_multi(uniques)

if success:
    # The unique values were created, so we can save the user.
    user = User(username=username, auth_id=auth_id, email=email)
    user.put()
    return user
else:
    # At least one of the values is not unique.
    # Make a list of the property names that failed.
    props = [name.split('.', 2)[1] for name in uniques]
    raise ValueError('Properties %r are not unique.' % props)

rawDescription: GAE datastore, how to atomically query and insert without ancestor or known entity key?


code:
a = "foo"
b = list()
b.append([a])
b

rawDescription: Python disable list string "breaking"

description: Python disable list string "breaking"


code:
import sys
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
# Tkinter is for python 2; tkinter is for python 3
if sys.version_info[0] < 3:
    import Tkinter as tk
    import tkMessageBox, tkFileDialog

else:
    import tkinter as tk
    from tkinter import messagebox as tkMessageBox
    from tkinter import filedialog as tkFileDialog

class MainApp(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title('App')
        # call the widgets
        self.okButton()
        self.quitButton()
        self.readDataButton()
        self.clearDataButton()
        self.velScale()
        self.canvas()

    # print messages on the screen
    def printMessage(self):
        if (self.data):
            print("Data is loaded and accessible from here (printMessage()).")
        else:
            print('No data loaded...')

    ### OK button
    def okButton(self):
        self.okButton = tk.Button(self, text='Test', command=self.printMessage)
        self.okButton.grid(column=1, row=1, sticky="nesw")

    ### Quit button
    def quitButton(self):
        self.quitButton = tk.Button(self, text='Quit', command=self.confirmQuit)
        self.quitButton.grid(column=1, row=2, sticky="nesw")
    # confirm quitting
    def confirmQuit(self):
        answer = tkMessageBox.askyesno(title="App", message="Do you really want to quit?")
        if (answer):
            self.quit()

    # Read data button
    def readDataButton(self):
        self.data = None
        self.readDataButton = tk.Button(self, text='Import data', command=self.readData)
        self.readDataButton.grid(column=1, row=3, sticky="nesw")
    # reading data
    def readData(self):
        import os
        fullPath = dataList = tkFileDialog.askopenfilename(initialdir='path/to/initialdir')
        dataDir = os.path.split(fullPath)[0]+'/'
        self.data = readData(fullPath)

    # Clear data from current session
    def clearDataButton(self):
        self.clearData = tk.Button(self, text='Clear data', command=self.confirmClearData)
        self.clearData.grid(column=1, row=4, sticky="nesw")
    # confirm clearing data
    def confirmClearData(self):
        answer = tkMessageBox.askyesno(title="App", message="Are you sure you want to clear the loaded data?")
        if (answer):
            self.data = None
            tkMessageBox.showwarning(title="App", message="Data has been deleted.")

    # Velocity scale
    def velScale(self):
        self.velVar = tk.StringVar()
        velLabel = tk.Label(self, text="Scale value:", textvariable=self.velVar)
        velLabel.grid(row=4, column=0, columnspan=2, sticky=tk.W+tk.E)
        velScale = tk.Scale(self, from_=-500, to=+500, orient=tk.HORIZONTAL, resolution=20,
                        sliderlength=20, showvalue=0,
                        length=200, width=20,
                        command=self.onVelScale)
        velScale.grid(column=1, row=5, sticky="nesw")
    # update velLabel
    def onVelScale(self, val):
        self.velVar.set("Scale value: {:+0.0f}".format(float(val)))

    # Canvas
    def canvas(self):
        self.f = Figure(figsize=(4,2))
        self.a = self.f.add_subplot(111)
        self.a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])

        self.canvas = FigureCanvasTkAgg(self.f, master=self)
        self.canvas.get_tk_widget().grid(column=2, row=1, rowspan=5, sticky="nesw")

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.parent)

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("800x600+10+10")
    root.resizable(0, 0)
    MainApp(root).pack(side=tk.TOP)
    root.mainloop()

rawDescription: Tkinter and Matplotlib: relative position of canvas created by FigureCanvasTkAgg


code:
#from scipy.stats import gaussian_kde
import matplotlib.pyplot as plt
import numpy as np

from scipy import interpolate

from scipy import ndimage

y=[ 191.78 ,   191.59,    191.59,    191.41,    191.47,    191.33,    191.25  \
  ,191.33 ,   191.48 ,   191.48,    191.51,    191.43,    191.42,    191.54    \
  ,191.5975,  191.555,   191.52 ,   191.25 ,   191.15  ,  191.01  ]
x = np.linspace(1 ,20,len(y))

# convert both to arrays
x_sm = np.array(x)
y_sm = np.array(y)

# resample to lots more points - needed for the smoothed curves
x_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)

# spline - always goes through all the data points x/y
y_spline = interpolate.spline(x, y, x_smooth)

spl = interpolate.UnivariateSpline(x, y)

sigma = 2
x_g1d = ndimage.gaussian_filter1d(x_sm, sigma)
y_g1d = ndimage.gaussian_filter1d(y_sm, sigma)

fig, ax = plt.subplots(figsize=(10, 10))
ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5), frameon=False)

plt.plot(x_sm, y_sm, 'green', linewidth=1)
plt.plot(x_smooth, y_spline, 'red', linewidth=1)
plt.plot(x_smooth, spl(x_smooth), 'yellow', linewidth=1)
plt.plot(x_g1d,y_g1d, 'magenta', linewidth=1)

plt.show()

rawDescription: How to smooth a line using gaussian kde kernel in python setting a bandwidth

description: Smooth a line using gaussian kde kernel in python setting a bandwidth


code:
import datetime
import os
dt=os.path.getmtime('/home/me/.bashrc')
print (datetime.datetime.fromtimestamp(dt))
print (datetime.datetime.utcfromtimestamp(dt))

rawDescription: How to get the file modification date in UTC from Python

description: Get the file modification date in UTC from Python


code:
import module1
import unittest

class MyTest(unittest.TestCase):
    def setUp(self):
        # Replace othermod.function with our own mock
        self.old_func1 = module1.func1
        module1.func1 = self.my_new_func1

    def tearDown(self):
        module1.func1 = self.old_func1

    def my_new_func1(self, x):
        """A mock othermod.function just for our tests."""
        return True

    def test_func1(self):
        module1.func1("arg1")

rawDescription: How do I redefine functions in python?

description: Redefine functions in python


code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import psd
from scipy.signal import decimate

f_line = 123.456
f_demod = 122

f_sample = 1000
t_total = 100
t_win = 10
ratio = 10

t = np.arange(0, t_total, 1 / f_sample)
x = np.sin(2*np.pi*f_line * t) + np.random.randn(len(t)) # sine plus white noise
lo = 2**.5 * np.exp(-2j*np.pi*f_demod * t) # local oscillator
y = decimate(x * lo, ratio) # demodulate and decimate to 100 Hz
z = decimate(y, ratio) # decimate further to 10 Hz

nfft = int(round(f_sample * t_win))
X, fx = psd(x, NFFT = nfft, noverlap = nfft/2, Fs = f_sample)

nfft = int(round(f_sample * t_win / ratio))
Y, fy = psd(y, NFFT = nfft, noverlap = nfft/2, Fs = f_sample / ratio)

nfft = int(round(f_sample * t_win / ratio**2))
Z, fz = psd(z, NFFT = nfft, noverlap = nfft/2, Fs = f_sample / ratio**2)

plt.semilogy(fx, X, fy + f_demod, Y, fz + f_demod, Z)
plt.xlabel('Frequency (Hz)')
plt.ylabel('PSD (V^2/Hz)')
plt.legend(('Full bandwidth FFT', '100 Hz FFT', '10 Hz FFT'))
plt.show()

rawDescription: FFT lots of detail around certain frequency


code:
f = open('file.txt')
lines = f.readlines()
matrix = [[a for a in b[:4]] for b in lines] # this gets all columns, up to 4

rawDescription: list comprehension selected indexes

description: List comprehension selected indexes


code:
class Article(models.Model):
    tags = models.ManyToManyField(ArticleTag, blank=True,
        related_name="articles")

rawDescription: Django many-to-many problem in admin

description: Django many-to-many problem in admin


code:
import math

def mid_digit(n):

    # num of digits
    a = math.trunc(math.log(n,10)+1)

    # moving half of digits to the right of decimal point
    b = n / 10 ** round(a/2 + 0.5)

    # getting the left most decimal digit
    c = math.trunc(math.modf(b)[0] * 10)

    return c

rawDescription: How to find the middle value of an integer without converting it to a string using Python3?

description: Find the middle value of an integer without converting it to a string using Python3


code:
import re

def parse_fields(text):
    r"""
    >>> list(parse_fields('hey,hello,,"hello,world",\'hey,world\''))
    ['hey', 'hello', '', 'hello,world', 'hey,world']
    >>> list(parse_fields('hey,hello,,"hello,world",\'hey,world\','))
    ['hey', 'hello', '', 'hello,world', 'hey,world', '']
    >>> list(parse_fields(',hey,hello,,"hello,world",\'hey,world\','))
    ['', 'hey', 'hello', '', 'hello,world', 'hey,world', '']
    >>> list(parse_fields(''))
    ['']
    >>> list(parse_fields(','))
    ['', '']
    >>> list(parse_fields('testing,quotes not at "the" beginning \'of\' the,string'))
    ['testing', 'quotes not at "the" beginning \'of\' the', 'string']
    >>> list(parse_fields('testing,"unterminated quotes'))
    ['testing', '"unterminated quotes']
    """
    pos = 0
    exp = re.compile(r"""(['"]?)(.*?)\1(,|$)""")
    while True:
        m = exp.search(text, pos)
        result = m.group(2)
        separator = m.group(3)

        yield result

        if not separator:
            break

        pos = m.end(0)

if __name__ == "__main__":
    import doctest
    doctest.testmod()

rawDescription: How do I split a comma delimited string in Python except for the commas that are within quotes

description: Split a comma delimited string in Python except for the commas that are within quotes


code:
def merged(dictoflists):
  result = dict()
  reversed = dict()
  for k, l in dictoflists.iteritems():
    intersecting = set(reversed.get(w) for w in l) - set([None])
    if intersecting:
      pickone = intersecting.pop()
      into = result[pickone]
    else:
      pickone = k
      into = result[k] = set()
    for ok in intersecting:
      into.update(result.pop(ok))
    into.update(l)
    for w in into:
      reversed[w] = pickone
  return dict((k, sorted(l)) for k, l in result.iteritems())

rawDescription: Merging all sub-arrays with mutual elements into one sub-array


code:
def solve(numbers, target):
  for op, res, nums in single_move_generator(numbers):
    if res == target:
      return [op]
    ops = solve(nums, target)
    if ops:
      return [op] + ops

print(*solve(numbers_to_use, target))

rawDescription: Recursively running a for loop within a for loop (python)


code:
def passfiles(alist):
    values = []
    for filenames in alist:
        values.append(filetocsv(filenames))
    return values

rawDescription: Passing a list through a function python3.4 windows


code:
td = {}
for ii in range(100):
    td[ii] = 10000+ii

a = np.hstack([np.ones(td[aa])*aa for aa in td])

rawDescription: Fast way to populate numpy array with multiple iterations of multiple numbers


code: grid = [[None for _ in xrange(20)] for __ in xrange(20)]

rawDescription: Creating a list of lists Python

description: Creating a list of lists Python


code:
d = ">"
for line in all_lines:
    s =  [e+d for e in line.split(d) if e != ""]

rawDescription: Python split() without removing the delimiter


code:
tweet_obj = json.loads(tweet)
if not tweet_obj['in_reply_to_user_id']: # replies has `None` in this field
    pass                                 # add some processing here

rawDescription: Tweepy syntax and Twitter streaming api

description: Tweepy syntax and Twitter streaming api


code:
params = ["my.exe", "-param1", "-param2", "value 2"]
if debug:
  print("executed command: " + " ".join(params))
result = subprocess.check_call(params)

rawDescription: Show in terminal commad executed by subprocess.check_call() in python


code:
import win32api, win32con
def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)

rawDescription: Controlling mouse with Python

description: Controlling mouse with Python


code:
max_value = max(scores.values())
keys = [ i for (i,v) in scores.iteritems() if v == max_value ]

rawDescription: Key to maxima of dictionary in python

description: Key to maxima of dictionary in python


code:
for i in range(0,18):
    for i2 in range(0,i):
        ...

rawDescription: Loop that skips the values it already done


code:
@patch('module.a')
@patch('module.b')
@patch('module.c')
def test_main_routine(c, b, a):
    manager = Mock()
    manager.attach_mock(a, 'a')
    manager.attach_mock(b, 'b')
    manager.attach_mock(c, 'c')

    module.main_routine()

    expected_calls = [call.a('a'), call.b('b'), call.c('c')]
    assert manager.mock_calls == expected_calls

rawDescription: Checking call order across multiple mocks


code:
import re

d = {}

with open('data', 'r') as f:

    for line in f:

        line =   re.sub('\s', '', line)

        key, value = line.split('=')

        d[key] = value

for el in d.items():

    print(el)

rawDescription: Python: How do i convert data in text file into a dictionary?


code:
s = "fname:John,lname:doe,mname:dunno,city:Florida"
sd = dict(u.split(":") for u in s.split(","))

rawDescription: How to convert comma-separated key value pairs into a dictionary using lambda functions

description: Convert comma-separated key value pairs into a dictionary using lambda functions


code:
sentence = 'This is a sentence'
split_values = []
tmp = ''
for c in sentence:
    if c == ' ':
        split_value.append(tmp)
        tmp = ''
    else:
        tmp += c
if tmp:
    splie_value.append(tmp)

rawDescription: Splitting strings in Python without split()


code:
import msvcrt
answer=msvcrt.getch()

rawDescription: How do I make a menu that does not require the user to press [enter] to make a selection?

description: Make a menu that does not require the user to press [enter] to make a selection


code:
def IntegerChecker(**kwargs): #A is Index, B is End Time, C is Distance, D is Speed Limit
    error = False
    err = {
        'index': ('Watch out!  The Index is not a number :o (this probably '
                  'won\'t break much in this version, might in later ones though!'),
        'end_time': 'Watch out!  The End Time is not a number :o',
        'distance': 'Watch out!  The Distance is not a number :o',
        'speed': 'Watch out!  The Speed Limit is not a number :o'
    }
    for key, value in kwargs.items():
        try:
            int(value)
        except ValueError:
            print(err.get(key))
            error = True
    return error

IntegerChecker(index=a, end_time=b, distance=c, speed=d)

rawDescription: Checking Multiple Integers in Python 3

description: Checking Multiple Integers in Python 3


code:
import numpy
a = numpy.arange(10)
b = a[:5]
a
b
a += 10
a
b
b += 10
a
b

rawDescription: Resize NumPy array to smaller size without copy


rawDescription: Replace items in a list with unique items starting from 0


rawDescription: How to append tuple to sub-sub-list?

description: Append tuple to sub-sub-list


code:
for key, dlist in dict1.items():
    if not dlist:
        list1.append("Free Period")
        continue
    for item in dlist:
        if item in list1:
            continue
        if item in elective:
            elecStorage.append(item)
        elif item in prereq:
            list1.append(item)

rawDescription: Look inside contents of list stored inside dictionary


code:
A = DeclareSort('A')
a = Const('a', A)

rawDescription: Creating constant from sort in Z3 Python API


code:
string = 'Saturday and Sunday and Monday and Tuesday and Wednesday and Thursday and Friday are days of the week.'
string.replace(' and ', ", ", (string.count(' and ')-1))

rawDescription: To replace but the last occurrence of string in a text


code:
import numpy as np

df1 = np.array([2,7,17,0])
p1 = np.array([1,6,11,20])
p2 = np.array([5,10,15,16])
name = np.array(['A','B','C','D'])

result = []

for d in df1:

    categories = np.logical_or(
        np.logical_and(d >= p1, d <= p2),
        np.logical_and(d <= p1, d >= p2))

    result.append(name[categories[0]] if np.any(categories) else '')

print(result)

rawDescription: python: if a number falls within a certain range, return the string corresponding to that range

description: Python: if a number falls within a certain range, return the string corresponding to that range


code:
from random import randint

List = [randint(0,99) for i in range(20)]
print("%3s" % List)
List.sort()
print("%3s" % List)

rawDescription: Python 3.x random input for lists

description: Python 3.x random input for lists


code:
from scipy.ndimage.interpolation import zoom
img3d2 = zoom(img3d, 4, order=0)

rawDescription: Plot volume planes in python mayavi with no voxel interpolation


code:
output = []
with open('input.txt', 'r') as f:
    for line in f:
        if line == '<<eof>>':
            break
        elif not line.startswith('<<row>>'):
            continue
        else:
            output.append(line.strip()[7:-8].split('|'))

rawDescription: Parsing a string pattern (Python)

description: Parsing a string pattern (Python)


code:
import re

def _search_line_for_key_value (key, line):
    key_finder = re.finditer(key + r'\s*=', line)
    try:
        first_match = next(key_finder)
    except StopIteration:
        return None
    value = re.match(r'\s*([^,\s]+)', line[first_match.end():])
    if not value:
        raise ValueError('A line was encountered with an invalid %s value' % key)
    try:
        next(key_finder)
    except StopIteration:
        return value.group(1)
    else:
        raise ValueError('A line was encountered with more than one %s value' % key)

def get_elset_material_dict (filename):
    results = {}
    for line in open(filename):
        elset = _search_line_for_key_value('ELSET', line)
        if elset is not None:
            results[elset] = _search_line_for_key_value('MATERIAL', line)
    return results

rawDescription: Create an array of strings with a combination of text found in a file using python


code:
import curses
import curses.textpad as textpad

def main(screen):
    """screen is a curses screen passed from the wrapper"""
    while True:
        textpad.Textbox(curses.newwin(1,13,4,0), insert_mode=True).edit()
        textpad.Textbox(curses.newwin(1,13,4,16), insert_mode=True).edit()

if __name__ == '__main__':
    curses.wrapper(main)

rawDescription: multiple Textboxes in curses

description: Multiple Textboxes in curses


code:
def find(string_list, search):
    return [s for s in string_list if search in s]

rawDescription: Changing lists with a given string

description: Changing lists with a given string


code:
from mock import patch
with patch('something') as mock_something:
    self.assertFalse(mock_something.called)

rawDescription: python something like assertFunctionNotCalled?

description: Python something like assertFunctionNotCalled


code:
from matplotlib.pyplot import rc, grid, figure, plot, rcParams, savefig
from math import radians

def generate_satellite_plot(observer_lat, observer_lon):
    rc('grid', color='#316931', linewidth=1, linestyle='-')
    rc('xtick', labelsize=15)
    rc('ytick', labelsize=15)

    # force square figure and square axes looks better for polar, IMO
    width, height = rcParams['figure.figsize']
    size = min(width, height)
    # make a square figure
    fig = figure(figsize=(size, size))

    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')
    ax.set_theta_zero_location('N')
    ax.set_theta_direction(-1)

    sat_positions = [[1, 30, 0], [2, 60, 90], [3, 30, 180], [4, 50, 270]]
    for (PRN, E, Az) in sat_positions:
        ax.annotate(str(PRN),
                    xy=(radians(Az), 90-E),  # theta, radius
                    bbox=dict(boxstyle="round", fc = 'green', alpha = 0.5),
                    horizontalalignment='center',
                    verticalalignment='center')

    ax.set_yticks(range(0, 90+10, 10))                   # Define the yticks
    yLabel = ['90', '', '', '60', '', '', '30', '', '', '']
    ax.set_yticklabels(yLabel)
    grid(True)

    savefig('foo.png')

rawDescription: Matplotlib polar plot is not plotting where it should


code:
from tkinter import *
import ctypes, os

def callback():
    active.set(False)
    #root.destroy()         # Uncoment this to close the window

def sleep():
    if not active.get(): return
    root.after(1000, sleep)
    timeLeft.set(timeLeft.get()-1)
    timeOutLabel['text'] = "Time Left: " + str(timeLeft.get())  #Update the label
    if timeLeft.get() == 0:                                     #sleep if timeLeft = 0
        os.system("Powercfg -H OFF")
        os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
        callback()

root = Tk()
root.geometry("400x268")
root.title("Alert")
root.configure(background='light blue')

timeLeft = IntVar()
timeLeft.set(10)            # Time in seconds until shutdown

active = BooleanVar()
active.set(True)            # Something to show us that countdown is still going.

label = Label(root, text="ALERT this device will go to sleep soon!",   fg="red")
label.config(font=("Courier", 12))
label.configure(background='light blue')
label.pack()
timeOutLabel = Label(root, text = 'Time left: ' + str(timeLeft.get()), background='light blue') # Label to show how much time we have left.
timeOutLabel.pack()
quitButton = Button(root, text="do not sleep!", command=callback)
quitButton.pack()
quitButton.place(x=150, y=150)

root.after(0, sleep)
root.mainloop()

rawDescription: How do I execute a command after some time but with a cancel button

description: Execute a command after some time but with a cancel button


code: 'test.mp3'.endswith(('.mp3', '.avi'))

rawDescription: Check if string ends with one of the strings from a list


code:
def __init__(self, *args, **kwargs):
    super(MySerializerClass, self).__init__(*args, **kwargs)
    if self.context.get('request', None):
        field = self.fields.get('b')
        field.queryset = field.queryset.filter(user=request.user)

rawDescription: django-rest-framework : restrict RelatedField queryset according to request

description: Django-rest-framework : restrict RelatedField queryset according to request


code:
#!/usr/bin/env python

import mechanize
import cookielib
import urllib
import logging
import sys

def main():

    br = mechanize.Browser()
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    r= br.open('http://www.reddit.com')

    # Select the second (index one) form
    br.select_form(nr=1)

    # User credentials
    br.form['user'] = 'user'
    br.form['passwd'] = 'passwd'

    # Login
    br.submit()

    # Open up comment page
    posting = 'http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/'
    rval = 'PoopSandwiches'
    # you can get the rval in other ways, but this will work for testing

    r = br.open(posting)

    # You need the 'uh' value from the first form
    br.select_form(nr=0)
    uh = br.form['uh']

    br.select_form(nr=7)
    thing_id = br.form['thing_id']
    id = '#' + br.form.attrs['id']
    # The id that gets posted is the form id with a '#' prepended.

    data = {'uh':uh, 'thing_id':thing_id, 'id':id, 'renderstyle':'html', 'r':rval, 'text':"Your text here!"}
    new_data_dict = dict((k, urllib.quote(v).replace('%20', '+')) for k, v in data.iteritems())

    # not sure if the replace needs to happen, I did it anyway
    new_data = 'thing_id=%(thing_id)s&text=%(text)s&id=%(id)s&r=%(r)s&uh=%(uh)s&renderstyle=%(renderstyle)s' %(new_data_dict)

    # not sure which of these headers are really needed, but it works with all
    # of them, so why not just include them.
    req = mechanize.Request('http://www.reddit.com/api/comment', new_data)
    req.add_header('Referer', posting)
    req.add_header('Accept', ' application/json, text/javascript, */*')
    req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    req.add_header('X-Requested-With', 'XMLHttpRequest')
    cj.add_cookie_header(req)
    res = mechanize.urlopen(req)

main()

rawDescription: Using Python and Mechanize to submit form data and authenticate


code:
import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.residentadvisor.net/dj/greggow/tracks')
html = r.content

soup = BeautifulSoup(html, 'html.parser')
div = soup.find_all('div', class_= "title")

for each in div:

    #3 options presented themselves, either with a href or not in title

    if each.find("a"):
        #Either a link back to the track
        if "track.aspx" in each.find("a")["href"]:
            each = each.find("a").get_text()

        #or to some other weird source
        else:
            each = str(each)
            each = each[each.find(">") + 1 : each.find("
") ]

    else:
        each = str(each)
        each = each[each.find(">") + 1 : each.find("
") ]
    print(each)

rawDescription: How to extract the track titles from this page with beautiful soup

description: Extract the track titles from this page with beautiful soup


code:
class Position(models.Model):
    website_postiton = models.IntegerField()
    category = models.ForeignKey('Category')
    directory = models.ForeignKey('Directory')

class Category(models.Model):
    n_category = models.CharField(max_length=100)

class Directory(models.Model):
    website_name = models.CharField(max_length=200)
    website_url = models.URLField()
    categories = models.ManyToManyField(Category, through=Position)

rawDescription: How to implement this model in Django?

description: Implement this model in Django


code:
from itertools import chain

num = 1
biglist = [[[1, 2, 3], [4, 5, 6, 7]], [[3, 7, 5], [1, 2, 4, 6]]]
been_with = set(chain(*[x for x in chain(*biglist) if num in x])) - {num}

rawDescription: How to determine how many unique other items an integer has been with in a list of lists of lists?

description: Determine how many unique other items an integer has been with in a list of lists of lists


code:
def make_ordered(d):
    if isinstance(d, dict):
        return OrderedDict(sorted((key, make_ordered(value)) for key, value in d.iteritems()))
    else:
        return d

rawDescription: Python complete ordering of a nested dict


code:
final_list = []
for destination in destinations:
    final_list += YourCDRModel.objects.filter(area__in=destination).values_list('number', flat=True).order_by('?')[0:3]

rawDescription: mysql select data for each value in array

description: Mysql select data for each value in array


code:
daemon_main.daemon = True
daemon_main.start()

rawDescription: How are daemon processes started in Python?


code:
import bsddb3.db as db
def bsdtest():
    d = db.DB()
    d.open('test.db', dbtype=db.DB_HASH, flags=db.DB_CREATE)
    # d.exists()
    for key in range(1000000):
        d.put(bytes(str(key), encoding='ascii'),
              bytes(str('value'), encoding='ascii'))
    d.close()

rawDescription: Running out of memory in Python using dict of namedtuples


code: self.canvas.create_image(0, 0, image=self.image, anchor="nw")

rawDescription: Tkinter canvas doesn't show entire photo image


code:
import maya.cmds as cmds

def makeIdentityCurvesWithSharedHistory(curves=[]):
    for curve in curves:
        curveShape = cmds.listRelatives(curve, shapes=True)[0]
        makeCircle = cmds.listConnections(curveShape, type='makeNurbCircle')[0]
        transformation = cmds.xform(curve, q=True, matrix=True)
        transformGeoNode = cmds.createNode('transformGeometry')
        cmds.setAttr('%s.transform' % transformGeoNode, transformation, type='matrix')
        cmds.connectAttr('%s.outputCurve' % makeCircle, '%s.inputGeometry' % transformGeoNode)
        cmds.connectAttr('%s.outputGeometry' % transformGeoNode, '%s.create' % curveShape, force=True)
        cmds.xform(curve, matrix=[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0])

circle1 = cmd.circle(nr=(0, 0, 1), c=(0, -1.1, 0), ch=1)
circle2 = cmd.duplicate(circle1[0], ic=1)
circle3 = cmd.duplicate(circle1[0], ic=1)
cmd.setAttr(circle2[0] + '.rotateZ', 120)
cmd.setAttr(circle3[0] + '.rotateZ', -120)

allCurves = circle1[0], circle2[0], circle3[0]
makeIdentityCurvesWithSharedHistory(allCurves)

rawDescription: Same python code works differently on differently Maya (2012 - 2015)


code:
from copy import deepcopy

def duplicate_quiz(modeladmin, request, queryset):
    for quiz in queryset:
        new_obj = deepcopy(quiz)
        new_obj.id = None
        new_obj.save()

        for question in quiz.questions.all():
            question_copy = deepcopy(question)
            question_copy.id = None
            question_copy.save()
            new_obj.questions.add(question_copy)

            for choice in question.choices.all():
                choice_copy = deepcopy(choice)
                choice_copy.id = None
                choice_copy.save()
                question_copy.choices.add(choice_copy)

        new_obj.save()

duplicate_quiz.short_description = "Duplicate Selected Quizzes"

class QuizAdmin(NestedModelAdmin):
    model = Quiz
    form = QuizForm
    inlines = [QuestionInline, DoubleDownQuestionInline]
    list_display = ('name', 'quiz_start_date',
                    'quiz_end_date')
    actions = [duplicate_quiz]

admin.site.register(Quiz, QuizAdmin)

rawDescription: Django admin - Duplicate an item under a NestedModelAdmin


code:
l = [None,None,None]
reduce(lambda x,y: x== y, l)
from functional import scanl
scanl(lambda x,y: x== y, None, l)
list(scanl(lambda x,y: x== y, None, l))

rawDescription: Why python reduce() behaves differently with the `None` element?


code:
from celery import task
from billiard import current_process

@task
def getName():
    p = current_process()
    return p.index

rawDescription: Get the name of celery worker from inside a celery task?


code:
def fullmatch(regex, string, flags=0):
    """Emulate python-3.4 re.fullmatch()."""
    return re.match("(?:" + regex + r")\Z", string, flags=flags)

rawDescription: Backport Python 3.4's regular expression "fullmatch()" to Python 2


code:
import matplotlib.pyplot as plt

a = [1,2,3]
b = [3,2,1]

def func1(x):
    plt.plot(x)

def func2(x):
    plt.plot(x)

fig = plt.figure()
func1(a)
func2(b)

rawDescription: Plotting to 1 figure using multiple functions with Matplotlib, Python


code:
import unittest

class FunctionalTests(unittest.TestCase):
    def setUp(self):
        from myapp import main
        app = main({})
        from webtest import TestApp
        self.testapp = TestApp(app)

    def test_root(self):
        res = self.testapp.get('/', status=200)
        self.failUnless('Pyramid' in res.body)

rawDescription: unit test to check if for a given path a correct context will be returned

description: Unit test to check if for a given path a correct context will be returned


code:
df # an example DataFrame
costs = [1, 0, 0, 0, 2]
df['f'] = df.dot(costs)
df

rawDescription: Pandas - Create new dataframe column using dot product of elements in each row


code:
import asyncio

@asyncio.coroutine
def echo_server():
    yield from asyncio.start_server(handle_connection, 'localhost', 8000)

@asyncio.coroutine
def handle_connection(reader, writer):
    while True:
        data = yield from reader.read(8192)
        if not data:
            break
        writer.write(data)

loop = asyncio.get_event_loop()
loop.run_until_complete(echo_server())
try:
    loop.run_forever()
finally:
    loop.close()

rawDescription: Program structure using asyncio

description: Program structure using asyncio


code: df.apply(lambda x: x[x['Col']], axis=1)

rawDescription: Pandas Series from Column with Column names


code:
for d, a in zip(Dates, Amount):
    ws.append([d, a, 12])

rawDescription: OpenPyXL - Insert list contents and go to next row (for loop)


code: elem = driver.find_element_by_css_selector("div.pager span.action-btn:last-of-type");

rawDescription: Selenium click on next button

description: Selenium click on next button


rawDescription: Python ABC seems to allow incomplete implementation


code:
def directed_graph_from_edges(edges):
    graph = {}
    for a,b in edges:
        graph.setdefault(a,set())
        graph[a].add(b)
    return graph

rawDescription: Python: Creating combinations from a list of lists in a tree-like data structure


code:
if level in easy:
    current_text = easy_level
    answers = easy_answers
elif level in medium:
    current_text = medium_level
    answers = medium_answers
elif level in hard:
    current_text = hard_level
    answers = hard_answers
ask_questions(current_text, answers)

rawDescription: Python: if statement with two variables

description: Python: if statement with two variables


code:
def mytest():
    s1 = 'thing1'
    s2 = 'a_number'
    s3 = ['personA','GenderA','personB','GenderB','personC','GenderC','personD','GenderD','personE','GenderE',]
    s4 = ['comment by F','comm_F_gender','comment','ano_num','comment by G','comm_G_gender','comment','ano_num','comment by H','comm_H_gender','comment','ano_num']
    with open('mytestfb.csv', 'a') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        exportlist=[s1,s2]
        for count in range(len(s3)/2):
            exportlist+=s3[count*2-1:count*2]
            try:
                exportlist+=s4[count*4-1+count*4]
            except IndexError:
                pass
        spamwriter.writerow(exportlist.encode('utf-8'))

rawDescription: python excel csv help. how to do formatting

description: Python excel csv help. how to do formatting


code:
M=30
N=40
X = np.zeros((M,N))  # random values, but 0s work too
Y = np.where(np.random.rand(M,N) > .5, True, False)
A=np.array([ 7,  8, 10, 13]), # in my setting, it's (1,4), not (4,)
B = [1,2,1,1]

# position in row where X should equal - 1, i.e. X[7,a0], X[8,a1], etc
a0=np.where(Y[7]==True)[0][0]
a1=np.where(Y[8]==True)[0][0]
a2=np.where(Y[8]==True)[0][1]
a3=np.where(Y[10]==True)[0][0]
a4=np.where(Y[13]==True)[0][0]

# For each row (i) indexed by A, take only B[i] entries where Y[i]==True.  Assume these indices in X = -1
for i in range(len(A[0])):
    X[A[0][i]][(Y[A][i]==True).nonzero()[0][0:B[i]]]=-1

np.sum(X) # should be -5
X[7,a0]+X[8,a1]+X[8,a2]+X[10,a3]+X[13,a4] # should be -5

rawDescription: Replacing values in numpy array

description: Replacing values in numpy array


code:
b = []
for item in a.values():
    b.extend(item) if isinstance(item,list) else b.append(item)

b

rawDescription: How can I iterate over multidimensional python dictionaries without having to detect if they have sub lists?

description: Iterate over multidimensional python dictionaries without having to detect if they have sub lists


rawDescription: Python Regex matching on unexpected parts of search string


code:
def key_collect():
    global key_score
    global score_rect
    k_rect = pygame.draw.rect(SURF, (0,0,0), (k_spritex, k_spritey, 30, 40), 1)
    p_score_rect = pygame.draw.rect(SURF, (0,0,0), (p_spritex, p_spritey, 30, 40), 1)
    if p_score_rect.colliderect(k_rect):
        if score_rect == True:
            key_score = key_score + 100
            score_rect = False
            return key_score, score_rect
    else:
        score_rect = True
        return key_score, score_rect

rawDescription: Creating a score function in pygame with collisions


code:
userdata = (('dlazarov',), ('ant1',))
[x[0] for x in userdata]

rawDescription: Converting tuples to lists and getting rid of inner tuple/list


rawDescription: Parsing TCL lists in Python

description: Parsing TCL lists in Python


code:
value = 5
user = input('Please enter a username: ')

with open('myfile.txt', 'r+') as f:
    var = f.readlines()
    if user in ''.join(var):
        for count, line in enumerate(var):
            if user in line:
                found = line.strip() + ', ' + str(value) + '\n'
                var[count] = found
    else:
        '{} not in the file but has been added'
        var.append(user + ' ' + str(value) + '\n')

with open('myfile.txt', 'w') as f:
        f.writelines(var)

rawDescription: Python 3 How do I append a list in a file?


code:
class Second(object):
    def __init__(self):
        self.variable3 = First()

class Third(Second):
    def __init__(self):
        super(Third, self).__init__()
        self.variable4 = self.variable3.subvar2

rawDescription: Composite and Hierarchy without instance shared variables


code:
with open('some_file_1.txt', 'r') as file1:
    with open('some_file_2.txt', 'r') as file2:
        same = set(file1).intersection(file2)

same.discard('\n')

with open('some_output_file.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

rawDescription: Compare two different files line by line in python


code:
import inspect

def staticmethods(cls):
    for name, method in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls, name, staticmethod(method.__func__))
    return cls

@staticmethods
class Test:
    def test():
        print("Test")

Test.test()

rawDescription: Any way to apply staticmethod to all class methods?


code:
def __init__(self):
    # initialize various variables

    wx.CallAfter(self.check_combobox, args)

def check_combobox(self, args):
    self.myTextField.Enable(False) if self.myCombo.GetValue() != "value1" else self.myTextField.Enable(True)

rawDescription: WXPython: getting the initial value of a combo box


code: (datetime.now() - timedelta(hours=24)).strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Building correct MySQL datetime formatted string for yesterday in Python


code: somestring = ('{:6.3f}' * len(mylist)).format(*mylist)

rawDescription: Most elegant way to .format() formatted string with arbitrary length list in Python 2?


code:
string = r'\n...\n'
re.search("Subject sentence is:(.*)Causal Verb is :(.*)predicate sentence is:(.*)", string)

rawDescription: Why do I need to add DOTALL to python regular expression to match new line in raw string


code: reversed_ = sum(1<<(numbits-1-i) for i in range(numbits) if original>>i&1)

rawDescription: How do you reverse the significant bits of an integer in python?

description: Reverse the significant bits of an integer in python


code:
import datetime;

today = datetime.datetime.now()
todayPlus2Hours = today + datetime.timedelta(hours=2)

print(todayPlus2Hours)

print(todayPlus2Hours.hour)
print(todayPlus2Hours.minute)
print(todayPlus2Hours.second)

rawDescription: Change localtime from UTC to UTC + 2 in python


code:
class SignDocTemplate(BaseDocTemplate):
   blocks_to_pages = {}
   def handle_flowable(self, flowables):
     f = flowables[0]
     BaseDocTemplate.handle_flowable(self, flowables)
     if hasattr(f,'flo_id'):
       if self.blocks_to_pages.has_key(self.canv._pageNumber):
          self.blocks_to_pages[self.canv._pageNumber].append(f.flo_id)
       else:
          self.blocks_to_pages[self.canv._pageNumber]= [f.flo_id,]

rawDescription: How to know on what page number flowable was placed during rendering a pdf with reportlab

description: Know on what page number flowable was placed during rendering a pdf with reportlab


code:
df.pivot(index='labels', columns='category', values='values').head()
df.pivot(index='labels', columns='category', values='values').plot()

rawDescription: Create line plot with 2 series splitted by column value


code:
class A(object):
    def __init__(self, param_a, **kwargs):
        self.param_a = param_a
        super(A, self).__init__(**kwargs)

class B(A):
    def __init__(self, param_b, **kwargs):
        self.param_b = param_b
        super(B, self).__init__(**kwargs)

class C(A):
    def __init__(self, param_c, **kwargs):
        self.param_c = param_c
        super(C, self).__init__(**kwargs)

class D(B, C):
    def __init__(self, param_d, **kwargs):
        self.param_d = param_d
        super(D, self).__init__(**kwargs)

d = D(param_a=1, param_b=2, param_c=3, param_d=4)

rawDescription: Python 3 builtin types __init__ doesn't call super().__init__?


code: your_sum = sum([ord(i) for i in '\xff\x1a'])

rawDescription: Multiple characters in Python ord function


rawDescription: Why does pygame.draw.shape return a Rect?


code:
import MySQLdb
import datetime

THEHOST="localhost"
THEUSER="user"
THEPASSWD="passwd"
THEDB="database"

connection=MySQLdb.connect(
    host=THEHOST,user=THEUSER,passwd=THEPASSWD,db=THEDB)
cursor=connection.cursor()

abc,efg,ijk=1,2,3

data={'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],
      '2': ['2', 'K', efg, 'xyz', None, None, None, None],
      '3': ['3', 'K', ijk, 'xyz', None, None, None,
            datetime.datetime(2010, 2, 5, 16, 31, 2)]}

sql='''\
CREATE TABLE IF NOT EXISTS temp (id int auto_increment primary key,
    field1 varchar(8),
    field2 int,
    field3 varchar(8),
    field4 bool,
    field5 varchar(8),
    field6 varchar(8),
    field7 datetime )'''

cursor.execute(sql)

sql='''\
INSERT INTO temp (id, field1, field2, field3, field4, field5, field6, field7)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
'''
cursor.executemany(sql, data.values())

rawDescription: How do I insert data from a Python dictionary to MySQL?

description: Insert data from a Python dictionary to MySQL


code: mylambda=pd.Series(lambda_calc, name='lambda', index = close_return[:,[1]])

rawDescription: Python loop indexing on time stamped data


code:
from multiprocessing import Process

class ProcHandler(Process):
    def __init__(self,  *args, **kwargs):
        #Initialize
        Process.__init__(self, *args, **kwargs)

    def run(self):
        p = bteqExec('python ./bteq/timer.py','')
        rc = p.wait()
        # do update the resulting to database. and make the web.py
        # Progress class read from database entry made by this Process.
        return

rawDescription: python web.py execute external program asynchronously

description: Python web.py execute external program asynchronously


code:
from glob import glob
paths = glob('set01/*/*.png')

rawDescription: Python function that similar to bash find command


rawDescription: How do you use msvcrt.getch to extract and use input?

description: Use msvcrt.getch to extract and use input


code:
y = []
for a in xs:
    for b in xs:
        if f(a, b):
            y.append(g(a, b))

rawDescription: Re-write the for loop function in python, need help to understand better


code:
def search(name, listofdict):
    return any( d["name"]==name for d in listofdict )

rawDescription: How to find out if element is in any dictionary for specific key in list of dictionaries?

description: Find out if element is in any dictionary for specific key in list of dictionaries


code:
args = ['add_phenotype.py', '-t', threads, '-s']
if zeroed_out_file:
    args.append('-z')

subprocess.call(args)

rawDescription: Python3 subprocess module: Passing an empty variable as a flag, is it possible?


code:
reachedHeight = False
while (not (reachedHeight and states[4,(i - 1)] >= 100000 and states[4,i] <= 100000)):
  if (not reachedHeight and states[4,i] >= 100000):
    reachedHeight = True
  ...

rawDescription: Crossing an altitude in Python

description: Crossing an altitude in Python


code:
h=float(input("h: "))
q=float(input("Angle: "))
l=float(input("Pendulum length: "))

rawDescription: Python pendulum

description: Python pendulum


code:
#!/usr/bin/python
import sys.argv

if sys.argv[1] == "stringhere":
    print("Argument is equal to string!")

rawDescription: How would I take a string from an argument and use it in an if statement?


code:
try:
    int(some_string)
    is_valid_number = True

except ValueError:
    is_valid_number = False

rawDescription: Validation Data Type Check going against expectations?


code:
import lxml.etree as ET
import matplotlib.pyplot as plt

text='''\
<table>
 <row>
   <x>10</x>
   <t>10:00</t>
</row>
<row>
   <x>20</x>
   <t>10:05</t>
</row>
</table>
'''

def convert_t(text):
    a,b=map(float,t.split(':'))
    return a+b/60.0

doc=ET.fromstring(text)
x=[float(x) for x in doc.xpath('//x/text()')]
t=[convert_t(t) for t in doc.xpath('//t/text()')]
plt.plot(x,t)
plt.show()

rawDescription: xml2array in python

description: Xml2array in python


code:
class B(A):
     __init__ = my_init

rawDescription: How do I override init?

description: Override init


code: x | y

rawDescription: Taking the max from multiple Counters instead of adding them up - Python


code:
matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
    matching[0]['qty'] += int(qty)
else:
    session['cart'].append(dict({'product_id': id, 'qty': int(qty)}))

rawDescription: How to append existing keys by value in python dictionary?

description: Append existing keys by value in python dictionary


code: coordlist = np.column_stack((x.ravel(), y.ravel(), z.ravel()))

rawDescription: re-arranging grid points with numpy

description: Re-arranging grid points with numpy


code:
while a:
    print('hi')

    a = False
    if not a:
        break

    print('bye')

rawDescription: Python: While Loop Check Throughout Loop if True


code: dict['hits'].update({'&lt': 30})

rawDescription: `Between` query to mongodb using python

description: `Between` query to mongodb using python