code:
from ctypes import *
f = c_float(12.3)
tmp = cast(pointer(f), POINTER(c_int))
tmp.contents
tmp.contents.value
hex(tmp.contents.value)
import struct
struct.unpack("f",struct.pack("I", 1095027917))

rawDescription: It is possible to use a pointer that just match the int value from a float variable in Python?


code: pm.rbinomial(100, .5, size=10)

rawDescription: Stochastic variables in pymc

description: Stochastic variables in pymc


code:
result_map = {}
for item in response:
    if item['country'] is None:
        continue
    if item['country'] not in result_map:
        result_map[item['country']] = item['percent']
    else:
        result_map[item['country']] += item['percent']

results = [
    {'country': country, 'percent': percent}
    for country, percent in result_map.items()
]

rawDescription: How to add value for same keys in a dict in python

description: Add value for same keys in a dict in python


code:
f.seek(offset)
get_records(f, count)

rawDescription: Fast way for multiple processes to read from central source in Python?


code:
BASE = ord('a') - 1

def str_to_nums(s):
    return [ord(ch) - BASE for ch in s]

def nums_to_str(nums):
    return "".join(chr(n + BASE) for n in nums)

print(str_to_nums("hi"))    # => [8, 9]
print(nums_to_str([8, 9]))  # => "hi"

print(str_to_nums("ca"))    # => [3, 1]
print(nums_to_str([3, 1]))  # => "ca"

rawDescription: converted letters to number now convert to three letters over and over

description: Converted letters to number now convert to three letters over and over


code:
# ...
os.mkfifo(filename)

p = Popen([..., filename, ...], stdout=PIPE)
with open(filename, 'w') as f:
     while True:
         indata = read_input() # read text to segment from files/sockets, etc
         f.write(indata)
         # read response from java process
         outdata = p.stdout.readline()# you need to figure out when to stop reading
         write_output(outdata) # write response via files/sockets, etc

rawDescription: How to avoid loading a large file repeatedly?

description: Avoid loading a large file repeatedly


code:
# Package Imports

import csv
import datetime
import matplotlib.pyplot as plt
import numpy as np
import dateutil.relativedelta as rd
import bisect
import scipy as sp

## File Settings

ipath = "/home/kane/tripkane_python/"
fname = "datetime_test_data.csv"

portfolio_list = []
dateList = []
valueList = []
x = []

portfolio = csv.DictReader(open(ipath + fname, "rb"))
portfolio_list.extend(portfolio)

for data in portfolio_list:
    dateList.append(data['date'])
    valueList.append(data[' value'])

for item in dateList:
    d = datetime.datetime.strptime(item, '%Y%m%d')
    t = d.toordinal()
    x.append(d)

dataArray = np.asarray([x, valueList])

stepList = [0, 3, 5]

TIda = []
TIv = []

for n in range(0, len(stepList)):
    TIda.append(x[stepList[n]])
    TIv.append(valueList[stepList[n]])

# Plot

fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111)

line1 = plt.plot(x, valueList, 'b')
lns = line1

labs = [l.get_label() for l in lns]
ax.legend(lns,
          labs,
          loc='upper left',
          frameon = False,
          shadow=False,
          fancybox=False,
          labelspacing=0.1,
          ncol=4,
          prop={'size':9}
          )
ax.set_title(fname , fontsize = 12)

plt.xticks(fontsize = 8)
plt.yticks(fontsize = 8)
ax.set_ylabel( 'Cents', fontsize = 10 )
ax.grid()

plt.step(TIda, TIv, 'r')

plt.show()

rawDescription: Complex step function overlaid onto matplotlib plot of time series code


code:
start_date = date.today() - timedelta(days=7)

MyModel.objects.filter(timestamp__gte=start_date).extra(select={'day': connection.ops.date_trunc_sql('day', 'timestamp')}).values('day').annotate(max_temperature=Max('temperature'))

rawDescription: django - get max values over several periods

description: Django - get max values over several periods


code:
df['kind'] = df.States + '_' + df.Sex
df.pivot_table('Num', cols=['kind'], rows='Rank')

rawDescription: Remake columns in pivot_table,pandas

description: Remake columns in pivot_table,pandas


rawDescription: python 3 convert byte string variable to regular string

description: Python 3 convert byte string variable to regular string


code:
def memoized(f):
    cache = {}
    def wrapper(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return wrapper

def get_count(target):
    @memoized
    def f(target, cur):
        if target < 0: return 0
        if target == 0: return 1
        return sum(f(target - n, n + 1) for n in range(cur, target + 1))
    return f(target, 1)

print(get_count(100))

rawDescription: find and print each unique combination that sums to 100 and return a count of all such combinations for numbers between 1 and 100

description: Find and print each unique combination that sums to 100 and return a count of all such combinations for numbers between 1 and 100


rawDescription: Are there any valid use cases for replacing a module with a class instance?


code:
class Node(object):
    def __getstate__(self):
        state = self.__dict__.copy()
        state.pop("neighbours")
        return state

rawDescription: Is it possible to force cPickle to use breadth-first rather than depth-first recursion?


code:
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
plt.show()

for i in range(2000):

    filename = "output_{0:04d}.dat".format(i)
    print("printing file = ", filename)
    xy = np.genfromtxt(filename)
    x = xy[:,0]; y = xy[:,1]
    plt.plot(x,y)
    plt.pause(0.01)

rawDescription: Animation of xy data in matplotlib

description: Animation of xy data in matplotlib


code:
import unittest
import sys

from StringIO import *
from while_loop import *
from mock import *

class TestJudge(unittest.TestCase):
    def testJudge_1(self):
        self.assertEqual(judge(16), 1)

    def testJudge_2(self):
        self.assertEqual(judge(15), 0)

class TestWhile(unittest.TestCase):
    def test_while_1(self):
        judge = Mock(side_effect=[0,0])
        out = StringIO()
        sys.stdout = out
        a = while_example(1, 1)
        output = out.getvalue().strip()
        self.assertEqual(output, "both a and b are OK")

    def test_while_2(self):
        judge = Mock(side_effect=[1,0])
        out = StringIO()
        sys.stdout = out
        a = while_example(18, 12)
        output = out.getvalue().strip()
        self.assertEqual(output, 'both a and b are not OK\nboth a and b are OK')

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

rawDescription: how to do Python unittest for while loop?

description: Do Python unittest for while loop


code:
import inspect

def labelable_yielded_case(case):

    argspec = inspect.getargspec(case)
    if argspec.defaults is not None:
        defaults_list = [''] * (len(argspec.args) - len(argspec.defaults)) + argspec.defaults
    else:
        defaults_list = [''] * len(argspec.args)
    argument_defaults_list = zip(argspec.args, defaults_list)
    case_wrappers = []

    def add_description(wrapper_id, argument_dict):

        case_wrappers[wrapper_id].description = case.__doc__.format(**argument_dict)

    def case_factory(*factory_args, **factory_kwargs):

        def case_wrapper_wrapper():

            wrapper_id = len(case_wrappers)

            def case_wrapper(*args, **kwargs):

                argument_list = []
                for argument in argument_defaults_list:
                    argument_list.append(list(argument))
                for index, value in enumerate(args):
                    argument_list[index][1] = value
                argument_dict = dict(argument_list)
                argument_dict.update(kwargs)
                add_description(wrapper_id, argument_dict)
                return case(**argument_dict)

            case_wrappers.append(case_wrapper)
            case_name = case.__name__ + str(wrapper_id)
            case_wrapper.__name__ = case_name
            if factory_args:
                setattr(factory_args[0].__class__, case_name, case_wrapper)
                return getattr(factory_args[0].__class__, case_name)
            else:
                return case_wrapper

        return case_wrapper_wrapper()

    return case_factory

class TestTest(object):

    def __init__(self):

        self.data = None

    def setUp(self):

        self.data = (1,2,3)

    def test_all(self):

        for index, value in enumerate((1,2,3)):
            yield self.validate_equality(), index, value

    @labelable_yielded_case
    def validate_equality(self, index, value):
        '''element {index} equals {value}'''

        assert self.data[index] == value, 'expected %d got %d' % (value, self.data[index])

rawDescription: getting test class instance in nose test object to sync up with instance in decorated generator target

description: Getting test class instance in nose test object to sync up with instance in decorated generator target


code:
for line in content:
    if line.startswith('some_identifier'):
        line.strip('\n')
        #put the line into an unused 'name' value field
        for dict in mylist:
            if dict['name'] == None:
                dict['name'] = line
                break

rawDescription: list of dict, how to fill out information later

description: List of dict, how to fill out information later


code:
class RegionField(SelectField):

    def __init__(self, *args, **kwargs):
        super(RegionField, self).__init__(*args, **kwargs)
        # a sample sqlalchemy query that returns a list of tuples (id, name)
        self.choices = models.Session.query(models.Region.id, models.Region.name).order_by(models.Region.name).all()

class AddCityForm(Form):
    region = RegionField()
    name = TextField(_('Name'))

rawDescription: How to make WTForms read from the datastore?

description: Make WTForms read from the datastore


code:
weights = [.3, .1, .6]
with open ('file2.txt') as f:
    count = int (f.readline ().strip () )
    for i in range (count):
        name = f.readline ().strip ()
        score = sum (w * s for w,s in zip (weights, (int (x) for x in f.readline ().strip ().split () ) ) )
        print ('{}\'s Score is {} %.'.format (name, score) )

rawDescription: Python inFile loops not getting every item in the file


code:
fig1 = plt.figure(1)
plt.plot([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], label="Test", color='g')
plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16],  label="Other Test",  color='r')
plt.grid(True)

fig1.savefig('Foo1.png')
# add plt.close() after you've saved the figure
plt.close()

fig2 = plt.figure(2)
plt.plot([0, 1, 2, 3, 4], [0, 5, 1, 9, 2], label="Test 2", color='g')
plt.plot([0, 1, 2, 3, 4], [0, 10, 50, 0, 10],  label="Other Test 2",  color='r')
plt.grid(True)

fig2.savefig('Foo2.png')

plt.show()

rawDescription: Matplotlib - Only show one figure

description: Matplotlib - Only show one figure


rawDescription: How to split coordinates in a string into a list of smaller lists

description: Split coordinates in a string into a list of smaller lists


code:
import os, time
from glob import glob
import sys
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

boundary = '--boundarydonotcross'

def request_headers():
    return {
        'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0',
        'Connection': 'close',
        'Content-Type': 'multipart/x-mixed-replace;boundary=%s' % boundary,
        'Expires': 'Mon, 3 Jan 2000 12:34:56 GMT',
        'Pragma': 'no-cache',
    }

def image_headers(filename):
    return {
        'X-Timestamp': time.time(),
        'Content-Length': os.path.getsize(filename),
        #FIXME: mime-type must be set according file content
        'Content-Type': 'image/jpeg',
    }

# FIXME: should take a binary stream
def image(filename):
    with open(filename, "rb") as f:
        # for byte in f.read(1) while/if byte ?
        byte = f.read(1)
        while byte:
            yield byte
            # Next byte
            byte = f.read(1)

# Basic HTTP server
class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        # Response headers (multipart)
        for k, v in pymjpeg.request_headers().items():
            self.send_header(k, v)
        # Multipart content
        for filename in glob('img/*'):
            # Part boundary string
            self.end_headers()
            self.wfile.write(pymjpeg.boundary)
            self.end_headers()
            # Part headers
            for k, v in pymjpeg.image_headers(filename).items():
                self.send_header(k, v)
            self.end_headers()
            # Part binary
            for chunk in pymjpeg.image(filename):
                self.wfile.write(chunk)
    def log_message(self, format, *args):
        return

