code:
def to_csv(self, data, options=None):
    options = options or {}
    data = self.to_simple(data, options)

    raw_data = StringIO.StringIO()
    first = True

    if "meta" in data.keys():#if multiple objects are returned
        objects = data.get("objects")

        for value in objects:
            test = {}
            self.flatten(value, test)
            if first:
                writer = csv.DictWriter(raw_data, test.keys(), quotechar="'", quoting=csv.QUOTE_NONNUMERIC)
                writer.writeheader()
                writer.writerow(test)
                first=False
            else:
                writer.writerow(test)
    else:
        test = {}
        self.flatten(data, test)
        if first:
            writer = csv.DictWriter(raw_data, test.keys(), quotechar="'", quoting=csv.QUOTE_NONNUMERIC)
            writer.writeheader()
            writer.writerow(test)
            first=False
        else:
            writer.writerow(test)
    CSVContent=raw_data.getvalue()
    return CSVContent

def flatten(self, data, odict = {}):
    if isinstance(data, list):
        for value in data:
            self.flatten(value, odict)
    elif isinstance(data, dict):
        for (key, value) in data.items():
            if not isinstance(value, (dict, list)):
                odict[key] = value
            else:
                self.flatten(value, odict)

rawDescription: need a recursive CSV serializer for Django tastypie

description: Need a recursive CSV serializer for Django tastypie


code:
sql = "update tf_data set authors=%(authors)s where tf_data_id=%(data_id)s"
# or :authors and :data_id, I get confused with all those sql dialects out there

authors = ', '.join(authors)
data_id = str(tf_data_id)

# db or whatever your db instance is called
db.execute(sql, {'authors': authors, 'data_id': data_id})

rawDescription: Replace a double backslash with a single backslash in a string in python


code:
with open("some_png.png","wb") as f:
     f.write(urllib2.urlopen("http://icons-search.com/img/yellowicon/TMNT_lin.zip/lin-png-256x256-Leonardo_256x256.png-256x256.png").read())

rawDescription: How can i grab some photos with python from website

description: Grab some photos with python from website


code: struct.pack("III", 3, 4, 5)

rawDescription: Python: Send Integer value over socket

description: Python: Send Integer value over socket


code: numpy.outer(weights, values)

rawDescription: numpy - scalar multiplication of column vector times row vector

description: Numpy - scalar multiplication of column vector times row vector


code:
diff  = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
comp = ["foo", "bar", "baz"]
fig, ax = plt.subplots(3, 1)
for foo in range(0, len(diff)):
        x = [diff[foo]]
        name = comp
        color = ['0.1', '0.2', '0.3']
        label = ['1000000', '1200000', '1400000']
        y = zip(*x)
        pos = np.arange(len(x))
        width = 1. / (1 + len(x))
        for idx, (serie, color,label) in enumerate(zip(y, color,label)):
                ax[foo].bar(pos + idx * width, serie, width, color=color,label=label)
        fig.set_size_inches(28.5, 10.5)
        ax[foo].set_xticks(pos + 1.5*width)
        plt.ylabel(name[foo])
        ax[foo].set_xticklabels(comp)
        ax[foo].legend()
        plt.gray()
fig.savefig("file" + '.jpg', bbox_inches='tight', pad_inches=0.5, dpi=100)
plt.clf()

rawDescription: subplots in matplotlib using histogram

description: Subplots in matplotlib using histogram


code:
import json

json_string = '''{
  "status": 200,
  "type": "url",
  "results": [
    {
      "url": "http://www.cnn.com",
      "queries": {
        "getinfo": {
          "cats": [
            {
              "conf": 99,
              "catid": 63
            }
          ],
          "a1cat": -1,
          "lcp": "cnn.com",
          "reputation": -1
        }
      }
    }
  ]
}'''

data = json.loads(json_string)

print(data["results"][0]["queries"]["getinfo"]["cats"][0]["catid"])

rawDescription: Tryting to find a best way of finding a word and printing that word and its value from JSON output using python


code:
from __future__ import print_function

def dividedata(data, col_num, test=None):
    "Doc string placeholder"

    # if no test function was passed, return (quite arbitrarily)
    # a shallow copy of the original list and an empty list
    if test==None: return data[:], []

    set0, set1 = [], []
    for row in data:
        if test(row[col_num]):
            set0.append(row)
        else:
            set1.append(row)

    return set0, set1

my_data = [[(0, 'y'), (0, 'n'), (1, 'n'), (2, 'y'), (3, 'y')],
           [(0, 'y'), (0, 'y'), (1, 'y'), (2, 'y'), (3, 'n')]]

their_data = [['slashdot', 'USA', 'yes', 18, 'None'],
              ['google', 'France', 'yes', 23, 'Premium'],
              ['digg', 'USA', 'yes', 24, 'Basic'],
              ['kiwitobes', 'France', 'yes', 23, 'Basic'],
              ['slashdot', 'France', 'yes', 19, 'None'],
              ['digg', 'New Zealand', 'yes', 12, 'Basic'],
              ['google', 'UK', 'yes', 18, 'Basic'],
              ['kiwitobes', 'France', 'yes', 19, 'Basic'],
              ['google', 'UK', 'no', 21, 'Premium'],
              ['(direct)', 'New Zealand', 'no', 12, 'None'],
              ['(direct)', 'UK', 'no', 21, 'Basic'],
              ['google', 'USA', 'no', 24, 'Premium'],
              ['digg', 'USA', 'no', 18, 'None'],
              ['google', 'UK', 'no', 18, 'None'],
              ['kiwitobes', 'UK', 'no', 19, 'None'],
              ['slashdot', 'UK', 'no', 21, 'None']]

c2y, c2n = dividedata(their_data, 2, lambda answer: answer=='yes')
c1y, c1n = dividedata(my_data, 1, lambda tup: tup[1]=='y')

print(c2y, c2n, sep='\n')
print(c1y, c1n, sep='\n')

rawDescription: How can I split a list of lists of tuples if I don't have a column formed by only one element in the column selected?

description: Split a list of lists of tuples if I don't have a column formed by only one element in the column selected


code:
def create_socket():
    sock = socket.socket()
    host = 'localhost'
    port = 8000
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host,port))
    return sock

def send_data(message, sock):
    """Get requests"""
    if message:
        sock.sendall(message)

    # Look for the response
    has_request = False
    while not has_request:
        data = sock.recv(1024)

        #First I get ACK, code not listed here...
        #Next iteration, I got my request message
        has_request = True
    return data

if __name__ == '__main__':
    server_sock = create_socket()
    server_data = send_data(event, server_sock)

    if server_data:
        parse_request(server_data, server_sock)

    #no more use of server_socket ?
    server_sock.close()

rawDescription: Prevent connected socket from closing in Python


code:
import urllib
from BeautifulSoup import *

url = "http://www.domain.com/page/path?page="
count_of_pages = 10

for page in xrange(1, count_of_pages):
    response = urllib.urlopen("%s%d" % (url, page))
    webPage = BeautifulSoup(webFile.read())

    # Parse page with great module BeaurifulSoap

rawDescription: to use Python (Beautifulsoup) to pickup texts on not a direct webpage

description: To use Python (Beautifulsoup) to pickup texts on not a direct webpage


code:
variable_values = [[0], [0, 1], [0, 1, 2], [1, 2]]
import itertools
list(itertools.product(*variable_values))

rawDescription: Best way to calculate all ways certain variables can be assigned

description: Calculate all ways certain variables can be assigned


code:
X = np.arange(500)
Y = np.arange(700)
xx, yy = np.meshgrid(X, Y)
xx.shape
yy.shape

rawDescription: Python - have a pcolor plot; now want a surface


code:
df1['days'] = (df1.inv / df1['mat'].map(df2.set_index('mat')['sale']) * 30).astype(int)
df1

rawDescription: Calculation involving two DataFrames

description: Calculation involving two DataFrames


code:
plt.boxplot(data_sgc, positions = range(4,(len(alignments.keys())*4), 4))
plt.ylabel("Alignment Gap Score")
plt.xlabel("Locus")
plt.xticks(range(4,((len(alignments.keys())+1)*4),4), [i[1] for i in medians_sgc], rotation=90, fontsize = 4)
plt.tick_params(axis='x', pad=4)
plt.tight_layout()
remove_border()

rawDescription: Matplotlib boxplot spacing on x axis

description: Matplotlib boxplot spacing on x axis


code:
css_provider = Gtk.CssProvider()
css_provider.load_from_data("""
    @binding-set unbind_search { unbind "<Control>f"; }
    GtkTreeView { gtk-key-bindings: unbind_search; }
""".encode('utf-8'))
context = Gtk.StyleContext()
context.add_provider_for_screen(
    Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER
)

rawDescription: Disable the interactive-search popup of GtkTreeView


code:
FEED_EXPORTERS = {
 'jsonlines': 'scrapy.contrib.exporter.JsonLinesItemExporter',
}
FEED_FORMAT = 'jsonlines'
FEED_URI = "NAME_OF_FILE.json"

rawDescription: scrapy is there a way to print json file without using -o -t parameters

description: Scrapy is there a way to print json file without using -o -t parameters


code:
directorylist = ['path', 'to', 'directory', 'file.txt']
import os
os.path.join(*directorylist)
os.path.sep + os.path.join(*directorylist)

rawDescription: How to form a path from elements of list in python?

description: Form a path from elements of list in python


code:
map(list, zip(A, B))
[list(x) for x in  zip(A, B)]

rawDescription: How to get C from A and B in the following case?

description: Get C from A and B in the following case


code: {key: 1 for key in x}

rawDescription: Creating a Simple Dictionary from a List


code:
from django.http import HttpResponse

def myview(request):
    return HttpResponse("return this string")

rawDescription: django: return string from view

description: Django: return string from view


code:
import requests
import jwt
import arrow
import OpenSSL.crypto

class GetToken(object):
    """
    Get Google API token as documented at https://developers.google.com/identity/protocols/OAuth2ServiceAccount
    """
    def __init__(self):
        self.expires = 0
        self.token = None

    def gettoken(self):
        now = arrow.now().timestamp
        # is the token still valid and exists ? (within a 10 seconds margin)
        if now < (self.expires - 10) and self.token:
            return self.token
        self.expires = now + 3600
        claim = {
            "iss": "dev_account_from_google_console@developer.gserviceaccount.com",
            "scope": "https://www.googleapis.com/auth/calendar.readonly",
            "aud": "https://www.googleapis.com/oauth2/v3/token",
            "exp": now,
            "iat": now,
            "sub": "account_with_delegated_rights@example.com"
        }
        p12 = OpenSSL.crypto.load_pkcs12(open('certificate_from_google_api_console.p12', 'rb').read(), 'notasecret')
        private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()).decode('utf-8')
        myjwt = jwt.encode(claim, private_key, algorithm='RS256', headers={"alg": "RS256", "typ": "JWT"}).decode('utf-8')
        data = {
            "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
            "assertion": myjwt
        }
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        r = requests.post("https://www.googleapis.com/oauth2/v3/token", data=data, headers=headers)
        print(r.json())

if __name__ == "__main__":
    t = GetToken()
    t.gettoken()

rawDescription: Google backend oAuth with Python3?

description: Google backend oAuth with Python3


code: next(d for d in data if d['name'] == 'SqueezePlay')['playerid']

rawDescription: search array of dictionaries and extract value

description: Search array of dictionaries and extract value


code: help('modules')

rawDescription: Where are the python modules stored?

description: Where are the python modules stored


code:
var_3Dlist = ...  # List of 3-D variables.
sum_list = [tf.reduce_sum(mat) for mat in var_3Dlist]
sum = tf.add_n(sum_list)

rawDescription: TensorFlow: how can I sum a list of tf.Variables?


