code:
import re

def parse_nested(text, left=r'[(]', right=r'[)]', sep=r','):
    """ Based on http://stackoverflow.com/a/17141899/190597 (falsetru) """
    pat = r'({}|{}|{})'.format(left, right, sep)
    tokens = re.split(pat, text)
    stack = [[]]
    for x in tokens:
        if not x or re.match(sep, x): continue
        if re.match(left, x):
            stack[-1].append([])
            stack.append(stack[-1][-1])
        elif re.match(right, x):
            stack.pop()
            if not stack:
                raise ValueError('error: opening bracket is missing')
        else:
            stack[-1].append(x)
    if len(stack) > 1:
        print(stack)
        raise ValueError('error: closing bracket is missing')
    return stack.pop()

text = '((wordOneWord2)OtherWord(FinalWord))'
print(parse_nested(text))
# [[['wordOneWord2'], 'OtherWord', ['FinalWord']]]

rawDescription: Turn a string with nested parenthesis into a nested list, python


code:
from PyQt4.QtCore import QUrl, QFileInfo, QFile, QIODevice
from PyQt4.QtGui import QApplication, QDialog, QProgressBar, QLabel, QPushButton, QDialogButtonBox, \
                    QVBoxLayout, QMessageBox
from PyQt4.QtNetwork import QHttp

url_to_download = 'http://www.riverbankcomputing.co.uk/static/Downloads/sip4/sip-4.12.3.zip'

class Downloader(QDialog):
    def __init__(self, parent=None):
        super(Downloader, self).__init__(parent)

        self.httpGetId = 0
        self.httpRequestAborted = False
        self.statusLabel = QLabel('Downloading %s' % url_to_download)
        self.closeButton = QPushButton("Close")
        self.closeButton.setAutoDefault(False)
        self.progressBar = QProgressBar()

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)

        self.http = QHttp(self)
        self.http.requestFinished.connect(self.httpRequestFinished)
        self.http.dataReadProgress.connect(self.updateDataReadProgress)
        self.http.responseHeaderReceived.connect(self.readResponseHeader)
        self.closeButton.clicked.connect(self.cancelDownload)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(self.progressBar)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle('Download Example')
        self.downloadFile()

    def downloadFile(self):
        url = QUrl(url_to_download)
        fileInfo = QFileInfo(url.path())
        fileName = fileInfo.fileName()

        if QFile.exists(fileName):
            QFile.remove(fileName)

        self.outFile = QFile(fileName)
        if not self.outFile.open(QIODevice.WriteOnly):
            QMessageBox.information(self, 'Error',
                    'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        mode = QHttp.ConnectionModeHttp
        port = url.port()
        if port == -1:
            port = 0
        self.http.setHost(url.host(), mode, port)
        self.httpRequestAborted = False

        path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            path = str(path)
        else:
            path = '/'

        # Download the file.
        self.httpGetId = self.http.get(path, self.outFile)

    def cancelDownload(self):
        self.statusLabel.setText("Download canceled.")
        self.httpRequestAborted = True
        self.http.abort()
        self.close()

    def httpRequestFinished(self, requestId, error):
        if requestId != self.httpGetId:
            return

        if self.httpRequestAborted:
            if self.outFile is not None:
                self.outFile.close()
                self.outFile.remove()
                self.outFile = None
            return

        self.outFile.close()

        if error:
            self.outFile.remove()
            QMessageBox.information(self, 'Error',
                    'Download failed: %s.' % self.http.errorString())

        self.statusLabel.setText('Done')

    def readResponseHeader(self, responseHeader):
        # Check for genuine error conditions.
        if responseHeader.statusCode() not in (200, 300, 301, 302, 303, 307):
            QMessageBox.information(self, 'Error',
                    'Download failed: %s.' % responseHeader.reasonPhrase())
            self.httpRequestAborted = True
            self.http.abort()

    def updateDataReadProgress(self, bytesRead, totalBytes):
        if self.httpRequestAborted:
            return
        self.progressBar.setMaximum(totalBytes)
        self.progressBar.setValue(bytesRead)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    downloader = Downloader()
    downloader.show()
    sys.exit(app.exec_())

rawDescription: Threading in pyqt4

description: Threading in pyqt4


code:
a=np.arange(1,4)
a
a.reshape(3,1)
np.vstack(a)

rawDescription: Create vertical numpy arrays in python

description: Create vertical numpy arrays in python


code:
import pymedia.audio.sound as sound
f = wave.open('myFile.wav', 'rb')
snd = sound.Output( f.getframerate(), f.getnchannels(), sound.AFMT_S16_LE )
s = f.readframes( 300000 )
snd.play(s)

rawDescription: Crossplatform sound with Python standard library


code:
a = np.arange(10)
a.flags.writeable = False
a[0] = 1
# Gives: RuntimeError: array is not writeable

rawDescription: Immutable numpy array?

description: Immutable numpy array


code:
import scipy.optimize as opt

negated_profit_func = lambda x : cost_func(x) - revenue_func(x)
result = opt.minimize_scalar(negated_profit_func, bounds = (0, 50), method = 'bounded')

print(result)

rawDescription: Scipy: Maximize Distance between Interpolated Curves


code:
import random
random.seed(1234)
g=Graph.Watts_Strogatz(1, 100, 2, 0.25)
random.seed(1234)
g2=Graph.Watts_Strogatz(1, 100, 2, 0.25)
g.get_edgelist() == g2.get_edgelist()

rawDescription: Seeding graph generator in python-igarph


code:
from ast import literal_eval
tup = literal_eval(a)

rawDescription: How to unstring a list/tuple without eval

description: Unstring a list/tuple without eval


code:
def convert(f):
    whole, frac = f.split()
    return int(whole) + fractions.Fraction(frac)

rawDescription: Is there a Python module where I could easily convert mixed fractions into a float?


code:
def lowerString(string):
  result = ""
  for i in string:
     # i is a character in the string
     result = result + lowerChar(i)
  # This shouldn't be under the for loop
  return result

rawDescription: python making my own lower case converter

description: Python making my own lower case converter


code:
def agregar_folios(self, valor):
    self.fecha_ultima_compra = timezone.now()
    if self.pk is not None:
        self._folios = models.F('folios') + valor
    else:
        self._folios = valor
    self.save()

def sustraer_folios(self, valor):
    self.fecha_ultimo_venta = timezone.now()
    if self.pk is not None:
        self._folios = models.F('folios') - valor
    else:
        self._folios = valor
    self.save()

rawDescription: Can't save model using F expression

description: Can't save model using F expression


rawDescription: How do I find the length (or dimensions, size) of a numpy matrix in python?

description: Find the length (or dimensions, size) of a numpy matrix in python


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

x = np.arange(-np.pi, np.pi, 0.01)

fig = plt.figure()
fig.suptitle('Main figure title')

ax1 = fig.add_subplot(311, title='Subplot 1 title')
ax1.plot(x, np.sin(x))

ax2 = fig.add_subplot(312)
ax2.set_title('Subplot 2 title')
ax2.plot(x, np.cos(x))

ax3 = fig.add_subplot(313)
ax3.set_title('Subplot 3 title')
ax3.plot(x, np.tan(x))

plt.show()

rawDescription: In matplotlib, what's the difference between title() and suptitle()?


code:
def toSqlListPlaceholder(array):
    return ",".join( ["%s"] * len(array) )

querystr = ("SELECT * FROM some_tbl WHERE some_column IN( %s );" %
            (toSqlListPlaceholder( someArray )) )
cursor.execute(querystr,someArray)

rawDescription: What's the "best" way to create a dynamic sql "in list" clause in Python from an array (or tuple) of strings?


code:
def flatten(g):
    return g.fillna(method='bfill').iloc[0]

df.groupby('Z').apply(flatten).reset_index(drop=True)

rawDescription: Combine rows and fill NaN values within groups


code:
def lists(l):
    '''
    Return the total number of lists in A (including A itself).
    Each element of A and any  nested lists are either ints or other lists.
    '''

    # convert the list to string and count the ['s
    # each [ is the start of a list, so the number of ['s equals
    # the number of lists
    nr_of_lists = str(l).count('[')

    # return the number of sublists
    return nr_of_lists

rawDescription: How to find the number of lists in an input? (python)

description: Find the number of lists in an input? (python)


code:
import sublime, sublime_plugin

class PythonREPLHelperCommand(sublime_plugin.EventListener):
  def on_activated(self, view):
    syntax = view.settings().get('syntax')
    if syntax=='Packages/Python/Python.tmLanguage':
      plugin_settings = sublime.load_settings('SublimeREPL.sublime-settings')
      plugin_settings.set("show_transferred_text", True)
    else:
      plugin_settings = sublime.load_settings('SublimeREPL.sublime-settings')
      plugin_settings.set("show_transferred_text", False)

rawDescription: Language-specific package settings in Sublime Text


code:
INSTALLED_APPS = (
    #...
    "somedir",
)

rawDescription: Django manage.py syncdb not creating models


code:
class TestResource(ModelResource):
   ...
   def prepend_urls(self):
      return [
        url(r"^(?P<resource_name>%s)/commands$" % self._meta.resource_name, self.wrap_view('handle_commands'), name="api_handle_commands"),
    ]

def handle_commands(self, request):
   command = request.POST['command']
   product = Product.objects.get(name=request.POST['product'])
   # do your stuff

rawDescription: Let tastypie client do CRUD without foreign key lookups


rawDescription: Django unique_together but only for filtering


code: x_values=[i[0] for i in points]

rawDescription: Elegant way to retrieve all x-coordinates


code:
def check_selling(track, excludes):
    """
    Returns True if all track's artists are allowed for selling. False otherwise
    """
    if track.artists.filter(selling=False).exists(): #If "selling" is a boolean
        excludes.append(track)
        return False
    return True

rawDescription: Django optimize for loop in method

description: Django optimize for loop in method


code:
write("""<html><head>
    <script>
    var x = %d, y = %d;
    </script>
    </head>""" % (x, y))

rawDescription: html & javascript to use Python variables in GAE

description: Html & javascript to use Python variables in GAE


code:
df = DataFrame(np.random.randn(5,2))
df
pd.set_option('display.precision',12)
df

rawDescription: Converting object to float loses too much precision - pandas


code:
from Tkinter import *
def getvalue():
    e1_var.get()
    l1 = Label(root, text=e1_var).grid()

root = Tk()
e1_var = StringVar
e1 = Entry(root, textvariable=e1_var).grid()
b1 = Button(root, command=getvalue).grid()
root.mainloop()

rawDescription: How to take an input from a user using an entry box in Python?

description: Take an input from a user using an entry box in Python


code:
def parse_signed_request(signed_request, app_secret):
    try:
        l = signed_request.split('.', 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
    except IndexError:
        raise ValueError("'signed_request' malformed")

    sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))

    data = json.loads(data)

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        raise ValueError("'signed_request' is using an unknown algorithm")
    else:
        expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        raise ValueError("'signed_request' signature mismatch")
    else:
        return data