httpd = HTTPServer(('', 8001), MyHandler)
httpd.serve_forever()

rawDescription: Create a mjpeg stream from jpeg images in python


code:
assert '^^' + 'Longer String'.center(19) + '^^' == '^^   Longer String   ^^'
assert '^^' + 'Short'.center(19) + '^^'         == '^^       Short       ^^'

rawDescription: String Formatting - Python

description: String Formatting - Python


rawDescription: Flatten numpy array

description: Flatten numpy array


code:
import collections
VersionInfo = collections.namedtuple('VersionInfo', 'obj icontains attrname')

Vinfos = [
    VersionInfo(AP_Release_Version, 'ap_version__icontains', 'ap_version'),
    VersionInfo(CP_Release_Version, 'cp_version__icontains', 'cp_version'),
    VersionInfo(GPS_Release_Version, 'gps_version__icontains', 'gps_version'),
]

for vinfo in Vinfos:
    kwargs = {vinfo.icontains : version }
    version_objs = vinfo.obj.objects.filter(**kwargs)

    for version_obj in version_objs:
        version_value = getattr(version_obj, vinfo.attrname)
        ...

rawDescription: How to optimize the code for this situation？

description: Optimize the code for this situation？


code:
class TestAllFormsMeetBasicBoundaryTests(TestCase):
    def all_subclasses(self, cls):
        return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                   for g in self.all_subclasses(s)]

    # this is teh awesome-sause! dynamically finding objects in the project FTW!
    def test_all_char_fields_contain_max_length_value(self):
        from django.apps import apps
        import django.forms
        import importlib
        log.info('loading all forms modules from apps')
        at_least_one_module_found = False
        for app_name in settings.PROJECT_APPS: #this is a list of in project apps
            app = apps.get_app_config(app_name)
            try:
                importlib.import_module('{0}.forms'.format(app.label))
                log.info('forms loaded from {0}'.format(app.label))
                at_least_one_module_found = True
            except ImportError as e:
                pass
        self.assertTrue(at_least_one_module_found, 'No forms modules were found in any of the apps. this should never be true!')
        all_forms = self.all_subclasses(django.forms.Form)

        messages = []
        for form in all_forms:
            for key in form.declared_fields.keys():
                field = form.declared_fields[key]
                if isinstance(field, django.forms.CharField) and form.__module__.partition('.')[0] in settings.PROJECT_APPS and field.max_length is None:
                    messages.append('{0}.{1}.{2} is missing a max_length value.'.format(form.__module__, form.__name__, key))
            pass

        self.assertEquals(0, len(messages),
                          'CharFields must always have a max_length attribute specified. please correct the following:\n--{0}'
                          .format('\n--'.join(messages)))

rawDescription: Get all form objects in a Django application


code:
import os

def sorted_ls(path):
    mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
    return list(sorted(os.listdir(path), key=mtime))

print(sorted_ls('documents'))

rawDescription: Directory Listing based on time

description: Directory Listing based on time


rawDescription: Python - convert list of tuples to string


code:
group.add_argument('-l', '--list', dest="list_server_or_group_name",
                   help='Get group or server state/configuration',
                   nargs='?', default=None, const='all')

rawDescription: argparse optional arguments

description: Argparse optional arguments


code:
#get the charset of an email
#courtesy http://ginstrom.com/scribbles/2007/11/19/parsing-multilingual-email-with-python/
def get_charset(message, default='ascii'):
    if message.get_content_charset():
        return message.get_content_charset()

    if message.get_charset():
        return message.get_charset()

    return default

#courtesy http://stackoverflow.com/questions/7166922/extracting-the-body-of-an-email-from-mbox-file-decoding-it-to-plain-text-regard
def get_body(message):
    body = None

    #Walk through the parts of the email to find the text body.
    if message.is_multipart():
        for part in message.walk():
            #If part is multipart, walk through the subparts.
            if part.is_multipart():
                for subpart in part.walk():
                    if subpart.get_content_type() == 'text/plain':
                        #Get the subpart payload (i.e., the message body).
                        charset = get_charset(subpart, get_charset(message))
                        body = unicode(subpart.get_payload(decode=True), charset)
            #Part isn't multipart so get the email body.
            elif part.get_content_type() == 'text/plain':
                charset = get_charset(subpart, get_charset(message))
                body = unicode(part.get_payload(decode=True), charset)
    #If this isn't a multi-part message then get the payload (i.e., the message body).
    elif message.get_content_type() == 'text/plain':
        charset = get_charset(subpart, get_charset(message))
        body = unicode(message.get_payload(decode=True), charset)

    return body

rawDescription: Python/Django/MySQL "Incorrect string value" error


code:
a = [1,3,12]
vector = numpy.zeros(shape=max(a) + 1)
vector[a] = 1

rawDescription: Create a numpy array when indexes of (fixed) elements are given


code:
from django.db.models.signals import pre_save

def calculate_things(sender, instance, **kwargs):
    # sender => Model
    # instance => Object pre saved
    ...
    # Your loginc here

class Entry(models.Model):
    ...
    # Model definition
    ...

    ... # You don't need re define save method.

pre_save.connect(calculate_things, sender=Entry)

rawDescription: Django Model Save Override Simpler Approach?


code:
input = "[2,3,4,5]"
map(float, input.strip('[]').split(','))
A = map(float, input.strip('[]').split(','))
print(A, type(A))

rawDescription: How to pass an entire list as command line argument in Python?

description: Pass an entire list as command line argument in Python


code:
con = sqlite.connect('temp.db')
with connection:
    cur = connection.cursor()
    cur.exectute('SELECT Sensor_Id FROM Sensors')
    sensor_ids = cur.fetchall()

# I would recommend this approach
sensor = { sid : Sensor(sid) for sid in sensor_ids }
# Which allows you to access them as
sensor['Main-hall-3'], sensor['Flap-track-fairing-7'] # etc.

# If the sensor ids are integers, you might prefer
sensor = { int(sid) : Sensor(sid) for sid in sensor_ids }
# Which allows you to access them as
sensor[3], sensor[7] # etc

# If you know that the ids are going to be CONSECUTIVE INTEGERS
# STARTING AT 0, then you could do
sensor = [ Sensor(sid) for sid in sensor_ids ]
# Which allows you to access them as
sensor[0], sensor[1] # etc

# Now, if you *really* insist on having the sensors bound to names,
# then you could try
import sys
current_module = sys.modules[__name__]
for sid in sensor_ids:
    setattr(current_module, 'sensor{}'.format(sid), Sensor(sid))
# Which would allow you to access them as
sensor1, sensor2 # etc

rawDescription: Create Class Instances from Database Query - Python


rawDescription: Crawl non-latin domain with scrapy

description: Crawl non-latin domain with scrapy


code:
def matchStr(ipadr = '10.20.30.40', matchIP = '10.20.'):
    return ipadr.startswith(matchIP)

rawDescription: Simple string match

description: Simple string match


code:
input_from_queue = ...  # e.g. `queue.dequeue_many(32)` or `tf.train.batch(..., 32)`
# input_from_queue.get_shape() ==> (32, 784)

input = tf.placeholder_with_default(input_from_queue, shape=(None, 784))
# input.get_shape() ==> (?, 784)

# ...
train_op = ...

sess.run(train_op)  # Takes examples from `queue`.
sess.run(train_op, feed_dict={input: ...})  # Takes examples from `feed_dict`.

rawDescription: How to mix queue-based and feed-based input in TensorFlow

description: Mix queue-based and feed-based input in TensorFlow


rawDescription: Scikit-Learn Classification and Regression with Weights


code:
import decimal
decimal.Decimal('100.1') + decimal.Decimal('0.1')
str(decimal.Decimal('100.1') + decimal.Decimal('0.1'))

rawDescription: Calc correct result of 100.1+0.1 as string


code:
global someVar
someVar = 55

rawDescription: Python function global variables?

description: Python function global variables


code:
# Get the figure and axis
fig, ax = plt.subplots()

def myHistogram(bins):
    # Clear any previous data, and plot the new histogram
    ax.clear()
    ax.hist(mydata, bins)
    fig.show()  # Seems to be necessary

interact(myHistogram, bins=(10, 50, 5))

rawDescription: IPython.html.widgets: saving the value for later


code:
import time
from datetime import datetime

ref = time.mktime(datetime(2001, 1, 1, 0, 0, 0).timetuple())
now = time.time() - ref

rawDescription: CoreData sqlite3 db - populating timestamp column with python script


code:
from itertools import chain
l = [(1,2,3),(4,5,6)]
list(chain.from_iterable(l))

rawDescription: How To Merge an Arbitrary Number of Tuples in Python?


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE

p = Popen(["grep", r"controller\|worker", file_name], stdout=PIPE)
output = p.communicate()[0]
if p.returncode == 0:
    print('found')
elif p.returncode == 1:
    print('not found')
else:
    print('error')

rawDescription: Substitution of subprocess.PIPE in Python?


code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time
import math
import numpy
import numpy as np
import random
from PIL import Image
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf

# Basic model parameters as external flags.
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')
flags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')
flags.DEFINE_integer('batch_size', 4, 'Batch size.  '
                     'Must divide evenly into the dataset sizes.')
flags.DEFINE_string('train_dir', 'data', 'Directory to put the training data.')
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
                     'for unit testing.')
NUM_CLASSES = 2
IMAGE_SIZE = 28
CHANNELS = 3
IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE * CHANNELS

def inference(images, hidden1_units, hidden2_units):
  # Hidden 1
  with tf.name_scope('hidden1'):
    weights = tf.Variable(
        tf.truncated_normal([IMAGE_PIXELS, hidden1_units],
                            stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))),
        name='weights')
    biases = tf.Variable(tf.zeros([hidden1_units]),
                         name='biases')
    hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)
  # Hidden 2
  with tf.name_scope('hidden2'):
    weights = tf.Variable(
        tf.truncated_normal([hidden1_units, hidden2_units],
                            stddev=1.0 / math.sqrt(float(hidden1_units))),
        name='weights')
    biases = tf.Variable(tf.zeros([hidden2_units]),
                         name='biases')
    hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)
  # Linear
  with tf.name_scope('softmax_linear'):
    weights = tf.Variable(
        tf.truncated_normal([hidden2_units, NUM_CLASSES],
                            stddev=1.0 / math.sqrt(float(hidden2_units))),
        name='weights')
    biases = tf.Variable(tf.zeros([NUM_CLASSES]),
                         name='biases')
    logits = tf.matmul(hidden2, weights) + biases
  return logits

def cal_loss(logits, labels):
  labels = tf.to_int64(labels)
  cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
      logits, labels, name='xentropy')
  loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')
  return loss

def training(loss, learning_rate):
  optimizer = tf.train.GradientDescentOptimizer(learning_rate)
  global_step = tf.Variable(0, name='global_step', trainable=False)
  train_op = optimizer.minimize(loss, global_step=global_step)
  return train_op

def evaluation(logits, labels):
  correct = tf.nn.in_top_k(logits, labels, 1)
  return tf.reduce_sum(tf.cast(correct, tf.int32))

def placeholder_inputs(batch_size):
  images_placeholder = tf.placeholder(tf.float32, shape=(batch_size,IMAGE_PIXELS))
  labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))
  return images_placeholder, labels_placeholder

def fill_feed_dict(images_feed,labels_feed, images_pl, labels_pl):
  feed_dict = {
      images_pl: images_feed,
      labels_pl: labels_feed,
  }
  return feed_dict