code:
def createPath(self, path, NameOfFile ):

    NameOfFile_ = []
    for obj in NameOfFile:
        name = ''.join(chr(i) for i in obj)
        name = name.replace("aaaa","bbbb")
        NameOfFile_.append(name)

    temp = []
    for j in range(path.shape[0]):
        rr = path[j][0]
        temp.append(NameOfFile_[rr])

    return np.array(temp)

rawDescription: I need to improve python function that works with loops and string how it does?


code: Arrays.copyOfRange(arr, 1, arr.length);

rawDescription: Index syntax in Java equivalent to [1:]

description: Index syntax in Java equivalent to [1:]


code:
@app.route('/getColors')
def add_colors():

    user = request.args.get("handle", 0, type = str)

    return render_template('colors.html',
                           avatar_url=process_data(data))

rawDescription: Rendering Jinja template in Flask following ajax response


rawDescription: Python 3, context based division

description: Python 3, context based division


code: fileMod = [item['fileMod'] for item in fileList if item['fileName'] == filename]

rawDescription: Check if python dictionary contains value and if so return related value


code:
FLANN_INDEX_KDTREE = 1  # bug: flann enums are missing

flann_params = dict(algorithm = FLANN_INDEX_KDTREE,
                    trees = 4)

def match_flann(desc1, desc2, r_threshold = 0.6):
    flann = cv2.flann_Index(desc2, flann_params)
    idx2, dist = flann.knnSearch(desc1, 2, params = {}) # bug: need to provide empty dict
    mask = dist[:,0] / dist[:,1] < r_threshold
    idx1 = np.arange(len(desc1))
    pairs = np.int32( zip(idx1, idx2[:,0]) )
    return pairs[mask]

rawDescription: OpenCV python's API: FlannBasedMatcher

description: OpenCV python's API: FlannBasedMatcher


code:
text_bytes = bytearray(plaintext,'utf-8')
num_bytes_padding = text_bytes[len(text_bytes) - 1]
text_bytes[-1 * num_bytes_padding:] = []
plaintext = text_bytes.decode('utf-8')

rawDescription: Why is my python format %s taking no space?


code:
import numpy as np
import bokeh.plotting, bokeh.models
bokeh.plotting.output_notebook()

x = np.random.random(10)
y = np.random.random(10)

f = bokeh.plotting.figure()

scatter = f.scatter(x, y, marker="square")

asterisk_glyph = bokeh.models.glyphs.Asterisk(**scatter.glyph.changed_properties_with_values())

scatter.set(glyph=asterisk_glyph)
scatter.glyph.size = 20

bokeh.plotting.show(f)

rawDescription: Is there anyway to change the scatter symbol of an existed Bokeh plot?


code:
def sortkey(x):
    return x[1]

rawDescription: How does the following lambda function work in place of 'itemgetter' in Python's sort function?


code:
# assuming r is a Rule
f = app.view_functions[r.endpoint]

rawDescription: How can I get the view function from an endpoint/rule?

description: Get the view function from an endpoint/rule


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

def build_axes_with_insets(numrows, numcols, numinsets, **kwargs):
    """
    Makes a *numrows* x *numcols* grid of subplots with *numinsets* subplots
    embedded as "sub-rows" in the last column of each row.

    Returns a figure object and a *numrows* x *numcols* object ndarray where
    all but the last column consists of axes objects, and the last column is a
    *numinsets* length object ndarray of axes objects.
    """
    fig = plt.figure(**kwargs)
    gs = plt.GridSpec(numrows*numinsets, numcols)

    axes = np.empty([numrows, numcols], dtype=object)
    for i in range(numrows):
        # Add "main" axes...
        for j in range(numcols - 1):
            axes[i, j] = fig.add_subplot(gs[i*numinsets:(i+1)*numinsets, j])

        # Add inset axes...
        for k in range(numinsets):
            m = k + i * numinsets
            axes[i, -1][k] = fig.add_subplot(gs[m, -1])

    return fig, axes

def plot(axes):
    """Recursive plotting function just to put something on each axes."""
    for ax in axes.flat:
        data = np.random.normal(0, 1, 100).cumsum()
        try:
            ax.plot(data)
            ax.set(xticklabels=[], yticklabels=[])
        except AttributeError:
            plot(ax)

fig, axes = build_axes_with_insets(2, 4, 3, figsize=(12, 6))
plot(axes)
fig.tight_layout()
plt.show()

rawDescription: Embedding several inset axes in another axis using matplotlib


code:
# this should give us a list of posts shared by all users
common = set.intersection(*[set(k.keys()) for k in results.values()])

# there's probably a more efficient (functional) way of summing the points
# by user instead of looping, but simple is good.
for user in results:
    for post_hash in common:
        points[user] += results[user][post_hash]

rawDescription: Filtering data in python

description: Filtering data in python


code:
import shutil

archive = zipfile.ZipFile(ifile)
path = os.path.join('/2015/MyCODE', folderName)

for name in aidlist_to_keep:
    try:
        archivefile = archive.open(name)
    except KeyError:
        # no such file in the archive
        continue
    with open(os.path.join(path, name), 'wb') as targetfile:
        shutil.copyfileobj(archivefile, targetfile)

rawDescription: Python and the zipfile module

description: Python and the zipfile module


code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
Z1 = 8.0
Z2 = 9.0
font = {'size'   : 18}
matplotlib.rc('font', **font)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

t = np.linspace(0, 2 * np.pi, 100)
x = np.cos(t)
y = np.sin(2 * t)
N = len(x)
z = np.zeros(N)
z[:,] = Z1

t = np.linspace(0, 2 * np.pi, 100)
x2 = 2 * np.cos(t)
y2 = 2 * np.sin(2*t)
N = len(x2)
z2 = np.zeros(N)
z2[:,] = Z2

#Plot the first orbit
ax.plot(x, y, z, 'k-', linewidth=3.0)
#Plot second orbit
ax.plot(x2, y2, z2, 'k-', linewidth=3.0)

i, h = np.meshgrid(np.arange(len(x)), np.linspace(Z1, Z2, 10))
X = (x2[i] - x[i]) / (Z2 - Z1) * (h - Z1) + x[i]
Y = (y2[i] - y[i]) / (Z2 - Z1) * (h - Z1) + y[i]
surf = ax.plot_surface(X, Y, h, color='m', alpha=0.3,
         linewidth=0)

#Set axis and things
ax.set_xticks([1.0,1.5,2])
ax.set_yticks([32,35,38])
ax.set_ylabel('$||u||_{2}$', fontsize=26, rotation=0, labelpad = 26)
ax.set_xlabel('$h$', fontsize=26)
ax.set_zlabel('$\mu$', fontsize=26, rotation=90)
plt.tight_layout()

plt.show()

rawDescription: How to join these two 3D lines together with a surface in Python's matplotlib

description: Join these two 3D lines together with a surface in Python's matplotlib


code:
def class_with_static(name, bases, body):
    static_block = body.pop("__static__", None)
    klass = type(name, bases, body)
    if static_block:
        static_block(klass)
    return klass

class Point(object):
    __metaclass__ = class_with_static

    def __static__(cls):
        cls.ORIGIN = cls()

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

assert isinstance(Point.ORIGIN, Point)
assert Point.ORIGIN.x == Point.ORIGIN.y == 0
assert not hasattr(Point, "__static__")

rawDescription: Class variables of same type in Python

description: Class variables of same type in Python


code:
from __future__ import print_function
from skimage import io, feature, color, measure, draw, img_as_float
import numpy as np

image = img_as_float(color.rgb2gray(io.imread('flame.png')))
edges = feature.canny(image)
coords = np.column_stack(np.nonzero(edges))

model, inliers = measure.ransac(coords, measure.CircleModel,
                                min_samples=3, residual_threshold=1,
                                max_trials=1000)

print(model.params)

rr, cc = draw.circle_perimeter(int(model.params[0]),
                               int(model.params[1]),
                               int(model.params[2]),
                               shape=image.shape)

image[rr, cc] = 1

import matplotlib.pyplot as plt
plt.imshow(image, cmap='gray')
plt.scatter(model.params[1], model.params[0], s=50, c='red')
plt.axis('off')
plt.savefig('/tmp/flame_center.png', bbox_inches='tight')
plt.show()

rawDescription: How to detect circlular region in images and centre it with Python?

description: Detect circlular region in images and centre it with Python


code:
options = {'group':Group, 'host':Host, 'location':Location, 'exchange':Exchange}
for key, modelclass in options.items():
    value = request.POST.get(key, None)
    if value:
        initial[key] = value
        obj = modelclass.objects.get(pk=value)
        filter = {}
        filter[key] = obj
        selectForm.fields['job'].queryset = selectForm.fields['job'].queryset.filter(**filter)

rawDescription: django compound querysets

description: Django compound querysets


code:
print ("Content-type: text/html\n\n")
print ("\n")
print ("<meta http-equiv=\"refresh\" content=\"0; url = http://192.168.1.109\" />")
print ("")

rawDescription: Refresh web page using a CGI Python script


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

n = 1000

x = np.logspace(2, 10, n)
y = x**1.5
y = y * np.random.lognormal(10, 3, n)

x_bins = np.logspace(np.log10(x.min()), np.log10(x.max()), np.sqrt(n))
y_bins = np.logspace(np.log10(y.min()), np.log10(y.max()), np.sqrt(n))
H, xedges, yedges = np.histogram2d(x, y, bins=[x_bins, y_bins])

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(x, y, 'o')
ax1.set_xscale('log')
ax1.set_yscale('log')

ax2 = fig.add_subplot(212)
ax2.pcolormesh(xedges, yedges, H.T)
ax2.set_xscale('log')
ax2.set_yscale('log')

rawDescription: Python - 2D Histogram plot in log scale -- Error: `cannot convert float NaN to integer`


code:
def get_column(game, col_num):
    x = []
    for i in range(3):
        x.append(game[i][col_num])
    return x

rawDescription: Noughts and Crosses loops

description: Noughts and Crosses loops


code:
import sys
import random
from PIL import Image

BLOCKLEN = 64 # Adjust and be careful here.

img = Image.open(sys.argv[1])
width, height = img.size

xblock = width / BLOCKLEN
yblock = height / BLOCKLEN
blockmap = [(xb*BLOCKLEN, yb*BLOCKLEN, (xb+1)*BLOCKLEN, (yb+1)*BLOCKLEN)
        for xb in xrange(xblock) for yb in xrange(yblock)]

shuffle = list(blockmap)
random.shuffle(shuffle)

result = Image.new(img.mode, (width, height))
for box, sbox in zip(blockmap, shuffle):
    c = img.crop(sbox)
    result.paste(c, box)
result.save(sys.argv[2])

rawDescription: How to reorder pixels

description: Reorder pixels


code:
import __builtin__
import inspect

[name for name, function in sorted(vars(__builtin__).items())
 if inspect.isbuiltin(function) or inspect.isfunction(function)]

rawDescription: How do I get a list of all the built-in functions in Python?

description: Get a list of all the built-in functions in Python


code:
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=preview.pdf'

#print PDF to response
return response

rawDescription: Django admin "Preview PDF" button

description: Django admin "Preview PDF" button


code:
xpath = './/div[@class="chat_dialog"][descendant::text()="zajac"]'
element = driver.find_element_by_xpath(xpath)

rawDescription: check if whole block has any childs with inner text

description: Check if whole block has any childs with inner text