def fb_registration(request):
    if request.POST:
        if 'signed_request' in request.POST:
            # parse and check data
            data = parse_signed_request(request.POST['signed_request'], settings.FACEBOOK_APP_SECRET)

            # lets try to check if user exists based on username or email
            try:
                check_user = User.objects.get(username=data['registration']['name'])
            except:
                state = "Username is already exist. Please try other account."
                return HttpResponseRedirect(reverse('accounts:register'))

            try:
                check_user = User.objects.get(email=data['registration']['email'])
            except:
                state = "Email is already exist. Please use other account."
                return HttpResponseRedirect(reverse('accounts:register'))

            #lets create now the user
            randompass = ''.join([choice('1234567890qwertyuiopasdfghjklzxcvbnm') for i in range(7)])
            user = User.objects.create_user(data['registration']['name'], data['registration']['email'], randompass)
            user.save()

            user = authenticate(username=data['registration']['name'], password=randompass)

            if user is not None:
                # save in user profile his facebook id
                fbid = 'http://www.facebook.com/profile.php?id=%s' % data['user_id']
                r = RPXAssociation(user=user, identifier=fbid)
                r.save()
                login(request, user)
            return HttpResponseRedirect(reverse('accounts:choose_plan'))
        else:
            state = "Registration request failed!"

    return HttpResponseRedirect(reverse('accounts:register'))

rawDescription: facebook signed request email

description: Facebook signed request email


code: plt.title(figure_title, y=1.08)

rawDescription: Python Matplotlib figure title overlaps axes label when using twiny


rawDescription: Hex string variable to hex value conversion in python


code:
def execute(func=None, *args, **kwargs):
    if func:
        func(*args, **kwargs)

rawDescription: Pass empty/noop function/lambda as default argument


code:
m = mock.Mock()
m(1,2,3)
m.call_args
m.assert_called_with(1,2,4)

rawDescription: python mock side-effect return value

description: Python mock side-effect return value


code:
def announce_start():
    # code to connect to irc server and announce deployment begins
    pass

def announce_finish():
    # code to connect to irc server and announce deployment finishes
    pass

@hosts(...)
def deploy_machine1():
    pass

@hosts(...)
def deploy_machine2():
    pass

def deploy():
    announce_start()
    execute(deploy_machine1)
    execute(deploy_machine2)
    announce_finish()

rawDescription: Fabric - Run a command locally before and after all tasks complete


code:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import itertools

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

mu_vec1 = np.array([0,0,0])
cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20)

eig_val, eig_vec = np.linalg.eig(cov_mat1)

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d', axisbg='black')

colors = ['red','blue','green']

for v,c in itertools.izip(eig_vec.T,colors):
    a = Arrow3D([0, v[0]], [0, v[1]],
                [0, v[2]], mutation_scale=20, lw=5, arrowstyle="-|>", color=c)
    ax.add_artist(a)
ax.axis('off')

plt.show()

rawDescription: Matplotlib - Separate colours for individual arrows


code:
import sys
sys.path.insert(0 ,"path-to-another-folder/")
import requests
requests.get

rawDescription: Override installed module in import

description: Override installed module in import


code: [x[1] for x in my_func(i) if x[0] == 0]

rawDescription: Is there a better way to do this python code?


rawDescription: Best way to get split version number with regular expression

description: Get split version number with regular expression


code:
import datetime
print(datetime.datetime.strptime('201502190759', '%Y%m%d%H%M'))

rawDescription: Convert string into datetime timestamp

description: Convert string into datetime timestamp


code:
class Foo(object):
    pass

class Thing(object):
    pass

# List of interesting classes
classes = [Foo, Thing]

# Construct a dictionary where the key is the Classes __name__ attribute
classByNames = {cls.__name__:cls for cls in classes}

# Example usage
cName = 'Foo'
if cName in classByNames:
    inst = classByNames[cName]()
    print(inst) # <__main__.Foo object at ...>
else:
    print("Unknown class %s" % cName)

rawDescription: Python invalid syntax when using eval(strClass)


code:
import re

# Gonna be using this a lot, so compile it.
digit_pattern = re.compile('[0-9]')

# We're creating a class because there's a little bit of state to maintain.
class OracleErrorFinder(object):
    def __init__(self, input_file):
        self.input_file = input_file
        # This seems weird, but there's a good reason.
        # When we get to the end of a match, we're going to have already consumed
        # the next character from the file. So we need to save it for the next round.
        next_char = None

    def find_next_match(self):
        # Possible states are
        # '': We haven't found any portion of the pattern yet.
        # 'O': We found an O
        # 'R': We found an OR
        # 'A': We found an ORA
        # '-': We found an ORA-
        # 'num1': We found ORA-[0-9]
        # 'num2': We found ORA-[0-9][0-9]
        # 'num3': We found ORA-[0-9][0-9][0-9]
        # 'num4': We found ORA-[0-9][0-9][0-9][0-9]
        # 'num5': We found ORA-[0-9][0-9][0-9][0-9][0-9], and we're done

        current_state = ''
        match_so_far = ''
        done = False
        while not done:
            if self.next_char:
                # If we have a leftover char from last time,
                # start with that and clear it.
                c = self.next_char
                self.next_char = None
            else:
                c = self.input_file.read(1)

            if '' == c:
               match_so_far = None
               done = True # End of stream and we didn't find a match. Time to stop.
            elif '' == current_state and 'O' == c:
                # We found the start of what we're looking for.
                # We don't know if it's the whole thing,
                # so we just save it and go to the next character.
                current_state = 'O'
                match_so_far = 'O'
            elif 'O' == current_state and 'R' == c:
                # We already have an O and now we found the next character!
                current_state = 'R'
                match_so_far += c
            elif 'R' == current_state and 'A' == c:
                current_state = 'A'
                match_so_far += c
            elif 'A' == current_state and '-' == c:
                current_state = '-'
                match_so_far += c
            elif '-' == current_state and digit_pattern.match(c):
                current_state = 'num1'
                match_so_far += c
            elif 'num1' == current_state:
                if digit_pattern.match(c):
                    current_state = 'num2'
                    match_so_far += c
                else:
                    # We found a full match,
                    # but not more numbers past the last one.
                    # Time to return what we found.
                    done = True
            elif 'num2' == current_state:
                if digit_pattern.match(c):
                    current_state = 'num3'
                    match_so_far += c
                else:
                    # We found a full match,
                    # but not more numbers past the last one.
                    # Time to return what we found.
                    done = True
            elif 'num3' == current_state:
                if digit_pattern.match(c):
                    current_state = 'num4'
                    match_so_far += c
                else:
                    # We found a full match,
                    # but not more numbers past the last one.
                    # Time to return what we found.
                    done = True
            elif 'num4' == current_state:
                if digit_pattern.match(c):
                    current_state = 'num5'
                    match_so_far += c
                else:
                    # We found a full match,
                    # but not more numbers past the last one.
                    # Time to return what we found.
                    done = True
            elif 'num5' == current_state:
                # We're done for sure!
                # Note that we read the next character from the file.
                # Important for code after the loop.
                done = True
            else:
                # We didn't find the next character we wanted.
                if 'O' == c:
                    # We didn't find a full match, but this starts
                    # a new one.
                    current_state = 'O'
                    match_so_far = 'O'
                else:
                    # This character doesn't match our pattern.
                    # It could be a character that's in the wrong place
                    # (such as the - in OR-) or a character that just
                    # doesn't appear in the pattern at all (like X).
                    # We might be in the middle of a partial
                    # match, so throw everything found so far away
                    # and keep going.
                    current_state = ''
                    match_so_far = ''

        # Save next char already consumed from file stream.
        # Could be empty string if we consumed the whole file,
        # but that's fine.
        self.next_char = c
        return match_so_far

with open(filename) as f:
    finder = OracleErrorFinder(f)
    while True:
        match = finder.find_next_match()
        if None is match:
            break
        # Print, send to file, add to list, what have you

rawDescription: Regex matching on record boundries

description: Regex matching on record boundries


code:
def application(environ, start_response):
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0

    request_body = environ['wsgi.input'].read(request_body_size)
    data = json.loads(request_body)
    build_id = data['BuildId']
    # etc.

rawDescription: How to read Json object with a python wsgi application

description: Read Json object with a python wsgi application


code:
import wx
import wx.lib.scrolledpanel as scrolledpanel

class ScrollableText(scrolledpanel.ScrolledPanel):
    def __init__(self, parent, id=-1, text=[[('black', 'adsf')]]):
        scrolledpanel.ScrolledPanel.__init__(self, parent, id)

        self.SetBackgroundColour('white')
        self.SetVirtualSize((1500, 1500))
        self.SetupScrolling(True, True)

        # a list of lists of (color, string) tuples
        self.Bind(wx.EVT_PAINT, self.redraw)
        self.Bind(wx.EVT_SIZE, self.resize)

        # setup the font
        self.font = wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL)
        if not self.font.IsFixedWidth():
            self.font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.NORMAL, wx.NORMAL)
        assert self.font.IsFixedWidth()

        self.text = text
        self.set_longest_line()

    def set_text(self, text):
        self.text = text
        self.set_longest_line()
        self.resize(None)
        self.Refresh()

    def set_longest_line(self):
        if len(self.text) > 0:
            self.longest_line = max([sum([len(s) for c, s in l]) for l in self.text])
        else:
            self.longest_line = 1

    def draw_lines(self, DC, start, end, lineheight):
        mw = 0
        DC.SetFont(self.font)
        for idx in range(max(0, start), min(end, len(self.text))):
            l = self.text[idx]
            combined = "".join([s[1] for s in l])
            extents = [0] + DC.GetPartialTextExtents(combined)
            for str in l:
                DC.SetTextForeground(str[0])
                DC.DrawText(str[1], extents[0], idx * lineheight)
                extents = extents[len(str[1]):]

    def resize(self, evt):
        DC = wx.ClientDC(self)
        DC.SetFont(self.font)

        # find line width and  height
        extent = DC.GetFullTextExtent('X'*self.longest_line)
        lineheight = extent[1]
        maxwidth = extent[0]

        # set virtual area
        vsize = (maxwidth, len(self.text) * lineheight)
        if self.GetVirtualSize() != vsize:
            self.SetVirtualSize(vsize)

    def redraw(self, evt):
        DC = wx.PaintDC(self)
        self.PrepareDC(DC)
        extent = DC.GetFullTextExtent('x'*self.longest_line)
        lineheight = extent[1]
        vs = self.GetViewStart()
        ppu = self.GetScrollPixelsPerUnit()
        ri = wx.RegionIterator(self.GetUpdateRegion())
        mmin, mmax = len(self.text), 0
        while ri:
            rect = ri.GetRect()
            # find the lines that need rendering
            min_y = rect[1] + vs[1] * ppu[1]
            max_y = rect[1] + rect[3] + vs[1] * ppu[1]
            min_line = int(min_y / lineheight) - 1
            max_line = int(max_y / lineheight) + 2
            mmin = min(min_line, mmin)
            mmax = max(max_line, mmax)
            ri.Next()
        self.draw_lines(DC, mmin, mmax, lineheight)

if __name__ == '__main__':
    class MainFrame(wx.Frame):
        def __init__(self, parent):
            wx.Frame.__init__(self, parent, -1)
            t = [[('black', l[:len(l)/2]), ('red', l[len(l)/2:])] for l in open('scrollable_text.py')]
            self.scrollable = ScrollableText(self, -1, t)

    app = wx.PySimpleApp(None,-1)
    frame = MainFrame(parent=None)
    frame.Show()
    app.MainLoop()