def do_eval(sess,
            eval_correct,
            images_placeholder,
            labels_placeholder,
            data_set):
  # And run one epoch of eval.
  true_count = 0  # Counts the number of correct predictions.
  steps_per_epoch = 4 // FLAGS.batch_size
  num_examples = steps_per_epoch * FLAGS.batch_size
  for step in xrange(steps_per_epoch):
    feed_dict = fill_feed_dict(train_images,train_labels,
                               images_placeholder,
                               labels_placeholder)
    true_count += sess.run(eval_correct, feed_dict=feed_dict)
  precision = true_count / num_examples
  print('  Num examples: %d  Num correct: %d  Precision @ 1: %0.04f' %
        (num_examples, true_count, precision))

# Get the sets of images and labels for training, validation, and
train_images = []
for filename in ['01.jpg', '02.jpg', '03.jpg', '04.jpg']:
  image = Image.open(filename)
  image = image.resize((IMAGE_SIZE,IMAGE_SIZE))
  train_images.append(np.array(image))

train_images = np.array(train_images)
train_images = train_images.reshape(4,IMAGE_PIXELS)

label = [0,1,1,1]
train_labels = np.array(label)

def run_training():
  # Tell TensorFlow that the model will be built into the default Graph.
  with tf.Graph().as_default():
    # Generate placeholders for the images and labels.
    images_placeholder, labels_placeholder = placeholder_inputs(4)

    # Build a Graph that computes predictions from the inference model.
    logits = inference(images_placeholder,
                             FLAGS.hidden1,
                             FLAGS.hidden2)

    # Add to the Graph the Ops for loss calculation.
    loss = cal_loss(logits, labels_placeholder)

    # Add to the Graph the Ops that calculate and apply gradients.
    train_op = training(loss, FLAGS.learning_rate)

    # Add the Op to compare the logits to the labels during evaluation.
    eval_correct = evaluation(logits, labels_placeholder)

    # Create a saver for writing training checkpoints.
    saver = tf.train.Saver()

    # Create a session for running Ops on the Graph.
    sess = tf.Session()

    # Run the Op to initialize the variables.
    init = tf.initialize_all_variables()
    sess.run(init)

    # And then after everything is built, start the training loop.
    for step in xrange(FLAGS.max_steps):
      start_time = time.time()
      feed_dict = fill_feed_dict(train_images,train_labels,
                                 images_placeholder,
                                 labels_placeholder)
      _, loss_value = sess.run([train_op, loss],
                               feed_dict=feed_dict)
      duration = time.time() - start_time
      if step % 100 == 0:
        # Print status to stdout.
        print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration))
      if (step + 1) % 1000 == 0 or (step + 1) == FLAGS.max_steps:
        saver.save(sess, FLAGS.train_dir, global_step=step)
        print('Training Data Eval:')
        do_eval(sess,
                eval_correct,
                images_placeholder,
                labels_placeholder,
                train_images)

def main(_):
  run_training()
if __name__ == '__main__':
  tf.app.run()

rawDescription: TensorFlow image classification

description: TensorFlow image classification


code:
def main():
    score = 0
    while True:
        # ask the questions and stuff
        if correct:
            score += 1
        # do other stuff
        if stop_condition:
            break
    print(name, ', you got a score of -', score)

rawDescription: How can I add a score to my game?

description: Add a score to my game


code:
f = open('one.txt')
text = f.readlines()
f.close()

lines = []
[lines.append(line) for line in text]

print(lines)

rawDescription: Reading strings written in multiple lines from a file and storing each string in a different variable


code:
# set the session expiration for 30 seconds from now
request.session['session_ok'] = int(time.time() + 60)

# check if it is expired
now = int(time.time())
session_expires = request.session.get('session_ok') or 0
if session_expires > now:
    session_ok = True
else:
    session_ok = False

rawDescription: How to set expiring session for single variable

description: Set expiring session for single variable


code: return render_to_response("azuriranje/stavka.html", {'form': form,}, context_instance=RequestContext(request))

rawDescription: Django_tables2: Add an edit and delete button next to each row


code:
import mayavi.mlab as mlab
import numpy as np

ncubes = 12
x = np.arange(0,ncubes)
y = np.arange(0,ncubes)
z = np.arange(0,ncubes)
value = np.arange(0,ncubes)
mlab.points3d(x, y, z, value, mode='cube',scale_mode='none', scale_factor=1.0)

mlab.show()

rawDescription: 3D Gridded Plots in Python

description: 3D Gridded Plots in Python


code:
class MonkeyPatchMiddleware(object):

   def __init__(self):
       from django.http import HttpResponse

       original_set_item = HttpResponse.__setitem__

       def __setitem__(self, header, value):
           if header == "Vary":
               raise ValueError
           original_set_item(self, header, value)

       HttpResponse.__setitem__ = __setitem__

rawDescription: Tracing from an effect back to its cause in a large Python codebase


code:
data = '' # contains last line of a read block if it didn't finish with \n
in_get, in_done, reading_file, ended = False, False, False, False
while not ended:
  if len(data) > 100:  # < update
    f.write( data )    # <
    data = ''          # <
  data += connection.recv(4096)
  i = data.find('\n')
  while i >= 0 and not ended:
    line = data[:i]
    data = data[i+1:]
    if in_get:
      filename = line
      reading_file = True
      f = open(filename,'wb')
      in_get = False
    elif in_done:
      if line != filename:  # done inside file content
        f.write( 'done\n' + line + '\n' )
      else:
        f.close()
        reading_file = False
      in_done = False
    else:
      if line == 'get' and not reading_file:
        in_get = True
      elif line == 'done':
        in_done = True
      elif line == 'end' and not reading_file:
        ended = True
        break;
      else:
        f.write( line + '\n' )
    i = data.find('\n')

rawDescription: Python multiple file transfer over TCP sockets


code:
# foo.py
import sys
import os
if __name__ == '__main__':
    foo_dir = os.path.dirname(os.path.realpath(__file__))
    parent_dir = os.path.dirname(foo_dir)
    sys.path.append(parent_dir)

import bar

rawDescription: Python Importing from Subdirectory

description: Python Importing from Subdirectory


code:
def ascending(ndig, first_digit_max):
    for x in xrange(0, first_digit_max+1):
        if ndig == 1:
            yield [x]
        else:
            for y in ascending(ndig-1, x):
                yield [x] + y

max_digits = 6
nums = sorted([int(''.join(map(str, num)))
               for ndig in xrange(1, max_digits+1)
               for num in ascending(ndig, 9)
               if any(num)])

rawDescription: Pythonic way of writing a sequence of integers in monotonically increasing order


code:
from tkinter import *
root = Tk()
w = Label(root, text="Take your Medicine \n :):)...Get Well Soon...")
w.pack()
root.mainloop()

rawDescription: Python + Windows: How to write a script that pops up a reminder on computer sleep/shutdown?


code:
my_product = models.MyProducts.query.filter_by(code=123456).first()  # @note: code is Integer, not a String, right?
if my_product:
    my_product.comment = "greeeeat product"
    db.session.add(my_product)
    db.session.commit()

rawDescription: How to update using SQLAlchemy and session?

description: Update using SQLAlchemy and session


code:
@api.model
def create(self, vals):
    res = super(ResUsers, self).create(vals)
    res.add_to_group()
    return res

rawDescription: Overwrite create method of res.users to add users upon creation to a group


rawDescription: Get Element value with minidom with Python


code:
import os,sys,site
os.environ["R_HOME"]='/usr/local/Cellar/r/3.0.1/R.framework/Resources'
site.addsitedir('/Users/kaiju/.virtualenvs/nauru_dev/lib/python2.7/site-packages')

# Activate the virtual environment
# Taken from http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/
activate_env = os.path.expanduser('/Users/kaiju/.virtualenvs/nauru_dev/bin/activate_this.py')
execfile(activate_env,dict(__file__=activate_env))

sys.path.insert(0,'/usr/local/var/django/code')
sys.path.insert(0,'/usr/local/var/django/code/ri')

# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "ri.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE","ri.settings")

# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

rawDescription: Django fails to find R when loading RPy2 under virtualenv


code:
lookup = re.compile(r'{{ *(\w+) *}}')
def interpolate(text, context):
    replacer = lambda m: context.get(m.group(1), '')
    return lookup.sub(replacer, text)

def in_your_view(self, whatever):
    # some stuff
    section_context = {
        "customer": document.customer,
        "foo": "bar",
    }
    for section in sections:
        section.interpolated = interpolate(section.section, section_context)

rawDescription: Django - render template tags before rendering template


code:
'stringstringstringstringstring' == 'string' * 5
'stringstringstringstringstring' is 'string' * 5

rawDescription: Unicode Dash not detected by if statement


code:
y = numpy.lib.recfunctions.append_fields(data_rec, 'copy_date', data_rec.date, dtypes=data_rec.date.dtype, usemask=False, asrecarray=True)
y.date
y
y.copy_date

rawDescription: python: how to add column to record array in numpy

description: Python: how to add column to record array in numpy


code: re.compile('a', re.M).findall('a')

rawDescription: Compiled regex in python doesn't match when in multiline mode


rawDescription: Migrating from Amazon S3 to Azure Storage (Django web app)


code:
import itertools
sum(int(i) for i in itertools.islice(open(filename), 3, None, 5))

rawDescription: Sum lines of string of numbers in file.txt


rawDescription: Getting started on python triple quotes

description: Getting started on python triple quotes


code:
import os
import time
import datetime
import logging

loggers = {}

def myLogger(name):
    global loggers

    if loggers.get(name):
        return loggers.get(name)
    else:
        logger = logging.getLogger(name)
        logger.setLevel(logging.DEBUG)
        now = datetime.datetime.now()
        handler = logging.FileHandler(
            '/root/credentials/Logs/ProvisioningPython'
            + now.strftime("%Y-%m-%d")
            + '.log')
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        loggers.update(dict(name=logger))

        return logger

rawDescription: Duplicate log output when using Python logging module


code:
t = type(obj)
if t._deferred:
  t = t.__base__

rawDescription: Django: Getting a Model type when Using a Defer Query


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('wrap.xlsx')
worksheet = workbook.add_worksheet()
wrap_format = workbook.add_format({'text_wrap': True})

values = ['1', '2', '3']

# Set an explicit row height for the wrapped text, if required.
#worksheet.set_row(1, 45)

worksheet.write(1, 1, '\n'.join(values), wrap_format)

workbook.close()

rawDescription: Adding items from list to a cell separated by new line


code:
def average_score(filename):

    averages = {}
    with open(filename) as fd:
      reader = c.reader(fd, delimiter=",")

      for row in reader:
        user, *scores = row

        # the user has no score
        if len(scores) == 0:
           continue

        averages[user] = sum([int(score) for score in scores]) / len(scores)

    sorted_averages = sorted(averages.items(), key = o.itemgetter(1), reverse = False)

    # This writes the average to the file, remove if necessary
    with open(filename, 'a') as fd:
      for item in sorted_averages:
        fd.write("{}: {}\n".format(item[0], item[1]))

    # This prints out to screen, remove if necessary
    for item in sorted_averages:
        print("{}: {}".format(item[0], item[1]))

rawDescription: how to compute the average, write it to a CSV file then sort it using python

description: Compute the average, write it to a CSV file then sort it using python


code:
mime = magic.from_buffer(data, mime=True)
if mime == None:
    # Workaround for issue with libmagic1==5.09-2 in Ubuntu 12.04. Fixed in libmagic 5.11-2.
    file_str = magic.from_buffer(data)
    if file_str.startswith('Composite Document File V2 Document'):
        mime = 'application/msword'

rawDescription: Why is magic.from_buffer returning None?

description: Why is magic.from_buffer returning None


code:
import requests
s = requests.Session()
s.post('http://www.example.com/login', data=dict(user='blah', pw='pw'))
r = s.get('http://www.example.com/page_behind_login')