code:
new_temp = list()
for temp_i in data.X11:
    if ~is_nan(temp_i):
        if isinstance(temp_i, six.string_types):
            b = temp_i.split(" ")
            if len(b) == 3 and (b[0])=='<':
                new_temp.append(0)
            elif len(b) == 2:
                if b[0] == '10+':
                    new_temp.append(10)
                else:
                    new_temp.append(int(b[0]))
        else:
            if isinstance(temp_i, float):
                new_temp.append(math.floor(temp_i))
            if isinstance(temp_i, int):
                if temp_i >= 10:
                    new_temp.append(10)
                elif temp_i < 1 and temp_i >= 0:
                    new_temp.append(0)
                elif temp_i < 0:
                    new_temp.append(-10)
    else:
        new_temp.append(-10)

rawDescription: How do I improve the performance of the following code in python

description: Improve the performance of the following code in python


code: command = ['grep', r'^\(Added: \|Modified: \|Deleted: \)', filename]

rawDescription: Avoid subprocess.Popen auto escaping my backslashes in grep


code: import time; time.sleep(0.1)

rawDescription: Setting schema for all queries of a connection in psycopg2: Getting race condition when setting search_path


code: x % b

rawDescription: How do I increment letters in python and then loop back to the beginning of the alphabet?

description: Increment letters in python and then loop back to the beginning of the alphabet


code:
self.btnButton.setDisable(True)
self.leInput.textChanged.connect(self.disableButton)
def disableButton(self):
    if len(self.leInput.text()) > 0:
        self.btnButton.setDisable(False)

rawDescription: PySide: How to disable a Button unless a Edit Field isn't empty


code:
def load(filename):
    ngrams = {}
    for line in open(filename):
        if line[0] == '\\':
            pass  # just ignore all these lines
        else:
            first, rest = line.split(None, 1)
            middle, last = rest.rsplit(None, 1)
            ngrams[middle] = first, last
    return ngrams

ngrams = load("ngrams.txt")

rawDescription: fastest way to store n-grams (strings with variable amount of words) in python

description: Fastest way to store n-grams (strings with variable amount of words) in python


code:
class AdFormLite(AdForm):
    class Meta:
        fields = ['category', 'sub_category']

rawDescription: Django - partially validating form

description: Django - partially validating form


code:
import Tkinter as tk

class ButtonBlock(object):
    def __init__(self, master):
        self.master = master
        self.button = []
        self.button_val = tk.IntVar()
        entry = tk.Entry()
        entry.grid(row=0, column=0)
        entry.bind('<Return>', self.onEnter)
    def onEnter(self, event):
        entry = event.widget
        num = int(entry.get())
        for button in self.button:
            button.destroy()
        for i in range(1, num+1):
            self.button.append(tk.Radiobutton(
                self.master, text=str(i), variable=self.button_val, value=i,
                command=self.onSelect))
            self.button[-1].grid(sticky='WENS', row=i, column=0, padx=1, pady=1)
    def onSelect(self):
        print(self.button_val.get())

if __name__ == '__main__':
    root = tk.Tk()
    ButtonBlock(root)
    root.mainloop()

rawDescription: Creating elements by loop Tkinter

description: Creating elements by loop Tkinter


code:
class TimeMaterialsForm(ModelForm):
   status = forms.ChoiceField(choices=STATUS_CHOICES)
   project_manager = forms.forms.ModelChoiceField(queryset=customUser.objects.filter(pm=True))
   ...

rawDescription: ChoiceField - choices based on boolean field


code:
t1 = time.localtime()
t1
t2 = time.gmtime()
t2
(time.mktime(t1) - time.mktime(t2)) / 60

rawDescription: Python time differences

description: Python time differences


rawDescription: How to split utf8 string by ascii header in python?

description: Split utf8 string by ascii header in python


code:
import decimal
from django.db import models
from django.core import exceptions
from django.utils.translation import ugettext_lazy as _

class CentsField(models.IntegerField):
    empty_strings_allowed = False
    default_error_messages = {
        'invalid': _("'%(value)s' value must be a decimal number."),
    }
    description = _("Fixed-point number")

    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if value is None or isinstance(value, decimal.Decimal):
            return value
        try:
            if isinstance(value, int):
                return decimal.Decimal(value) / 100
            else:
                return decimal.Decimal(value)
        except decimal.InvalidOperation:
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
            )

    def get_prep_value(self, value):
        return int(value * 100)

rawDescription: django integer model field with float form input

description: Django integer model field with float form input