rawDescription: How do I keep a wx.html.HtmlWindow at the same position during resize (without flicker)?

description: Keep a wx.html.HtmlWindow at the same position during resize (without flicker)


code:
from a import *
if name == "Michael" and age == 15:
    print('Simple!')

rawDescription: Python: How can I import all variables?

description: Python: How can I import all variables


code: arg2 = arg2 or myClass()

rawDescription: Argument Presence Checking via Identity or Boolean Operation?


code:
rows = 486
columns = 5
A = [[None] * columns for x in xrange(rows)]
len(A)
len(A[0])

rawDescription: Creating N-dimensional dynamical array based on user's input?


code:
# Length along line that is closest to the point
print(line.project(p))

# Now combine with interpolated point on line
np = line.interpolate(line.project(p))
print(np)  # POINT (5 7)

rawDescription: Coordinate of the closest point on a line


code:
def coef(pot):
    return (pot.movable + pot.convertible) / float(pot.total)

l.sort(key=lambda x: (coef(x), x.total), reverse=True)

rawDescription: sorting function in python

description: Sorting function in python


code:
response = urlfetch.fetch(your_url, follow_redirects=False)
location = response.headers['Location']

rawDescription: How do I get the URL of an HTTP redirect's target?

description: Get the URL of an HTTP redirect's target


code:
soup = BeautifulSoup(html_doc)

with open('Output.txt','w') as f:
    for link in soup.find_all(rel="bookmark"):
        f.write(link.get('href'))

rawDescription: BeautifulSoup Python saving Output links to txt file


code:
import csv
import urllib2
from bs4 import BeautifulSoup

records = []
for index in range(39):
    url = get_url(index)  # where is the formatting in your example happening?
    response = urllib2.urlopen(url)
    try:
        html = response.read()
    except Exception:
        raise
    else:
        my_parse(html)
    finally:
        try:
            response.close()
        except (UnboundLocalError, NameError):
            raise UnboundLocalError

def my_parse(html):
    soup = BeautifulSoup(html)
    table2 = soup.find_all('table')[1]
    for tr in table2.find_all('tr')[2:]:
        tds = tr.find_all('td')
        url = tds[8].a.get('href')
        records.append([elem.text.encode('utf-8') for elem in tds])
        # perhaps you want to update one of the elements of this last
        # record with the found url now?

# It's more efficient to write only once
with open('listing.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(records)

rawDescription: BeautifulSoup / Python - Convert HTML table to CSV and get href for one column


code:
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

def main():
    start, stop = dt.datetime(2012,3,1), dt.datetime(2012,4,1)

    fig, ax = plt.subplots()
    for color in ['blue', 'red', 'green']:
        starts, stops = generate_data(start, stop)
        plot_durations(starts, stops, ax, facecolor=color, alpha=0.5)
    plt.show()

def plot_durations(starts, stops, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    # Make the default alignment center, unless specified otherwise
    kwargs['align'] = kwargs.get('align', 'center')

    # Convert things to matplotlib's internal date format...
    starts, stops = mpl.dates.date2num(starts), mpl.dates.date2num(stops)

    # Break things into start days and start times
    start_times = starts % 1
    start_days = starts - start_times
    durations = stops - starts
    start_times += int(starts[0]) # So that we have a valid date...

    # Plot the bars
    artist = ax.bar(start_days, durations, bottom=start_times, **kwargs)

    # Tell matplotlib to treat the axes as dates...
    ax.xaxis_date()
    ax.yaxis_date()
    ax.figure.autofmt_xdate()
    return artist

def generate_data(start, stop):
    """Generate some random data..."""
    # Make a series of events 1 day apart
    starts = mpl.dates.drange(start, stop, dt.timedelta(days=1))

    # Vary the datetimes so that they occur at random times
    # Remember, 1.0 is equivalent to 1 day in this case...
    starts += np.random.random(starts.size)

    # Make some random stopping times...
    stops = starts + 0.2 * np.random.random(starts.size)

    # Convert back to datetime objects...
    return mpl.dates.num2date(starts), mpl.dates.num2date(stops)

if __name__ == '__main__':
    main()

rawDescription: How to create broken vertical bar graphs in matpltolib?

description: Create broken vertical bar graphs in matpltolib


rawDescription: Reverse part of an array using NumPy

description: Reverse part of an array using NumPy


code:
import re
pat = r"\b(?:{})\b".format('|'.join([r'student',r'study(?:ing)?']))
print(pat)
# => \b(?:student|study(?:ing)?)\b
regEX=re.compile(pat,re.I)
s = "He is studying here."
mObj = regEX.search(s)
if mObj:
    print(mObj.group(0))
# => studying

rawDescription: how to exclude sentences containing specific word

description: Exclude sentences containing specific word


code:
import subprocess
st = subprocess.check_output(["mdls", "-name", "kMDItemDateAdded", "-raw", "Untitled.gif"])

rawDescription: Python OS X - get 'date added' info from file


code:
def getGroups(boardstr, xlen, ylen):
    board = Board(boardstr, xlen, ylen)
    groups = MyClass.findGroups(board.get_field())
    return groups

def groups_3():
    # ... setup for level 3
    return getGroups(boardstr, xlen, ylen)

def groups_10():
    # ... setup for level 10
    return getGroups(boardstr, xlen, ylen)

# decorator function
def params(funcarglist):
    def wrapper(function):
        function.funcarglist = funcarglist
        return function
    return wrapper

def pytest_generate_tests(metafunc):
    # called once per each test function
    for funcargs in getattr(metafunc.function, 'funcarglist', ()):
        # schedule a new test function run with applied **funcargs
        metafunc.addcall(funcargs=funcargs)

class TestClass:

    groups_3 = groups_3()
    groups_10 = groups_10()

    @params([dict(g=groups_3, e=9),
             dict(g=groups_10, e=22)])
    def test_total_groups(self, g, e):
        assert len(g) == e

    @params([dict(g=groups_3, e=5),
             dict(g=groups_10, e=7)])
    def test_total_clickable_groups(self, g, e):
        assert len([grp for grp in g if grp.clickable is True]) == e

    @params([dict(g=groups_3, e=3),
             dict(g=groups_10, e=3)])
    def test_total_colors(self, g, e):
        assert len(np.unique([grp.color for grp in g])) == e

rawDescription: py.test: Get expected values for test functions for different fixtures from configuration

description: Py.test: Get expected values for test functions for different fixtures from configuration


rawDescription: Slice pandas dataframe to get only oneday's data


code:
from scrapy.http import Request
from scrapy.utils.httpobj import urlparse_cached

class CrissCrossOffsiteMiddleware(object):

    def process_spider_output(self, response, result, spider):
        domainr = urlparse_cached(response.url).hostname
        for x in result:
            if isinstance(x, Request):
                if x.dont_filter:
                    yield x
                else:
                    domaino = urlparse_cached(x).hostname
                    if domaino == domainr:
                        yield x
            else:
                yield x

rawDescription: Set allowed_domains per starter_url in scrapy?


code: df.groupby('textId').filter(lambda x: set(x['score']) >= set([1.,2.,3.]))

rawDescription: How to select dataframe rows according to multi-(other column)-condition on columnar groups?

description: Select dataframe rows according to multi-(other column)-condition on columnar groups


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")))
finally:
    ff.quit()

rawDescription: After successful web login with selenium, can not use newly loaded page


code:
df = pd.read_csv(cusp.csv, sep='\s+')
df.cusip.isin(['XXXX', 'ZZZZ'])
df[df.cusip.isin(['XXXX', 'ZZZZ'])]

rawDescription: Subset a DF in Pandas Python

description: Subset a DF in Pandas Python


code:
dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]
dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]
consolidated = {i['code']:i['number'] for i in dict1}
for i in dict2:
    if i['code'] in consolidated:
        consolidated[i['code']] += i['number']
    else:
        consolidated[i['code']] = i['number']
print(consolidated)

rawDescription: Problems comparing different dictionaries in python


code: ax = plot_dataframe(tracts, column='CRIME', scheme='QUANTILES', k=3, colormap='OrRd', legend=True)

rawDescription: Choropleth map from Geopandas GeoDataFame


code:
def write(self, cr, uid, ids, vals, context=None):
    if vals.has_key('high_temp') and vals.has_key('low_temp'):
        high_temp = vals['high_temp']
        low_temp = vals['low_temp']
        a = 65 - ((high_temp + low_temp)/2)
        if a < 0:
            a = 0
        vals['heat_degree_day'] = a
        vals['hw_degree_day'] = a + 5
    return super(degree_day, self).write(cr, uid, ids, vals, context=context)

def create(self, cr, uid, vals, context=None):
    if vals.has_key('high_temp') and vals.has_key('low_temp'):
        high_temp = vals['high_temp']
        low_temp = vals['low_temp']
        a = 65 - ((high_temp + low_temp)/2)
        if a < 0:
            a = 0
        vals['heat_degree_day'] = a
        vals['hw_degree_day'] = a + 5
    return super(degree_day, self).create(cr, uid, vals, context=context)

rawDescription: readonly field not writing to database when on_change event modifies it

description: Readonly field not writing to database when on_change event modifies it


code:
p1 = re.compile(r'(?:%s)\s((?:to\s)?(\w+|\d+\w+)\s\w+)' % words)
dd = re.search(p1,str1)
dd.group()
cc = re.search(p1,str2)
cc.group()

rawDescription: Modifying a Regex Expression

description: Modifying a Regex Expression


code:
lis = []
a=['1545','1254','1545']
for i in a:
    if i not in lis:
        lis.append(i)

lis
set(a)

rawDescription: How to find a duplicate in a list without using set in python?

description: Find a duplicate in a list without using set in python


code:
import itertools

myList = [[1,2,3],[4,5],[6],[7,8,9]]

itr = itertools.chain.from_iterator(myList)

rawDescription: Flat generators in Python

description: Flat generators in Python


code:
for key, group in itertools.groupby(...):
    next(group)
    for val in group:
        ...

rawDescription: Skip the first element in Python iterable


code: [par.cromosoma for par in poblacionOrdenada]

rawDescription: Make a list of attribute from a list of objects


code:
image = cv2.imread('image.png')
height, width, depth = image.shape

image = image.astype('float')
B, G, R = image[:, :, 0], image[:, :, 1], image[:, :, 2]
num = R - B
den = R + B
image = np.where(den == 0, 1, (num/den)*255.0).clip(0.0, 255.0)

cv2.imwrite('newImage.png',image)

rawDescription: How to increase pixel math speed using NumPy

description: Increase pixel math speed using NumPy


code:
SUV.__bases__
Car.__bases__

rawDescription: retrieve inheritance relationship information in python

description: Retrieve inheritance relationship information in python


code:
def Main():
    Class_A_Input = int(raw_input('Enter Class A tickets sold: '))
    total_profit(Class_A_Input)

def total_profit(Class_A_Tickets):
    print (Class_A_Tickets * 15)
    a = Class_A_Tickets * 15
    b = str(a)
    text_file = open('test.txt', 'w')
    text_file.write(b)
    text_file.close()

Main()

rawDescription: Python - Send Function Into Text Document


code:
response = urllib2.urlopen(URL)
lines=response.read().splitlines()

rawDescription: How to download file from url using python in the same format?

description: Download file from url using python in the same format