rawDescription: Accessing websites using Python

description: Accessing websites using Python


code:
for X,Y in data:
   scatter(X, Y, c=numpy.random.rand(3,1))

rawDescription: How to generate random colors in matplotlib?

description: Generate random colors in matplotlib


code:
#!/usr/bin/env python3
if input("What do you do? ").strip().lower() == 'look':
    print("You see a room of equal length and "
          "width, You see foreign symbols on the wall.")
else:
    print("nothing")

rawDescription: Python 3 - If statement

description: Python 3 - If statement


code:
from itertools import izip
for i, j in izip(handle1, handle2):
    ...

rawDescription: zip() alternative for iterating through two iterables

description: Zip() alternative for iterating through two iterables


code:
# -*- coding: utf-8 -*-
from urllib import urlencode
from urllib2 import urlopen

params = dict(address=u"我不知道中国人。", sensor="false")
query = urlencode([(k, v.encode('utf-8') if isinstance(v, unicode) else v)
                   for k, v in params.items()])
r = urlopen("http://maps.googleapis.com/maps/api/geocode/json?" + query)
# ...

rawDescription: Urllib2.urlopen python chinese in windows


code:
for item in A.T:
    print(item)

rawDescription: Extracting Columns from numpy array

description: Extracting Columns from numpy array


code:
def pathchange(old, new):
    if not(os.path.exists(new)):
        os.mkdir(new)
    os.chdir(new)

rawDescription: Image download output does not save all images in a specific folder


code:
df
df.dtypes
df.convert_objects(convert_numeric=True)
df.convert_objects(convert_numeric=True).dtypes

rawDescription: Assign pandas dataframe column dtypes

description: Assign pandas dataframe column dtypes


code:
def operate():
    number = input("Enter a number to start: ")
    while True:
        readline("data.csv", number)
        op = raw_input("Repeat (R), Next (N), Previous (P), or Quit (Q) ")
        if op == "R": pass
        elif op == "N": number += 1
        elif op == "P": number -= 1
        elif op == "Q": break
        else: raise Exception("Incorrect command")

operate()

rawDescription: Python: Increment / Decrement a global variable (or alternative method)


code:
with zipfile.ZipFile('/path/to/file', 'r') as z:
    f = z.open('member.csv')
    table = pd.io.parsers.read_table(f, ...)

rawDescription: Pandas: convert WinZipped csv file to Data Frame


code:
def test():
  return ['item0', 'item1']
test()
test()[0]

rawDescription: What does appending [0] to methods in python do?


code:
import os
import sys

path = 'C:/Users/dana/Desktop/text_files_2/'

for filename in os.listdir(path):
    filename_splitext = os.path.splitext(filename)
    if filename_splitext[1] in ['.rtf', '.py', '.TEXT', '.text']:
        os.rename(os.path.join(path, filename),
                os.path.join(path, 'file_' + filename_splitext[0] +  '.txt'))

rawDescription: How to change multiple filenames in a directory using Python

description: Change multiple filenames in a directory using Python


code:
import libtorrent as lt
piece_size = 256 * 1024
creator_str = "python-libtorrent"
thetracker = "your desired tracker"
theurlseed = "your desired url seed"

fs = lt.file_storage()
lt.add_files(fs, "/tmp/torrentme")
fs.num_files()

t = lt.create_torrent(fs, piece_size)
t.add_tracker(thetracker)
lt.set_piece_hashes(t, ".")

t.set_creator(creator_str)
t.add_url_seed(theurlseed)
t.generate()

rawDescription: Python package to create "webseed" torrent file?


code:
import collections, weakref

class OrderedSet(collections.MutableSet):
    def __init__(self, values=()):
        self._od = collections.OrderedDict().fromkeys(values)
    def __len__(self):
        return len(self._od)
    def __iter__(self):
        return iter(self._od)
    def __contains__(self, value):
        return value in self._od
    def add(self, value):
        self._od[value] = None
    def discard(self, value):
        self._od.pop(value, None)

class OrderedWeakrefSet(weakref.WeakSet):
    def __init__(self, values=()):
        super(OrderedWeakrefSet, self).__init__()
        self.data = OrderedSet()
        for elem in values:
            self.add(elem)

rawDescription: Indexable weak ordered set in Python

description: Indexable weak ordered set in Python


code:
sns.violinplot(x=value, y=prob, inner=None, color="white", cut=0)
sns.stripplot(x=value, y=prob, jitter=.3,  color="black", alpha=.1, size=4)

rawDescription: Python Violin Plots

description: Python Violin Plots


fname: Mike

lname: Huckabee

party: Rep

state: Alabama

code: AL

primarytype: primary

state: Alaska

code: AK

primarytype: caucus

state: Arizona

code: AZ

state: Arkansas

code: AR

state: Iowa

code: IA

state: Kansas

code: KS

state: Kentucky

code: KY

state: Louisiana

code: LA

state: Maine

code: ME

state: Maryland

code: MD

state: Massachusetts

code: MA

state: Michigan

code: MI

state: Minnesota

code: MN

state: Mississippi

code: MS

state: Missouri

code: MO

state: Montana

code: MT

state: Nebraska

code: NE

state: Nevada

code: NV

state: New Hampshire

code: NH

state: New Jersey

code: NJ

state: New Mexico

code: NM

state: New York

code: NY

state: North Carolina

code: NC

state: North Dakota

code: ND

state: Ohio

code: OH

state: Oklahoma

code: OK

state: Oregon

code: OR

state: Virgin Islands

code: VI

state: Northern Marianas

code: MP

status: called

polltype: exit

code: GA

state: Georgia

code: TN

state: Tennessee

polltype: entrance

description: Python lxml not picking up tags


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

path='/home/project/df.csv'
df=pd.read_csv(path,sep=',',header='infer')
xs =range(0,101)
ys =list(df['B'].ix[0:100])
zs=list(df['C'].ix[0:100])
ws=list(df['D'].ix[0:100])

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.itervalues():
        sp.set_visible(False)

def three_way_plot(xs,ys,ws,zs,category):
    fig, host = plt.subplots()
    fig.subplots_adjust(right=0.6)
    par1 = host.twinx()
    par2 = host.twinx()
    par2.spines["right"].set_position(("axes", 1.1))
    p1, = host.plot(xs, ys, "blue", linewidth=2.0, label="B")
    p2, = par1.plot(xs, ws, "r-", label="C")
    p3, = par2.plot(xs, zs, "g-", label="D")
    host.set_xlim(min(xs), max(xs))
    host.set_ylim(min(ys), max(ys) + 200)
    par1.set_ylim(min(ws), max(ws) + 200)
    par2.set_ylim(min(zs), max(zs))
    host.set_xlabel("A", fontsize=14)
    host.set_ylabel("B", fontsize=14)
    par1.set_ylabel("C", fontsize=14)
    par2.set_ylabel("D", fontsize=14)
    host.yaxis.label.set_color(p1.get_color())
    par1.yaxis.label.set_color(p2.get_color())
    par2.yaxis.label.set_color(p3.get_color())
    lines = [p1, p2, p3]
    labels = ["mary had a little lamb","The mummy returns","Die another day","Welcome back"]*25
    start, end, step_size = 0, len(df) - 1, 4
    host.set_xticks(np.arange(start, end, step_size))
    host.set_xticklabels(labels, rotation='vertical', fontsize=10)
    host.legend(lines, [l.get_label() for l in lines])
    plt.tight_layout()
    plt.show()

three_way_plot(xs,ys,ws,zs,"category")

rawDescription: Aligning/rotating text labels on x axis in matplotlib with 3 plots


rawDescription: Apply multiple regular expressions to a text at same time in python


code:
class Student(models.Model):
  name = models.CharField(max_length=128, unique=True)
  friends = models.ManyToManyField('self', blank = True)

rawDescription: Calling an instance of same class inside class


code: isinstance(obj, types.FunctionType)

rawDescription: Python 2: function abstract type

description: Python 2: function abstract type


code:
import os
import sys
import tty
import termios
import select
import subprocess

master, slave = os.openpty()
stdin = sys.stdin.fileno()

try:
    old_settings = termios.tcgetattr(sys.stdout)
    tty.setraw(sys.stdout)

    process = subprocess.Popen(
        args=["/bin/bash"],
        stdin=slave,
        stdout=sys.stdout,
        stderr=sys.stderr,
        close_fds=True,
        start_new_session=True,
    )

    while True:
        if process.poll() is not None:
            break

        r, _, _ = select.select([sys.stdin], [], [], 0.2)

        if sys.stdin in r:
            os.write(master, os.read(stdin, 1024))
finally:
    termios.tcsetattr(sys.stdout, termios.TCSADRAIN, old_settings)
    os.close(master)
    os.close(slave)

rawDescription: How do I reproduce `stdin=sys.stdin` with `stdin=PIPE`?

description: Reproduce `stdin=sys.stdin` with `stdin=PIPE`


code:
arguments = {}
if location is not None:
    arguments['Location'] = location
else:
    arguments['Location__isnull'] = False

if gender is not None:
    arguments['Gender'] = gender
else:
    arguments['Gender__isnull'] = False

query_results = UserProfile.objects.filter(**arguments)

rawDescription: how to rid "" from a string to non string

description: Rid "" from a string to non string


code:
import matplotlib.pyplot as plt

# detect peaks somehow
i, j = detect_peaks(array2d)

# plot
fig, ax = plt.subplots()
ax.imshow(array2d)
ax.scatter(i, j)
plt.show()

rawDescription: python plot peaks on matplotlib.image.AxesImage object

description: Python plot peaks on matplotlib.image.AxesImage object


code:
x = [1,2,3]  #x coordinates of each bar
y = [0,0,0]  #y coordinates of each bar
z = [0,0,0]  #z coordinates of each bar
dx = [0.5, 0.5, 0.5]  #width of each bar
dy = [0.5, 0.5, 0.5]  #depth of each bar
dz = [5, 4, 7]        #height of each bar

rawDescription: Parameters required by bar3d with python


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

#set up x and y
dates = [datetime.datetime(2015, 3, 12), datetime.datetime(2015, 3, 15), datetime.datetime(2015, 3, 17), datetime.datetime(2015, 3, 21), datetime.datetime(2015, 3, 9), datetime.datetime(2015, 3, 16)]
x = numpy.arange(0, len(dates), 1)
## create a time axis in seconds
tim = [(date-dates[0]).total_seconds() for date in dates]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, tim)
# get the y-axis limits
ylim = ax.get_ylim()
# invert the y-axis
ax.set_ylim(ylim[::-1])

# create ticks and tick labels
nticks = 5
timarr = numpy.linspace(ylim[-1], ylim[0], nticks)
labels = [(dates[0]+datetime.timedelta(seconds=t)).strftime('%m/%d/%Y') for t in timarr]
ax.set_yticks(timarr)
ax.set_yticklabels(labels)

plt.show()

rawDescription: Inverting y axis of datetimes in Python

description: Inverting y axis of datetimes in Python


code:
d = {'A': 1, 'B': 1, 'C': 1, 'D': 4}

# Use .values() and .keys() and .items() for Python 3.x
min_val = min(d.itervalues())
remaining = d.viewkeys() - (k for k, v in d.iteritems() if v == min_val)
# set(['D'])

rawDescription: Remove the smallest element(s) from a set


code:
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']

class IsAuthenticatedOrReadOnly(BasePermission):
    """
    The request is authenticated as a user, or is a read-only request.
    """

    def has_permission(self, request, view):
        if (request.method in SAFE_METHODS or
            request.user and
            request.user.is_authenticated()):
            return True
        return False

rawDescription: Django REST Framework - Separate permissions per methods