code:
class Window(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()

        self.container = QtGui.QWidget()
        self.setCentralWidget(self.container)
        self.container_lay = QtGui.QVBoxLayout()
        self.container.setLayout(self.container_lay)

        # Input
        self.le = QtGui.QLineEdit()
        self.container_lay.addWidget(self.le)

        # enter button
        self.enter_btn = QtGui.QPushButton("Enter")
        self.container_lay.addWidget(self.enter_btn)
        self.enter_btn.clicked.connect(self.run) # No '()' on run you want to reference the method.

        # display
        self.container_lay.addWidget(QtGui.QLabel("Answer:"))
        self.ans = QtGui.QLabel()
        self.container_lay.addWidget(self.ans)

    def run(self):
        precision = self.le.text()
        pi = str(round(math.pi, precision)) # probably different formatting
        self.ans.setText(pi)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    window = Window()
    window.show()

    sys.exit(app.exec_())

rawDescription: How can I add a submit, output and input box using PyQt4?

description: Add a submit, output and input box using PyQt4


code:
import smtplib

def sendmail(sender, recipient, subject, body, server="localhost"):
    "Sends an e-mail to the specified recipient."

    body = "
" + body + "
"

    headers = ["From: " + sender,
               "Subject: " + subject,
               "To: " + recipient,
               "MIME-Version: 1.0",
               "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(server)
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
    session.quit()

rawDescription: Sending email from gmail using Python

description: Sending email from gmail using Python


code:
import numpy as np
@np.vectorize
def diff_if_bigger(x, y):
     return y - x if y > x else 0
diff_if_bigger(np.array([5.6,7.0]), 8)

rawDescription: Numpy vectorize as a decorator with arguments


code:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
db.create_all()
db.session.commit()

rawDescription: sqlalchemy create tables

description: Sqlalchemy create tables


code: c = [a for a in (m.split('=')[1] for m in matches) if a != '1']

rawDescription: Python: 'as' keyword in list comprehension?


code:
from django.db.models import F
from datetime import datetime

min_date = datetime(2013,12,31)
result = Table.objects.filter(in_time__gte=min_date).\
exclude(in_time__eq=F('actual_time'))

rawDescription: Django - query for to give rows where one column Not equals to another column in same model


code:
from datetime import timedelta, datetime
from time import sleep

endtime = datetime.utcnow() + timedelta(seconds = 2)

while True:
    sleep(1) # just an example
    if datetime.utcnow() > endtime: # if more than two seconds has elapsed
        break

rawDescription: program timeout in windows for python

description: Program timeout in windows for python


code:
from social.backends.google import GoogleOAuth2

def save_profile(backend, user, response, *args, **kwargs):
    if isinstance(backend, GoogleOAuth2):
        if response.get('image') and response['image'].get('url'):
            url = response['image'].get('url')
            ext = url.split('.')[-1]
            user.avatar.save(
               '{0}.{1}'.format('avatar', ext),
               ContentFile(urllib2.urlopen(url).read()),
               save=False
            )
            user.save()

rawDescription: Python Social Auth get Google avatar

description: Python Social Auth get Google avatar


rawDescription: Select a substring before the second occurrence of a character without a string slice


rawDescription: Python int to binary?

description: Python int to binary


code:
class Node(object):
    def __init__(self, id_):
            self.id_ = id_

class Atom(Node):
    def __init__(self, symbol, id_):
            super(Atom, self).__init__(id_)
            self.symbol = symbol

a = Atom("FE", 1)
a.symbol
a.id_
type(a)

rawDescription: Understanding objects in Python

description: Understanding objects in Python


code:
from flask import Flask, request

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def parse_request():
    data = request.data
    # use data here

rawDescription: how to send data from android device to python website

description: Send data from android device to python website


rawDescription: Python - Complete difference between two lists same length


code:
for root, dirs, files in os.walk(your_dir_path):
    for file in files:
        file = os.path.join(root, file)
        with open(file) as f:
             ...

rawDescription: Search a string in a directory

description: Search a string in a directory


code:
import random

def randomIntWithNDigits(n):
    numbers = '12456789'
    result = ''
    for i in range(0,n):
        result+= random.choice(numbers)
    return result

rawDescription: How to generate but exclude a certain number in a certain digit integer in python

description: Generate but exclude a certain number in a certain digit integer in python


code:
class UserList(Base):
    ...
    contactCount = column_property(
        select(
            [func.count()],
            contact_id == Contact.id,
        ).label('contactCount'),
        deferred=True,
    )

rawDescription: Add a custom column

description: Add a custom column


code: values = {'query': ipStr}

rawDescription: Python 3 Urllib Posting Issues

description: Python 3 Urllib Posting Issues


rawDescription: How do i sort a dictionary by value that has tuples as values

description: Sort a dictionary by value that has tuples as values


rawDescription: How does one use python globals() to update a dictionary variable?

description: Use python globals() to update a dictionary variable


code:
def delete_contract(self, contract_name):
    action = ActionChains(selenium_context) # create ActionChains object
    contract = page_loc.find_element_by_css_selector('span[ng-click="deleteContract()"]')
    action.move_to_element(contract).perform() # move the mouse to the element
    contract.click()

rawDescription: Selenium/Python - How to click on a button that appears only when cursor is hovering over it?


code:
self.bind_all("<B1-Motion>", self.on_motion)
...
def on_motion(self, event):
    widget = self.winfo_containing(event.x_root, event.y_root)
    ...

rawDescription: How to detect when a pressed mouse enters a widget in a different Frame

description: Detect when a pressed mouse enters a widget in a different Frame


code:
import re
def cmpauthors(b1,b2):
    a1 = re.search("by (.*) \(\d+\)", b1)
    if a1 == None:
        return -1
    a2 = re.search("by (.*) \(\d+\)", b2)
    if a2 == None:
        return 1
    return cmp(a1.group(1),a2.group(1))

infile = open("Test100.txt","r")
lines = infile.readlines()
lines.sort(cmp=cmpauthors)
print("Alphabetical by Authors\n")
for line in lines:
    print(line)

rawDescription: How do i alphabetize a text file of books by author

description: Alphabetize a text file of books by author


code:
while True:
    caloriesGoal = float(input('Enter the calorie goal the day: '))
    if 1500 <= caloriesGoal <= 3000:
        break
    else:
        print("Error: Goal must be between 1500 and 3000 calories!")

totalConsumed = 0
items = 0

while True:
      caloriesConsumed = float(input('Item {}: How many calories was it? (-1 to stop)'.format(items+1)))

      if caloriesConsumed < 0:
          print("Input stopped")
          break

      totalConsumed += caloriesConsumed
      items += 1

      if totalConsumed > caloriesGoal:
          print("Goal reached/exceeded!")
          break

print('You consumed {} calories in {} items.'.format(totalConsumed, items))

if caloriesGoal > totalConsumed:
      print('The user is within their goal by ', (caloriesGoal - totalConsumed))
else:
      print('The user exceeded their goal by', (totalConsumed - caloriesGoal))

rawDescription: How to use a while loop to add values up?

description: Use a while loop to add values up


code:
data_pad = ("00000000")

file_pad = binascii.unhexlify(data_pad)

with open(pack, 'ab') as file_con_pad:
    file_con_pad.write(file_pad)
    print ('4 bit padding added')

rawDescription: Python3 Appending Null bytes with bytearray()


code:
from collections import Counter
from operator import itemgetter
from itertools import imap

[(name, count) for name, count in Counter(imap(itemgetter(1), names)).iteritems() if count > 3]

rawDescription: python count number of triple-repeats in one field of a list of tuples

description: Python count number of triple-repeats in one field of a list of tuples


code:
from bs4 import BeautifulSoup
url = 'http://www.zap.com.br/imoveis/rio-de-janeiro+rio-de-janeiro/apartamento-padrao/venda/'
import urllib2
response = urllib2.urlopen(url).read()
len(BeautifulSoup(response, 'lxml').find_all('div'))
len(BeautifulSoup(response, 'html.parser').find_all('div'))
len(BeautifulSoup(response, 'html5lib').find_all('div'))

rawDescription: Beautifulsoup not working on a specific site


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()

d = {'a':['e1','e2','e3'],'b':['e1','e2'],'c':['e1']}
row = 0
col = 0

for key in d.keys():
    row += 1
    worksheet.write(row, col,     key)
    for item in d[key]:
        worksheet.write(row, col + 1, item)
        row += 1

workbook.close()

rawDescription: Python, write dictionary values in an excel file


code:
import subprocess
p = subprocess.Popen('less', shell=True, stdout = subprocess.PIPE, stdin = subprocess.PIPE)
p.stdin.write('hey!!!'.encode('utf-8'))
print(p.communicate())

rawDescription: From a python3 script, how to I pipe a string into a bash program?


code: [i+(j,) for i, j in zip(list_1, list_2)]

rawDescription: Merging a list of tuples with a list into a list


code:
import pyexcel as pe
import pyexcel.ext.xls
sheet = pe.get_sheet(file_name="example.xls")
sheet # just to show what the sheet contains
sheet.row += [12, 11, 10] # now add it to its row
sheet.save_as("new_example.xls") # save it to a new file
pe.get_sheet(file_name="new_example.xls") # read it back

rawDescription: adding row data in spreadsheet using pyexcel python

description: Adding row data in spreadsheet using pyexcel python


code:
import numpy as np
text_x = np.arange(1.5, 5.6)
text_y = [yval+0.06 for yval in y[:-1]]

for t, tx, ty in zip(text[:-1], text_x, text_y):
    plt.text(tx, ty, t)

rawDescription: Python: Add text to step plot

description: Python: Add text to step plot


code:
class YExtension(Extension):
    tags = set(['y'])

    def preprocess(self, source, name, filename=None):
        # insert some code here that replaces '{% xyz %}foo bar{% endxyz %}'
        # with something like: '{% xyz %}foo bar{% raw %}foo bar{% endraw %}{% endxyz %}'
        return source

rawDescription: Compile subsection of Jinja2 AST

description: Compile subsection of Jinja2 AST


code:
import pygame
import random

screen_width = 500
screen_height = 500

pygame.init()
screen = pygame.display.set_mode((screen_width,screen_height))
clock = pygame.time.Clock()

black = (0, 0, 0)
red = (255,0,0)
blue = (0, 0, 255)

fps = 30

#the size of our player square
playerSize = 50

#rectangles get declared with x, y, w, h
obstacle = [0, 0, 350, 50]

obstacleMoveSpeed = 5
#how fast to move obstalce down

def check_collision(playerRect, obstacleRect):
    #convert rectangles into x,y,w,h
    playerX = playerRect[0]
    playerY = playerRect[1]
    playerWidth = playerRect[2]
    playerHeight = playerRect[3]

    obstacleX = obstacle[0]
    obstacleY = obstacle[1]
    obstacleWidth = obstacle[2]
    obstacleHeight = obstacle[3]

    #get the right left top and bottom
    myRight = playerX + playerWidth
    myLeft = playerX
    myTop = playerY
    myBottom = playerY + playerHeight

    otherRight = obstacleX + obstacleWidth
    otherLeft = obstacleX
    otherTop = obstacleY
    otherBottom = obstacleY + obstacleHeight

    #now the collision code
    collision = True

    if ((myRight < otherLeft) or (myLeft > otherRight) or (myBottom < otherTop) or (myTop > otherBottom)):
        collision = False

    return collision

"""def randomOb(randomize, obstacle, obstacle2):

                if randomize == 0:
                        pygame.draw.rect(screen, red, obstacle)
                        obstacle = [0, 0, 350, 50]
                        randomize = random.randrange(0,2)
                if randomize == 1:
                        pygame.draw.rect(screen, red, obstacle2)
                        obstacle2 = [150, 0, 410, 50]
                        randomize = random.randrange(0,2)

                randomize = random.randrange(0,2)
                return randomize"""

def game_loop():

        randomize = random.randrange(0,2)
        playerRect = [(screen_width / 2)-(playerSize/2), 400, playerSize, playerSize]
        screen_padding = random.randint(0, 100)
        #(screen_width / 2)-(playerSize/2) just figures out how to center the player
        while 1:

                for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                                exit()
                        if event.type == pygame.KEYDOWN:
                                if event.key == pygame.K_LEFT:
                                        playerRect = [(screen_width * 0.2)-(playerSize/2), 400, playerSize, playerSize]
                                if event.key == pygame.K_RIGHT:
                                        playerRect = [(screen_width * 0.8)-(playerSize/2), 400, playerSize, playerSize]
                        if event.type == pygame.KEYUP:
                                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                                        playerRect = [(screen_width / 2)-(playerSize/2), 400, playerSize, playerSize]

                #move obstacle downward
                obstacle[1] = obstacle[1] + obstacleMoveSpeed

                if (check_collision(playerRect, obstacle)):
                        print("COLLISION")
                if obstacle[1] > screen_height + screen_padding:
                        obstacle[1] = -50
                        screen_padding = random.randint(0, 100)
                        orientation = bool(random.getrandbits(1))
                        if orientation:
                                obstacle[0] = 0
                        else:
                                obstacle[0] = 150

                #drawing code
                screen.fill(black)

                #draw our player
                pygame.draw.rect(screen, blue, playerRect)

                pygame.draw.rect(screen, red, obstacle)

                """randomOb(randomize, obstacle, obstacle2)
                if obstacle[1] > 500 or obstacle2[1] > 500:
                        randomize = random.randrange(0,2)
                        randomOb(randomize, obstacle, obstacle2)"""

                pygame.display.update()

                clock.tick(fps)

game_loop()

rawDescription: Pygame, i need to have obstacles repeat randomly


code:
from PIL import Image

im = Image.open("myfile.png")
im.save("myfile.pbm")

rawDescription: I have a PNG image, and wondering how to efficiently convert it to PBM in python


code:
import os
os.environ['LOGNAME']

rawDescription: Log in Profile in python

description: Log in Profile in python


code:
h2 = soup.find("h2", text="Ads")
a = h2.find_next_sibling("a")

rawDescription: How to get <a href>'s that appear after a specific <h2>?

description: Get <a href>'s that appear after a specific <h2>


code:
from pysnmp.hlapi.asyncore import *
snmpEngine = SnmpEngine()
for oid in ['1.3.6.1.2.1.2.2.1.8.1', '1.3.6.1.2.1.2.2.1.8.2']:
    g = getCmd(snmpEngine,
               CommunityData('public'),
               UdpTransportTarget(('demo.snmplabs.com', 161)),
               ContextData(),
               ObjectType(ObjectIdentity(oid)))
    print(next(g))

rawDescription: Reuse getCmd object in pysnmp

description: Reuse getCmd object in pysnmp


code:
import numpy as np

def foo(a, b):
    # cond is a boolean array marking where the condition is met
    cond = a[1:] < a[:-1]
    cond = np.insert(cond, 0, False)
    # values is an array of the items in from a that will be used to fill b
    values = a[cond]
    values = np.insert(values, 0, b[0])
    # labels is an array of increasing indices into values
    label = cond.cumsum()
    b[:] = values[label]

rawDescription: Vectorize numpy array for loop

description: Vectorize numpy array for loop


code: datetime.date(year, month, 1).weekday()

rawDescription: Python calendar, counting empty days of the week before the first of the month


rawDescription: Comparing two websites in two windows using selenium webdriver and python


code:
g = sns.lmplot(x="total_bill", y="tip",
               data=tips, line_kws={'color': 'red'})
sns.plt.show()

rawDescription: How to change the line color in seaborn lmplot

description: Change the line color in seaborn lmplot


code:
doc = """<xml>
    <mapshape title="Bar" extras="">
    <kml></kml>
    </mapshape>

    <mapshape title="Foo" extras="">
    <kml></kml>
    </mapshape>
</xml>"""

import lxml.etree as etree

xml = etree.fromstring(doc)
for mapshape in xml:
    kml = etree.tostring(mapshape.getchildren()[0])
    parseKML(kml)

rawDescription: Python:JS: How to parse multiple kml node in one xml file?


code:
def mean(x):
    return float(sum(x))/len(x)

...
for key, value in d.items():
    if len(value) == 1:
        avg_diff = None # or 0 -- this indicates there was only 1 purchase
    else:
        # This requires your dates to be sorted, ascending
        sv = sorted(value)
        avg_diff = mean([sv[i] - sv[i-1] for i in range(len(sv)) if i])
    writer.writerow( [key, avg_diff] )

rawDescription: Averaging the difference between multiple values in a dictionary


code:
from urllib.request import urlretrieve
import urllib

url   = 'http://www.example.com'
values = {'example_param1' : 'example value 1',
          'example_param2' : 'example value 2'}

data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # data should be bytes

save_path = save_root + fund_provider + '.json'
urlretrieve(url, save_path, data=data )

rawDescription: Python 3, How To Use Python To Save Data From This Page?


rawDescription: Fastest Way to Update a bunch of records in queryset in Django


code:
def mysplit(html):
    in_tag = False
    in_word = False
    for i, ch in enumerate(html):
        if ch == '<':
            in_tag = True
        elif ch == '>':
            in_tag = False
        space = ch.isspace() and not in_tag
        if not in_word and not space:
            in_word = True
            begin = i
        elif in_word and space:
            in_word = False
            yield html[begin:i]
    if in_word:
        yield html[begin:]

testhtml = 'I like this thing'
print(list(mysplit(testhtml)))
# prints: ['I', 'like', 'this', 'thing']

rawDescription: How to split HTML text ignoring spaces in tags

description: Split HTML text ignoring spaces in tags


code:
import os, sys
os.environ['ETS_TOOLKIT'] = 'qt4'

from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
from numpy import linspace, pi, sin
from enthought.enable.api import Component, Container, Window
from enthought.chaco.api import create_line_plot, \
                                add_default_axes, \
                                add_default_grids, \
                                OverlayPlotContainer

x = linspace(-pi,pi,100)
y = sin(x)
plot = create_line_plot((x,y))
add_default_grids(plot)
add_default_axes(plot)
container = OverlayPlotContainer(padding = 50)
container.add(plot)
plot_window = Window(None, -1, component=container)
plot_window.control.setWindowTitle('hello')
plot_window.control.resize(400,400)
plot_window.control.show()

app.exec_()

rawDescription: Python: Embed Chaco in PyQt4 Mystery

description: Python: Embed Chaco in PyQt4 Mystery


code:
import re
[i for i in some_list if not re.match(r"[98]\B|+\(91\)", i)]

rawDescription: Using startswith() function inside lists in python


code:
with mock.patch('builtins.input', side_effect=[5, 6, 7]):
    self.apple_counter()

rawDescription: Python testing using mock library for user input in a loop


rawDescription: Python 3 bytes.index: better way?

description: Python 3 bytes.index: better way


code:
class MyClass:
  def fun(self):
    self.variable = input('Enter Here:')

  def fun_2(self):
    print(self.variable)

mc = MyClass()

window = Tk()
button = Button(text = 'Button', command = mc.fun )
button2 = Button(text = 'Button2', command = mc.fun_2 )
button.pack()
button2.pack()

rawDescription: Return statement not working python 3

description: Return statement not working python 3


rawDescription: hex to binary (2 hex digits at a time) - python

description: Hex to binary (2 hex digits at a time) - python


code:
from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

rawDescription: How to print from Flask @app.route to python console

description: Print from Flask @app.route to python console


code:
f = open(filepath, 'r')
answer = {}
for line in f:
    k, v = line.strip().split('=')
    answer[k.strip()] = v.strip()

f.close()

rawDescription: Python - converting textfile contents into dictionary values/keys easily


code:
import multiprocessing as mp
import timeit

def timeout(func, args=(), kwargs=None, TIMEOUT=10, default=None, err=.05):

    if hasattr(args, "__iter__") and not isinstance(args, basestring):
        args = args
    else:
        args = [args]
    kwargs = {} if kwargs is None else kwargs

    pool = mp.Pool(processes = 1)

    try:
        result = pool.apply_async(func, args=args, kwds=kwargs)
        val = result.get(timeout = TIMEOUT * (1 + err))
    except mp.TimeoutError:
        pool.terminate()
        return default
    else:
        pool.close()
        pool.join()
        return val

def Timeit(command, setup=''):
    return timeit.Timer(command, setup=setup).timeit(1)

def timeit_timeout(command, setup='', TIMEOUT=10, default=None, err=.05):
    return timeout(Timeit, args=command, kwargs={'setup':setup},
                   TIMEOUT=TIMEOUT, default=default, err=err)

rawDescription: Timeout on a Python function call inside timeit


code:
for pos, link in enumerate(soup.find_all('a', href=re.compile("bangladesh"))):
    tip = link.get('href')
    print(tip)
    if (pos + 1) == 2:
        webbrowser.open(tip)

rawDescription: I have parsed all "href" links from a webpage. I want to open only one of them with my browser. How can I do that?


rawDescription: How to make a set of lists

description: Make a set of lists


code:
def strike(text):
    result = ''
    for c in text:
        result = result + c + '\u0336'
    return result

rawDescription: Python: Create strikethrough / strikeout / overstrike string type


code:
with mock.patch('oauth2client.client.flow_from_clientsecrets') as mockflow, \
        mock.patch('oauth2client.file.Storage') as MockStorage, \
        mock.patch('webbrowser.open') as mockwbopen, \
        mock.patch('yourmodule.input') as mockinput:
    # set the credentials to invalid
    storage = MockStorage.return_value
    credential = storage.get.return_value
    credentials.invalid = True

    # run the method and see if we get what we want
    result = BloggerInterface().get_credentials()

    # check that the flow was initialised correctly
    mockflow.assert_called_with(
        'client_secret.json', 'https://www.googleapis.com/auth/blogger',
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    MockStorage.assert_called_with('credentials.dat')

    # With invalid credentials, the code should obtain a auth url from the
    # flow, pass it to the browser. Then the authentication code should be taken
    # from input and passed back to the flow for exchange. Test these
    # interactions took place:
    flow.step1_get_authorize_url.assert_called_once_with()
    mockwbopen.assert_called_once_with(flow.step1_get_authorize_url.return_value)
    flow.step2_exchange.assert_called_once_with(mockinput.return_value)
    storage.put(flow.step2_exchange.return_value)
    assert result == flow.step2_exchange.return_value

rawDescription: How would I unit test code like this?

description: How would I unit test code like this


code:
d = locals()
np.concatenate([d[x] for x in list3], 1)

rawDescription: Python concatenate arrays based on information from a list


rawDescription: List of Lists to List of Dictionaries

description: List of Lists to List of Dictionaries


rawDescription: Alternating between iterators in Python

description: Alternating between iterators in Python


rawDescription: Ruby equivalent for python array

description: Ruby equivalent for python array


code:
def my_big_function():
    ...
    def set_symbolstyle_value(key, **kwargs):
        try:
            session.curves[PathNameNew + key].symbolStyle.setValues(**kwargs)
        except MyException:
            do_something()

    set_symbolstyle_value('_S201-16', show=True)
    set_symbolstyle_value('_S201-16', marker=FILLED_DIAMOND)
    ...

rawDescription: Try, Except:Pass on multiple lines

description: Try, Except:Pass on multiple lines


code:
mydate = datetime.datetime.now()
myxmldate = '<start>%s</start>' % mydate.isoformat()

rawDescription: python, how i do xml = '<start>%??</start>' % datetime.datetime

description: Python, how i do xml = '<start>%??</start>' % datetime.datetime


code:
def fib(n):
    def fib(n):
        return n if n <= 1 else fib(n-1)+fib(n-2)
    return fib(n)

rawDescription: Is there a way to refer to the current function in python?


code:
import cv2
import numpy as np
x = np.random.randint(1,10, (5,5))
x
y = cv2.inRange(x,4,8)
y
z = np.transpose(np.where(y>0))
z

rawDescription: Fast finding pixel position with current color interval


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

r = 0.25
d = 2*r
s = 0

def meshgrid_triangles(n, m):
    """ Returns triangles to mesh a np.meshgrid of n x m points """
    tri = []
    for i in range(n-1):
        for j in range(m-1):
            a = i + j*(n)
            b = (i+1) + j*n
            d = i + (j+1)*n
            c = (i+1) + (j+1)*n
            if j%2 == 1:
                tri += [[a, b, d], [b, c, d]]
            else:
                tri += [[a, b, c], [a, c, d]]
    return np.array(tri, dtype=np.int32)

x0 = np.arange(4) * d
y0 = np.arange(5) * d
x, y = np.meshgrid(x0, y0)
x[1::2] -= r
triangles = meshgrid_triangles(4, 5)
triangulation = mtri.Triangulation(x.ravel(), y.ravel(), triangles)
plt.scatter(x, y, color='red')
plt.triplot(triangulation, 'g-h')

plt.show()

rawDescription: Connect all 2D Points from NumPy 2D Arrays as a triangular meshgrid


code:
class B(A):
    def __init__(self):
        A.__init__(self)

rawDescription: Way to call super(MyClass, self).__init__() without MyClass?


code:
all_lines = []

# first read all lines in a file ( I assume file its not too big to do it)
with open('data.csv', 'r') as f:
    all_lines  = [l.rstrip() for l in f.readlines()]

# then process specific lines as you need.
for l in all_lines[2:4]:
    a,b,c = map(float, l.split())
    print(a,b,c)
    # or save the values in other file

t = sum(map(float,all_lines[5].split()))
print(t)

for l in all_lines[7:7+t]:
    a,b,c = map(float, l.split())
    print(a,b,c)
    # or save the values in other file

rawDescription: Modify values on specific lines of a file


code:
import os

os.environ['LD_LIBRARY_PATH'] = os.getcwd()  # or whatever path you want

rawDescription: Set LD_LIBRARY_PATH before importing in python


code:
import urllib2
req = urllib2.Request("http://foo.com/post_here", "<xml data to post>")
response = urllib2.urlopen(req)
the_page = response.read()

rawDescription: Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python?


code:
from __future__ import print_function # only for module main() test function
import csv
import sys
PY3 = sys.version_info[0] > 2

def read_properties(filename, delimiter=':'):
    ''' Reads a given properties file with each line of the format key=value.
        Returns a dictionary containing the pairs.
            filename -- the name of the file to be read
    '''
    open_kwargs = {'mode': 'r', 'newline': ''} if PY3 else {'mode': 'rb'}
    with open(filename, **open_kwargs) as csvfile:
        reader = csv.reader(csvfile, delimiter=delimiter, escapechar='\\',
                            quoting=csv.QUOTE_NONE)
        return {row[0]: row[1] for row in reader}

def write_properties(filename, dictionary, delimiter=':'):
    ''' Writes the provided dictionary in key sorted order to a properties
        file with each line in the format: key<delimiter>value
            filename -- the name of the file to be written
            dictionary -- a dictionary containing the key/value pairs.
    '''
    open_kwargs = {'mode': 'w', 'newline': ''} if PY3 else {'mode': 'wb'}
    with open(filename, **open_kwargs) as csvfile:
        writer = csv.writer(csvfile, delimiter=delimiter, escapechar='\\',
                            quoting=csv.QUOTE_NONE)
        writer.writerows(sorted(dictionary.items()))

def main():
    data = {
        'Answer': '6*7=42',
        'Knights': 'Ni!',
        'Spam': 'Eggs',
    }

    filename='test.properties'
    write_properties(filename, data)
    newdata = read_properties(filename)

    print('Read in: ')
    print(newdata)
    print()

    with open(filename, 'rb') as propfile:
        contents = propfile.read()
    print('File contents: (%d bytes)' % len(contents))
    print(repr(contents))

    print(['Failure!', 'Success!'][data == newdata])

if __name__ == '__main__':
     main()

rawDescription: Configparser set with no section

description: Configparser set with no section


code:
def foo():
  print('hi')

l = [1,2,foo]
l
l[2]()

rawDescription: function accidentally called when defining list

description: Function accidentally called when defining list


code: gq

rawDescription: Is there a Vim equivalent to the Linux/Unix "fold" command?


code:
import re
text = "I am doctor break I stays in CA break   you can contact me on +000000\n"
re.split(r'\s+break\s+', text)

rawDescription: dis-juncting ( or Break) the string based on a punctuation in python

description: Dis-juncting ( or Break) the string based on a punctuation in python


code:
from getpass import getpass
getpass()

rawDescription: Can i get console input without echo in python?

description: Get console input without echo in python


code:
from tkinter import *
from tkinter import ttk

def win1():
    mainframe = ttk.Frame(root, padding = '3 3 12 12')
    mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
    mainframe.columnconfigure(0, weight = 1)
    mainframe.rowconfigure(0, weight = 1)

    ttk.Button(mainframe, text = 'Next', command = win2).grid(
        column = 1, row = 1, sticky = W)
    ttk.Button(mainframe, text = 'Quit', command = quit).grid(
        column = 1, row = 2, sticky = W)

    root.mainloop()

def quit():
    root.destroy()

def win2():
    root.withdraw()
    new = Toplevel()
    new.title('Window 2')
    mainframe = ttk.Frame(new, padding = '3 3 12 12')
    mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
    mainframe.columnconfigure(0, weight = 1)
    mainframe.rowconfigure(0, weight = 1)

    ttk.Button(mainframe, text = 'Next', command = win2).grid(
        column = 1, row = 1, sticky = W)

root = Tk()
win1()

rawDescription: Python - tkinter: Opening and closing dialog windows


code:
# tempTradeDays is the initial DatetimeIndex
dateRange = []
tempYear = None
dictYears = tempTradeDays.groupby(tempTradeDays.year)
for yr in dictYears.keys():
    tempYear = pd.DatetimeIndex(dictYears[yr]).groupby(pd.DatetimeIndex(dictYears[yr]).month)
    for m in tempYear.keys():
        dateRange.append(max(tempYear[m]))
dateRange = pd.DatetimeIndex(dateRange).order()

rawDescription: Get last date in each month of a time series pandas


code:
filenames = g.glob('*.TXT')

for filename in filenames:
    for col in csv.DictReader(open(filename,'rU')):
        ...

rawDescription: Is there a way to grab the names of the files that glob parses through?


code:
df = pd.read_csv(r'c:\data\earthquake.csv', parse_dates=[0], index_col=[0])

df.plot()

rawDescription: Earthquake Plotting using Pandas, from csv file


rawDescription: Python: Choose number of bits to represent binary number


code:
import pylab as pl
import numpy as np

n = 300                                     #number of sample data
x,y = np.random.rand(2,n)                   #generate random sample locations

pl.subplot(121)                             #sub-plot area 1 out of 2
pl.scatter(x,y,lw=0,c='k')                  #darw sample points
pl.axis('image')                            #necessary for correct aspect ratio

pl.subplot(122)                             #sub-plot area 2 out of 2

pl.hexbin(x,y,C=None,gridsize=15,bins=None,mincnt=1)        #hexbinning

pl.scatter(x,y,lw=0.5,c='k',edgecolor='w')  #overlaying the sample points
pl.axis('image')                            #necessary for correct aspect ratio

pl.show()                                   #to show the plot

rawDescription: Is there a tutorial for creating a hexbin heat map using Matplotlib?


code:
rectColor = black
while True:
    display.fill(white)

    keys = pygame.key.get_pressed()
    if keys[k_right]:
        rectColor = yellow

    pygame.draw.rect(display, rectColor, [50,leady,15,15])

    #draw everything else

    pygame.display.update()

rawDescription: Changing an already drawn rectangle's color?


code: table.style = 'LightShading-Accent1'

rawDescription: How do I get rid of the default styling on a table object in a python-docx generated word document?

description: Get rid of the default styling on a table object in a python-docx generated word document


code:
import requests

url = r'http://test.com/login_check.php'
parameters = {'x' : '0' ,
              'y' : '0',
              'url':'login.php',
              'password':'1234',
              'id':'userid'}

login_response = requests.get(url, params=parameters)
htmlContent = login_response.text

rawDescription: how can i change from python2 http request code to python3 Requests

description: Change from python2 http request code to python3 Requests


code:
type(None)
type('')
bool(None) == bool('')
None == ''

rawDescription: Python : Is None the same as ""?

description: Python : Is None the same as ""


code:
from numpy import array
a=array([1,4,5,57,45,34])
from numpy import where
where(a==5)

rawDescription: How to find an index of an element in an array using numpy?

description: Find an index of an element in an array using numpy


code:
import rpy2.robjects as ro

ro.globalenv['res'] = res_frompy
ro.globalenv['log2FoldChang'] = log2FoldChang_frompy
ro.globalenv['padj'] = padj_frompy

ro.r('with(res, plot(log2FoldChange, padj))')

rawDescription: Syntax for rpy2 base.with function

description: Syntax for rpy2 base.with function


code:
from suds.client import Client
c = Client('https://www.e-conomic.com/secure/api1/EconomicWebService.asmx?WSDL')
c.service.Account_Create(10, '20', 'ProfitAndLoss')

rawDescription: How to connect to webservice using suds?

description: Connect to webservice using suds


code:
root = Tk()

text = Text(root, **kw)
text.pack()

def text_print(*args):
    print('Hello World!')

text.bind('a', text_print)

rawDescription: Call a function using bind in tk text widget


code:
import numpy as np
a = np.zeros(100).reshape(10,10)
b = np.ones(4).reshape(2,2)
a[4:6, 4:6] = b
a

rawDescription: Replace values in bigger numpy array with smaller array


code:
class Contact(models.Model):
    sender = models.EmailField()
    subject = models.CharField(max_length=25)
    message = models.TextField()

    def __unicode__(self):
        return self.subject

rawDescription: Models bleeding together in models.py?

description: Models bleeding together in models.py


code:
xls = pd.ExcelFile('path_to_file.xls')
df1 = xls.parse('Sheet1')
df2 = xls.parse('Sheet2')

rawDescription: Using Pandas to pd.read_excel() for multiple worksheets of the same workbook


code: value = repr(v)

rawDescription: How to convert a Python object into the correct string representation

description: Convert a Python object into the correct string representation


rawDescription: Binary list from indexes of ascending integer list (Python)


code:
from selenium import webdriver
from urllib2 import urlopen

url = 'http://www.google.com'
file_name = 'C:/Users/Desktop/test.txt'

conn = urlopen(url)
data = conn.read()
conn.close()

file = open(file_name,'wt')
file.write(data)
file.close()

browser = webdriver.Firefox()
browser.get('file:///'+file_name)
html = browser.page_source
browser.quit()

rawDescription: How can I render JavaScript HTML to HTML in python?

description: Render JavaScript HTML to HTML in python


code:
def traceback_col_seq(self):
    """
    Traces back the column sequence to determine final global alignment.
    Recalculates the score using score_cell.
    """
    i, j = self.maxI-1, self.maxJ-1
    self.traceback = list() #stores final sequence
    matrixDict = {0:'M',1:'Ic',2:'Ir'} #mapping between numeric value and matrix
    chars = self.col_seq[j-1] + self.row_seq[i-1] #store first characters
    thisM, thisC, thisR = self.score_cell(i,j, chars)
    cell = max(thisM), max(thisC), max(thisR) #determine where to start
    prevMatrix = matrixDict[cell.index(max(cell))] #store where to go first
    while i > 0 or j > 0:
        #loop until the top left corner of the matrix is reached
        if prevMatrix == 'M':
            self.traceback.append(self.col_seq[j-1])
            i -= 1; j -= 1
            prevMatrix = matrixDict[thisM.index(max(thisM))]
        elif prevMatrix == 'Ic':
            self.traceback.append(self.col_seq[j-1].lower())
            j -= 1
            prevMatrix = matrixDict[thisC.index(max(thisC))]
        elif prevMatrix == 'Ir':
            self.traceback.append('-')
            i -= 1
            prevMatrix = matrixDict[thisR.index(max(thisR))]
        chars = self.col_seq[j-1] + self.row_seq[i-1] #store next characters
        thisM, thisC, thisR = self.score_cell(i,j, chars) #rescore next cell
    return ''.join(self.traceback[::-1])

rawDescription: Traceback in dynamic programming implementation of Needleman-Wunsch algorithm


code:
class Task(CeleryTask):
    """
    Override the Celery Task baseclass to send subtasks to the same
    queue as the main task.
    """

    def subtask(self, args=None, kwargs=None, options=None,
                *starargs, **starkwargs):

        kwargs = kwargs or {}
        options = options or {}

        # override the queue if not passed in as an option
        if set(('queue', 'exchange', 'routing_key')) & set(options.keys()):
            options.update(self.request.delivery_info)

        return super().subtask(args, kwargs, options,
                               *starargs, **starkwargs)

rawDescription: Do subtasks inherit the queue of their parent task?


code:
body = str("The following items are in the list: ")
items = ["a", "b", "c", "d"]  # list of strings
for i in items:
    body = body.__add__(i + ",")
print(body)

rawDescription: How do I add all of the items from a list to a variable?

description: Add all of the items from a list to a variable


code:
import win32com.client
wordApp = win32com.client.Dispatch('Word.Application') # alternately DispatchEx
wordApp.visible = True                                 # alternately False or leave out
wordDoc = wordApp.Documents.Open('c:/my_word_doc.docx')
myRange = wordDoc.Content
myRange.Find.Execute(FindText='peanuts')
myRange.Bookmarks.Add(Name='X')
wordDoc.SaveAs('c:/my_word_doc.docx')
wordDoc.Close()
wordApp.Quit()

rawDescription: How to insert bookmark in Word using Python (win32com)?

description: Insert bookmark in Word using Python (win32com)


code:
from django.test import override_settings

class TestView(TestCase):
    @override_settings(EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend')
    def test_view(self):
       ...

rawDescription: Avoid django.core.mail.outbox as e-mail backend in test execution on Django


code:
import glob
list_of_files = glob.glob('C:/begpython/wavnk/*.lab')

rawDescription: directory and file related doubts?

description: Directory and file related doubts


code:
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from collections import defaultdict

# read names and postions from bed file
positions = defaultdict(list)
with open('positions.bed') as f:
    for line in f:
        name, start, stop = line.split()
        positions[name].append((int(start), int(stop)))

# parse faste file and turn into dictionary
records = SeqIO.to_dict(SeqIO.parse(open('sequences.fasta'), 'fasta'))

# search for short sequences
short_seq_records = []
for name in positions:
    for (start, stop) in positions[name]:
        long_seq_record = records[name]
        long_seq = long_seq_record.seq
        alphabet = long_seq.alphabet
        short_seq = str(long_seq)[start-1:stop]
        short_seq_record = SeqRecord(Seq(short_seq, alphabet), id=name, description='')
        short_seq_records.append(short_seq_record)

# write to file
with open('output.fasta', 'w') as f:
    SeqIO.write(short_seq_records, f, 'fasta')

rawDescription: Python: Extract DNA sequence from FASTA file using Bed file


code:
def sequence():
 numbers1=[25,30,45,67]
 numbers2=[25,30,45,67]
 count=0
 for i in numbers1:
  for i2 in numbers2:
   if i-i2!=0:
      count+=1
 if count==(len(numbers1)*len(numbers2))-len(numbers1):
  print("all numbers are different.")

a=sequence()

rawDescription: Python Assistance on sequences

description: Python Assistance on sequences


code:
import os
import stat

executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH
for filename in os.listdir('.'):
    if os.path.isfile(filename):
        st = os.stat(filename)
        mode = st.st_mode
        if mode & executable:
            print(filename,oct(mode))

rawDescription: How do I search for an executable file using python in linux?

description: Search for an executable file using python in linux


code: ax = fig.add_subplot(111, aspect="equal")

rawDescription: How to make a non-square contourf-plot

description: Make a non-square contourf-plot


code:
number = 7568934
multiplier = [3, 1, 3, 1, 3, 1, 1]

for idx, digit in enumerate(str(number)):
  print('Res: ' + str(int(digit) * multiplier[idx]))

rawDescription: How do you multiply each digit by different numbers in python?

description: Multiply each digit by different numbers in python


code:
import json

class MyCalendar:
    def __init__(self, _year, _weeks):
        self.year = _year
        self.weeks = _weeks

    def to_JSON(self):
        # Dumps the JSON correctly, passing over the __dict__ of the class to assmble it.
        return json.dumps(self, default=lambda o: o.__dict__)

class MyWeek:
    def __init__(self, _week, _days):
        self.weeknumber = _week
        self.days = _days

class MyDay:
    def __init__(self, _day, _courses):
        self.daynumber = _day
        self.courses = _courses

class MyCourse:
    def __init__(self, _id, _title):
        self.id = _id
        self.title = _title

def json_calendar(dct):
    year = dct['year'] # year, for quick reference.
    weeks = {} # our weeks, as a dict.

    for week in dct['weeks']: # iterate through the available weeks in the given dct.
        days = {} # our days, as a dict.
        for day in dct['weeks'][week]['days']: # iterate through the available days in the week.
            courses = {} # our courses, as a dict.
            for course in dct['weeks'][week]['days'][day]['courses']: # iterate through the available courses in the day.
                courseId = int(course) # course id
                courseTitle = dct['weeks'][week]['days'][day]['courses'][course]['title'] # course title

                courses[courseId] = MyCourse(courseId, courseTitle) # Assemble our courses into the courses dict.

            days[int(day)] = MyDay(day, courses) # Assemble our days into the day dict.

        weeks[int(week)] = MyWeek(week, days) # Assemble our weeks into the weeks dict.

    return MyCalendar(year, weeks) # Assemble and return our calendar.

rawDescription: Deserialize the JSON string into object in Python


code:
import wx
from wx.lib.stattext import GenStaticText as StaticText

if wx.Platform == "__WXMAC__":
    from Carbon.Appearance import kThemeBrushDialogBackgroundActive

class EllipticStaticText(StaticText):

    def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, name="ellipticstatictext"):
        """
        Default class constructor.

        :param `parent`: the L{EllipticStaticText} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `label`: the text label;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the static text style;
        :param `name`: the window name.
        """

        StaticText.__init__(self, parent, id, label, pos, size, style, name)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{EllipticStaticText}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        event.Skip()
        self.Refresh()

    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{EllipticStaticText}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty to reduce flicker.
        """

        pass

    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{EllipticStaticText}.

        :param `event`: a `wx.PaintEvent` to be processed.
        """

        dc = wx.BufferedPaintDC(self)
        width, height = self.GetClientSize()

        if not width or not height:
            return

        clr = self.GetBackgroundColour()

        if wx.Platform == "__WXMAC__":
            # if colour is still the default then use the theme's  background on Mac
            themeColour = wx.MacThemeColour(kThemeBrushDialogBackgroundActive)
            backBrush = wx.Brush(themeColour)
        else:
            backBrush = wx.Brush(clr, wx.SOLID)

        dc.SetBackground(backBrush)
        dc.Clear()

        if self.IsEnabled():
            dc.SetTextForeground(self.GetForegroundColour())
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        dc.SetFont(self.GetFont())

        label = self.GetLabel()
        text = self.ChopText(dc, label, width)

        dc.DrawText(text, 0, 0)

    def ChopText(self, dc, text, max_size):
        """
        Chops the input `text` if its size does not fit in `max_size`, by cutting the
        text and adding ellipsis at the end.

        :param `dc`: a `wx.DC` device context;
        :param `text`: the text to chop;
        :param `max_size`: the maximum size in which the text should fit.
        """

        # first check if the text fits with no problems
        x, y = dc.GetTextExtent(text)

        if x <= max_size:
            return text

        textLen = len(text)
        last_good_length = 0

        for i in xrange(textLen, -1, -1):
            s = text[0:i]
            s += "..."

            x, y = dc.GetTextExtent(s)
            last_good_length = i

            if x < max_size:
                break

        ret = text[0:last_good_length] + "..."
        return ret

    def Example():

        app = wx.PySimpleApp()
        frame = wx.Frame(None, -1, "EllipticStaticText example ;-)", size=(400, 300))

        panel = wx.Panel(frame, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)

        elliptic = EllipticStaticText(panel, -1, r"F:\myreservoir\re\util\python\hm_evaluation\data\HM_Evaluation_0.9.9.7.exe")
        whitePanel = wx.Panel(panel, -1)
        whitePanel.SetBackgroundColour(wx.WHITE)

        sizer.Add(elliptic, 0, wx.ALL|wx.EXPAND, 10)
        sizer.Add(whitePanel, 1, wx.ALL|wx.EXPAND, 10)

        panel.SetSizer(sizer)
        sizer.Layout()

        frame.CenterOnScreen()
        frame.Show()

        app.MainLoop()

    if __name__ == "__main__":

        Example()

rawDescription: Limiting StaticText width

description: Limiting StaticText width


rawDescription: Minimizing the execution time in mongoengine


code:
import os
path = 'path\\to\\your\\directory\\'
files = os.listdir (path)
for i in files:
    if i.endswith('.py'):
        os.system("python "+path+i)

rawDescription: Running a folder/directory as a whole in Python


code:
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

import math

def initFun():
    glClearColor(1.0,1.0,1.0,0.0)
    glColor3f(0.0,0.0, 0.0)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluOrtho2D(0,700,0,700)

def displayFun():
    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(0.0,0.0,1.0)
    xpts=[]
    ypts=[]
    N=len(newlist)
    for i in range(0,N):
        xpts.append(700+100-float(newlist[i][4])*20)
        ypts.append(700+1300-float(newlist[i][5])*20)

    glBegin(GL_POINTS)
    for j in range(0,N):
        glVertex2f(xpts[j],ypts[j])

    glEnd()
    glFlush()

if __name__ == '__main__':
    glutInit()
    glutInitWindowSize(700,700)
    glutCreateWindow("My Display")
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    glutDisplayFunc(displayFun)
    initFun()
    glutMainLoop()

rawDescription: How do I resize,scale or magnify the distances between points plotted in OpenGl

description: Resize,scale or magnify the distances between points plotted in OpenGl


code:
import boto
from boto.s3.key import Key
conn = boto.connect_s3('ap-southeast-2')
bucket = conn.get_bucket('bucket-name')
k = Key(bucket)
k.key = 'filename.txt'
k.open()
k.read(10)

rawDescription: Read a file line by line from S3 using boto?


code:
T = TypeVar('T', bound=BaseModel)

def deserialize(data: Dict[str, Any], clazz: Callable[..., T]) -> T:
    """ Deserialize dictionary into a model object of type clazz. """

rawDescription: Correct way use type hints / generics to describe arguments of type class ("type")


code:
import string

def make_new_words(start_word):
    """create new words from given start word and returns new words"""
    new_words = []
    for i, letter in enumerate(start_word):
        word_as_list = list(start_word)
        for char in string.ascii_lowercase:
            word_as_list[i] = char
            new_words.append("".join(word_as_list))

    return new_words

rawDescription: Create new words from start word python

description: Create new words from start word python


code: foo['z']=foo.apply(lambda x: x[x['C1']], axis=1)

rawDescription: Assigning values to a column based on the values stored in another column


code:
# list the shape nodes
nurbsShapes = maya.cmds.listRelatives(curSel, allDescendents=True, noIntermediate=True, fullPath=True, type="nurbsCurve", path=True)
# list the transform nodes to each shape node
nurbsTransforms = maya.cmds.listRelatives(nurbsShapes, type='transform', parent=True)
# select the transform nodes
cmds.select(nurbsTransforms)

rawDescription: python maya - Select children 'nurbs' then hides key

description: Python maya - Select children 'nurbs' then hides key


code: command = lambda: bot_analysis_frame(eventConditionL,eventBreakL)

rawDescription: Tkinter Button Command Being Called Automatically?


code:
xpath = '//p[@class="attrs"]/span[text()="description:"]/following-sibling::strong'
description = browser.find_by_xpath(xpath).first.text

rawDescription: How to find element value using Splinter?

description: Find element value using Splinter


code:
# get the data as a python string
with open ("CM120102.CSV", "r") as myfile:
    data=myfile.read()

# munge in python - get rid of the garbage in the input (lots of xff bytes)
import re
data = re.sub(r'[^a-zA-Z0-9_\.;:\n]', '', data) # get rid of the rubbish
data = data + '\n' # the very last one is missing?
data = re.sub(r';\n', r'\n', data) # last ; separator on line is problematic

# now let's suck into a pandas DataFrame
from StringIO import StringIO
import pandas as pd
df = pd.read_csv(StringIO(data), index_col=None, header=0,
    skipinitialspace=True, sep=';', parse_dates=True)

rawDescription: Skipping 0xff byte when using pandas read_csv


code:
import seaborn as sns
import pandas as pd
import numpy as np

arr = np.random.random((3,3))
df = pd.DataFrame(arr)
ax = sns.heatmap(arr)

cax = plt.gcf().axes[-1]
cax.tick_params(labelsize=20)

rawDescription: Change tick size on colorbar of seaborn heatmap


code:
def get_query_set(self, context):
    ctype, object_pk = self.get_target_ctype_pk(context)
    if not object_pk:
        return self.comment_model.objects.none()

    qs = self.comment_model.objects.filter(
        content_type = ctype,
        object_pk    = smart_text(object_pk),
        site__pk     = settings.SITE_ID,
    )

rawDescription: Django: Example of generic relations using the contenttypes framework?


code:
series = pd.Series(list("abcdefghijklmnop"*30))
series.value_counts()

rawDescription: pandas.dataframe.describe with text fields

description: Pandas.dataframe.describe with text fields


rawDescription: Quickest way to calculate the average growth rate across columns of a numpy array


code:
class escapeMode(object):
    '''
    Enum to represent the escape mode.
    '''
    ## Escape all values
    ALLWAYS     = 1
    ## Escape only values containing seperators or starting with quotation
    NECESSARY   = 2

rawDescription: Documentation after members in python (with doxygen)


code:
import re

re.split(re.compile("|".join([", ", " "])), "Firstname, Lastname Email")

rawDescription: Python: split string with delimiters from a list


code:
import requests, base64

usrPass = "userid:password"
b64Val = base64.b64encode(usrPass)
r=requests.post(api_URL,
                headers={"Authorization":b64Val},
                data=payload)

rawDescription: Base64 Authentication Python

description: Base64 Authentication Python


code:
for link in links:
    link.send_keys(Keys.CONTROL + Keys.RETURN)

    # switch to new window
    driver.switch_to_window(driver.window_handles[-1])

    link.send_keys(Keys.CONTROL + Keys.PAGE_UP) # dont know why
    time.sleep(5)
    test() # Want to call test function
    link.send_keys(Keys.CONTROL + 'w')

    #switch back to the first window
    driver.switch_to_window(driver.window_handles[0])

rawDescription: web element not detecting in selenium in a FOR LOOP

description: Web element not detecting in selenium in a FOR LOOP


code:
import os, time

allfiles = []
now = time.time()

# walk will return triples (current dir, list of subdirs, list of regular files)
# file names are relative to dir at first
for dir, subdirs, files in os.walk("/storage/disk-1/Media/Video/TV"):
    for f in files:
        if not f.endswith(".avi"):
            continue
        # compute full path name
        f = os.path.join(dir, f)
        st = os.stat(f)
        if st.st_mtime < now - 3600*24*7:
            # too old
            continue
        allfiles.append((f, st))

rawDescription: Using Python, how do I get an array of file info objects, based on a search of a file system?


code:
import datetime
d1 = datetime.datetime.strptime("00:08:30.291", "%H:%M:%S.%f")
d1
d2
dt1 = datetime.timedelta(minutes=d1.minute, seconds=d1.second, microseconds=d1.microsecond)
dt2 = datetime.timedelta(minutes=d2.minute, seconds=d2.second, microseconds=d2.microsecond)
fin = dt1 + dt2
fin
str(fin)

rawDescription: Adding up time durations in Python

description: Adding up time durations in Python


code:
def field_max(table, field):
    """
    return the maximum value for column `field` in table

    table should be a collection of records or an open table
    field should be a field name (either `str` or `unicode`)
    """
    return max([rec[field] for rec in table])

rawDescription: python dbf max query

description: Python dbf max query


code:
my_list = ['identification_2442942_23.txt', 'identification_9353289532_133.txt', 'identification_1321_9.txt']
[i[i.rfind('_') + 1:i.rfind('.')] for i in my_list]

rawDescription: parse a string with multiple delimiters

description: Parse a string with multiple delimiters


code:
import logging

class FormatterWithHeader(logging.Formatter):
    def __init__(self, header, fmt=None, datefmt=None, style='%'):
        super().__init__(fmt, datefmt, style)
        self.header = header # This is hard coded but you could make dynamic
        # Override the normal format method
        self.format = self.first_line_format

    def first_line_format(self, record):
        # First time in, switch back to the normal format function
        self.format = super().format
        return self.header + "\n" + self.format(record)

def test_logger():
    logger = logging.getLogger("test")
    logger.setLevel(logging.DEBUG)
    formatter = FormatterWithHeader('First Line Only')
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.info("This line will kick out a header first.")
    logger.info("This line will *not* kick out a header.")

rawDescription: Write header to a python log file, but only if a record gets written


code:
array = np.random.random((100,100,100))
center = (30,10,25)
radius = 5.0
x, y, z = np.ogrid[-center[0]:array.shape[0]-center[0],-center[1] :array.shape[1]-center[1], -center[2]:array.shape[2]-center[2]]
indexes = numpy.transpose((x**2+y**2+z**2 <= radius**2).nonzero())

rawDescription: numpy histogram indexing

description: Numpy histogram indexing


code:
def TileImage(imgs, picturesPerRow=16):
    """ Convert to a true list of 16x16 images
    """

    # Calculate how many columns
    picturesPerColumn = imgs.shape[0]/picturesPerRow + 1*((imgs.shape[0]%picturesPerRow)!=0)

    # Padding
    rowPadding = picturesPerRow - imgs.shape[0]%picturesPerRow
    imgs = vstack([imgs,zeros([rowPadding,imgs.shape[1]])])

    # Reshaping all images
    imgs = imgs.reshape(imgs.shape[0],16,16)

    # Tiling Loop (The conditionals are not necessary anymore)
    tiled = []
    for i in range(0,picturesPerColumn*picturesPerRow,picturesPerRow):
        tiled.append(hstack(imgs[i:i+picturesPerRow,:,:]))

    return vstack(tiled)

rawDescription: Cleanly tile numpy array of images stored in a flattened 1D format


code:
chkdict = {} # A dictionary that we'll use to check for existance of an entry (whether is extension already processed or not)
setdef = chkdict.setdefault # Extracting a pointer of a method out of an instance may lead to faster access, thus improving performance a little
# Recurse through a directory:
for root, dirs, files in os.walk("ymir work"):
    # Loop through all files in currently examined directory:
    for file in files:
        ext = path.splitext(file) # Get an extension of a file
        # If file has no extension or file is named ".bashrc" or ".ds_store" for instance, then ignore it, otherwise write it to x:
        if ext[0] and ext[1]: ext = ext[1].lower()
        else: continue
        if not ext in chkdict:
            # D.setdefault(k[, d]) does: D.get(k, d), also set D[k] = d if k not in D
            # You decide whether to use my method with dict.setdefault(k, k)
            # Or you can write ext separately and then do: chkdict[ext] = None
            # Second solution might even be faster as setdefault() will check for existance again
            # But to be certain you should run the timeit test
            x.write("\t\"%s\"\n" % setdef(ext, ext))
            #x.write("\t\"%s\"\n" % ext)
            #chkdict[ext] = None
del chkdict # If you're not inside a function, better to free the memory as soon as you can (if you don't need the data stored there any longer)

rawDescription: How to extract extentions and save them without repetition

description: Extract extentions and save them without repetition


rawDescription: How do you filter for rows in a table where the count is highest in Django?

description: Filter for rows in a table where the count is highest in Django


code:
import urllib
resp = urllib.urlopen('http://bit.ly/bcFOko')
resp.getcode()
resp.url

rawDescription: Detect destination of shortened, or "tiny" url


code:
import urllib.parse
import webbrowser
def google(x): webbrowser.open("https://encrypted.google.com/search?hl=en&q=" + urllib.parse.quote(x))
google("new hampshire")

rawDescription: How to Open A URL in Python 3.5.1

description: Open A URL in Python 3.5.1


code:
with self.app.test_client() as client:
    client.post('/v0/scenes/test/foo',
                data=dict(image=(StringIO('fake image'), 'image.png')),
                headers={'content-md5': 'some hash'});

rawDescription: Flask and Werkzeug: Testing a post request with custom headers


code:
semilogx(lambd, power_earth/max(power_earth), 'b-', lw=4, zorder=5)
# Area under the curve
fillb_earth = fill_between(lambd, power_earth/max(power_earth), color='none', lw=0)
# Get the path
path_earth, = fillb_earth.get_paths()
# Create a Patch
mask_earth = PathPatch(path_earth, fc='none')
# Add it to the current axes
gca().add_patch(mask_earth)
# Add the image
im_earth = imshow(colors, cmap="spectral", extent=[min(lambd), max(lambd), 0, 1.1])
# Clip the image with the Patch
im_earth.set_clip_path(mask_earth)

rawDescription: matplotlib - clip image using line(s)

description: Matplotlib - clip image using line(s)


code:
QuestionBox = vizinfo.add("") #Add the vizinfo object
#Create an invisible Radio button to be the default selected one, so that one of the visible ones must be chosen by the user
invisibleRadio = QuestionBox.add(viz.RADIO, 0, "")
invisibleRadio.visible(0) #invisible

rawDescription: Buttons in vizard

description: Buttons in vizard


code:
import numpy as np
import pandas as pd

window = 30
df = pd.DataFrame(np.random.randn(100), columns=['Data'])

counts = pd.rolling_apply(df, window+1, lambda s: s[s < s[-1]].shape[0])

rawDescription: Pandas - What is the fastest way to count values greater than x in a rolling window?


code:
import json
# open the file "filename" in write ("w") mode
file = open("filename", "w")
# just an example dictionary to be dumped into "filename"
output = {"stuff": [1, 2, 3]}
# dumps "output" encoded in the JSON format into "filename"
json.dump(output, file)
file.close()

rawDescription: How do i save my Python crawler output to a JSON file?

description: Save my Python crawler output to a JSON file


code: import nodetypes as nt

rawDescription: Module longname and shortname

description: Module longname and shortname


code:
for stline in streamedtweets.readlines():
    processedStreamed = processTweet(stline)
    streamedsentiment =  NBClassifier.classify(extract_features(getFeatureVector(processedStreamed)))
    outputfile.append((streamedsentiment, stline))
    os.chdir(r'C:\Users\wildcat\Downloads\NLTK')

rawDescription: My data is being printed all on one line while writing into a CSV file


code:
from itertools import groupby
from operator import itemgetter

[[k, sum(v[1] for v in g)] for k, g in groupby(multiDimList, itemgetter(0))]

# result: [['a', 3], ['b', 2], ['c', 6]]

rawDescription: Multi Dimensional List - Sum Integer Element X by Common String Element Y


rawDescription: Insert list of lists into single column of pandas df


code:
class OwnedTable(tables.Table):
    roles = tables.Column(empty_values=())

    def render_roles(self):
        user = self.context["request"].user
        ...

rawDescription: Display relevant records from many to many in django-tables2


code:
ps = set()
for x, y in hull:
    ps.add(x)
    ps.add(y)
ps = numpy.array(list(ps))
center = vecs[ps].mean(axis=0)
A = vecs[ps] - center
h = vecs[ps[numpy.argsort(numpy.arctan2(A[:,1], A[:,0]))]]

rawDescription: Convex Hull and SciPy

description: Convex Hull and SciPy


rawDescription: Join lists and individual floats to single string in Python


code: tar = tarfile.TarFile.gzopen(os.path.join(backup_dir, directory+'.tar.gz'), mode='w', compresslevel=5)

rawDescription: Python: Assign a compression level to tarfile


code:
class ChatComment(models.Model):
    owner = models.ForeignKey(User)
    when = models.DateTimeField(auto_now_add=True)
    message = models.CharField(...)
    ...
    chatroom = models.ForeignKey(ChatRoom)

class PublicDocument(models.Model):
    owner = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(...)
    payload = models.FileField(...)

class DocumentReview(models.Model):
    author = models.ForeignKey(User)
    document = models.ForeignKey(PublicDocument)
    when = models.DateTimeField(auto_now_add=True)
    text = models.CharField(...)

rawDescription: Storing User Information Django

description: Storing User Information Django


code:
print(end1 + end2 + end3 + end4 + end5 + end6, end="")
print(end7 + end8 + end9 + end10 + end11 + end12)

rawDescription: printing in one line in python 3.4

description: Printing in one line in python 3.4


code:
c = a
a = b
b = b + c

rawDescription: Fibonacci being very strange in Python

description: Fibonacci being very strange in Python


code:
mikes_farm_list = FarmOwner.Objects.filter(owner="Mike").values_list('farms', flat=True)
Charges.Objects.filter(chargeId=3383, farms__in=mikes_farm_list)

rawDescription: Accessing table data created through manytomanyfield in django


code:
import sys
import xml.etree.ElementTree as etree

xsi =  "http://www.w3.org/2001/XMLSchema-instance"
xsd =  "http://www.w3.org/2001/XMLSchema"
ns = {"xmlns:xsi": xsi, "xmlns:xsd": xsd}
for attr, uri in ns.items():
    etree.register_namespace(attr.split(":")[1], uri)

foo = etree.Element("foo",
    dict(thing1="this", thing2="that")) # put `**ns))` if xsi, xsd are unused
somedata = etree.SubElement(foo, "somedata", dict(bar="1"))
etree.SubElement(somedata, "moredata",
    {"whatsit": "42", etree.QName(xsi, "type"): etree.QName(xsd, "string")})

etree.ElementTree(foo).write(sys.stdout, xml_declaration=True)

rawDescription: Python 2.7 and xml.etree: how to create an XML file with multiple namespaces?


code:
def go():
        print(check.get())
        if(check.get() == 0):

                print("off")

                w.delete(ALL)
                tegnefladen()
                update()

        else:

                print("on")
                update()

rawDescription: tkinter's IntVar() and .get()'ing it

description: Tkinter's IntVar() and .get()'ing it


code:
PENDING = 0
DONE = 1
STATUS_CHOICES = (
    (PENDING, 'Pending'),
    (DONE, 'Done'),
)

rawDescription: Django: Best way to implement "status" field in modules


code:
all_values = set()
for person_values in data.values():
    all_values = all_values.union(person_values)
all_values_list = list(all_values)

thecsv = csv.writer(open("your.csv", 'w'))
thecsv.writerow(all_values_list)
for name, values in data.items():
    row = [1 if i in values else 0 for i in all_values_list]
    thecsv.writerow([name] + row)

rawDescription: create a cross tab (maybe/sort of, not sure what its called) with Python

description: Create a cross tab (maybe/sort of, not sure what its called) with Python


code:
from collections import OrderedDict
class TestCase(OrderedDict):
    def run(self, test_cases=None):
        if test_cases is None:
            test_cases = default_all_test_cases # add all your default test cases here
        for test_case in test_cases:
            test_case.run()

rawDescription: Default argument to represent "do all"

description: Default argument to represent "do all"


code:
import subprocess
PIPE = subprocess.PIPE

proc = subprocess.Popen(['ls'], stdout=PIPE)
for line in iter(proc.stdout.readline, ''):
    if line.startswith('a'):
        print(line)

rawDescription: Monitoring the shell through python

description: Monitoring the shell through python


code:
a = np.frombuffer(data, dtype=np.uint8)
a.shape = (-1, 4)
rearranged = a[:,[2,1,0,3]]

rawDescription: Swap subarrays of a numpy array

description: Swap subarrays of a numpy array


code:
from selenium import webdriver

class WidgetArea():

  def setUp(self):
    self.driver = webdriver.Firefox()
    self.driver.implicitly_wait(30)
    self.driver.maximize_window()
    self.driver.get("http://demoqa.com/")

  def tearDown(self):
    self.driver.quit()

  def widget_area(self):
    elements = self.driver.find_elements_by_xpath("//div[@id='secondary']/aside")
    try:
        assert len(elements) == 4
        print("Test pass")
    except AssertionError:
        print("Assertion failed")

  def widget_list(self):
    elements = self.driver.find_elements_by_xpath("//ul[@id='menu-widget']/li")
    try:
        assert len(elements) == 7
        print("Test pass")
    except AssertionError:
        print("Assertion failed")

  def interaction(self):
    elements = self.driver.find_elements_by_xpath("//ul[@id='menu-interactions']/li")
    try:
        assert len(elements) == 5
        print("Test pass")
    except AssertionError:
        print("Assertion failed")

  def main(self):
    self.setUp()
    self.widget_area()
    self.widget_list()
    self.interaction()
    self.tearDown()

if __name__ == '__main__':
    new = WidgetArea()
    new.main()

rawDescription: How to run several tests with one Firefox instance, Selenium WebDriver with Python?

description: Run several tests with one Firefox instance, Selenium WebDriver with Python


code:
import csv

with open("IDList.csv","rb") as inf:
    incsv = csv.reader(inf)
    not_wanted = set(row[0] for row in incsv)

with open("Database.csv","rb") as inf, open("FilteredDatabase.csv","wb") as outf:
    incsv = csv.reader(inf)
    outcsv = csv.writer(outf)
    outcsv.writerows(row for row in incsv if row[0] not in not_wanted)

rawDescription: Filter Excel Table

description: Filter Excel Table