code:
import numpy as np
from scipy.cluster.hierarchy import fclusterdata

# a custom function that just computes Euclidean distance
def mydist(p1, p2):
    diff = p1 - p2
    return np.vdot(diff, diff) ** 0.5

X = np.random.randn(100, 2)

fclust1 = fclusterdata(X, 2, metric=mydist)
fclust2 = fclusterdata(X, 2, metric='euclidean')

print(np.allclose(fclust1, fclust2))
# True

rawDescription: How to specify a distance function for clustering?

description: Specify a distance function for clustering


code:
def find_all(target, substring):
    current_pos = target.find(substring)
    while current_pos != -1:
        yield current_pos
        current_pos += len(substring)
        current_pos = target.find(substring, current_pos)

rawDescription: Finding the second, third, or further times that a string of characters occurs in a string in python


code:
urlpatterns = patterns('app.views',
    url(r'^dashboard$', 'dashboard', name='dashboard'),
    url(r'^dashboard/(?P<date>[\d]{8})/$', 'dashboard', name='dashboard'),
    url(r'^dashboard/(?P<account_uid>[\da-zA-Z-]{36})/$', 'dashboard', name='dashboard'),
    url(r'^dashboard/(?P<date>[\d]{8})/(?P<account_uid>[\da-z-]{36})/$', 'dashboard', name='dashboard'),
)

rawDescription: Same view with multiple URL patterns and optional arguments


code:
with open('out.txt', 'w', encoding='utf-8') as f:
    csvfile = csv.writer(f)
    maxsize = 1024                # max file size in bytes
    for row in data():
        csvfile.writerow(row)
        if f.tell() > maxsize:    # f.tell() gives byte offset, no need to worry about multiwide chars
            break

rawDescription: Stop Python Script from Writing to File after it reaches a certain size in linux


code:
import numpy as np
from scipy.spatial import Delaunay

points = np.random.rand(30, 2)
tri = Delaunay(points)

p = tri.points[tri.vertices]

# Triangle vertices
A = p[:,0,:].T
B = p[:,1,:].T
C = p[:,2,:].T

# See http://en.wikipedia.org/wiki/Circumscribed_circle#Circumscribed_circles_of_triangles
# The following is just a direct transcription of the formula there
a = A - C
b = B - C

def dot2(u, v):
    return u[0]*v[0] + u[1]*v[1]

def cross2(u, v, w):
    """u x (v x w)"""
    return dot2(u, w)*v - dot2(u, v)*w

def ncross2(u, v):
    """|| u x v ||^2"""
    return sq2(u)*sq2(v) - dot2(u, v)**2

def sq2(u):
    return dot2(u, u)

cc = cross2(sq2(a) * b - sq2(b) * a, a, b) / (2*ncross2(a, b)) + C

# Grab the Voronoi edges
vc = cc[:,tri.neighbors]
vc[:,tri.neighbors == -1] = np.nan # edges at infinity, plotting those would need more work...

lines = []
lines.extend(zip(cc.T, vc[:,:,0].T))
lines.extend(zip(cc.T, vc[:,:,1].T))
lines.extend(zip(cc.T, vc[:,:,2].T))

# Plot it
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

lines = LineCollection(lines, edgecolor='k')

plt.hold(1)
plt.plot(points[:,0], points[:,1], '.')
plt.plot(cc[0], cc[1], '*')
plt.gca().add_collection(lines)
plt.axis('equal')
plt.xlim(-0.1, 1.1)
plt.ylim(-0.1, 1.1)
plt.show()

rawDescription: Python: Calculate Voronoi Tesselation from Scipy's Delaunay Triangulation in 3D


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

mol=np.random.rand(6,3)*10.0

fig3d = plt.figure(figsize = ( 6.5, 6.5 ) )

fig3d.canvas.set_window_title('3D')

ax3d = fig3d.gca(projection='3d')
ax3d.scatter(mol[:,0], mol[:,1], mol[:,2], s=200)

# List to save your projections to
projections = []

# This is called everytime you release the mouse button
def on_click(event):
    azim, elev = ax3d.azim, ax3d.elev
    projections.append((azim, elev))
    print(azim, elev)

cid = fig3d.canvas.mpl_connect('button_release_event', on_click)

plt.show()

rawDescription: How to get azimuth and elevation from a matplotlib figure

description: Get azimuth and elevation from a matplotlib figure


code:
pkts_rxd = []
def process_and_send(pkt):
    pkts_rxd.append(pkt)
    sendp(pkt, 'eth1')
sniff(prn=process_and_send, iface='eth0', count=100)

rawDescription: How to read complete IP frames from TCP socket in Python?

description: Read complete IP frames from TCP socket in Python


code:
cj = cookielib.CookieJar()
opener = build_opener(ProxyHandler({'http': 'ip:port'}), HTTPCookieProcessor(cj))

rawDescription: Both using cookies and a proxy in Python with urllib2


code:
Column('created_on', DateTime, default=datetime.datetime.now)

Column('last_updated', DateTime, onupdate=datetime.datetime.now)

rawDescription: What's equivalent to Django's auto_now, auto_now_add in SQLAlchemy?


code:
class BoxLayoutWithBlueCircle(BoxLayout):

    def add_buttons(self, how_many):
        self.clear_widgets()

        for i in range(how_many):
            button = Button(text='button_{}'.format(i))
            # add here more attributes, like size
            self.add_widget(button)

rawDescription: How to add widget automatically or dynamically into program?

description: Add widget automatically or dynamically into program


code: size = number_of_elements * number_of_basis_functions**2

rawDescription: How to assemble large sparse matrices effectively in python/scipy

description: Assemble large sparse matrices effectively in python/scipy


code:
from time import time

class DecayingSet:
    def __init__(self, timeout): # timeout in seconds
        from collections import deque
        self.timeout = timeout
        self.d = deque()
        self.present = set()

    def add(self, thing):
        # Return True if `thing` not already in set,
        # else return False.
        result = thing not in self.present
        if result:
            self.present.add(thing)
            self.d.append((time(), thing))
        self.clean()
        return result

    def clean(self):
        # forget stuff added >= `timeout` seconds ago
        now = time()
        d = self.d
        while d and now - d[0][0] >= self.timeout:
            _, thing = d.popleft()
            self.present.remove(thing)

rawDescription: Best way to limit incoming messages to avoid duplicates

description: Limit incoming messages to avoid duplicates


code:
english_vocab = set(w.lower() for w in nltk.corpus.words.words())
text_vocab = set(w.lower() for w in text if w.lower().isalpha())
unusual = text_vocab.difference(english_vocab)

rawDescription: NLTK and language detection

description: NLTK and language detection


code:
# The following code will search 'mm/dd/yyyy' (e.g. NOV/30/2016 ),
# and replace with 'mm-dd-yyyy' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
    content = f.read()
content_new = re.sub('(\w{2})/(\d{2})/(\d{4})', r'\1-\2-\3', content, flags = re.M)

rawDescription: replace string in file with using regular expressions

description: Replace string in file with using regular expressions


code:
from __future__ import division

from wand.image import Image

def crop_center(image):
    dst_landscape = 1 > image.width / image.height
    wh = image.width if dst_landscape else image.height
    image.crop(
        left=int((image.width - wh) / 2),
        top=int((image.height - wh) / 2),
        width=int(wh),
        height=int(wh)
    )

rawDescription: Create square thumbnails with Python + MagickWand


code:
import urllib
def submitcheckout(request):
    print(urllib.unquote(request.COOKIES['cart']))

rawDescription: Formatting Django request cookies

description: Formatting Django request cookies


code: post.user_key = shuffle(users)[0].key

rawDescription: How to set an ndb keyProperty

description: Set an ndb keyProperty


code:
from datetime import datetime
from bson.objectid import ObjectId

newdate = datetime.utcnow() + timedelta(seconds=-10)
dummy_id = ObjectId.from_datetime(newdate)

result = collection.find( { "_id": { "$gt": dummy_id } } )

rawDescription: How to look up the entries added to a table in last 5 seconds using Pymongo in python for mongodb

description: Look up the entries added to a table in last 5 seconds using Pymongo in python for mongodb


code:
import cairo

surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, 128, 128)
ctx = cairo.Context (surface)

posX = posY = 0

img = cairo.ImageSurface.create_from_png('sample.png')
ctx.set_source_surface(img, posX, posY)
ctx.paint()

# Draw mask
ctx.set_operator(cairo.OPERATOR_DEST_IN)
img = cairo.ImageSurface.create_from_png('mask.png')
ctx.set_source_surface(img, posX, posY)
ctx.paint()

surface.write_to_png ("example.png") # Output to PNG

rawDescription: Image compositing

description: Image compositing


code:
import sys, os, glob

dir_path = sys.argv[1]
if dir_path[-1] != os.sep: dir_path+=os.sep

file_list = glob.glob(dir_path+'*.txt') #use standard *NIX wildcards to get your file names, in this case, all the files with a .txt extension

with open('out_file.csv', 'w') as out_file:
    for filename in file_list:
        with open(filename, 'r') as in_file:
            for line in in_file:
                if 'STRING=SOME_STRING' in line:
                    out_file.write(line.split(':')[0]+'\n')

rawDescription: Find "string" in Text File - Add it to Excel File Using Python


rawDescription: Check whether a list starts with the elements of another list


code:
def in_language(bnf):
    if ...: # corresponding to: S => 0 S 1
        return True
    if ...: # corresponding to: S => 1 S 0
        return True
    if ...: # corresponding to: S => 0
        return True
    return False

rawDescription: newB struggling with Backus Naur at Udacity Comp. Sci. 101

description: NewB struggling with Backus Naur at Udacity Comp. Sci. 101


code:
from configobj import ConfigObj

conf = ConfigObj('filename.ini')
section = conf['section']
value = section['value']

rawDescription: ConfigObj/ConfigParser vs. using YAML for Python settings file