code:
def recursive(y):
    if y < 10:
        return y
    else:
        z = raw_input("Please enter a number: ")
        return recursive(int(z))

rawDescription: Can someone tell me why this recursive method with raw_input is not returning?


rawDescription: How do I do this replace regex in python?

description: Do this replace regex in python


code:
from tkinter import *
from tkinter import ttk
root = Tk()
backspace = ttk.Button(root, text="←")
backspace.grid(row=0, column=0, padx=2, pady=0, sticky="nw")

plusminus = ttk.Button(root, text="→")
plusminus.grid(row=0, column=1, padx=2, pady=2, sticky="nw")

sqroot = ttk.Button(root, text="√")
sqroot.grid(row=0, column=2, padx=2, pady=2, sticky="nw")

root.mainloop()

rawDescription: How to bring up symbols in Python ttk.buttons

description: Bring up symbols in Python ttk.buttons


rawDescription: Pandas data frame to dictionary of lists


code:
from Bio import SubsMat
SubsMat.function = my_own_replacement_for_function

rawDescription: How to override a function in a package?

description: Override a function in a package


code:
from itertools import chain
from itertools import combinations
# Huge name!
from itertools import combinations_with_replacement as cwr
from itertools import starmap
from itertools import product

from operator import add

def _weird_combinations(rep, no_rep, n_from_rep, n_from_norep):
    return starmap(add, product(cwr(rep, n_from_rep),
                                combinations(no_rep, n_from_norep)))

def weird_combinations(rep, no_rep, n):
    rep, no_rep = list(rep), list(no_rep)

    # Allow Nones in the output to represent drawing less than n elements.
    # If either input has None in it, this will be confusing.
    rep.append(None)

    # We can't draw more elements from no_rep than it has.
    # However, we can draw as many from rep as we want.
    least_from_rep = max(0, n-len(no_rep))
    return chain.from_iterable(
            _weird_combinations(rep, no_rep, n_from_rep, n-n_from_rep)
            for n_from_rep in xrange(least_from_rep, n+1))

rawDescription: Python combination of 2 lists (1 repeat, 1 non-repeat)


code:
header = "Header！\n"
header_bytes = bytes(header, 'utf-8')
socketData.sendall(header_bytes + image_data)

rawDescription: How to send Images via SocketServer in Python 3?

description: Send Images via SocketServer in Python 3


code:
inp = input().split()
n, a = inp[0], inp[1:]

rawDescription: Python 3.x - Enter n variables all in the same line


code:
logging.basicConfig(filename=logname,
                            filemode='a',
                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%H:%M:%S',
                            level=logging.DEBUG)

logging.info("Running Urban Planning")

self.logger = logging.getLogger('urbanGUI')

rawDescription: Using the logging python class to write to a file?


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

def main():
    a = -1
    b = 1

    y, x = np.ogrid[-5:5:100j, -5:5:100j]
    plt.contour(x.ravel(), y.ravel(), pow(y, 2) - pow(x, 3) - x * a - b, [0])
    plt.grid()
    plt.show()

if __name__ == '__main__':
    main()

rawDescription: Python -- matplotlib elliptic curves

description: Python -- matplotlib elliptic curves


rawDescription: How to tell if a class is descended from another class

description: Tell if a class is descended from another class


code:
env = Environment()
env['PROGSUFFIX'] = '.bin'    # or env.Replace(PROGSUFFIX='.bin')
for file in Glob('*.cpp'):
    env.Program([file])

rawDescription: How to force scons to generate binary file with .bin extension?

description: Force scons to generate binary file with .bin extension


code:
msg = "Enter three numbers separated by spaces: "
n1, n2, n3 = (int(n) for n in input(msg).split())

rawDescription: Initialize several variable from console input


code:
codfiscal_in_f1_set = set()
with open("file1.csv", 'r') as f1:
    for line in f1:
        line = line.strip()
        if not line:
            continue

        codfiscal_in_f1_set.add(line.split(";")[1])

with open("file2.csv", 'r') as f2, open("file3.csv", "w") as output_file:
    for line in f2:
        line = line.strip()
        if not line:
            continue

        codfiscal = line.split(";")[1]
        if codfiscal not in codfiscal_in_f1_set:
            output_file.write(line + "\n")

rawDescription: Python 2 csv files parser that outputs what is in file1.csv but not in file2.csv


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

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

rawDescription: After submitting form, how to wait for element to load before clicking on said element? (Selenium / Python)


code:
import math

def ceil_dt(dt):
    # how many secs have passed this hour
    nsecs = dt.minute*60 + dt.second + dt.microsecond*1e-6
    # number of seconds to next quarter hour mark
    # Non-analytic (brute force is fun) way:
    #   delta = next(x for x in xrange(0,3601,900) if x>=nsecs) - nsecs
    # analytic way:
    delta = math.ceil(nsecs / 900) * 900
    #time + number of seconds to quarter hour mark.
    return dt + datetime.timedelta(seconds=delta)

rawDescription: Python - Ceil a datetime to next quarter of an hour


rawDescription: Matplotlib half hour major locator on candlestick chart


code:
import re
import csv

strings = ("Frequency", "Symbol", "Polar", "Mod", "FEC", "RF", "Signal", "Carrier", "BitRate")
sat_raw = open('/BLScan/reports/1520.txt', 'r')
sat_out = open('1520out.txt', 'w')
csv_writer = csv.writer(sat_out)
csv_output = []
for line in sat_raw:
    if any(s in line for s in strings):
        try:
            m = re.match(r'^.*:\s+(\S+)', line)
            value = m.groups()[0]
            # Attempt to convert to int, thus removing the decimal part
            value = int(float(value))
        except ValueError:
            pass # Ignore conversion
        except AttributeError:
            pass # Ignore case when m is None (no match)
        csv_output.append(value)
    elif line.startswith('TP N'):
        # Before we start a new set of values, write out the old set
        if csv_output:
            csv_writer.writerow(csv_output)
            csv_output=[]

# If we reach the end of the file, don't miss the last set of values
if csv_output:
    csv_writer.writerow(csv_output)

sat_raw.close()
sat_out.close()

rawDescription: Python parsing a text file and logical methods


code:
line = r"""enabled='false' script='var name=\'Bob\'\\n ' index='0' value=''"""
re.findall(r"([a-zA-Z]*)='((?:[^'\\]|\\.)*)'\s*", line)

rawDescription: Python regex issues - Attempting to parse string


code:
colors = im.getdata() #all pixel values
# initialize lists for dark and light pixels
darkList=[]
lightList=[]
# set counter for dark and light pixels
dark = 0
light = 0
for item in colors:  # iterate over each tuple
    if sqrt((item[0]-255)**2 + (item[1]-255)**2) < 128:  # See if Euclidean distance is less than 128
        lightList.append(item)  # append pixel to light pixel list
        light+=1   # increment light pixel counter
    else:
        darkList.append(item)  # append pixel to dark pixel list
        dark+=1   # increment dark pixel counter

print("Total light pixels =",light)
print(lightList)
print("Total dark pixels =",dark)
print(darkList)

rawDescription: Calculate Euclidean distance for each item in a list


code:
df
pd.to_datetime(df['Date']) + pd.to_timedelta(df['Time'], unit='m')

rawDescription: How to create a 5-minute interval datetime index using incomplete dataset (Python)

description: Create a 5-minute interval datetime index using incomplete dataset (Python)


code:
def get(self, request, format=None):
    if UserFile.objects.filter(fileid_id=1, userid_id=2).exists():
        content = {
            'status': 'Request Successful.'
        }
        return Response(content)
    else:
        content = {
            'status': 'Request Failed.'
        }
        return Response(content)

rawDescription: DjangoModelPermission with multiple databases


code:
class A(object):
    def method(self, other):
         other.somevar = 5

class B(object):
    pass

def main():
    a = A()
    b = B()

    b.somevar = "Hello World"
    a.method(b)
    print(b.somevar) # now prints '5'

rawDescription: python/pygame, pass input from a class to another class

description: Python/pygame, pass input from a class to another class


code:
import subprocess as sub
import threading

class RunCmd(threading.Thread):
    def __init__(self, cmd, timeout):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.timeout = timeout

    def run(self):
        self.p = sub.Popen(self.cmd)
        self.p.wait()

    def Run(self):
        self.start()
        self.join(self.timeout)

        if self.is_alive():
            self.p.terminate()      #use self.p.kill() if process needs a kill -9
            self.join()

RunCmd(["./someProg", "arg1"], 60).Run()

rawDescription: Python: kill or terminate subprocess when timeout


code:
for name in 'a', 'b', 'c':
    try:
        thing = getattr(obj, name)
    except AttributeError:
        pass
    else:
        break

rawDescription: getting dynamic attribute in python

description: Getting dynamic attribute in python


code:
import sys
"funcs" in sys.modules
import funcs
"funcs" in sys.modules
sys.modules["funcs"] is funcs
del funcs
"funcs" in sys.modules
sys.modules["funcs"]
del sys.modules["funcs"]
import funcs

rawDescription: ReImporting a module after deleting it

description: ReImporting a module after deleting it


code:
def shift(pairs):
    it = iter(pairs)
    (_, p) = next(it)
    for (n, p2) in it:
        yield (p, n)
        p = p2

rawDescription: if anything in collections do such segment reversing ? | python

description: If anything in collections do such segment reversing ? | python


code:
log = '[date] [thread] [loglevel] [class] some text describing the event that happened.'
[part.strip() for part in re.split('[\[\]]', log) if part.strip()]

rawDescription: Python and regex: split a string with parenthesis


code:
s="1254jf4h"
num=[]
alpah=[]
for n,i in enumerate(s):
  if i.isdigit():
     num.append(i)
  else:
     alpah.append(i)
alpah
num

rawDescription: How do I extract certain digits from raw input in Python?

description: Extract certain digits from raw input in Python


code:
x = Function('x')(z)
y = Function('y')(z)

rawDescription: Implicit Differentiation Sympy

description: Implicit Differentiation Sympy


code:
def switch(self):
    items = self.left.selectedItems()
    for item in items:
        n = self.left.row(item)    # get the index/row of the item
        i = self.left.takeItem(n)  # pop
        self.right.addItem(i)      # add to right QListWidget

rawDescription: Switch items between two QListWidgets in python


rawDescription: Get a list of the absolute paths of all the images in a page using BeautifulSoup


code:
keys = pygame.keys.get_pressed()

if keys[pygame.K_RIGHT] and keys[pygame.K_LEFT]:
    move_fullcube = left

rawDescription: Can i press two keys simultaneously for a single event using Pygame?

description: Press two keys simultaneously for a single event using Pygame


code:
inrels = graph.cypher.query('START strt=node({mynode}) \
                            MATCH strt<-[r:follows]-neighbor \
                            WHERE neighbor.attr = {myattr} \
                            RETURN r', {'mynode': self.eid, 'myattr': someattr})

firstrel = inrel.next()

rawDescription: How to enter a neo4j Cypher query using Bulbs?

description: Enter a neo4j Cypher query using Bulbs


code:
import numpy as np
arr=np.loadtxt('all_user_token_counts.csv',delimiter=',',
                  dtype = '|U10,<U10,int')
print(arr)

# [(u'@5raphaels', u'in', 15) (u'@5raphaels', u'for', 15)
#  (u'@5raphaels', u'unless', 11) (u'@5raphaels', u'you', 11)]

rawDescription: how do i import from a unicode (utf-8) csv file into a numpy array

description: Import from a unicode (utf-8) csv file into a numpy array


code:
manager = mp.Manager()
d = manager.dict()

rawDescription: Dynamic worker pool management in python multiprocessing


rawDescription: How to Iterate a dictionary of references to matplotlib figures