code:
start = dt.datetime(2015, 7, 1)
data = pd.io.data.DataReader('AAPL', 'yahoo', start)
data = data.reset_index()
data['Date2'] = data['Date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
tuples = [tuple(x) for x in data[['Date2','Open','High','Low','Close']].values]

fig, ax = plt.subplots()
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.xticks(rotation=45)
plt.xlabel("Date")
plt.ylabel("Price")
plt.title("AAPL")
candlestick_ohlc(ax, tuples, width=.6, colorup='g', alpha =.4);

rawDescription: Display csv with candlestick_ohlc

description: Display csv with candlestick_ohlc


rawDescription: regex to find postition between two markers in string

description: Regex to find postition between two markers in string


rawDescription: Multi edge python igraph questions

description: Multi edge python igraph questions


code:
from functools import wraps

def validate_params(view_func):
    def _decorator(request, *args, **kwargs):
        dct = getattr(request, request.METHOD)
        if not isValid(dct):
            return HttpResponse('Bad request', status=401)
        else:
            response = view_func(request, *args, **kwargs)
            return response
    return wraps(view_func)(_decorator)

rawDescription: macro like functionality in python django

description: Macro like functionality in python django


rawDescription: How to use columns of a key in a dict in Python?

description: Use columns of a key in a dict in Python


code:
import wx
import wx.html2

app = wx.App(False)
frame = wx.Frame(None, -1, 'test')
browser = wx.html2.WebView.New(frame)
def loaded(e):
    if e.GetURL() == 'about:blank':  # Skip if it's a blank page.
        return
    browser.RunScript("document.getElementById('id-search-field').value = 'test'")
browser.Bind(wx.html2.EVT_WEBVIEW_LOADED, loaded)
browser.LoadURL("https://www.python.org/")
frame.Show()
app.MainLoop()

rawDescription: How to programmatically fill a textBox from wx.html2.WebView wxpython object?

description: Programmatically fill a textBox from wx.html2.WebView wxpython object


code:
import re

def splitParagraphIntoSentences(paragraph):
    ''' break a paragraph into sentences
    and return a list '''

    sentenceEnders = re.compile('[.!?]')
    sentenceList = sentenceEnders.split(paragraph)
    return sentenceList

if __name__ == '__main__':
    p = "This is a sentence. This is an excited sentence! And do you think this is a question? so what to do then because many people will say this ok. and then what ?"

    sentences = splitParagraphIntoSentences(p)

    file = open('another.txt', "w")

    for s in sentences:
        if s.strip():
            file.write('"' + s.strip() + '"\n')  # Add a newline after each sentence

    file.close()

rawDescription: How to convert paragraphs to double quotes sentences in python

description: Convert paragraphs to double quotes sentences in python


code:
class UserDetailsForm(RegistrationForm):
    middle_name = ...
    phone_number = ...

    class Meta:
        model = User
        fields = ('username', ..., 'password2')

rawDescription: How to create a collection of fields from two Django forms?

description: Create a collection of fields from two Django forms


code:
for i in file.readline().split(" ")[1:]:
    str += (file.readline().split(" ")[1:])[i] + " "

rawDescription: Join specific string indexes python

description: Join specific string indexes python


rawDescription: adding extra axis ticks using matplotlib

description: Adding extra axis ticks using matplotlib


code:
body = {}
body['Name'] = "PTestServiceGroup %s" % time.strftime("%d%m%H%M%S")
body['ServiceIds'] = [service_id1, service_id2]  # wherever these come from

data = json.dumps(body)

rawDescription: parameterizing python POST request containing JSON body

description: Parameterizing python POST request containing JSON body


code:
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from PIL import Image
import cStringIO

msg = MIMEMultipart()

im = Image.new("RGB", (200, 200))
memf = cStringIO.StringIO()
im.save(memf, "JPEG")
img = MIMEImage(memf.getvalue())

msg.attach(img)

rawDescription: Converting PIL image to MIMEImage

description: Converting PIL image to MIMEImage


code:
bz = bugzilla.Bugzilla(url='https://bugzilla.redhat.com/xmlrpc.cgi')
bug = bz.getbug(495561)

rawDescription: How do I use bugzilla's webservice xml-rpc with python?

description: Use bugzilla's webservice xml-rpc with python


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

plt.ion()

ax = plt.axes(projection='3d')
n = 3

xs = np.random.randint(23, 32, n)
ys = np.random.randint(0, 100, n)
zs = np.random.randint(0, 10, n)
scatter = ax.scatter(xs, ys, zs=zs)

plt.draw()
scatter.set_visible(False)
plt.draw()
scatter.set_visible(True)
plt.draw()

rawDescription: re-plotting lines after clearing Axes3D

description: Re-plotting lines after clearing Axes3D


code:
import sys
import os
import time
from PyQt4 import QtCore, QtGui

class Ui_ProgressBarDialog(QtGui.QWidget):
    def __init__(self, process, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.thread = process
        self.setupUi(self)
        self.center()
        self.thread.start()

    def center(self):
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def setupUi(self, ProgressBarDialog):
        ProgressBarDialog.setObjectName("ProgressBarDialog")
        ProgressBarDialog.resize(400, 33)
        self.verticalLayout = QtGui.QVBoxLayout(ProgressBarDialog)
        self.verticalLayout.setObjectName("verticalLayout")
        self.progressBar = QtGui.QProgressBar(ProgressBarDialog)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.verticalLayout.addWidget(self.progressBar)

        self.retranslateUi(ProgressBarDialog)

        #Close when the thread finishes (normally)
        QtCore.QObject.connect(
            self.thread,
            QtCore.SIGNAL("finished()"),
            self.close
        )

        #Close when the thread is terminated (exception, cancelled etc)
        QtCore.QObject.connect(
            self.thread,
            QtCore.SIGNAL("terminated()"),
            self.close
        )

        #Let the thread update the progress bar position
        QtCore.QObject.connect(
            self.thread,
            QtCore.SIGNAL("updateProgress"),
            self.progressBar.setValue
        )

        #Repaint when the progress bar value changes
        QtCore.QObject.connect(
            self.progressBar,
            QtCore.SIGNAL("valueChanged(int)"),
            ProgressBarDialog.repaint
        )

        QtCore.QMetaObject.connectSlotsByName(ProgressBarDialog)

    def retranslateUi(self, ProgressBarDialog):
        ProgressBarDialog.setWindowTitle("Please Wait")

    def closeEvent(self, event):
        if self.thread.exit_status == self.thread.RUNNING:
            if QtGui.QMessageBox.question(None, 'Cancel Download', "Are you sure you want to cancel the download?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
                if self.thread.exit_status == self.thread.RUNNING:
                    self.thread.exiting = True
                    while self.thread.exiting:
                        time.sleep(0.25)
                elif self.thread.exit_status == self.thread.SUCCESS:
                    self.thread.exit_status = self.thread.CANCELLED
            else:
                if self.thread.exit_status == self.thread.RUNNING:
                    event.ignore()

app = QtGui.QApplication(sys.argv)
filename = str(QtGui.QFileDialog.getSaveFileName(
    None,
    "Save as",
    os.getcwd(),
    "Data files: (*.dat)"
))

class DeviceDataStreamHandler(QtCore.QThread):
    RUNNING = 1
    SUCCESS = 0
    FAILURE = -1
    CANCELLED = -2

    class CancelledError(Exception):
        pass

    def __init__(self, parent = None, **kwargs):
        QtCore.QThread.__init__(self, parent)
        self.exiting = False
        self.exit_status = DeviceDataStreamHandler.RUNNING
        self.device = device
        self.filename = filename

    def run(self):
        progress = 0
        try:
            temp_binary_file = open(self.filename, "wb")
            #getDataStream is an interator returing strings
            for data in self.device.getDataStream():
                temp_binary_file.write(data)
                progress += 1
                self.emit(QtCore.SIGNAL("updateProgress"), progress)
                if self.exiting:
                    raise DeviceDataStreamHandler.CancelledError()
            self.exit_status = DeviceDataStreamHandler.SUCCESS
        except DeviceDataStreamHandler.CancelledError:
            self.exit_status = DeviceDataStreamHandler.CANCELLED
            self.device.cancelDownload()
        except Exception as E:
            self.exit_status = DeviceDataStreamHandler.FAILURE
            self.error_details = str(E)
        finally:
            temp_binary_file.close()
            if self.exit_status == DeviceDataStreamHandler.CANCELLED:
                os.unlink(filename)
        self.exiting = False

class HardwareDeviceObject(object):
    def __init__(self):
        #initialises comms with a hardware device
        self.event_count = 0
        self.capture = False

    def startCapture(self):
        self.capture = True

    def cancelDownload():
        self.capture = False

    def read(self):
        #returns a string sent from the device
        time.sleep(1)
        self.event_count += 1
        return self.event_count

    def getDataStream(self):
        class DataStreamIterator(object):
            def __init__(self, ds, max_capture_count = 100):
                self.ds = ds
                self.capture_count = 0
                self.max_capture_count = max_capture_count

            def __iter__(self):
                return self

            def next(self):
                #return string received from device
                if self.ds.capture and self.capture_count < self.max_capture_count:
                    self.capture_count += 1
                    return self.ds.read()
                else:
                    raise StopIteration()

        self.startCapture()
        return DataStreamIterator(self)

capture = DeviceDataStreamHandler(device = HardwareDeviceObject(), filename = filename)
form = ProgressBarDialog.Ui_ProgressBarDialog(capture)
form.setWindowTitle("Dumping sessions")
form.progressBar.setMaximum(100) #expect 100 outputs from the device
form.progressBar.setValue(0)
form.show()

app.exec_()
if capture.exit_status == DeviceDataStreamHandler.SUCCESS:
    QtGui.QMessageBox.information(None, 'Success', "Save to disk successful", QtGui.QMessageBox.Ok)
elif capture.exit_status == DeviceDataStreamHandler.FAILURE:
    QtGui.QMessageBox.critical(None, 'Error interacting with device', "{}".format(capture.error_details), QtGui.QMessageBox.Ok)

rawDescription: PyQT4 QWidget must receive 'close' signal twice before closing


code:
class DerivedGatherer(BaseGatherer):

    def __init__(self):
        super(DerivedGatherer, self).__init__()
        self.counter = 0

    def get_string(self):
        self.counter += 10
        super_string = super(DerivedGatherer, self).get_string()
        return super_string[0:1] + 'loc=' + str(self.counter) + super_string[1:]

class DerivedDoer(BaseDoer):

    def do_it(self, some_derived_gatherer):
        while(~some_stop_condition()):
            super(DerivedDoer, self).do_it(some_derived_gatherer)

rawDescription: Python - how to properly extend classes to modify the operation of base methods


code: user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

rawDescription: django delete self and not a self referential entity

description: Django delete self and not a self referential entity


code:
list1 = range(1, 100)
list2 = range(10, 50, 5)

new_values = []

for x in list1:
    for y in list2:
        new_values.append(x*y)

rawDescription: Multiplying two sets of numbers in python


code:
ids = Employee.objects.filter(company='Private').values_list('id', flat=True)
Person.objects.filter(id__in=ids).values('name', 'age')

rawDescription: how to subquery in queryset in django?

description: Subquery in queryset in django


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

values = (20, 35, 30, 35, 27, 12, 38)
index = np.array((-3000, -2000, -1000, 0, 1000, 2000, 3000))
barwidth = 400
plt.bar(index, values, barwidth)
plt.xticks(index + barwidth/2)
plt.show()

rawDescription: plt.bar (matplotlib in python) does not make bars

description: Plt.bar (matplotlib in python) does not make bars


code:
import os
import pandas as pd
import multiprocessing as mp
def fixer(a_queue):
    a_file = a_queue.get()
    lines = []
    opened_file = open(a_file)
    for each_line in opened_file:
        lines.append(each_line.replace('mad', 'rational'))
    opened_file.close()
    df = pd.DataFrame(lines)
    #some pandas magics here
    df.to_csv(a_file[:-4] + '_fixed.csv')
if __name__ == "__main__":
    my_path = os.getcwd()
    my_files = list(os.walk(my_path))[0][2] #I just get the list of file names here
    processors = mp.cpu_count()
    queue = mp.Queue()
    for each_file in my_files:
        queue.put(each_file)
    processes = [mp.Process(target = fixer, args=(queue,)) for core in range(processors)]
    for process in processes:
        process.start()
    for process in processes:
        process.join()

rawDescription: Python multiprocessing: parsing, editing, and writing long series of csv files


code:
pstr = ctypes.create_string_buffer( 1000 )
f.write( pstr.raw )

rawDescription: Blob object for python (ctypes), C++

description: Blob object for python (ctypes), C++


code:
import os
import subprocess

os.chdir('path')
subprocess.call('command',shell=True)

rawDescription: Send commands to the terminal(Ubuntu) from ipython notebook


code:
class WebSites(object):
    def __init__():
        self.SiteName = ""
        self.Rank = 0

import cPickle
# to serialize the object
with open("data.dump", "wb") as output:
    cPickle.dump(WebSites(), output, cPickle.HIGHEST_PROTOCOL)

# to deserialize the object
with open("data.dump", "rb") as input:
    obj = cPickle.load(input) # protocol version is auto detected

rawDescription: Read write classes to files in an efficent way


code:
def shift(array, n):
    return array[n:] + array[:n]

rawDescription: moving an array in a circular way

description: Moving an array in a circular way


code: session.query(Person).filter(extract('day', Person.birthdate) == 24).all()

rawDescription: Using SQLAlchemy to filter by day in a date field


rawDescription: Cash Flow compounding

description: Cash Flow compounding


code:
wb = load_workbook("my_book.xlsx")
worksheet1 = wb.active()
cell_value = '=HYPERLINK("http://mypage.com", "My Page")'
worksheet1.cell(row=1, column=1, value=cell_value)

rawDescription: Add link to text within cell, not entire cell


code: input("something\n").replace(' ','')

rawDescription: How to give input permission to accept a name with a space?

description: Give input permission to accept a name with a space


code:
from BeautifulSoup import BeautifulSoup as Soup
from soupselect import select
import urllib
soup = Soup(urllib.urlopen('http://slashdot.org/'))
select(soup, 'div.title h3')

rawDescription: jquery-like HTML parsing in Python?

description: Jquery-like HTML parsing in Python


code:
a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
a
a.astype(numpy.int64)

rawDescription: Convert ndarray from float64 to integer

description: Convert ndarray from float64 to integer


code:
match = re.match("(?P<letter>A)", "A")
match.groupdict()

rawDescription: How to get the name of a regex named capturing group?

description: Get the name of a regex named capturing group


code:
arr = []
for sublist in li:
    for item in sublist:
        arr.append( item )

rawDescription: Confusing python list comprehension

description: Confusing python list comprehension


code: scale_str = ax.get_yaxis().get_scale()

rawDescription: Check axes scale in matplotlib

description: Check axes scale in matplotlib


code:
import csv
import string

input_file = open('DesktopData.csv', 'r')
output_file = open('fixformat.csv', 'w')
data = csv.reader(input_file)
writer = csv.writer(output_file,quoting=csv.QUOTE_ALL)# dialect='excel')
specials = '%'

for line in data:
    line = str(line)
    new_line = str.replace(line,specials,'')
    writer.writerow(new_line.split(','))

input_file.close()
output_file.close()

rawDescription: Remove specific character from a csv file, and rewrite to a new file


code:
import smtplib
import sys
import os
import csv
import subprocess
from subprocess import CalledProcessError, Popen, PIPE
import psutil
import re

# Set up mail info
FROM = "it@mail.com"
TO = ["mine@mail.com"] # must be a list
SUBJECTERR = "Batchserver runnning"
TEXTERR = "Batch server running"
SUBJECT = "Batch Server status "
TEXT = "Batch Server running relax"

#Gives response

name = "system.EXE"

running = False
for process in psutil.process_iter():
    if re.search(name, repr(process)):
        running = True
        break
if not running:
    cmd = '\\\\sesrv414\\Applications\\Software\\BIN\\system.EXE'
    p = Popen(cmd, stdin=PIPE, bufsize=0)

server = smtplib.SMTP("email.serv.net",25) # Send the mail
messageErr = "From:%s \nTo:%s \nSubject:%s \n\n%s\n" %(FROM, ", ".join(TO),
SUBJECTERR,   TEXTERR)
server.sendmail(FROM, TO, messageErr)
server.quit()

sys.stderr.close();
sys.stderr = sys.__stderr__

rawDescription: Python script opens process but not sending mail


code:
def prepare_params(params):
    prepared = {}
    for name, value in params.iteritems():
        if value is True:
            value = 'true'
        elif value is False:
            value = 'false'
        prepared[name] = value
    return prepared

rawDescription: Boolean serialization and case-sensitive REST API's


code:
class A(Document):
    meta = {
        'abstract': True
    }
    pass

class B(Document):
    meta = {
        'abstract': True
    }
    pass

class C(A, B):
    specific_field_1 = ...
    specific_field_2 = ...

    meta = {
        'collection': 'class_c',
    }

rawDescription: How will create abstract model at the Mongoengine?


code:
false = lambda *_: False
true  = lambda *_: True

rawDescription: Python function that always return the same boolean value


code:
pn = '1234'
r = requests.get(ajaxurl + '?part_number=' + pn, headers=headers, cookies=cookies)

rawDescription: Sending an jquery AJAX GET request with Python request library


rawDescription: scatterplot instead of a lineplot while using the plotfile function of matplotlib

description: Scatterplot instead of a lineplot while using the plotfile function of matplotlib


code:
df.B // 4
df.groupby(df.B // 4).last()

rawDescription: Resample based on a column value

description: Resample based on a column value


code:
import numpy as np

class Site:
    def __init__(self, a):
        self.a = a
    def set_a(self, new_a):
        self.a = new_a

vSite = np.vectorize(Site)

init_arry = np.arange(9).reshape((3,3))

lattice = np.empty((3,3), dtype=object)
lattice[:,:] = vSite(init_arry)

rawDescription: numpy array of objects

description: Numpy array of objects


code:
for method_name in [ 'method1', 'method2' ]:
    locals()[ method_name ] = Mock( )

rawDescription: How can I get pointer type behaviour in python

description: Get pointer type behaviour in python


code:
0 and 'string'
1 and 'string'
'string' or 10
'' or 10

rawDescription: Strings and the and operator: best practice, differences with +


code:
class QStandardItemEditorCreator(QItemEditorCreatorBase):
    def __init__(self, cls):
        super(QStandardItemEditorCreator, self).__init__()
        self.propertyName = cls.staticMetaObject.userProperty().name()
        self.cls = cls

    def createWidget(self, parent):
        return self.cls(parent)

    def valuePropertyName(self):
        return self.propertyName

rawDescription: QStandardItemEditorCreator in PySide

description: QStandardItemEditorCreator in PySide


rawDescription: Matplotlib window appears at the back?

description: Matplotlib window appears at the back


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

x = np.random.uniform(-1, 1, 4)
y = np.random.uniform(-1, 1, 4)

p1, = plt.plot([1,2,3])
p2, = plt.plot([3,2,1])
l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')

p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r')
p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g')

# This removes l1 from the axes.
plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
# Add l1 as a separate artist to the axes
plt.gca().add_artist(l1)

rawDescription: How to add a second legend for subgroups in matplotlib scatterplot

description: Add a second legend for subgroups in matplotlib scatterplot


code:
import numpy as np
a = np.array([[1.], [2.], [3.]])
a
a = a.astype('float32')
a

rawDescription: matlab single() function in numpy?

description: Matlab single() function in numpy


rawDescription: Selenium webdriver python, cannot find by value?


code:
import os
import sys
import time

def main():
    """
    Starts the loop check.
    """
    if len(sys.argv) == 2:

        filename = sys.argv[1]

        while True:

            # Clears the window
            os.system("cls")

            print("Tailing: ", filename)

            # Opens the file and reads the lines from it
            with open(filename) as fileToRead:

                for line in fileToRead:
                    # Gets rid of the newline at the end
                    line = line.strip("\n")
                    print(line)  # lint:ok

                # Closes the file
                fileToRead.close()

            # Waits a bit
            time.sleep(0.5)

main()

rawDescription: Redirecting Python output to a console window


code:
x0 = self.frame.winfo_screenwidth()/2
y0 = self.frame.winfo_screenheight()/2
self.canvas.create_window((x0,y0), window=self.frame, anchor = "center")

rawDescription: How to center frame in tkinter Canvas

description: Center frame in tkinter Canvas


code:
{
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'INFO',
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'INFO',
            'propagate': True
        },
        'django.request': {
            'handlers': ['default'],
            'level': 'WARN',
            'propagate': False
        },
    }
}

rawDescription: python: complete example of dict for logging.config.dictConfig?

description: Python: complete example of dict for logging.config.dictConfig


code: data = dict((k,request.form[k]) for k in request.form.iterkeys())

rawDescription: Syntax Error in for loop Python

description: Syntax Error in for loop Python


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_csv.py
#
#  Copyright 2015 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

SEPARATOR = ","

def add_empty(infile, outfile):
    with open(outfile, "w") as outf:
        with open(infile, "r") as inf:
            line = inf.readline()       # Copy the header
            outf.write(line)

            while True:
                line = inf.readline()
                if line == "": break    # EOF
                outf.write("" + SEPARATOR + line)

def main():
    add_empty("test.csv", "testshifted.csv")
    return 0

if __name__ == '__main__':
    main()

rawDescription: How to shift the columns of table from CSV?

description: Shift the columns of table from CSV


code:
x
x.flatten()

rawDescription: Changing an array from (rows, columns) to (rows) in numpy


code:
x=[]
y=[]
for i in range(len(LIST)):
    for j in LIST[i]:
        x.append(j[0])
        y.append(j[1])

rawDescription: Obtaining the first and second "column's" from a pair of lists


code:
class RenderEntity(BaseHandler):
    #renders entity on a template
    def get(self, entity_id):
        entity = Entity.get_by_id('Entity', entity_id)

        # TODO: determine user_id and reciever_user_id
        if user_id == receiver_user_id:
            entity.seen = True
            entity.put()

        self.render('entity_template.html', entity = entity)

rawDescription: Google App Engine Python: Know if an entity has been 'seen' by a user


code: tn.expect([r"\w+ login: "])

rawDescription: How to include regular expression in tn.read_until()?

description: Include regular expression in tn.read_until()


code:
class A(object):
    def __len__(self):
        return 2**80
a = A()
len(a)
a.__len__()

rawDescription: python: what is this funny notation? [0,1,3].__len__()

description: Python: what is this funny notation? [0,1,3].__len__()


code:
from PyQt4.QtGui import QSizePolicy
from PyQt4.QtCore import QSize

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as Canvas
from matplotlib.figure import Figure

from matplotlib import rcParams
rcParams['font.size'] = 9
from matplotlib import pyplot

class MatplotlibWidget(Canvas):
    """
    MatplotlibWidget inherits PyQt4.QtGui.QWidget
    and matplotlib.backend_bases.FigureCanvasBase

    Options: option_name (default_value)
    -------
    parent (None): parent widget
    title (''): figure title
    xlabel (''): X-axis label
    ylabel (''): Y-axis label
    xlim (None): X-axis limits ([min, max])
    ylim (None): Y-axis limits ([min, max])
    xscale ('linear'): X-axis scale
    yscale ('linear'): Y-axis scale
    width (4): width in inches
    height (3): height in inches
    dpi (100): resolution in dpi
    hold (False): if False, figure will be cleared each time plot is called

    Widget attributes:
    -----------------
    figure: instance of matplotlib.figure.Figure
    axes: figure axes

    Example:
    -------
    self.widget = MatplotlibWidget(self, yscale='log', hold=True)
    from numpy import linspace
    x = linspace(-10, 10)
    self.widget.axes.plot(x, x**2)
    self.wdiget.axes.plot(x, x**3)
    """
    def __init__(self, parent=None, title='', xlabel='', ylabel='',
                 xlim=None, ylim=None, xscale='linear', yscale='linear',
                 width=4, height=3, dpi=100, hold=False):
        self.figure = pyplot.figure(figsize=(width, height), dpi=dpi)
        self.axes = self.figure.add_subplot(111)
        self.axes.set_title(title)
        self.axes.set_xlabel(xlabel)
        self.axes.set_ylabel(ylabel)
        if xscale is not None:
            self.axes.set_xscale(xscale)
        if yscale is not None:
            self.axes.set_yscale(yscale)
        if xlim is not None:
            self.axes.set_xlim(*xlim)
        if ylim is not None:
            self.axes.set_ylim(*ylim)
        self.axes.hold(hold)

        Canvas.__init__(self, self.figure)
        self.setParent(parent)

        Canvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        Canvas.updateGeometry(self)

    def sizeHint(self):
        w, h = self.get_width_height()
        return QSize(w, h)

    def minimumSizeHint(self):
        return QSize(10, 10)

rawDescription: Axes instance argument was not found in a figure


code:
import math as mt
import matplotlib.pyplot as pl
import numpy as np
import random as rd

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

# Parameter (reference height)
h = 0.0

# Code to generate the data
n = 200
alpha = 0.75 * mt.pi
theta = [alpha + 2.0 * mt.pi * (float(k) / float(n)) for k in range(0, n + 1)]
xs = [1.0 * mt.cos(k) for k in theta]
ys = [1.0 * mt.sin(k) for k in theta]
zs = [abs(k - alpha - mt.pi) * rd.random() for k in theta]

# Code to convert data in 3D polygons
v = []
for k in range(0, len(xs) - 1):
    x = [xs[k], xs[k+1], xs[k+1], xs[k]]
    y = [ys[k], ys[k+1], ys[k+1], ys[k]]
    z = [zs[k], zs[k+1],       h,     h]
    v.append(zip(x, y, z))
poly3dCollection = Poly3DCollection(v)

# Code to plot the 3D polygons
fig = pl.figure()
ax = Axes3D(fig)
ax.add_collection3d(poly3dCollection)
ax.set_xlim([min(xs), max(xs)])
ax.set_ylim([min(ys), max(ys)])
ax.set_zlim([min(zs), max(zs)])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

pl.show()

rawDescription: Vertically fill 3d matplotlib plot

description: Vertically fill 3d matplotlib plot


rawDescription: merge two lists in equal amounts

description: Merge two lists in equal amounts


code:
import os
import sys
directory = os.path.dirname(os.path.abspath(__file__))
sys.stdout = open(os.path.join(directory, "demo-logfiles", "log_file_template.txt"), "a")

rawDescription: Python - Interpreting paths differently when running in shell vs. when running within another script?


rawDescription: In Python, how should one extract the second-last directory name in a path?


code:
import os
import ConfigParser
from Tkinter import *
import Tkinter as tk
import os
import ttk
os.system('echo OS ready')
os.system('chmod 755 *')
import subprocess
from subprocess import call
import sys

os.system('rm stdout')

#Creating new Window to display output
t = Tk()
t.title('output Run Display')
t.geometry('100x100')
t.state('normal')
little = Label(t, text="NRUNTEST OUTPUT LOG").grid(column = 0, row = 0)
log = Text(t, state='disabled', width=50, height=50, wrap='none')
log.grid(row = 1, column = 0,sticky=(N,W,E,S))
s = ttk.Scrollbar(t,orient=VERTICAL,command=log.yview)
s.grid(column=1,row=1,sticky=(N,S))
log.configure(yscrollcommand=s.set)
ttk.Sizegrip().grid(column=1, row=1, sticky=(S,E))

with open("stdout","wb") as out:
    with open("stderr","wb") as err:
        test=subprocess.Popen('tem',shell=True,stdout=out,stderr=err)
fout = open('stdout','r')
ferr = open('stderr','r')
def verify():

    data_out = fout.readlines()
    data_out = ''.join(data_out)

    log['state'] = 'normal'
    log.insert('end',data_out)
    log['state'] = 'disabled'
    #print data_out

    t.after(1000,verify)
    fout.close()

verify()

t.mainloop()

rawDescription: Python/Tkinter: Loop iterations not completing


code:
import asyncore
import socket

class User(asyncore.dispatcher_with_send):

    def __init__(self, sock, server):
        asyncore.dispatcher_with_send.__init__(self, sock)
        self.server = server

    def handle_read(self):
        data = self.recv(4096)
        # parse User auth protocol here, authenticate, set phase flag, etc.
        # if authenticated, send data to server
        if self.server:
            self.server.send(data)

    def handle_close(self):
        if self.server:
            self.server.close()
        self.close()

class Listener(asyncore.dispatcher_with_send):

    def __init__(self, listener_addr, server):
        asyncore.dispatcher_with_send.__init__(self)
        self.server = server
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(listener_addr)
        self.listen(1)

    def handle_accept(self):
        conn, addr = self.accept()
        # this listener only accepts 1 client. while it is serving 1 client
        # it will reject all other clients.
        if not self.server.user:
            self.server.user = User(conn, self.server)
        else:
            conn.close()

class Server(asyncore.dispatcher_with_send):

    def __init__(self, server_addr, listener_addr):
        asyncore.dispatcher_with_send.__init__(self)
        self.server_addr = server_addr
        self.listener_addr = listener_addr
        self.listener = None
        self.user = None

    def start(self):
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect(self.server_addr)

    def handle_error(self, *n):
        self.close()

    def handle_read(self):
        data = self.recv(4096)
        # parse SomeServer auth protocol here, set phase flag, etc.
        if not self.listener:
            self.listener = Listener(self.listener_addr, self)
        # if user is attached, send data
        elif self.user:
            self.user.send(data)

    def handle_close(self):
        if self.user:
            self.user.server = None
            self.user.close()
            self.user = None
        if self.listener:
            self.listener.close()
            self.listener = None
        self.close()
        self.start()

if __name__ == '__main__':
    app = Server(('someserver', 143), ('localhost', 8080))
    app.start()
    asyncore.loop()

rawDescription: Need help creating a TCP relay between two sockets


rawDescription: How to append to a list inside of a list in python

description: Append to a list inside of a list in python


rawDescription: Change a django form field to a hidden field


code:
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x = numpy.array([0,5,10,15,20,30,40,50])
y = numpy.array([0,0,0,12,40,40,40,40])

coeffs = numpy.polyfit(x, y, deg=4)#you can change degree as you see fit
poly = numpy.poly1d(coeffs)
yp = numpy.polyval(poly, x)

interpLength = 10
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

plt.plot(x, y, '.', x, yp, '-', new_x,new_y, '--')
plt.show()

rawDescription: Python Curve Fitting

description: Python Curve Fitting


code:
# Loading the pyPdf Library
from pyPdf import PdfFileWriter, PdfFileReader

# Creating a routine that appends files to the output file
def append_pdf(input,output):
    [output.addPage(input.getPage(page_num)) for page_num in range(input.numPages)]

# Creating an object where pdf pages are appended to
output = PdfFileWriter()

# Appending two pdf-pages from two different files
append_pdf(PdfFileReader(open("SamplePage1.pdf","rb")),output)
append_pdf(PdfFileReader(open("SamplePage2.pdf","rb")),output)

# Writing all the collected pages to a file
output.write(open("CombinedPages.pdf","wb"))

rawDescription: Merge PDF files

description: Merge PDF files


code:
def transform(model, **kwargs):
    for p in ('alpha', 'theta', ...):
        if 'p' not in kwargs and hasattr(model, p):
            kwargs[p] = getattr(model, p)

rawDescription: Define variables using a list of names

description: Define variables using a list of names


code:
import csv

with open(filename,"r") as fin:
    with open(outname,"w") as fout:
        writer=csv.writer(fout)
        for row in csv.reader(fin):
            writer.writerow(row[:-1])

rawDescription: Delete or remove last column in CSV file using Python


code:
import numpy
import matplotlib.pyplot as plt

def adjust_borders(fig, targets):
    "Translate desired pixel sizes into percentages based on figure size."
    dpi = fig.get_dpi()
    width, height = [float(v * dpi) for v in fig.get_size_inches()]
    conversions = {
        'top': lambda v: 1.0 - (v / height),
        'bottom': lambda v: v / height,
        'right': lambda v: 1.0 - (v / width),
        'left': lambda v: v / width,
        'hspace': lambda v: v / height,
        'wspace': lambda v: v / width,
        }
    opts = dict((k, conversions[k](v)) for k, v in targets.items())
    fig.subplots_adjust(**opts)

fig = plt.figure(figsize=(7, 5))
for i in range(4):
    ax = fig.add_subplot(2, 2, i+1)
    ax.plot([1,2,3], [4,5,1])
    ax.set_xticks([])
    ax.set_yticks([])

# target sizes in pixels.
targets = dict(left=10, right=10, top=10, bottom=30, hspace=30, wspace=30)
# hook up a function to adjust the borders when the window is resized
fig.canvas.mpl_connect('resize_event', lambda e: adjust_borders(fig, targets))
adjust_borders(fig, targets)
plt.show()

rawDescription: Python/Matplotlib - Figure Borders in wxPython


code:
import numpy as np
import healpy as hp
NSIDE = 32
m = hp.ma(np.arange(hp.nside2npix(NSIDE), dtype=np.double))
mask = np.zeros(hp.nside2npix(NSIDE), dtype=np.bool)
pixel_theta, pixel_phi = hp.pix2ang(NSIDE, np.arange(hp.nside2npix(NSIDE)))
mask[pixel_theta > np.pi/2] = 1
m.mask = mask
hp.mollview(m)

rawDescription: How can I partially plot a Healpix map using Healpy?

description: Partially plot a Healpix map using Healpy


code:
b = quopri.decodestring('=C4=EE=E1=F0=FB=E9 =E4=E5=ED=FC')
print(b.decode('windows-1251'))

rawDescription: Change "Quoted-printable" encoding to "utf-8"


rawDescription: in Python and linux how to get given user's id

description: In Python and linux how to get given user's id


code:
import unittest
from unittest.mock import Mock

from app import Foo

class AppTest(unittest.TestCase):

    def test_callback(self):
        foo = Foo()
        f = Mock()
        foo.set_handler(f)

        foo.run('John/20')
        f.assert_called_with('John', 20)

        foo.run('John/xyz')
        f.assert_called_with('John', -1)

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

rawDescription: What is the right way to test callback invocation using Python unittest?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
import matplotlib as mpl

# Generate data. In this case, we'll make a bunch of center-points and generate
# verticies by subtracting random offsets from those center-points
numpoly, numverts = 100, 4
centers = 100 * (np.random.random((numpoly,2)) - 0.5)
offsets = 10 * (np.random.random((numverts,numpoly,2)) - 0.5)
verts = centers + offsets
verts = np.swapaxes(verts, 0, 1)

# In your case, "verts" might be something like:
# verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...)
# If "data" in your case is a numpy array, there are cleaner ways to reorder
# things to suit.

# Color scalar...
# If you have rgb values in your "colorval" array, you could just pass them
# in as "facecolors=colorval" when you create the PolyCollection
z = np.random.random(numpoly) * 500

fig, ax = plt.subplots()

# Make the collection and add it to the plot.
coll = PolyCollection(verts, array=z, cmap=mpl.cm.jet, edgecolors='none')
ax.add_collection(coll)
ax.autoscale_view()

# Add a colorbar for the PolyCollection
fig.colorbar(coll, ax=ax)
plt.show()

rawDescription: Draw polygons more efficiently with matplotlib


code:
dictionary = {}
file_data.readline()   # skip the first line
for key in file_data:
    key = key.replace('"', '').strip()
    k = key.split(",")
    dictionary[k[0]] = k[1]

rawDescription: Python - make a dictionary from a csv file with multiple categories


code:
def age_over_18(go_enjoy_yourself):
    def are_you_over_18():
        if age > 18:
            return go_enjoy_yourself()
        else:
            return 'So you should go home and rethink your life.'

    return are_you_over_18

rawDescription: Can I delay a decorator to happen until I call the function?

description: Delay a decorator to happen until I call the function


rawDescription: Python: how to replace values in masked array according to a condition


code:
data = {}
for n in graph.by_tag('value'):
    if n.content:
        data[n.attributes['xid']] = float(n.content)
    else:
        data[n.attributes['xid']] = np.nan

rawDescription: In python how does "if-else and for" in a dictionary comprehension work


code:
slider = QtGui.QSlider()
slider.setValue( 5 )
print( slider.value() ) # Will print '5'

rawDescription: How to get values from the slider in pyside?

description: Get values from the slider in pyside


rawDescription: Renaming the keys of a dictionary

description: Renaming the keys of a dictionary


code:
import lxml.etree as le
with open('data.xml') as f:
    doc=le.parse( f )
patientID="SKU55527"
studyInstanceUID="25.2.9.2.1107.5.1.4.49339.30000007010207164403100000013"
xpath='''\
    /PatientsTree
        /Patient[@PatientID="{p}"]
            /Study[@StudyInstanceUID="{s}"]
                /Series'''.format(p=patientID,s=studyInstanceUID)
seriesInstanceUID=doc.xpath(xpath)
for node in seriesInstanceUID:
    print(node.attrib)
    # {'SeriesInstanceUID': '2.16.840.1.113669.1919.1198835358'}

rawDescription: path to element with conditions on parent(s) attributes using xpath,lxml,python

description: Path to element with conditions on parent(s) attributes using xpath,lxml,python


code:
arr[..., index].shape
arr[..., np.in1d(np.arange(arr.shape[-1]),index)].shape
arr[..., ~np.in1d(np.arange(arr.shape[-1]),index)].shape

rawDescription: numpy: accessing array elements not in a given index list

description: Numpy: accessing array elements not in a given index list


code:
from itertools import groupby
from operator import itemgetter
dict(((u, sum(row['score'] for row in rows)) for u, rows in
    groupby(sorted(d, key=itemgetter('alias')), key=itemgetter('alias'))))
# {'2133232': 158, 'u234243': 416}

rawDescription: How can I do comparison in List of dictionaries for key values?

description: Do comparison in List of dictionaries for key values


code:
import networkx as nx
G = nx.path_graph(4)
I = nx.incidence_matrix(G,oriented=True)
I.todense()
L = nx.laplacian_matrix(G)
L.todense()
(I*I.T).todense()

rawDescription: Why does laplacian computed by Networkx and by incidence matrix is different


code:
import os
def download(ftp,file, localdir):
    f = open(os.path.join(localdir, file),"wb")
    ftp.retrbinary("RETR " + file,f.write)
    f.close()

rawDescription: Download from FTP with Python - Pathname


code:
import re
def extract(s):
    r = re.compile(r'\.(\d+)\.log\.((\d*)\.)?gz')
    m = r.search(s)
    file = int(m.group(1))
    if not m.group(2):
        return (file, -1)
    index = int(m.group(3))
    return (file, index)

def comparator(s1, s2): return cmp(extract(s1), extract(s2))

rawDescription: python sort list

description: Python sort list


code:
phrase, column = 'aaa', 3
fn = lambda l : len(l) >= column and len(l[column-1]) >= len(phrase) and phrase == l[column-1][:len(phrase)]
fp = open('output.txt', 'w')
fp.write(''.join(row for row in open('input.txt') if fn(row.split('\t'))))
fp.close()

rawDescription: Python to find rows whose n-th column starts with aaa


code:
def intercala_listas(a, b):
    c = list(zip(a, b))
    return [elt for sublist in c for elt in sublist]

rawDescription: Python intercalate lists

description: Python intercalate lists


code:
form = CommentForm(request.POST)
if form.is_valid():
    name = form.cleaned_data['name']
    url = form.cleaned_data['url']
    comment = form.cleaned_data['comment']

    my_comment = Comment(name=name,url=url,comment=comment)
    my_comment.save()

rawDescription: How does a Django form know where to save its data when not using ModelForm?


rawDescription: How to sort a list of strings containing numbers numerically

description: Sort a list of strings containing numbers numerically


code:
"""
Make a pie chart - see
http://matplotlib.sf.net/matplotlib.pylab.html#-pie for the docstring.

This example shows a basic pie chart with labels optional features,
like autolabeling the percentage, offsetting a slice with "explode",
adding a shadow, and changing the starting angle.

"""
from pylab import *

# make a square figure and axes
figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])

# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode=(0, 0.05, 0, 0)

pie(fracs, explode=explode, labels=labels,
                autopct='%1.0f%%', shadow=True, startangle=90)
                # The default startangle is 0, which would start
                # the Frogs slice on the x-axis.  With startangle=90,
                # everything is rotated counter-clockwise by 90 degrees,
                # so the plotting starts on the positive y-axis.

title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

show()

rawDescription: How can I round the values displayed in a matplotlib pie chart?

description: Round the values displayed in a matplotlib pie chart


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'Group': ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'], 'Subgroup': ['Group 1', 'Group 1', 'Group 1', 'Group 1', 'Group 1', 'Group 1', 'Group 2', 'Group 2', 'Group 2'], 'Keyword': ['kw 1', 'kw 1', 'kw 1', 'kw 2', '+kw +2', 'kw 2', 'kw 3', 'kw 3', 'kw 3'], 'Normalized': ['kw 1', 'kw 1', 'kw 1', 'kw 2', 'kw 2', 'kw 2', 'kw 3', 'kw 3', 'kw 3'], 'Criterion Type': ['Exact', 'Phrase', 'Broad', 'Phrase', 'Broadified', 'Exact', 'Broad', 'Exact', 'Phrase'], 'Max CPC': [1.62, 1.73, 0.87, 1.70, 0.85, 1.60, 0.99, 1.58, 1.68], 'CPC Rank': [2, 1, 3, 1, 3, 2, 3, 2, 1], 'Type Rank': [1, 2, 3, 2, 3, 1, 3, 1, 2]})
df = df[['Group', 'Subgroup', 'Keyword', 'Normalized', 'Criterion Type', 'Max CPC', 'CPC Rank', 'Type Rank']]