code:
from random import randint, choice
Animals_to_choose = [Passaro, Sapo, Rato, Coelho, Cobra, Tartaruga, Lobo]
someset = set()
n_animals_to_create = 10

for number in range(n_animals_to_create):
    newanimal = choice(Animals_to_choose)()
    newanimal.number = number
    someset.add(newanimal)

rawDescription: List with constructors, whats the behavior?


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon

data = np.random.rand(4, 4)
plt.imshow(data)

points_xy = np.array(plt.ginput(3))
p = Polygon(points_xy, alpha=0.3)
plt.gca().add_artist(p)

plt.draw()
plt.show()

rawDescription: Matplotlib does not display points specified from ginput


code:
dimention = {}
for x in range(number_of_wall):
    wall = 1
    wall_area = input("What is the area of wall {}" .format(wall) + " in " + room_name + ": ")
    if room_name not in dimention:
        dimention[room_name] = [wall_area]
    else:
        dimention[room_name].append(wall_area)
    wall = wall + 1
print(dimention)

rawDescription: How do you append multiple keys to a value in a list?

description: Append multiple keys to a value in a list


code:
try:
    module = __import__("actions.%s" % a, globals(), locals(), fromlist=["*"])
    # What goes here?
    # let's try to grab and instanciate objects
    for item_name in dir(module):
        try:
           new_action = getattr(module, item_name)()
           # here we have a new_action that is the instanciated class, do what you want with ;)
        except:
           pass

except ImportError:
    pass

rawDescription: Dynamically importing a module and instantiating a class in Python


rawDescription: Python: How much memory does attribute takes?


code:
while True:
    parent_thread.join(interval)
    if not parent_thread.is_alive():
        break
    do_something()

rawDescription: Detect Interpreter shut down in daemon thread


code: sorted( ..., key = lambda s: ( not s.startswith( "_" ), s ) )

rawDescription: Custom sort of directory contents

description: Custom sort of directory contents


code:
root.rowconfigure(1, weight=1)
# [...]
text.grid(row=1, column=0, sticky=tk.W + tk.E + tk.N + tk.S)

rawDescription: Growing a widget vertically when resizing the window (using the grid geometry manager)


code:
cmd = """osascript -e 'tell app "Finder" to sleep'"""
def stupidtrick():
    os.system(cmd)

rawDescription: How to run an AppleScript from within a Python script?

description: Run an AppleScript from within a Python script


code:
subprocess.Popen("curl --data-binary \@"+input_file_path+" -o "+ file_name +" localhost:30",
    stdout=subprocess.PIPE,
    shell=True)

rawDescription: subprocess popen + curl + binary data

description: Subprocess popen + curl + binary data


rawDescription: Plot labelled and unlabeled data matplotlib


code:
import csv
import os
import glob

directory = raw_input ("INPUT Folder")
output = raw_input("OUTPUT Folder:")
in_files = os.path.join(directory, '*.csv')

for in_file in glob.glob(in_files):
    with open(in_file) as input_file:
        reader = csv.reader(input_file)
        cols = []
        for row in reader:
            cols.append(row)

    # "outdent" this code so it only needs to run once for each in_file
    filename = os.path.splitext(os.path.basename(in_file))[0] + '.csv'

    # Indent this to the same level as the rest of the "for in_file" loop!
    with open (os.path.join(output, filename), 'wb') as output_file:
        writer = csv.writer(output_file)
        for i in range(len(max(cols, key=len))):
            writer.writerow ([(c[i] if i<len(c) else '') for c in cols])

rawDescription: Transposing all csv files within a folder


code:
from lxml import etree
s = """<?xml version="1.0" standalone="yes" ?>
<!DOCTYPE widget [
<!ENTITY widgets-ns "http://www.w3.org/ns/widgets">
<!ENTITY pass "pass&.html">
]>
<xyz:widget xmlns:xyz="&widgets-ns;">
  <xyz:content src="&pass;"/>
  <xyz:name>bv</xyz:name>
</xyz:widget>
"""
etree.fromstring(s)
etree.fromstring(s).xpath("//xyz:content/@src",
                          namespaces={"xyz": "http://www.w3.org/ns/widgets"})

rawDescription: Python: Which XML parser supports DTD !ENTITY definitions?


rawDescription: Use lists inside a list with itertools.product


code:
from distutils.spawn import find_executable

clang_executable = find_executable('clang')

rawDescription: How to check for clang presence in Python?

description: Check for clang presence in Python


code:
from subprocess import check_call

check_call("""
source /etc/profile.d/modules.sh
module purge
module load intel

./my_code
""", shell=True, executable="/bin/bash")

rawDescription: translating bash script to python

description: Translating bash script to python


code: np.loadtxt(file, converters = {1: lambda s: int(s.strip(":"))})

rawDescription: Weird lines in python file, can't extract column


code:
g = {k:i for i,k in enumerate(arr)}

keypair = None
for i,k in enumerate(arr2):
    if k in g:
        keypair = (i, g[k])
        break;

rawDescription: Python: Find fast match in 2 lists (Collision)


code:
""" Supplies the internal functions for functools.py in the standard library """

class partial:
    """
    partial(func, *args, **keywords) - new function with partial application
    of the given arguments and keywords.
    """
    __slots__ = ['func', 'args', 'keywords']

    def __init__(self, func, *args, **keywords):
        if not callable(func):
            raise TypeError("the first argument must be callable")
        self.func = func
        self.args = args
        self.keywords = keywords

    def __call__(self, *fargs, **fkeywords):
        newkeywords = self.keywords.copy()
        newkeywords.update(fkeywords)
        return self.func(*(self.args + fargs), **newkeywords)

rawDescription: _functools module

description: _functools module


code:
whatname = ""
list_of_names = []

def regc():
    global whatname
    whatname = raw_input("Please introduce your clients first and last name.")
    list_of_names.append(whatname)
    contactsav()

rawDescription: How do i store data from my program and be able to reaccess and see/edit it when i reopen it? Python

description: Store data from my program and be able to reaccess and see/edit it when i reopen it? Python


code:
df = DataFrame(data['values'])
df.columns = ["date","price"]
df
df.head()
df['date'] = pd.to_datetime(df['date'],unit='s')
df.head()
df.dtypes

rawDescription: Convert unix time to readable date in pandas DataFrame


code:
from itertools import product

chars = '0123456789' # chars to look for

for length in range(1, 3): # only do lengths of 1 + 2
    to_attempt = product(chars, repeat=length)
    for attempt in to_attempt:
        print(''.join(attempt))

rawDescription: brute force script in python 3.2

description: Brute force script in python 3.2


rawDescription: 4 x 4 Floats to numpy Matrix

description: 4 x 4 Floats to numpy Matrix


code:
import os
import glob

path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
    name = file.split(os.path.sep)[-1]
    name2 = name.split(".")[0]
    print(name2)

rawDescription: error with splitting file path string by / in python

description: Error with splitting file path string by / in python


code:
for c in companies:
     exec('{} = pd.DataFrame()'.format(c))

rawDescription: Create multiple dataframes in loop

description: Create multiple dataframes in loop


code:
legend = g.ax_joint.get_legend()
labels = (x.get_text() for x in legend.get_texts())
g.ax_joint.legend(legend.legendHandles, labels, loc='lower right')

rawDescription: Move existing legend in Matplotlib 1.5.1


rawDescription: Change the amount of text printed in cells in Pandas with .head() method


code:
from gzip import GzipFile

class GzipWrap(object):
    # input is a filelike object that feeds the input
    def __init__(self, input, filename = None):
        self.input = input
        self.buffer = ''
        self.zipper = GzipFile(filename, mode = 'wb', fileobj = self)

    def read(self, size=-1):
        if (size < 0) or len(self.buffer) < size:
            for s in self.input:
                self.zipper.write(s)
                if size > 0 and len(self.buffer) >= size:
                    self.zipper.flush()
                    break
            else:
                self.zipper.close()
            if size < 0:
                ret = self.buffer
                self.buffer = ''
        else:
            ret, self.buffer = self.buffer[:size], self.buffer[size:]
        return ret

    def flush(self):
        pass

    def write(self, data):
        self.buffer += data

    def close(self):
        self.input.close()

rawDescription: Python: Creating a streaming gzip'd file-like?


code:
class SomeView(APIView):
    permission_classes = (AllowAny,)

rawDescription: Overide JWT so that a user can register via a mobile device


code:
for cp in celfones:
    temp = celfones[count]
    tempf = temp[3]
    count += 1

    if lower_price == "none" and upper_price == "none":

        if temp[1] == search_brand:
            templist.append(temp)

    elif lower_price != "none" and upper_price == "none":
        lower_price = float(lower_price)

        if temp[1] == search_brand and temp[2] >= lower_price:
            templist.append(temp)

        elif search_brand == "NONE" and temp[2] >= lower_price:
            templist.append(temp)

    elif lower_price == "none" and upper_price != "none":
        upper_price = float(upper_price)

        if temp[1] == search_brand and temp[2] <= upper_price:
            templist.append(temp)

        elif search_brand == "NONE" and temp[2] <= upper_price:
            templist.append(temp)

    elif lower_price != "none" and upper_price != "none":
        lower_price = float(lower_price)
        upper_price = float(upper_price)

        if search_brand == "NONE" and temp[2] >= lower_price and temp[2] <= upper_price:
            templist.append(temp)

        elif temp[1] == search_brand and temp[2] >= lower_price and temp[2] <= upper_price:
            templist.append(temp)

    else:
        print ("you did not enter any search parameter")

print (len(templist), "celfone(s) found.")  ### counting of results

rawDescription: Output does not print result even though the two choices are none but the first option is the right choice in python list


code:
if all(word in theTextContents.split() for word in myWords):
    ...

rawDescription: Better logic for testing string contents


code:
args = [1, 2, 3]
foo(*args) # equivalent to foo(1, 2, 3)

rawDescription: Python: Function and Argument list.... is it possible?


code:
with open("data.dat") as f:
    a = pickle.load(f)

rawDescription: How to initialize an instance using pickle()?

description: Initialize an instance using pickle()


rawDescription: How to convert a '\u5f71\u89c6\...' in to its real meaning?(python)

description: Convert a '\u5f71\u89c6\...' in to its real meaning?(python)


rawDescription: Ignore part of a python tuple

description: Ignore part of a python tuple


code:
import json

class JSONObject:
  def __init__( self, dict ):
      vars(self).update( dict )

#this is valid json string
data='{"channel":{"lastBuild":"2013-11-12", "component":["test1", "test2"]}}'

jsonobject = json.loads( data, object_hook= JSONObject)

print( jsonobject.channel.component[0]  )
print( jsonobject.channel.lastBuild  )

rawDescription: how to convert json to python class?

description: Convert json to python class


code:
names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
pairs = [x.split(':') for x in names.split(", ")]
attrs = [x[1] for x in pairs if x[0]=='name']
attrs
def is_name_attribute(x):
    return x in attrs
is_name_attribute('fred')
is_name_attribute('gauss')

rawDescription: Python: problem processing a string

description: Python: problem processing a string


code:
from base64 import b64decode
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Hash import SHA256, HMAC
from Crypto.Protocol.KDF import PBKDF2

# The hmac starts from 0 to 64 (length).
hmac_size = 64
hmac = data[:hmac_size]

# The cipher text starts after the hmac to the end.
# The cipher text is base64 encoded, so I decoded it.
ciphertext = data[hmac_size:]
ciphertext = b64decode(ciphertext)

# The IV starts from 0 to 16 (length) of the ciphertext.
iv = ciphertext[:16]

# The key size is 256 bits -> 32 bytes.
key_size = 32

# The passphrase of the key.
password = 'mypassphrase'