#Sort by custom priority based on their Criterion Type
df = df.sort(['Group', 'Subgroup', 'Normalized', 'Type Rank'])
#Reset index and drop old one
df = df.reset_index(drop=True)
print(df)
#Create df1 which is a Series of the Max CPC column in its correctly ranked order
df1 = df.sort(['Group', 'Subgroup', 'Normalized', 'CPC Rank'])['Max CPC']
#Reset index and drop old one
df1 = df1.reset_index(drop=True)
print(df1)

#Add the df1 Series to df and name the column New CPC
df['New CPC'] = df1

print(df)

rawDescription: Python Pandas groupby, rank, then assign value based on custom rank


code:
@classmethod
def gen_graph_from_text(cls, file):
    self = cls()
    file = open(file, 'r')
    for line in file:
        origin = line[0]
        destinations = line[1:-1]
        self.add_node(origin)
        for destination in destinations:
            self.add_node(destination)
            edge = Edge(origin, destination)
            self.add_connection(edge)
    return self

rawDescription: Alternative Constructors in Python

description: Alternative Constructors in Python


code:
import re
strs = 'NL20INGB0001234567'
re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)

rawDescription: Change part of string into *

description: Change part of string into *


code:
# 'n' is the number of tags you'll be returning, I suppose
', '.join(items.get_top_tags(i)[0].get_name() for i in range(n))

rawDescription: python for loop adding commas between items

description: Python for loop adding commas between items


rawDescription: Python how to get multibyte variable size in 8-bit?


code:
# Import relevant packages
import numpy as np
from scipy import ndimage
from PIL import Image

# Read in image - change filename to whatever you want
img = ndimage.imread('image.jpg')

# Create kernel
ker = (1/81.0)*np.ones((9,9))

# Convolve
out = ndimage.convolve(img, ker)

# Convert back to PIL image
out = Image.fromArray(out, 'RGB')

rawDescription: Convolution with kernel size larger than 5x5 in python-pillow


code:
@event.listens_for(cls, 'before_update')
def before_udpate(mapper, connection, target):
    state = db.inspect(target)
    changes = {}

    for attr in state.attrs:
        hist = state.get_history(attr.key, True)

        if not hist.has_changes():
            continue

        # hist.deleted holds old value
        # hist.added holds new value
        changes[attr.key] = hist.added

    # now changes map keys to new values

rawDescription: Tracking model changes in SQLAlchemy

description: Tracking model changes in SQLAlchemy


code:
"""
This is the xyz package.
"""

rawDescription: how to document a python package

description: Document a python package


code:
def remove_ace(path,usernames):
    """Remove the ace for the given users."""
    if not os.path.exists(path):
        raise WindowsError('Path %s could not be found.' % path)
    total = 0
    for x in usernames:
        userx, domain, utype = win32security.LookupAccountName("", x)
        sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()
        num_delete = 0
        for index in range(0, dacl.GetAceCount()):
            ace = dacl.GetAce(index - num_delete)
            if userx == ace[2]:
                dacl.DeleteAce(index - num_delete)
                num_delete += 1
                total += 1
        if num_delete > 0:
            sd.SetSecurityDescriptorDacl(1, dacl, 0)
            win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
    if total > 0:
        return True

rawDescription: Remove file permissions on windows with python


code:
import os.path

folder = os.path.expanduser("~/usr/my_name/Pictures")

rawDescription: How to find a folder path in mac os x using python?

description: Find a folder path in mac os x using python


code: from module import *

rawDescription: Most pythonic way to import all objects in a module as their name in the module


code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig=plt.figure(figsize=(15,5.5))
ax1=plt.subplot2grid((1,3),(0,0))
ax2=plt.subplot2grid((1,3),(0,1))
ax3=plt.subplot2grid((1,3),(0,2))

image=np.random.random_integers(1,10,size=(100,100))
im = ax1.imshow(image,interpolation="none",aspect='equal')

divider = make_axes_locatable(ax1)
cax = divider.append_axes("bottom",size="5%",pad=0.7)
cbar=fig.colorbar(im,cax=cax,orientation=u'horizontal')

x=np.linspace(0,1)
ax2.plot(x,x**2)
ax3.plot(x,x**3)

plt.show()

rawDescription: matplotlib change size of subplots

description: Matplotlib change size of subplots