# The key is generated using PBKDF2 Key Derivation Function.
# In the case of Zend2 Crypt module, the iteration number is 5000,
# the result length is the key_size * 2 (64) and the HMAC is computed
# using the SHA256 algorithm
the_hash = PBKDF2(password, iv, count=5000, dkLen=64, prf=lambda p, s:
                  HMAC.new(p, s, SHA256).digest())

# The key starts from 0 to key_size (32).
key = the_hash[:key_size]

# The hmac key starts after the key to the end.
key_hmac = the_hash[key_size:]

# HMAC verification
hmac_new = HMAC.new(key_hmac, 'aes%s' % ciphertext, SHA256).hexdigest()
if hmac_new != hmac:
    raise Exception('HMAC verification failed.')

# Instanciate the cipher (AES CBC).
cipher = AES.new(key, AES.MODE_CBC, iv)

# It's time to decrypt the data! The ciphertext starts after the IV (so, 16 after).
data = cipher.decrypt(ciphertext[16:])

rawDescription: How to decrypt Zend2 encrypted data?

description: Decrypt Zend2 encrypted data


code:
from datetime import datetime
past = datetime.now()
present = datetime.now()
past < present
datetime(3000, 1, 1) < present
present - datetime(2000, 4, 4)

rawDescription: How to compare two dates?

description: Compare two dates


code:
result = []
for i,c in enumerate(string):
    result.append(chr(ord(c)^(x if i%2 else 0)))
print("".join(result))

rawDescription: decode javascript sequence into python

description: Decode javascript sequence into python


code:
import datetime
cutoff = datetime.datetime.strptime('2015-2-19', '%Y-%m-%d')
a = datetime.datetime.strptime('2015-3-20', '%Y-%m-%d')
b = datetime.datetime.strptime('2015-1-2', '%Y-%m-%d')
c = datetime.datetime.strptime('2015-2-9', '%Y-%m-%d')
d = datetime.datetime.strptime('2015-2-09', '%Y-%m-%d')
a>=cutoff
b>=cutoff
c>=cutoff
d>=cutoff

rawDescription: Python: if date is passed or not logic with strings


code: filter(str.isupper, list)

rawDescription: using method as function in python

description: Using method as function in python


code:
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

rawDescription: Where can I find source code for itertools.combinations() function


code:
import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)

model = QtGui.QStringListModel()
model.setStringList(['some', 'words', 'in', 'my', 'dictionary'])

completer = QtGui.QCompleter()
completer.setModel(model)

lineedit = QtGui.QLineEdit()
lineedit.setCompleter(completer)
lineedit.show()

sys.exit(app.exec_())

rawDescription: How can i create a searchbar in pyqt

description: Create a searchbar in pyqt


code:
clock = pygame.time.Clock()
while True:
    clock.tick(1000)  # waits until the next ms
    #clear your frame here
    #update and draw your text here
    #flip your display window here

rawDescription: Creating a countdown timer in Pygame

description: Creating a countdown timer in Pygame


code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW)
s.sendto('\xff'*6 + '\x00\x50\xe4\x59\xd9\x30'*16, ('168.1.0.0', 4444))

rawDescription: How to send custom tcp packets on windows?

description: Send custom tcp packets on windows


code:
splitlists = [mylist[i:i+n] for i in range(0, len(mylist), n-1)]
splitlists[-1].append(splitlists[0][0])

rawDescription: In Python how do you split a list into evenly sized chunks starting with the last element from the previous chunk?


code:
class BaseType(type):
    def __init__(cls, name, bases, clsdict):
        super(BaseType, cls).__init__(name, bases, clsdict)
        setattr(cls,'_v_properties_set',
                set(cls._properties) if cls._properties else set())

class BaseElement(object):
    __metaclass__ = BaseType
    _properties = None

class ElementFlavour1(BaseElement):
    _properties = 'a', 'b', 'c'

class ElementFlavourN(BaseElement):
    _properties = 'e', 'f', 'g'

print(ElementFlavourN._v_properties_set)
# set(['e', 'g', 'f'])

rawDescription: Attaching attributes to a class on creation


code:
def get_venue_link_list(links):
    for link in links:
        linkset.add(link.get("href"))
    return linkset

rawDescription: Looping through set stops after first run - Python


code:
import sys, os, glob

newnames = ["North", "South", "East", "West"]

for folder_name in glob.glob(sys.argv[1]):
    for new_name, old_name in zip(newnames, sorted(os.listdir(folder_name))):
       os.rename(os.path.join(folder_name, old_name), os.path.join(folder_name, new_name))

rawDescription: How does one rename multiple files within folders using python?

description: Rename multiple files within folders using python


code:
import shutil

# Parse playlist for filenames with ending .ts and put them into the list ts_filenames
with open('playlist.m3u8', 'r') as playlist:
    ts_filenames = [line.rstrip() for line in playlist
                    if line.rstrip().endswith('.ts')]

# open one ts_file from the list after another and append them to merged.ts
with open('merged.ts', 'wb') as merged:
    for ts_file in ts_filenames:
        with open(ts_file, 'rb') as mergefile:
            shutil.copyfileobj(mergefile, merged)

rawDescription: Concatenate the files present in .m3u8 in python


rawDescription: Where would I find the attributes of the related object using ParsePy?


code:
def some_view(request):
    if request.method == 'POST':
        form1 = GeneralForm(request.POST, prefix='form1')
        form2 = GeneralForm(request.POST, prefix='form2')
        if all([form1.is_valid(), form2.is_valid()]):
            pass # Do stuff with the forms
    else:
        form1 = GeneralForm(prefix='form1')
        form2 = GeneralForm(prefix='form2')
    return render_to_response('some_template.html', {
        'form1': form1,
        'form2': form2,
    })

rawDescription: Django Forms - How to Use Prefix Parameter


code:
prefix = '\\item '

with open('new.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       dest.write("\\begin{enumerate}\n")
       for line in src:
           dest.write('%s%s\n' % (prefix, line.rstrip('\n')))
       dest.write("\\end{enumerate}\n")

rawDescription: How to prepend a text , Write To Beginning Every Line in TXT and end with an extra row

description: Prepend a text , Write To Beginning Every Line in TXT and end with an extra row


code: re.findall(r'\d+[ym]', '3m10y')

rawDescription: using 'or' condition in re.split

description: Using 'or' condition in re.split


code:
a = np.array([[[1,2,3],[2,3,4,5], [2, 2]],[[3,4,5,6,7],[1],[2,3,10]]])
D = max(len(x) for x in y for y in a)
padded = [[x + [0] * (D-len(x)) for x in y] for y in a]
mask = [[[0] * len(x) + [1] * (D-len(x)) for x in y] for y in a]
result = np.ma.masked_array(padded, np.array(mask, dtype=np.bool))
result
np.sum(result, axis=-1)

rawDescription: How to convert a tuple of depth 2 to a 2D Numpy array?

description: Convert a tuple of depth 2 to a 2D Numpy array


code:
def list_range(self, low, high, rangelist = None):

    if rangelist is None:
        rangelist = []
    # here goes the code of helper_list_range

rawDescription: How to recurse without changing variables

description: Recurse without changing variables


code:
import inspect
import views

urlpatterns = [url(r'^%s$' % name, view) for name, view in views.__dict__.items()
               if callable(view) and
               inspect.getargspec(view)[0][0] == 'request']

rawDescription: Django: How to map urls to views dynamically with or without urls.py


code:
pattern = re.compile(r'([12345])\s+\(d+)\s+\(.*\S)')
f = open('XX.txt', 'r') # No calling readlines; lazy iteration is better
for line in f:
    m = pattern.match(line)
    if m:
        cu.execute('''INSERT INTO bugInfo2 (pa, k, details) VALUES(?,?,?)''',
            (m.group(2), m.group(1), m.group(3)))

rawDescription: Help parsing text file in python

description: Help parsing text file in python


code: getattr(settings, 'UNDER_TEST', False)

rawDescription: Django LiveServerTestCase: disable SSL at test-time


code:
from string import ascii_letters
from itertools import product

for i in range(1, 3): # do 1 and 2 chars
    chars = product(ascii_letters, repeat=i)
    for combo in chars:
        print(''.join(combo))

rawDescription: python incrementing character loops

description: Python incrementing character loops


code:
class HTTPAuthXMLRPCHandler(XMLRPCHandler):
    @auth.login_required
    def handle_request(self):
        return XMLRPCHandler.handle_request(self)

handler = HTTPAuthXMLRPCHandler('xmlrpc')
handler.connect(app, '/xml-rpc')

rawDescription: Use Flask XML-RPC with HTTPAuth?

description: Use Flask XML-RPC with HTTPAuth


rawDescription: How can one pull every other value within a list?


code:
from matplotlib.mlab import griddata
import numpy as np

#-- Your coordinates
x = np.random.random(100)
y = np.random.random(100)
z = np.random.random(100)*10
#--

#-- Your new grid
xsteps=200    # resolution in x
ysteps=200    # resolution in y
xi = linspace(min(x), max(x), xsteps)
yi = linspace(min(y), max(y), ysteps)
Z = griddata(x, y, z, xi, yi)  # interpolates between points in your data
#--

plt.pcolormesh(xi, yi, Z, cmap=plt.cm.hot)   # plot your elevation map :D
plt.show()

rawDescription: Converting coordinates vector to numpy 2D matrix


code:
conn = sqlite3.connect(':memory:')
conn.execute("attach ? as 'schemaname'", (filename,))

rawDescription: Python Sqlite3: Create a schema without having to use a second database


code:
class ResultStatusField(models.CharField):

  def __init__(self, *args, **kwargs):

    SENT = 0
    ACCEPTED = 1
    DECLINED = 2

    SHARE_STATUSES = (
      (SENT, 'Sent'),
      (ACCEPTED, 'Approved'),
      (DECLINED, 'Declined')
    )

    kwargs['choices'] = SHARE_STATUSES
    kwargs['default'] = SENT
    kwargs['max_length'] = 2

    super(ResultStatusField, self).__init__(*args, **kwargs)

rawDescription: Creating custom Django CharField with choices


code:
final_ads = {}
for a in ads:
    final_ads.setdefault(a['spot_id'], []).append(a)

rawDescription: Python: How can I group this list of items by category?


code:
import shapely.geometry as shgeo
line = vstack( (x,y) ).T
line = shgeo.LineString( line )
surrounding_polygon = line.buffer( 10,cap_style=3 ) # 10=Dist

rawDescription: Python - get surrounding area of line (coordinates)


code:
from datetime import datetime
import pytz

import rethinkdb as r

# Init
r.connect('localhost', 28015).repl()
if 'test' in r.db_list().run():
    r.db_drop('test').run()

r.db_create('test').run()
r.db('test').table_create('stories').run()

paris = pytz.timezone('Europe/Paris')

r.table('stories').insert({
    'title': u'Foobar',
    'published_at': paris.localize(datetime.strptime(
        '2014-03-17 14:00', '%Y-%m-%d %H:%M'
    ), is_dst=False)
}).run()

for document in r.table("stories").run():
    print(document['published_at'])
    print(type(document['published_at']))

rawDescription: What is the best way to insert python datetime in rethinkdb?


code:
import tkinter as tk
from tkinter import *
class Gui():
    def __init__(self, root):
        self.root=root
        self.entry = tk.Entry(root)
        stvar=tk.StringVar()
        stvar.set("one")

        self.canvas=tk.Canvas(root, width=300, height=200, background='white')
        self.canvas.grid(row=0,column=1)

        frame = Frame(self.root)
        frame.grid(row=0,column=0, sticky="n")

        self.option=tk.OptionMenu(frame, stvar, "one", "two", "three")
        label1=Label(frame, text="Figure").grid(row=0,column=0, sticky="nw")
        label2=Label(frame, text="X").grid(row=1,column=0, sticky="w")
        label3=Label(frame, text="Y").grid(row=2,column=0, sticky="w")
        self.option.grid(row=0,column=1,sticky="nwe")
        entry = Entry(frame).grid(row = 1,column = 1,sticky = E+ W)
        entry1 = Entry(frame).grid(row = 2,column = 1, sticky = E)
        Button1=Button(frame,text="Draw").grid(row = 3,column = 1, sticky = "we")
        figure1=self.canvas.create_rectangle(80, 80, 120, 120, fill="blue")

        #Grid.columnconfigure(self.root,1,weight=1, size=200)
if __name__== '__main__':
    root=tk.Tk()
    gui=Gui(root)
    root.mainloop()

rawDescription: Python Canvas and Grid Tkinter

description: Python Canvas and Grid Tkinter


code: r = requests.put(url, data=json.dumps(payload), headers=headers)

rawDescription: Python-requests and Meteor / MongoDB collectionapi update not working


code:
import matplotlib.pyplot as plt
x = [0, 1, 2, 3]
y = [0, 1, 2, 3]
plt.plot(x, y)
plt.ylabel('$\\frac{V_i}{V_o}$', rotation=0, size=25)
plt.xlabel('$D$')
ax = plt.gca()
ax.set_yticks([max(y)])
ax.set_xticks([max(x)])
plt.hlines([max(y)], 0 ,max(x), linestyles='--')
plt.vlines([max(x)], 0, max(y), linestyles='--')
plt.axis([0, 4, 0, 4])
plt.show()

rawDescription: Make sober plots with matplotlib

description: Make sober plots with matplotlib


code:
def serviceInterface(request):
    if request.method == 'POST':
        service = Service.objects.get(name=request.POST.get('Name'))
        selected_form = getattr(forms, service.associatedForm)
        form = selected_form()
        return render(request, 'serviceInterface.html', {'name': service.name,'form': form})

rawDescription: Select specific form in django

description: Select specific form in django


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

# Generate data:
x, y, z = 10 * np.random.random((3,10))

# Set up a regular grid of interpolation points
xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100)
xi, yi = np.meshgrid(xi, yi)

# Interpolate
rbf = scipy.interpolate.Rbf(x, y, z, function='linear')
zi = rbf(xi, yi)

plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
           extent=[x.min(), x.max(), y.min(), y.max()])
plt.scatter(x, y, c=z)
plt.colorbar()
plt.show()

rawDescription: Python : 2d contour plot from 3 lists : x, y and rho?


code:
class A:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3
    def seta(self):
        def afunction():  # no self here
            self.a = 4
        afunction()       # have to call the function
    def geta(self):
        return self.a

rawDescription: Python scope inside a nested function inside a class?


code: f = lambda x: f1(f2(x))

rawDescription: Mimic Haskell with Python

description: Mimic Haskell with Python


code:
s='Link: http://google.com/song.mp3 Another link, http://yahoo.com/another_song.mp3'
re.findall('http.*?mp3', s)

rawDescription: Extract a substring that starts with "http" and ends with ".mp3" from a string


code:
def change(a):
    a = 10
    print(a) # prints 10

x = 5
change(x)
print(x) # prints 5

rawDescription: python assignment to an object inside itself

description: Python assignment to an object inside itself


code:
def ret_tup():
    return 1,2 # can also be written with parens

a,b = ret_tup()

rawDescription: Understanding some Python code

description: Understanding some Python code


code:
from matplotlib.pyplot import *
import numpy as np

#put some dummy data into s
s=np.vectorize(complex)(range(2048),range(2048))

power, freq=psd(s, 2048, 194171, window=np.bartlett(2048),Fc=14050000)
figure()
semilogy(freq[256:-256], power[256:-256])
show()

rawDescription: trimming matplotlib power spectrum chart

description: Trimming matplotlib power spectrum chart


code:
raw = a # just in case you want the original string at a later point
toDisplay = []
a = a.split() # a now looks like ['aia','air','amp']
for i in a:
    temp = find(f, i)
    if(temp):
        toDisplay.append(temp)

for i in toDisplay:
    print ('{0: <6}'.format(i[0][0]) + '{0:<20}'.format(i[0][1]) + ("{0:>8.2f}".format(i[0][2])))

rawDescription: Multiple inputs to produce wanted output


code: output = [b / m for b, m in zip(data[::2], data[1::2])]

rawDescription: Dividing the first element of a list by the second and the third by the fourth and so on


rawDescription: Python Selenium find element and return HTML tags


code:
wait.until(EC.element_to_be_clickable((By.ID, 'main_buttonMissionTextNext')))
while EC.element_to_be_clickable((By.ID,'main_buttonMissionTextNext')):
    driver.find_element_by_id("main_buttonMissionTextNext").click()
    if not driver.find_element_by_id("main_buttonMissionTextNext").click().is_enabled():
        break
    wait.until(EC.element_to_be_clickable((By.ID, 'main_buttonMissionTextNext')))

rawDescription: How can I make Selenium click through a variable number of "next" buttons?

description: Make Selenium click through a variable number of "next" buttons


rawDescription: How to download an image with querystring in it

description: Download an image with querystring in it


code:
import re
year_of_birth = 1920
re.sub('(?m)[bB]orn[^,.?!:;]+', '\g<0> in %d' % year_of_birth, content)

rawDescription: Injecting additional text in a string

description: Injecting additional text in a string


code:
tuple(os.path.join(self._path,each)
    for each in os.listdir(self._path)
    if os.path.isfile(os.path.join(self._path,each))
    and each.endswith('png') or each.endswith('jpg')
)

rawDescription: getting rid of not .DS_Store and .localized in OSx path from listdir

description: Getting rid of not .DS_Store and .localized in OSx path from listdir


code:
# ... fill table, then:
self.ui.tableWidget.setSortingEnabled(True)
self.ui.tableWidget.resizeRowsToContents()
self.ui.tableWidget.horizontalHeader().sortIndicatorChanged.connect(
    self.ui.tableWidget.resizeRowsToContents)

rawDescription: Python-QTableWidget: How to catch signal when sorting in header is clicked


code:
try:
    conn1 = mysqldb.connect(...)
    conn2 = mysqldb.connect(...)
    ...
except:  # add specific exception here
    ...  # support failure when connecting

rawDescription: Python try connecting to multiple mysqldb hosts


code:
import select
import os

os.mkfifo('my.fifo')
f = os.open('my.fifo', os.O_RDONLY|os.O_NONBLOCK)

try:
    kq = select.kqueue()

    # Add FD to the queue
    kq.control([select.kevent(f, select.KQ_FILTER_READ, select.KQ_EV_ADD|select.KQ_EV_ENABLE)], 0)

    # Should break as soon as we received something.
    i = 0
    while True:
        events = kq.control(None, 1, 1.0) # max_events, timeout
        print(i, events)
        i += 1
        if len(events) >= 1:
            print('We got:', os.read(f, events[0].data))
            break

    # Remove FD from the queue.
    kq.control([select.kevent(f, select.KQ_FILTER_READ, select.KQ_EV_DELETE)], 0)

    # Should never receive anything now even if we write to the pipe.
    i = 0
    while True:
        events = kq.control(None, 1, 1.0) # max_events, timeout
        print(i, events)
        i += 1
        if len(events) >= 1:
            print('We got:', os.read(f, events[0].data))
            break

finally:
    os.close(f)
    os.remove('my.fifo')

rawDescription: what is similar function to epoll's unregister function for kqueue?

description: What is similar function to epoll's unregister function for kqueue


code:
def filterbyvalue(seq, position, value):
   for el in seq:
       if el[position]==value: yield el

myarray = [('31.10', 'John', 'Smith', 'ZK'),('01.11', 'John', 'Smith', 'OK'),('31.10', 'John', 'Doe', 'ZK'),('01.11', 'John', 'Doe', 'ZK')]

results = filterbyvalue(myarray, 2, "Doe")
for x in results:
    print(x)

rawDescription: Filter Python list

description: Filter Python list


code:
s = "10101000000"
zeros = 4

if s.endswith("0" * zeros):
    s = s[:-zeros]

rawDescription: Delete a certain number of zeros from right of a string


code:
@receiver(post_save, sender=Company)
def create_invoicing_data(sender, instance, created, **kwargs):
    if created:
        invdata = InvoicingData(company=instance)
        # set any other fields on invdata if desired
        invdata.save()

rawDescription: Create model instance using data from related object


rawDescription: Finding MultiIndex indices for a given cross-section


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        f = GradientFrame(root)
        f.pack(fill="both", expand=True)

class GradientFrame(tk.Canvas):
    '''A gradient frame which uses a canvas to draw the background'''
    def __init__(self, parent, borderwidth=1, relief="sunken"):
        tk.Canvas.__init__(self, parent, borderwidth=borderwidth, relief=relief)
        self._color1 = "red"
        self._color2 = "black"
        self.bind("<Configure>", self._draw_gradient)

    def _draw_gradient(self, event=None):
        '''Draw the gradient'''
        self.delete("gradient")
        width = self.winfo_width()
        height = self.winfo_height()
        limit = width
        (r1,g1,b1) = self.winfo_rgb(self._color1)
        (r2,g2,b2) = self.winfo_rgb(self._color2)
        r_ratio = float(r2-r1) / limit
        g_ratio = float(g2-g1) / limit
        b_ratio = float(b2-b1) / limit

        for i in range(limit):
            nr = int(r1 + (r_ratio * i))
            ng = int(g1 + (g_ratio * i))
            nb = int(b1 + (b_ratio * i))
            color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
            self.create_line(i,0,i,height, tags=("gradient",), fill=color)
        self.lower("gradient")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Is it possible to apply gradient colours to BG of Tkinter python widgets


code:
temp = {}
for key, number, date in input_list:
    if key not in temp: # we see this key for the first time
        temp[key] = (key, number, date)
    else:
        if temp[key][2] < date: # the new date is larger than the old one
            temp[key] = (key, number, date)
result = temp.values()

rawDescription: Python, remove duplicates from list of tuples


code:
#!/usr/bin/env python
import wx
class MyFrame(wx.Frame):
    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition)
        Buttons = []
        Buttons.append(wx.Button(self,-1, "Approve Location"))
        Buttons.append(wx.Button(self,-1, "Approve Item"))
        Buttons.append(wx.Button(self,-1, "Change Qty"))
        Buttons.append(wx.Button(self,-1, "Approve"))
        sizer = wx.GridBagSizer(5,3)
        sizer.Add(Buttons[0], (0, 5), (1,1), wx.EXPAND)
        sizer.Add(Buttons[1], (1, 4), (1,1), wx.EXPAND)
        sizer.Add(Buttons[2], (1, 5), (1,1), wx.EXPAND)
        sizer.Add(Buttons[3], (2, 5), (1,1), wx.EXPAND)
        self.SetSizerAndFit(sizer)
        self.Centre()
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "Gridbagsizer")
        frame.Show(True)
        self.SetTopWindow(frame)
        return True
if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()

rawDescription: alligment of objects in wxpython

description: Alligment of objects in wxpython


code:
{"command": "repl_open",
"caption": "Python",
"id": "repl_python",
"mnemonic": "p",
"args": {
  "type": "subprocess",
  "encoding": "utf8",
  "cmd": ["/usr/local/bin/python", "-i", "-u"],
  "cwd": "$file_path",
  "syntax": "Packages/Python/Python.tmLanguage",
  "external_id": "python"
  }
},

rawDescription: Directing Sublime Text 2 Packages to the correct python installation