code:
import matplotlib.pyplot as plt
import numpy as np
import sys
from PyQt4 import QtGui, QtCore

class Form(QtGui.QWidget):
    def __init__(self):
        super(Form, self).__init__()

        self.func_selector = QtGui.QComboBox()
        self.func_selector.setFocus()
        self.func_selector.addItem("Sin", 'np.sin')
        self.func_selector.addItem("Cos", 'np.cos')
        self.func_selector.addItem("Tan", 'np.tan')

        self.parameter_edit = QtGui.QLineEdit("np.linspace(lower, upper, n)")

        self.output_edit = QtGui.QLineEdit("Output (Press Enter)")
        self.output_edit.returnPressed.connect(self.updateUI)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.func_selector)
        layout.addWidget(self.parameter_edit)
        layout.addWidget(self.output_edit)

        self.setLayout(layout)
        self.setWindowTitle("Function Evaluator")

    def updateUI(self):
        # A dictionary of local variables that can be used by eval()
        locs = {'lower': 0, 'upper': 2*np.pi, 'n': 10}

        x = self.parameter_edit.text()

        # Get a content of the selected QComboBox's item
        f = self.func_selector.itemData(self.func_selector.currentIndex())
        # In python2 a QComboBox item's content is wrapped in QVariant, so we must unwrap it:
        if sys.version_info.major == 2:
            f = f.toString()

        y = eval('{}({})'.format(f, x), None, locs)
        self.output_edit.setText(str(y))

        # if the function returns multiple values, show a plot
        if isinstance(y, np.ndarray):
            x_eval = eval(str(x), None, locs)
            plt.plot(x_eval, y)
            plt.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()
    app.exec_()

rawDescription: Simple PyQt Function Evaluator

description: Simple PyQt Function Evaluator


code:
g = df.groupby(...)
g.max()-g.min()

rawDescription: Pandas: Achieving speed of 'built-in' methods (e.g. mean,std) for groups manipulations


rawDescription: Kivy: Get widgets ids and accessing widgets by unique property


code:
def fibonacci(n):
    return n >= 2 and fibonacci(n-1) + fibonacci(n-2) or n

rawDescription: python syntax: how to return 0 instead of False when evaluating 0

description: Python syntax: how to return 0 instead of False when evaluating 0


code: ls = [(key, value) for key, value in globals().items() if isinstance(value, tuple) and len(value) == 3 and all(isinstance(e, int) for e in value) ]

rawDescription: Get all objects of a given structure, and their global names


code:
import pandas as pd
df = pd.read_csv('test.csv', sep='\s+')
print(df)

rawDescription: Read and save data file with variable number of columns in python


rawDescription: Python decode "\u041b" string

description: Python decode "\u041b" string


code:
def inner_join(a, b):
    d = {}
    for row in b:
        d[row[0]] = row
    for row_a in a:
        row_b = d.get(row_a[0])
        if row_b is not None: # join
            yield row_a + row_b[1:]

rawDescription: How do I merge two lists of tuples based on a key?

description: Merge two lists of tuples based on a key


rawDescription: Python 3.x - Seperating Long Binary String to Short


code: ['actor1', 'actor2']

rawDescription: Keep CSV commas inside fields with Python


code:
import cv2
import numpy as np
from pylab import *

img = cv2.imread( r'C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg' )
img = cv2.cvtColor(img, cv2.cv.CV_BGR2RGB)  # cv2 defaul color code is BGR
h,w,c = img.shape # (768, 1024, 3)

noise = np.random.randint(0,50,(h, w)) # design jitter/noise here
zitter = np.zeros_like(img)
zitter[:,:,1] = noise

noise_added = cv2.add(img, zitter)
combined = np.vstack((img[:h/2,:,:], noise_added[h/2:,:,:]))

imshow(combined, interpolation='none')

rawDescription: Random flipping and RGB jittering/slight value change of image?


code: roscore

rawDescription: How to get data in python from ROS in real-time?

description: Get data in python from ROS in real-time


code: tk.bind("<Motion>", add_tracked)

rawDescription: Avoid event grab during motion in Tkinter


code:
import calendar
calendar.monthrange(2016, 3)

rawDescription: how to get the first day and last day of current month in python

description: Get the first day and last day of current month in python


rawDescription: How to calculate moving average in Python 3?

description: Calculate moving average in Python 3


code:
from testapp.models import User

def exists(x):
    return User.objects.filter(pk=x).exists()

def get(x):
    try:
        User.objects.get(pk=x)
        return True
    except User.DoesNotExist:
        return False

rawDescription: What is more efficient .objects.filter().exists() or get() and a try


rawDescription: How to read a dictionary from a file in Python 2.7?

description: Read a dictionary from a file in Python 2.7


rawDescription: Python combine two lists of objects recursively by comparing datetimes


rawDescription: Indexing a nested list in python

description: Indexing a nested list in python


code:
superVar = {'subVar1': 'a', 'subVar2': 'b'}
superVar['subVar1']
# 'a'
superVar['subVar2']
# 'b'

rawDescription: Is it possible to assign variables within the assignment of another variable?


code:
match = regexp.match(url) # "group/soccer players/users/123"
if match:
    group = match.group("group") # "soccer players"
    user = match.group("user") # "123"

rawDescription: Regex to match space and a string until a forward slash


code:
with open(filename, 'r') as inputfile:
    lines = list(inputfile)

key = lines[::2]   # every second line
defi = lines[1::2] # every second line, starting with the second

rawDescription: Linking two items from two seperate lists together. python


code:
import re
def callback(match):
    return next(callback.v)
callback.v=iter(('1','2','3'))

s = "blah blah blah"
print(re.sub(r'blah',callback,s))

rawDescription: Python regex: how to replace each instance of an occurrence with a different value?


code: exclude = ('bar',)  # with the comma so its treated as a tuple

rawDescription: How can I prevent a field from displaying on a ModelForm?

description: Prevent a field from displaying on a ModelForm


code: s = ''.join(filter(lambda c: c not in '.,!', list(s)))

rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


code:
ax1.get_position()
ax2.get_position()

rawDescription: matplolib: what are the units in the axes positioning [l,b,w,h] (imshow involved)?

description: Matplolib: what are the units in the axes positioning [l,b,w,h] (imshow involved)


code:
def reLayout(self):
    QWidget().setLayout(self.layout())
    layout = QGridLayout(self)
    ...

rawDescription: replacing layout on a QWidget with another layout

description: Replacing layout on a QWidget with another layout


code:
import sublime
import sublime_plugin

class MyInsertProgressBarCommand(sublime_plugin.TextCommand):
    def run(self, edit, value):
        view = self.view
        width, _ = view.viewport_extent()
        em_width = view.em_width()
        # the number of columns are the width divided by the width of a char
        # subtract two to add a little border
        columns = int(width / em_width) - 2

        # subtract two, because we surround it with [ and ]
        bar_length = columns - 2
        # calculate the size of the filled and the remaining part
        filled_length = int(bar_length * value / 100)
        remaining_length = bar_length - filled_length
        # assemble the string for the progress bar
        text = "[{0}{1}]\n".format("=" * filled_length, "." * remaining_length)
        # add the text for the percentages
        if value >= 100:
            percentage_text = "finished!"
        else:
            percentage_text = "{:3.2f} %".format(value)
        text += " " * (columns - len(percentage_text)) + percentage_text

        # replace the content of the view
        view.replace(edit, sublime.Region(0, view.size()), text)
        # reset sels
        view.sel().clear()
        view.sel().add(sublime.Region(0, 0))

class ProgressBarCommand(sublime_plugin.WindowCommand):
    def run(self):
        self.window.create_output_panel("progess_bar")
        self.window.run_command("show_panel", {"panel": "output.progess_bar"})

        def test_progress_bar():
            import random
            test_progress_bar.value += 2 * random.random()
            if test_progress_bar.value >= 100:
                self.finish_progress()
                return
            self.show_progress(test_progress_bar.value)

            sublime.set_timeout(test_progress_bar, 100)
        test_progress_bar.value = 0

        sublime.set_timeout_async(test_progress_bar, 1)

    def show_progress(self, progess):
        view = self.window.find_output_panel("progess_bar")
        view.run_command("my_insert_progress_bar", {"value": progess})

    def finish_progress(self):
        self.show_progress(100)
        sublime.set_timeout(self._destroy, 5000)

    def _destroy(self):
        self.window.destroy_output_panel("progess_bar")

rawDescription: Progress bar in Sublime Text with Python


code: crc32('the quick brown fox') & 0xffffffff

rawDescription: Why does python's zlib.crc32 need a bitwise AND to be considered "stable"?


code: json_dump = json.dump(list(Dj.objects.values_list('field', flat=True)))

rawDescription: creating a json array in python

description: Creating a json array in python


code:
import bs4 as bs
import urllib2
import re

url = 'http://patft.uspto.gov//netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&p=1&u=%2Fnetahtml%2FPTO%2Fsearch-bool.html&r=2&f=G&l=50&co1=AND&d=PTXT&s1=%22X+ray%22.ABTX.&s2=detect.ABTX.&OS=ABST/%22X+ray%22+AND+ABST/detect&RS=ABST/%22X+ray%22+AND+ABST/detect'
soup = bs.BeautifulSoup(urllib2.urlopen(url).read())

anchor = soup.findAll(text=re.compile("Assi"))[0]
assignee = ' '.join(anchor.find_next('td').stripped_strings)
print(assignee)

rawDescription: Python BeautifulSoup how to get the index or of the HTML table


code: ['-'.join(el) for el in combinations(sorted(a), 2)]

rawDescription: Pythonic way to build a Combination String


rawDescription: Concat every 4 strings from a list?

description: Concat every 4 strings from a list


code:
import cv2
import glob
import numpy as np

X_data = []
files = glob.glob ("C:/Users/xxx/Desktop/asdf/*.PNG")
for myFile in files:
    print(myFile)
    image = cv2.imread (myFile)
    X_data.append (image)

print('X_data shape:', np.array(X_data).shape)

rawDescription: Create Numpy array of images

description: Create Numpy array of images


code:
for t in sub:
   regons.append(re.search(t,s).span())
regons

rawDescription: A more complex version of "How can I tell if a string repeats itself in Python?"


code:
def handle_starttag(self, tag, attrs):
    if tag == 'p':
        self.__text.append('\n\n')
    elif tag == 'br':
        self.__text.append('\n')
    elif tag == 'a':
        for name, value in attrs:
            if name == 'href':
                self.hosts.add(urlparse(value).netloc.split(':')[0].lower())
                break

rawDescription: Python: Returning only hosts/a href with my HTML parser


rawDescription: Query database in Django for sum of two fields, sorting wrong


rawDescription: Interpolating an array within an astropy table column


code:
class Mixin(object):
    def foo(self):
        assert self.__class__ is not Mixin  # no point calling directly
        # find the other base
        other = [b for b in self.__class__.__bases__ if b is not Mixin]
        # what to do if there's more than 1 real base?
        # pick base explicitly
        base = other[1]
        # call it,
        return something(base.foo(self, some_args))

rawDescription: Extract a mixin from a common function in Python


rawDescription: how to make phone number mask on Django?

description: Make phone number mask on Django


code:
data    = self.request.POST
comment = data.get('comment')

rawDescription: How to get text from modal and insert in email body?

description: Get text from modal and insert in email body


code:
from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.

rawDescription: matplotlib: marker size / color as extra dimension

description: Matplotlib: marker size / color as extra dimension


code: np.dstack((a, b, c)).squeeze()

rawDescription: combining vectors as column matrix in numpy

description: Combining vectors as column matrix in numpy


code:
def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()

rawDescription: How to delete only the content of file in python

description: Delete only the content of file in python


code:
prioritylist = ('r','u','d','l')
for direction in prioritylist:
  success, newlocation = move(direction, location)
  if success: break

rawDescription: Python - 2 Questions: Editing a variable in a function and changing the order of if else statements internally/during runtime


rawDescription: Dictionary __gt__ and __lt__ implementation


code:
from django.shortcuts import render
@login_required
def index(request, template_name):
    return render(request, template_name,extra={})

rawDescription: if condition in template to display link in django

description: If condition in template to display link in django


code:
my_string = 'Hello(John)this is(Phil)'
matches = re.findall(paren_regex, my_string) # find all regex matches

for match in matches:
    my_string = my_string.replace(match, ' {0} '.format(match)) # replace the existing

my_string = re.sub(' +', ' ', my_string).rstrip() # remove duplicate spaces

rawDescription: Going through very long strings, moving characters around


code:
plt.show()
fig.savefig('./Results/evol_conc_v'+str(vinit)+'a_'+str(a)+'.png') # Use fig. here

rawDescription: Save image with matplotlib.pyplot

description: Save image with matplotlib.pyplot


code:
print ('My Job Name', {'BRANCH_NAME': branch , 'VERSION': version})
# ('My Job Name', {'BRANCH_NAME': 'xyz', 'VERSION': '12.2'})

rawDescription: Python string formatting displays issue

description: Python string formatting displays issue


code:
from Crypto.PublicKey import RSA
with open("keyfile", "rb") as f:
    key = RSA.importKey(f.read())

rawDescription: Trying to generate RSA signature with Python from working C# code


code:
from email.mime import multipart, nonmultipart, text
from email.generator import BytesGenerator
from email import policy
from io import BytesIO

def _encode_multipart_formdata(self, fields, files):
    msg = multipart.MIMEMultipart('form-data')

    for (key, value) in fields.items():
        part = text.MIMEText(value)
        part['Content-Disposition'] = 'form-data; name="{}"'.format(key)
        msg.attach(part)

    for (key, filepath, filename) in files:
        if os.path.isfile(filepath):
            ct = self._get_content_type3(filename)
            part = nonmultipart.MIMENonMultipart(*ct.split('/'))
            part['Content-Disposition'] = (
                'form-data; name="{}"; filename="{}"'.format(
                    key, filename))
            with open(filepath, "rb") as f:
                part.set_payload(f.read())
            msg.attach(part)

    body = BytesIO()
    generator = BytesGenerator(
        body, mangle_from_=False, policy=policy.HTTP)
    generator.flatten(msg)
    return msg['content-type'], body.getvalue().partition(b'\r\n\r\n')[-1]

rawDescription: Python 3.4 - Multipart Post Using Standard Library


code:
import web

TEMPLATE = '''$def with (rows, cols)

Results:

$for col in cols:
    $col

$for row in rows:

    $for col in cols:
        $row[col]

'''

class query:
    def GET(self, arg):
        res = db.select('player', what='id,name')
        cols = []
        rows = res.list()
        if rows:
            cols = rows[0].keys()
        return tmpl(rows, cols)

db = web.database(dbn='mysql')
tmpl = web.template.Template(TEMPLATE)
urls = ('/(.*)', 'query')

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()

rawDescription: Simple way to display results of a sql query using web.py


rawDescription: Avoid using for loop in np.array operations. Python


code:
with open(filename) as f:
    exec(compile(f.read(), filename, "exec"))

rawDescription: Python importing a function with file's name contained in a variable


code:
with open("fiancee_wordfreq.csv" , "wb") as f:
     writer = csv.writer(f)
     for pair in cn.items():
         writer.writerow(pair)

rawDescription: How do I write words and their frequencies into two separate columns in CSV file

description: Write words and their frequencies into two separate columns in CSV file


rawDescription: Fuzzy Group By, Grouping Similar Words

description: Fuzzy Group By, Grouping Similar Words


code:
x = pd.DataFrame([MyStruct(field1=3, field2=4, field3=5), MyStruct(field1=4, field2=5, field3=6)], columns=['field1', 'field2', 'field3'])
x.field2

rawDescription: How to collect the value corresponding to a field of an array/list of named tuples

description: Collect the value corresponding to a field of an array/list of named tuples


rawDescription: How to get a value from every column in a Numpy matrix

description: Get a value from every column in a Numpy matrix


code:
column1 = ['xxx', 'aaa', 'ttt']
column2 = ['yyy', 'bbb', 'hhh']

rawDescription: How to Split into Columns

description: Split into Columns


code:
list_of_dates = ['0000000', '20140930', '11111111', '20140926', '20140925', '33333333']

# Create valid dates
now = datetime.now()
valid_days = [(now - timedelta(days=i)).strftime('%Y%m%d') for i in range(-14, 0) if (now-timedelta(days=i)).weekday() not in (5,6)]
# filter list
filtered = list(set(list_of_dates) & set(valid_days))

rawDescription: Removing certain files specified in a list


code:
c = 'why do pangolins dream of quiche'
c is a
c is b

rawDescription: What does python sys.intern do, and when should it be used?


code:
import pandas as pd
import functools

A = pd.DataFrame([[2, 1], [2, 1], [2, 1]], columns=['A', 'B'], index = [1, 2, 3])
B = pd.DataFrame([[1, 1], [2, 2], [3, 3]], columns=['A', 'B'], index = [1, 2, 3])
C = pd.DataFrame([[1, 2], [1, 2], [1, 2]], columns=['A', 'B'], index = [1, 2, 3])

df_all = {'df1': A, 'df2': B, 'df3': C}
merge = functools.partial(pd.merge, left_index=True, right_index=True, how='inner')
df = functools.reduce(merge, df_all.values())
print(df)

rawDescription: Looping through df dictionary in order to merge df's in Pandas


code:
from operator import attrgetter
C = map(attrgetter('Bar'), (A, B))

rawDescription: Python: Get attribute from a list of objects of the same type in the most efficient way


code:
class Car(Vehicule):
    def __init__(self):
        super(Car,self).__init__()
    def _getSpatials(self):
        print("Calling Car's spatials getter")
        return super(Car,self).spatials
    def _setSpatials(self,value):
        print("Calling Car's spatials setter")
        super(Car,self)._setSpatials(value)
    spatials=property(_getSpatials,_setSpatials)

v=Vehicule()
c=Car()
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 1
c.spatials = 10
# Calling Car's spatials setter
# Calling Vehicule's spatials setter
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 10

rawDescription: Overwrite property using Python

description: Overwrite property using Python


code:
dir(object)
dir(gtk.Container)

rawDescription: How can I get all the property names of a GTK Container?

description: Get all the property names of a GTK Container


code:
import urllib
import urllib2
token = xxx-xxxx
stopcode = 70142
query_args = {"token":token, "stopcode":stopcode}
encoded_args = urllib.urlencode(query_args)

request = urllib2.Request(url+encoded_args)
response = urllib2.urlopen(request)

print(response.read())

rawDescription: Using Urllib2 with 511 api that requires token


code: df.columns[(df < 0).any()]

rawDescription: Get list of column names for columns that contain negative values


code: im = scipy.misc.imread('flower.png', flatten=True).astype(np.uint8)

rawDescription: Image erosion and dilation with Scipy

description: Image erosion and dilation with Scipy


code:
text.delete(1.0, 'end')
# print new serial data

rawDescription: print the data on window screen and then clear the window screen before printing other data.in python

description: Print the data on window screen and then clear the window screen before printing other data.in python


rawDescription: Calculate mean over values in lines of CSV file if month, week day, and time match a conditon


rawDescription: How to create LinkExtractor rule which based on href in Scrapy

description: Create LinkExtractor rule which based on href in Scrapy


code:
import logging

formatter = logging.Formatter("[%(asctime)s] {%(module)s:%(lineno)d} (levelname)s - %(message)s")
file_handler = logging.FileHandler('example.log')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)

logger = logging.getLogger('app')
logger.addHandler(file_handler)
logger.setLevel(logging.INFO)

logger.info('Logger initialized')

rawDescription: Python logging creates multiple logs

description: Python logging creates multiple logs


code:
from time import sleep
from threading import Thread

thrd = Thread(target=you_function_to_run)
thrd.daemon = True
thrd.start()
sleep(60)

rawDescription: Kill Python script after 60 second in simplest way


code:
for row in reader:
    if not any(t in row[2].lower() for t in ignore):
        tweet_set = set(row[2].lower().split())
        if alert_set.intersection(tweet_set):
            print(row[2])

rawDescription: using 2 sets one ingnore and 1 alert to parse a large set in python

description: Using 2 sets one ingnore and 1 alert to parse a large set in python


code:
from collections import OrderedDict

l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]]
d = OrderedDict()
for sub in l:
    k = sub[0]
    if k not in d or sub[1] < d[k][1]:
        d[sub[0]] = sub

rawDescription: Removing duplicates from a list of lists based on a comparison of an element of the inner lists


code:
from lxml import html
html_document = ... #Get your document contents here from a file or whatever

tree = html.fromstring(html_document)
text_document = tree.text_content()

rawDescription: Parsing HTML documents using lxml in python


code: {('column_%d' % i): index[i:81:9] for i in xrange(9)}

rawDescription: Possible to compress into a dictionary comprehension?


code:
for name in dir(np):
    obj = getattr(np, name)
    if hasattr(obj, 'dtype'):
        try:
            npn = obj(0)
            nat = npn.item()
            print('%s (%r) -> %s'%(name, npn.dtype.char, type(nat)))
        except:
            pass

rawDescription: Converting numpy dtypes to native python types


code:
timeit.timeit("re.sub('(.*)\((.+)\)(.*)', '\g<1>\g<3> \g<2>', a)", setup="a = 'LC(Carbadidomethyl)RLK'; import re")
timeit.timeit("begin, end  = a.find('('), a.find(')') ; b = a[:begin] + a[end+1:] + ' ' + a[begin+1:end]", setup="a = 'LC(Carbamidomethyl)RL'")

rawDescription: Extracting part of string in parenthesis using python


code:
import numpy as np

a = np.zeros(25, dtype= np.character).reshape(5,5)
b = np.array([1,2,3,4,5,6,7,8,9])
a[1:4,1:4] = b.reshape(3,3)
print(a)

rawDescription: Python - adding string elements from a list into an array


code:
mystring = "foofoofoo{something}{anything}foofoofoo";
re.findall(r"(\{[^}]*\})", mystring);

rawDescription: Python - Match substring occurrences between { } with regex


code:
proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
tmp = proc.stdout.read()

rawDescription: in python, get the output of system command as a string

description: In python, get the output of system command as a string


code:
for row in location:
    result = {}
    building_id = buildings.get(row['Build'])
    if building_id:
        result['BuildingID'] = building_id

rawDescription: Nested DictReaders not resetting

description: Nested DictReaders not resetting


code:
url_link = "http://finance.yahoo.com/q?s=^GSPC&d=t"
page = html.fromstring(requests.get(url_link).text)
for span_text in page.xpath("//span[@class='rtq_exch']/text()"):
    print(span_text)

rawDescription: using lxml and requests in python to grab text between certain tags with a specific class name

description: Using lxml and requests in python to grab text between certain tags with a specific class name


rawDescription: How to know if a number is in another number python

description: Know if a number is in another number python


rawDescription: PYTHON: Difference between if not i.find("Hey") and if i.find("Hey") == -1


rawDescription: Regular Expressions: Print last in group


code:
10
DVD
DVD_TEST

20
TV

rawDescription: How to properly parse parent/child XML with Python

description: Properly parse parent/child XML with Python


code:
class A:
    def __init__(self, shape):
        self.shape = shape
        self.matrix = numpy.zeros(shape)

    def __getinitargs__(self):
        return (self.shape,)

rawDescription: How to pickle a class instance's variables selectively?

description: Pickle a class instance's variables selectively


code:
def first_true4():
    di={}
    for i, ele in enumerate(np.argmax(a,axis=1)):
        if ele==0 and a[i][0]==0:
            di[i]=None
        else:
            di[i]=ele

    return di

rawDescription: Finding first non-zero value along axis of a sorted two dimensional numpy array


rawDescription: Is there a way to zip json into rows and columns in web2py?


rawDescription: Python: run script in all subdirectories


code:
#!/bin/python
from ctypes import *
# define the struct and it's fields
class DHStruct(Structure):
    _fields_ = [("temp",c_double),("humidity",c_double)]
#reference the library
dhtlib = CDLL("libdht4py.so")
# set the return type as the object above
dhtlib.readDHT.restype = POINTER(DHStruct)
# dereference the pointer using ctype's -contents and access the struct fields.
print ( dhtlib.readDHT().contents.temp ,   dhtlib.readDHT().contents.humidity  )

rawDescription: What methods can I use to return a struct to a Python Ctypes call to the function in a shared object?


code:
def type_convert(data):
    for item in data:
        try:
            yield int(item)
            continue
        except (ValueError, TypeError) as WrongTypeError:
            pass
        try:
            yield float(item)
            continue
        except (ValueError, TypeError) as WrongTypeError:
            pass
        yield item

for a in type_convert(['a','1','1.0']):
    print (a)

rawDescription: Yield Only Once Per Iteration

description: Yield Only Once Per Iteration


code:
from pandas import read_clipboard
from matplotlib.dates import date2num
names = ['date', 'open', 'close', 'high', 'low']
df = read_clipboard(sep=',', names=names, parse_dates=['date'])
df['d'] = df.date.map(date2num)

rawDescription: How to read and plot time series data files as candlestick chart?

description: Read and plot time series data files as candlestick chart


code:
html = """

Attendance list

        {0}

"""

items = [['Jason', 'Brown', 'Leeds', '40'], ['Sarah', 'Robinson', 'Bristol', '32'], ['Carlo', 'Baldi', 'Manchester', '41']]
tr = "
{0}
"
td = "{0}	"
subitems = [tr.format(''.join([td.format(a) for a in item])) for item in items]
# print html.format("".join(subitems)) # or write, whichever

rawDescription: Table within an html document using python list


code:
res = ts.resample('D', how='mean')
res

rawDescription: Index a Pandas dataframe grouped by date and aggregated?


code:
import re
[int(re.sub('[\[\]]', '', s)) for s in qtyList]

rawDescription: Splitting or pulling only integers in an array - python


rawDescription: i did not comprehend sum(iterable[, start]) in python

description: I did not comprehend sum(iterable[, start]) in python


code: K[np.ix_(imp_list, bath_list)].sum()

rawDescription: Partial sum over an array given a list of indices


rawDescription: How to recognize which mathematical function generated a curve given by X and Y arrays in sympy

description: Recognize which mathematical function generated a curve given by X and Y arrays in sympy


code: [fp1, fp2] + lst1 + lst2

rawDescription: splitting lists and values

description: Splitting lists and values


code:
#another.py
import fourth

fourth.first.some_function()
#etc.

rawDescription: Automatically import to all Python files in the given folder?


rawDescription: What is the best way to implement nested dictionaries in Python?


code:
def topfunction():
    tinyfunction()
    for i in range(100000):
        manytinyfunction()

rawDescription: Python profiling - What are the columns in runsnakerun output?


code:
print(find_dupe_rows(array1, array2, array3))
# [[ True  True  True  True  True]
#  [ True  True False  True False]
#  [ True  True False False False]]

rawDescription: Detect the first unique rows in multiple numpy 2-d arrays


rawDescription: Word frequency in a string without spaces and with special characters?


rawDescription: Extracting all full words between in a certain amount of characters


code:
from collections import Counter
def prune(dicto, min_df=2):
    # Create all counters
    counters = [Counter(d.keys()) for d in dicto]

    # Sum all counters
    total = sum(counters, Counter())

    # Create set with keys of high frequency
    keys = set(k for k, v in total.items() if v >= min_df)

    # Reconstruct counters using high frequency keys
    counters = (Counter({k: v for k, v in d.items() if k in keys}) for d in dicto)

    # With filter(None, ...) we take only the non empty counters.
    return filter(None, counters)

rawDescription: Dictionary within a list using Counter

description: Dictionary within a list using Counter


rawDescription: Looping in a dictionary

description: Looping in a dictionary


code:
longest = max(len(x) for x in res.keys())
header = ['Domain', 'Visits1', 'Sessions1', 'Visits2', 'Sessions2']
print('{:{w}s} '.format(header[0], w=longest), end='')
print(' '.join(header[1:]))
for domain, data in res.items():
    print('{:{w}s}'.format(domain, w=longest), end=' ')
    for head in header[1:]:
        value = data.get(head, 0)
        print('{:{w}d}'.format(value, w=len(head)), end=' ')
    print()

rawDescription: Comparing and Printing values from two dictionaries


code:
import random
lst = [1,2,4,5,3]
[random.choice(lst) for _ in range(len(lst))]

rawDescription: shuffle a python array WITH replacement

description: Shuffle a python array WITH replacement


code:
def safe_eval(eval_str, variable_dict = None):
    '''welll... mostly safe:
        http://lybniz2.sourceforge.net/safeeval.html
    '''
    if variable_dict == None:
        variable_dict = {}
    return eval(eval_str, {"__builtins__" : None}, variable_dict)

rawDescription: Execute operations given by the user with(out) eval()


code:
SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'project.myapp.utils.get_username',
    'social.pipeline.social_auth.associate_by_email',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
)

rawDescription: Python Social Auth: How to define a different username scheme?


rawDescription: How would I write this query in GeoDjango? (It's a library for geographic calculations in Django)


code:
angle = 0
radius = 87
while angle < 360:
    x = radius*sin(angle)
    y = radius*cos(angle)
    Ball.move(x - Ball.getCenter().getX(), y - Ball.getCenter().getY())
    angle += 0.01

rawDescription: Zelle Graphics animation

description: Zelle Graphics animation


code:
if set(a).intersection(b):
    print("yep!")

if any(i in b for i in a):
    print("also yep, but slow")

bset = set(b)
if any(i in bset for i in a):
    print("still yep, not so bad")

rawDescription: Check a generated string against a preset string in python


code:
# Bad!
obj.moveToThread(thread)
thread.method_of_obj(param)

# Good!
obj.moveToThread(thread)
obj.method_of_obj(param)

rawDescription: QThread use in Python

description: QThread use in Python


rawDescription: Finding hour of daily max using Pandas in Python


code: [[k, v.values()] for k, v in dict_1.iteritems()]

rawDescription: Sorting by the values of a sub-dictionary and then by primary keys


code:
with quitting_smtp_cm(smtplib.SMTP('smtp.gmail.com', 587)) as s:
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login('address','passw')
    s.sendmail(sender, recipients, composed)

rawDescription: python: sending a mail, fails when inside a "with" block

description: Python: sending a mail, fails when inside a "with" block


code:
import thread
thread.start_new_thread(upload_function()) #using the upload-process in a new function

rawDescription: Running a background process on Windows 7/XP


code:
mat = array([['a', 'b', 'c', 'd'],
             ['e', 'f', 'g', 'h'],
             ['i', 'j', 'k', 'l'],
             ['m', 'n', 'o', 'p']],
             dtype='|S1')

def enum_upperdiag(mat):
   n = len(mat) - 1
   for row in range(n):
      for col in range(n):
         if row + col >= n: break
         for j in range(row+1,n):
            for k in range(col+1, n):
               if j + k > n: continue
               indexOf_j = (j, col)
               indexOf_k = (row, k)
               yield indexOf_j, indexOf_k

rawDescription: NumPy: Iterating over items to right, bottom of given element w/ its index


rawDescription: array statement in python

description: Array statement in python


code: elem = webdriver.find_element_by_css_selector("a[title='Go to previous month']")[0]

rawDescription: Clicking JavaScript links in Selenium WebDriver and Python


code:
import re
def touni(match):
    return unichr(int(match.group(1), 16))

source = '\\x{4e8b}\\x{696d}'
print(re.sub(r'\\x\{([\da-f]+)\}', touni, source))

rawDescription: Python UTF-8 conversion

description: Python UTF-8 conversion


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

# This is the main window from my GUI

class CustomMainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(CustomMainWindow, self).__init__()
        self.setGeometry(300, 300, 2500, 1500)
        self.setWindowTitle("my first window")
        # ...
        self.startTheThread()

    ''''''

    def theCallbackFunc(self, msg):
        print('the thread has sent this message to the GUI:')
        print(msg)
        print('---------')

    ''''''

    def startTheThread(self):
        # Create the new thread. The target function is 'myThread'. The
        # function we created in the beginning.
        t = threading.Thread(name = 'myThread', target = myThread, args = (self.theCallbackFunc))
        t.start()

    ''''''

''' End CustomMainWindow '''

# This is the startup code.

if __name__== '__main__':
    app = QtGui.QApplication(sys.argv)
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec_())

''' End Main '''

rawDescription: Simplest way for PyQT Threading

description: Simplest way for PyQT Threading


code:
getattr(old_image, "id", "Spam") # gets old_image.id, if that does not exist, it
                                 # defaults to the str "Spam" Of course, in this
                                 # context, you probably want
                                 # getattr(old_image, field_name)

rawDescription: django - get field which name is dynamic

description: Django - get field which name is dynamic


code: L = [L[i] for i in ndx]

rawDescription: Is there a python method to re-order a list based on the provided new indices?


code:
from collections import Counter
[[k,c[k]] for k in Counter([i[0] for i in dates])]

rawDescription: python count number of times the date has appeared

description: Python count number of times the date has appeared


rawDescription: concat two dataframe using python

description: Concat two dataframe using python


code:
class ProductFilter(django_filters.FilterSet):
    def __init__(self, **kwargs):
        attribute = kwargs.pop['attribute']
        super(ProductFilter, self).__init__(**kwargs)

rawDescription: django pass extra arguments to filterset_class

description: Django pass extra arguments to filterset_class


code:
cr.execute("""select max(numero_bl) as part from livraisons
           where split_part(numero_bl, '-', 2) >= %s""",
        ((datetime.datetime.strftime(datetime.datetime.now(), '%Y')),))

rawDescription: Sql query (with Desc order and Limit) not working on python (OpenERP)


code:
def parse(self, response):
    sel = Selector(response)
    sites = sel.css('div.paid-featured-item div.listing-item')
    cars = []
    for site in sites:
        car = CarItem()
        car['ATitle'] = site.css('div.item-title h3 span.title a::text').extract()
        cars.append(car)
    return cars

rawDescription: python can't specific xpath for <a> tag

description: Python can't specific xpath for <a> tag


rawDescription: extracting data from the tweets of the twitter using python

description: Extracting data from the tweets of the twitter using python


rawDescription: Convert a column in pandas dataframe from String to Float


rawDescription: How to parse the JSON coming from all the URL's using Python?

description: Parse the JSON coming from all the URL's using Python


code:
class ImageGalleryManager(models.Manager):
    def update_counter(self, pk):
        self.filter(id=pk).update(count=F('count')+1)

class ImageGallery(models.Model):
    ...
    count = models.PositiveIntegerField(default=0)

    objects = ImageGalleryManager()

rawDescription: Django: DetailView, Where to update a counter?


code: import IPython; IPython.embed()

rawDescription: Getting a request object as in a view function but called from `manage.py shell`


code:
axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

rawDescription: How do I set the figure title and axes labels font size in Matplotlib?

description: Set the figure title and axes labels font size in Matplotlib


code: {key: sorted(range(len(a)), key=lambda i: a[i][key]) for key in ('name', 'age')}

rawDescription: Get sorted list of indices, for a list of dictionaries sorted by a given key


code: x = Popen(['ls', '-l'], stdout=PIPE, stderr=STDOUT, stdin=PIPE, shell=False)

rawDescription: Popen mixed data stream?

description: Popen mixed data stream


rawDescription: How to return a tuple containing a None value from the C API?

description: Return a tuple containing a None value from the C API


code:
S = struct('tree1', struct('leaf1', {1}, 'leaf2', {2}));
save('filename.mat', '-struct', 'S')

rawDescription: Importing matlab structs within structs in python


code: exclude_set = set(exclude_list)

rawDescription: Why is using a dict so much faster to exclude one list from another?


code: self.redirect('/success?email=' + email + '&product=' + product)

rawDescription: passing variables to a template on a redirect in python

description: Passing variables to a template on a redirect in python


code:
class MyClass(QPushButton):

    def __init__(self, name: str) -> None:
        super().__init__(name)
        self._name = name

    @pyqtSlot()
    def log_info(self):
        log(self._name)

self.flip = MyClass("Flip Image")
self.flip.clicked.connect(self.do_flip)
self.flip.clicked.connect(self.flip.log_info)

rawDescription: PyQt5 log a signal

description: PyQt5 log a signal


rawDescription: Dataframe how to keep only unique rows and plot curve


code:
df.unstack(['A', 'B'])
df.unstack(['A', 'B']).fillna(0).stack(['A', 'B'])

rawDescription: Filling in date gaps in MultiIndex Pandas Dataframe


code:
from django.http import Http404, HttpResponseRedirect
def fake_redirect(request, path):
    if request.user.is_authenticated:
        raise Http404()
    else:
        return HttpResponseRedirect('/login/?next=/%s' % path)

urlpatterns = patterns('',

    ...

    (r'^(?P<path>.+)$', fake_redirect),
)

rawDescription: Django: information leakage problem when using @login_required and setting LOGIN_URL


code:
import re
mylist.sort(key=lambda x: float('.'.join(re.findall(' w(\d+)\-(\d+) ', x)[0]
)))

rawDescription: How to sort this list? python

description: Sort this list? python


code:
def ModeList(lst):
    counts = {}
    for item in lst:
        counts[item] = counts.get(item, 0) + 1
    bycount = sorted(counts, key=counts.get)
    result = [bycount.pop()]
    while counts and counts[bycount[-1]] == counts[result[0]]:
        result.append(bycount.pop())
    return result

rawDescription: Mode of a List - Python

description: Mode of a List - Python


code:
from twisted.internet import reactor
root_window.protocol("WM_DELETE_WINDOW", reactor.stop)
reactor.run()

rawDescription: Initiating TCP Client after running reactor.run()


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

delta_Y = .5

zorder = 0
for i, Y in enumerate(data):
  baseline = min(Y)
  #change needed for minimum of Y to be delta_Y above previous curve
  y_change = delta_Y * i - baseline
  Y = Y + y_change
  plt.fill_between(np.linspace(0, 1000, 1000), Y, np.ones(1000) * delta_Y * i, zorder = zorder)
  zorder -= 1

rawDescription: Plot staggered histograms/lines as in FACS


rawDescription: bottom up fibonacci in python using O(1) space

description: Bottom up fibonacci in python using O(1) space


code:
def has_duplicates(l):
    s = set()
    for x in l:
        if x not in s:
            s.add(x)
        else:
            return true
    return false

get_first_duplicate([3, 5, 3])
# returns True

rawDescription: Python: Compare more numbers

description: Python: Compare more numbers


code:
a = 'aSATMPA23.37aSAAWAKE----aSATMPA15.14-aSASLEEPING-'
re.findall(r'aSATMPA\d+.\d+',a)

rawDescription: python regex find/match one or more in a string

description: Python regex find/match one or more in a string


code:
map(lambda x:x.lower(),["A","B","C"])
map(lambda x:x.upper(),["a","b","c"])

rawDescription: Convert a Python list with strings all to lowercase or uppercase


code:
# use ID as the column to join on in df2 and the index of df1
result = df2.merge(df1, left_on="ID", right_index=True, how="inner")

rawDescription: Combining DataFrames without Nans

description: Combining DataFrames without Nans


code:
project_ids = set([node.project.id for node in nodes])
projects = Project.objects.filter(id__in=project_ids)

rawDescription: Select all of django foreign key model if condition or part if another condition


code: my_opmenu.list = list1

rawDescription: Get list variable from tkinter OptionMenu in Python


code:
s = "DeltaE = 0.0000 | TDMI^2 = 5.657 , Intensity = 0.5604E+06"
m = re.search(r"DeltaE =\s+(\S+).* TDMI\^2 =\s+(\S+).* Intensity =\s+(\S+)", s)
m.group(1)
m.group(2)
m.group(3)
float(m.group(2))
float(m.group(3))
float(m.group(1))

rawDescription: Python: re.search not working

description: Python: re.search not working


code:
def all_high_bitscores(a,thresh=0.9):

    # set of indices for the elements in a that we're going to keep
    keep = np.zeros(a.size,np.bool)

    for qid in set(a['queryid']):
        idx = a['queryid'] == qid
        keep[idx] = a[idx]['bitscore'] >= a[idx]['bitscore'].max()*thresh

    return a[keep]

rawDescription: Extract highest values of numpy structured array


code:
import PIL
PIL.__path__

rawDescription: Find which libjpeg is being used by PIL / PILLOW


code: url(r'^cq/', include('cq.urls')),

rawDescription: Django admin custom view and urls

description: Django admin custom view and urls


code:
from datetime import datetime, timedelta

startDate = datetime(your_year, 1, 1)
endDate = (startDate + timedelta(days=days_from_the_begining)).weekday()

rawDescription: How to calculate day of the week provided the year and the day?

description: Calculate day of the week provided the year and the day


code:
df2 = pd.read_csv('out.csv', header=[0, 1])
df2

rawDescription: How can I write a csv file with multiple header lines with pandas to_csv()?

description: Write a csv file with multiple header lines with pandas to_csv()


code:
import numpy as np
import pylab as plt
import itertools

n = 13
roots = np.roots( [1,] + [0,]*(n-1) + [-1,] )
colors = itertools.cycle(['r', 'g', 'b', 'y'])

plt.figure(figsize=(6,6))

for root in roots:
    plt.arrow(0,0,root.real,root.imag,ec=colors.next())

plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
plt.show()

rawDescription: MatPlotLib: Plot complex roots unity as arrow-vectors on complex plane


code:
import os

if os.fork():
    # parent
    do_stuff()

else:
    # child
    os.setsid()
    os.execl('prog', 'prog')

rawDescription: background process in python with -e option on terminal

description: Background process in python with -e option on terminal


code: filter(Goal.country == Germany)

rawDescription: Create a search "engine" to get information from a Google DataStore in python


code:
Namespace(letter=['a'])
Namespace(letter=['b'])
Namespace(letter=['a', 'b'])
Namespace(letter=['a', 'b'])

rawDescription: Set default value with argparse and same dest attribute


rawDescription: Identifying a function call in a python script line in runtime


rawDescription: How can I separate the numeric parts of filenames using Python?

description: Separate the numeric parts of filenames using Python


code:
dfL = pd.concat([df]*100)
timeit('c = dfL["path"].str.split(",").apply(Counter); d = pd.DataFrame({n: c.apply(lambda x: x.get(n, 0)) for n in wordlist})', 'from __main__ import dfL, wordlist; import pandas as pd; from collections import Counter', number=100)
timeit('splitted = dfL["path"].str.split(","); d = pd.DataFrame({name : splitted.apply(lambda x: x.count(name)) for name in wordlist})', 'from __main__ import dfL, wordlist; import pandas as pd', number=100)
wordlist = wordlist + list(lowercase) + list(uppercase)
timeit('c = dfL["path"].str.split(",").apply(Counter); d = pd.DataFrame({n: c.apply(lambda x: x.get(n, 0)) for n in wordlist})', 'from __main__ import dfL, wordlist; import pandas as pd; from collections import Counter', number=100)
timeit('splitted = dfL["path"].str.split(","); d = pd.DataFrame({name : splitted.apply(lambda x: x.count(name)) for name in wordlist})', 'from __main__ import dfL, wordlist; import pandas as pd', number=100)

rawDescription: pandas dataframe count row values

description: Pandas dataframe count row values


code: np.meshgrid(A, B, C)

rawDescription: Generation of multidimensional Grid in Python


code:
def bar(a):
    return [ x**3 for x in a ]

rawDescription: For loops clarity

description: For loops clarity


code:
mask = b > a[..., -1:]
index = np.argmax(mask, axis=-1)

rawDescription: Gridwise application of the bisection method


code: get_lerp_factor(0, 9, 16)

rawDescription: How to code a Python function that accepts float, list or numpy.array?

description: Code a Python function that accepts float, list or numpy.array


code: globals()[module] = __import__(module)

rawDescription: NameError when trying to use module that has been imported


code:
class Demo(object):
    __slots__ = ('foo',)
d = Demo()
d.foo = 'bar'
d.bar = 'foo'

rawDescription: If everything is an object, why can't I add attributes to some?


code:
import requests

url = "http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ&render=download"

response = requests.get(url, stream=True)
print(response.status_code)

# Write server response to file
with open("nasdaq.csv", 'wb') as f:
    for chunk in response.iter_content(chunk_size=1024):
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)

rawDescription: Using python requests to mask as a browser and download a file


code:
def f(x):
    return x*(x+1)

def derivative(x, h):
    rise = f(x+h) - f(x)
    run = h
    slope = rise/run
    return slope

rawDescription: Repeating calculations in Python

description: Repeating calculations in Python


code:
xx = numpy.array([1, 10, 100, 1000])
numpy.random.normal(xx)

rawDescription: Does calling random.normal on an array of values add noise?


rawDescription: wxpython start multiple timers within a for loop

description: Wxpython start multiple timers within a for loop


code:
import base64
from M2Crypto import SMIME, X509, BIO

raw_sig = """base64 PKCS7 envelop"""
msg = "challenge message to verify"

sm_obj = SMIME.SMIME()
x509 = X509.load_cert('ISSUER.crt') # public key cert used by the remote
                                             # client when signing the message
sk = X509.X509_Stack()
sk.push(x509)
sm_obj.set_x509_stack(sk)

st = X509.X509_Store()
st.load_info('ROOT.crt') # Public cert for the CA which signed
                                    # the above certificate
sm_obj.set_x509_store(st)

# re-wrap signature so that it fits base64 standards
cooked_sig = '\n'.join(raw_sig[pos:pos+76] for pos in xrange(0, len(raw_sig), 76))

# now, wrap the signature in a PKCS7 block
sig = """
-----BEGIN PKCS7-----
%s
-----END PKCS7-----
""" % cooked_sig

# print sig

# and load it into an SMIME p7 object through the BIO I/O buffer:
buf = BIO.MemoryBuffer(sig)
p7 = SMIME.load_pkcs7_bio(buf)

signers = p7.get0_signers(sk)
certificat = signers[0]

rawDescription: Extract userCertificate from PKCS7 envelop in python


rawDescription: Python hashlib - Update and Digest for list comprehension


code: import time

rawDescription: Erratic problem with App Engine when writing files directly to the blobstore


code: df.columns[df.std() == 0.0]

rawDescription: How can you check if a column in a DataFrame is stale?

description: Check if a column in a DataFrame is stale


code:
import numpy as np
from pandas import *
df = DataFrame([3]*4+[4]*4+[1]*4, columns=['A'])
df
df.reset_index().groupby('A')['index'].apply(lambda x: np.array(x))

rawDescription: Finding consecutive segments in a pandas data frame


code: "- >/dev/null 2>/dev/null"

rawDescription: convert Ghostscript from os.popen to subsession.popen python

description: Convert Ghostscript from os.popen to subsession.popen python


rawDescription: Regex-Match password in mail URL

description: Regex-Match password in mail URL


code: deleted_column = list(map(lambda x: x.pop(which_column), triangle))

rawDescription: Python - Delete column from a matrix without numPy


code:
class _:
    class isYummy: pass

    class chocolate:
        class sweet: pass

        class lindt:
            class tasty: pass

            class _:
                class smooth: pass
                class creamy: level = 1
# ...

rawDescription: Tips on how to parse custom file format

description: Tips on how to parse custom file format


code:
import requests
import os
url = 'http://someplace'
folder = 'path/to/folder/'
for card in os.listdir(folder):
    data = {'identifier': '.'.join(card.split('.')[:-1]), 'type': 'Inventory Card'}
    files = {'card': open(os.path.join(folder, card), 'rb')}
    requests.post(url, data=data, files=files, auth=('username', 'pass'))

rawDescription: Iterate through folder, extracting filename without extension assign as API variable name in Python


code: segdists = np.hypot(d[:,0], d[:,1])

rawDescription: Calculating euclidean distance between consecutive points of an array with numpy


code: object_dict = dict((x.id, x) for x in object_list)

rawDescription: reduce python list of objects to dict object.id -> object

description: Reduce python list of objects to dict object.id -> object


code:
my_array = np.random.rand(100,100)
my_list = my_array.tolist()
timeit.timeit("my_array[:, 1]", setup="from __main__ import my_array", number=10000)
timeit.timeit("[item[1] for item in my_list]", setup="from __main__ import my_list", number=10000)
timeit.timeit("list(zip(*my_list)[1])", setup="from __main__ import my_list", number=10000)

rawDescription: Python list of lists -> make sublists of element n


rawDescription: Returning all keys that have the same corresponding value in a dictionary with python


code:
import Image, numpy
i = Image.open('img.png')
i = i.convert('L')    #convert to grayscale
a = numpy.asarray(i) # a is readonly

b = abs(numpy.fft.rfft2(a))

j = Image.fromarray(b)
j.save('img2.png')

rawDescription: fft and array-to-image / image-to-array-conversion

description: Fft and array-to-image / image-to-array-conversion


code:
groups = [funA, funB, funC]
for group in groups:
    for item in group():
        yield item

rawDescription: Python - is there any way to organize a group of yields in sub function to yield outside the main function?


code:
import threading, Queue

Stop = object()

def consumer(real_dict, queue):
    while True:
        try:
            item = queue.get(timeout=100)
            if item == Stop:
                break
            user, submission = item
            real_dict[user] = submission
        except Queue.Empty:
            continue

q = Queue.Queue()
thedict={}

t = threading.Thread(target=consumer, args=(thedict,q,))
t.start()

rawDescription: Python threading in web programming

description: Python threading in web programming


code:
dict1 = {'barry': {'gpa':'2.9','major':'biology'},
         'sarah': {'gpa':'3.2','major':'economics'},
         'george': {'gpa':'2.5','major':'english'}}

dict2 = {'john': {'position':'Lecturer','department':'economics'},
         'lisa': {'position':'researcher','department':'physics'},
         'james': {'position':'tutor','department':'english'}}

rawDescription: How to check if list item is in dictionary. If so, print the data associated with it

description: Check if list item is in dictionary. If so, print the data associated with it


rawDescription: Making a python dictionary from a huge textfile?


code:
import random
from matplotlib import pyplot as plt
from matplotlib import animation

def data_generator_1(t):
    if t<100:
        x1.append(t)
        y1.append(random.randint(1, 100))

def data_generator_2(t):
    if t<100:
        x2.append(t)
        y2.append(random.randint(1, 100))

def init():
    global x1
    global y1
    x1 = []
    y1 = []

    global x2
    global y2
    x2 = []
    y2 = []

    l1, l2 = plt.plot(x1, y1, x2, y2)
    return l1, l2

def animate(i):
    data_generator_1(i)
    data_generator_2(i)
    l1, l2 = plt.plot(x1, y1, x2, y2)
    plt.setp(l1, ls='--', c='k')
    plt.setp(l2, c='gray')
    return l1, l2

fig = plt.figure()
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=1000, interval=1000, blit=True)
plt.show()

rawDescription: Overplotting dynamically

description: Overplotting dynamically


code:
channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

rawDescription: Can I have a Python script listen on a message queue continuously or do I have to loop?

description: Have a Python script listen on a message queue continuously or do I have to loop


code:
rng = range(1,29)
dates = pd.date_range('1/1/2000', periods=len(rng))
r = pd.DataFrame(rng, index=dates, columns=['A'])
r2 = r.resample("1w", how={'A': np.sum})

rawDescription: Pandas rolling sum, variating length

description: Pandas rolling sum, variating length


code:
import sklearn.cluster
import numpy as np

data = [
    ['bob', 1, 3, 7],
    ['joe', 2, 4, 8],
    ['bill', 1, 6, 4],
]

labels = [x[0] for x in data]
a = np.array([x[1:] for x in data])
clust_centers = 2

model = sklearn.cluster.k_means(a, clust_centers)

rawDescription: Python Relating k-means cluster to instance


code:
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')

rawDescription: Append a list of strings to a file in a single line? - Python


rawDescription: numpy tile without memory allocation

description: Numpy tile without memory allocation


rawDescription: Pandas read multiindexed csv with blanks


code:
class ClassModel(object):
    number = None

class FunctionModel(object):
    number = None
    def __call__(myself, clsself):
        return myself.number + clsself.number

rawDescription: Attach a method to a class while the class is being created


code:
b = wx.Button(self, 10, "Default Button", (20, 20))
b.myname = "default button"
self.Bind(wx.EVT_BUTTON, self.OnClick, b)

rawDescription: Best way to get the name of a button that called an event?

description: Get the name of a button that called an event


rawDescription: Django manytomany field, how to get check for 80% subset/ match?


rawDescription: Defining function with function object passed in as argument


code:
from PIL import ImageGrab
im = ImageGrab.grab()
im.save('screenshot.png')

rawDescription: Python windows 7 screenshot without PIL

description: Python windows 7 screenshot without PIL


code:
def somescriptfunc():
    # does something
    pass

if __name__ == "__main__":
    # do something if this script is invoked
    # as python scriptname. Otherwise, gets ignored.

    import cProfile
    cProfile.run('somescriptfunc()')

rawDescription: Can't figure out how to invoke cProfile inside of a program


code:
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

rawDescription: Iterate two lists in the same loop

description: Iterate two lists in the same loop


code:
@QtCore.Slot(QTreeWidgetItem, QTreeWidgetItem)
def on_list_currentItemChanged(self, current=None, previous=None):
    if current is not None and current.isSelected():
        self.ui.actionDelete_Task.setEnabled(True)
    else:
        self.ui.actionDelete_Task.setEnabled(False)

rawDescription: Clear selected list item (so there's no selected list item) in Python/PySide


code: map(lambda x: int(x[2]), l)

rawDescription: Why use the map() function?

description: Why use the map() function


code:
UL = (center_L1[0] + (length / 2.) * cos(angle) - (thickness / 2.) * sin(angle),
      center_L1[1] + (thickness / 2.) * cos(angle) + (length / 2.) * sin(angle))
UR = (center_L1[0] - (length / 2.) * cos(angle) - (thickness / 2.) * sin(angle),
      center_L1[1] + (thickness / 2.) * cos(angle) - (length / 2.) * sin(angle))
BL = (center_L1[0] + (length / 2.) * cos(angle) + (thickness / 2.) * sin(angle),
      center_L1[1] - (thickness / 2.) * cos(angle) + (length / 2.) * sin(angle))
BR = (center_L1[0] - (length / 2.) * cos(angle) + (thickness / 2.) * sin(angle),
      center_L1[1] - (thickness / 2.) * cos(angle) - (length / 2.) * sin(angle))

rawDescription: Pygame draw anti-aliased thick line

description: Pygame draw anti-aliased thick line


code:
subgraphs = nx.connected_components(G)
subgraphs
[G.edges(subgraph) for subgraph in subgraphs]

rawDescription: Split a tuple of tuples (or list of lists) of paired values into independent complete sets?


code: print('\n'.join(['\n'.join(['{}:{}'.format(i,j) for i,j in d.items()]) for d in storeItems]))

rawDescription: Python OrderedDict with dictionary within list?


code:
re.sub(r'(?<![a-zA-Z])r_', 'l_',"gr_shoulder_r_tmp")
re.sub(r'(?<![a-zA-Z])r_', 'l_',"r_shoulder_tmp")

rawDescription: regex sbustitute only specific hit sequence

description: Regex sbustitute only specific hit sequence


code:
import trace
tracer=trace.Trace()
tracer.run('mytest.test()')

rawDescription: python echoing commands contained in a script?

description: Python echoing commands contained in a script


code:
n_set_points = 100
n_test_points = 10000
n_dims = 60

set_points = np.random.rand(n_set_points, n_dims)
test_points = np.random.rand(n_test_points, n_dims)

rawDescription: Fast evaluation of a product

description: Fast evaluation of a product


code:
def genFn(a, b, c):
    # some initialisation / pre-computation
    startPt = fn(a, b, c)
    data = (yield startPt)
    while True:
        # perform some computation
        data = (yield result)

f = genFn(5, 6, 7)
startPt = f.send(None)  # first yield returns the start point
for data in dataseries[startPt:]:
    k = f.send(data)

rawDescription: How to store and retrieve meta-information in generator function object instance?

description: Store and retrieve meta-information in generator function object instance


code:
listWords = ["go", "make", "do", "some", "lot"]
listOccurrences = [2, 4, 8, 1, 5]
listTmp = zip(listOccurrences, listWords)
listTmp
listTmp.sort(reverse=True)
listTmp
zip(*listTmp)
listOccurrences, listWord = zip(*listTmp)

rawDescription: Sort two lists in python?

description: Sort two lists in python


rawDescription: Python: Only saving three latest scores

description: Python: Only saving three latest scores


code:
_lib = C.LibraryLoader(C.CDLL).LoadLibrary(lib_path)
_myfunc = _lib.myfunc
_myfunc.argtypes = [C.c_void_p]
_myfunc.restype = C.POINTER(C.c_char)

rawDescription: GDAL: Get pointer/handle of underlying C object


code:
import json
import sys
from subprocess import Popen, PIPE

marshal, unmarshal = json.dumps, json.loads

p = Popen([sys.executable, 'some_script.py'], stdin=PIPE, stdout=PIPE)
result = unmarshal(p.communicate(marshal(args))[0])

rawDescription: Getting return infromation from another python script


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

def main():
    # Generate some data...
    x, y = np.mgrid[:141, :101]
    z = np.cos(np.hypot(x, y))

    # Plot the figure...
    fig, ax = plt.subplots()
    ax.pcolormesh(x, y, z, cmap=mpl.cm.Reds)
    ax.set_xlabel('Hours')

    ax.xaxis.set_major_locator(ScaledLocator(dx=6))
    ax.xaxis.set_major_formatter(ScaledFormatter(dx=6))

    plt.show()

class ScaledLocator(mpl.ticker.MaxNLocator):
    """
    Locates regular intervals along an axis scaled by *dx* and shifted by
    *x0*. For example, this would locate minutes on an axis plotted in seconds
    if dx=60.  This differs from MultipleLocator in that an approriate interval
    of dx units will be chosen similar to the default MaxNLocator.
    """
    def __init__(self, dx=1.0, x0=0.0):
        self.dx = dx
        self.x0 = x0
        mpl.ticker.MaxNLocator.__init__(self, nbins=9, steps=[1, 2, 5, 10])

    def rescale(self, x):
        return x / self.dx + self.x0
    def inv_rescale(self, x):
        return  (x - self.x0) * self.dx

    def __call__(self):
        vmin, vmax = self.axis.get_view_interval()
        vmin, vmax = self.rescale(vmin), self.rescale(vmax)
        vmin, vmax = mpl.transforms.nonsingular(vmin, vmax, expander = 0.05)
        locs = self.bin_boundaries(vmin, vmax)
        locs = self.inv_rescale(locs)
        prune = self._prune
        if prune=='lower':
            locs = locs[1:]
        elif prune=='upper':
            locs = locs[:-1]
        elif prune=='both':
            locs = locs[1:-1]
        return self.raise_if_exceeds(locs)

class ScaledFormatter(mpl.ticker.OldScalarFormatter):
    """Formats tick labels scaled by *dx* and shifted by *x0*."""
    def __init__(self, dx=1.0, x0=0.0, **kwargs):
        self.dx, self.x0 = dx, x0

    def rescale(self, x):
        return x / self.dx + self.x0

    def __call__(self, x, pos=None):
        xmin, xmax = self.axis.get_view_interval()
        xmin, xmax = self.rescale(xmin), self.rescale(xmax)
        d = abs(xmax - xmin)
        x = self.rescale(x)
        s = self.pprint_val(x, d)
        return s

if __name__ == '__main__':
    main()

rawDescription: Customize x-axis in matplotlib

description: Customize x-axis in matplotlib


code:
def nearest(ts):
    # Given a presorted list of timestamps:  s = sorted(index)
    i = bisect_left(s, ts)
    return min(s[max(0, i-1): i+2], key=lambda t: abs(ts - t))

rawDescription: Python - Locating the closest timestamp

description: Python - Locating the closest timestamp


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

file = r'C:\dickster\data.xlsx'
list_dfs = []

xls = xlrd.open_workbook(file, on_demand=True)
for sheet_name in xls.sheet_names():
    df = pd.read_excel(file,sheet_name)
    df['time'] = sheet_name
    list_dfs.append(df)

dfs = pd.concat(list_dfs,axis=0)
dfs = dfs.sort(['time','code'])

rawDescription: Pandas combine multiple excel worksheets on specific index


rawDescription: efficiently find maxes of one column over id in a Pandas dataframe

description: Efficiently find maxes of one column over id in a Pandas dataframe


rawDescription: sort names in alphabitical order in mysql using python

description: Sort names in alphabitical order in mysql using python


rawDescription: How to analyse bitmap image in python, using PIL?

description: Analyse bitmap image in python, using PIL


code:
def build_re(glob_str):
    opts = re.compile('([.]|[*][*]/|[*]|[?])|(.)')
    out = ''
    for (pattern_match, literal_text) in opts.findall(glob_str):
        if pattern_match == '.':
            out += '[.]'
        elif pattern_match == '**/':
            out += '(?:.*/)?'
        elif pattern_match == '*':
            out += '[^/]*'
        elif pattern_match == '?':
            out += '.'
        elif literal_text:
            out += literal_text
    return out

rawDescription: Is it possible to transform fnmatch.translate("**/*.py") into a semantically correct regex?


code:
from string import punctuation
with open('ttext.txt') as text,  open('filterlist.txt') as filter_words:
    st = set(word.lower().rstrip(punctuation+"\n") for word in  filter_words)
    txt = next(text).lower().split()
    out = [word  for word in txt if word not in st]

rawDescription: filter words from one text file in another text file?

description: Filter words from one text file in another text file


code: df['one'] = pd.to_datetime(df['one'])

rawDescription: Slicing a DataFrame

description: Slicing a DataFrame


code:
def validate_emails(names, domain, catchall):
    # run validation logic
    for name in names:
        email = name + "@" + domain
        has_mx = validate_email(email, check_mx=True)
        is_real = validate_email(email, verify=True)
        is_catchall = name == catchall

        if not has_mx:
            yield name, False, "no mx record"
            break
        elif is_real and is_catchall:
            yield name, False, "catchall detected"
        elif is_real and not is_catchall:
            yield email, True, "probably valid"
        else:
            yield email, False, "not valid"

rawDescription: Surfacing results as they are printed on HTML Page


rawDescription: How to convert lists in a dictionary to dictionaries in a lists (Python)

description: Convert lists in a dictionary to dictionaries in a lists (Python)


code:
def collapse_newlines(s):
    # Collapse multiple consecutive newlines into one; removes trailing newlines
    return '\n'.join(filter(None, s.split('\n')))

def read_tabbed_file(filename):
    with open(filename) as f:
        row = None
        for line in f:
            if line.count('\t') < 4:   # Note continuation
                row[-1] += line
                continue

            if row is not None:
                row[-1] = collapse_newlines(row[-1])
                yield row

            row = line.split('\t')

        if row is not None:
            row[-1] = collapse_newlines(row[-1])
            yield row

rawDescription: Remove multiple EOL in file

description: Remove multiple EOL in file


code:
def all_or_filter_args(request, item):
    """Return dictionary of arguments for filter() if item is specified in request."""
    value = request.get(item)
    if value is None:
        return {}
    return { item : value }

rawDescription: Django wildcard query

description: Django wildcard query


code:
def lowes_feedback_response(seller):
    try:
        return models.Feedback.filter(seller=seller).order_by('-seller_feedback')[0].customer_feedback
    except models.Feedback.DoesNotExist:
        return None

rawDescription: Django: Efficient model for ordered list of objects


rawDescription: Python 3: How to move an item from list x to list y and remove it from list x?


code:
a = 1
b = 1
a is b
id(a) == id(b)

rawDescription: Types for which "is" keyword may be equivalent to equality operator in Python


code:
A
n = 3 # Number of elements to keep per row
A

rawDescription: argpartsort/partsort of 2D array keeping original array dimensions

description: Argpartsort/partsort of 2D array keeping original array dimensions


code:
newpath = name + ".txt"
with open(newpath, "r") as newfile:
    loaded = newfile.read()

rawDescription: reading from a text document in python using a variable

description: Reading from a text document in python using a variable


code:
with precision_context(PRECISION) as ctx:
    # Enter `localcontext(Context(prec=precision))`
    with ctx:
        print(SMALL_NUMBER + 1) # prints 1.000

rawDescription: Python decimal custom context

description: Python decimal custom context


code:
if click[2] == 1:
    pygame.draw.rect(gameDisplay,black, (100,200,100,200))
    pygame.display.update()

rawDescription: after i click on image for blit when MOUSEBUTTONDOWN the new blit then disappear in pygame

description: After i click on image for blit when MOUSEBUTTONDOWN the new blit then disappear in pygame


code:
from operator import attrgetter
sorted(item_list, key=attrgetter('fitness'))

rawDescription: How to sort a collection of objects by an variable they all hold?

description: Sort a collection of objects by an variable they all hold


code:
import os
os.path.commonprefix(['foo2you and you', 'foo bar and you'])

rawDescription: Return leading string common to (the start of) words in a list in python


code: transposedlist = [entry for entry in transposedlist if any(e.isdigit() for e in entry)]

rawDescription: Delete column if items don't contain a Number


code:
Hello #world I am in #London and it is #sunny today it is #2016
['#world', '#London', '#sunny', '#2016']
['Hello', 'I', 'am', 'in']

Hello #London I am in #London and it is #sunny today it is #2016
['#London', '#London', '#sunny', '#2016']
['Hello', 'I', 'am', 'in']

Hello #Austin I am at #SXSW and this is just a # hashtag symbol
['#Austin', '#SXSW']
['Hello', 'I', 'am', 'at']

rawDescription: Splitting string data into keywords in Python in customized order and store specific keywords seprately


code:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts', size = 20)
plt.ylabel('Probability')
plt.title('Histogram of IQ', size = 50)
plt.text(60, .025, r'$\mu=100,\ \sigma=15$', size = 30)
plt.axis([40, 160, 0, 0.03])
plt.xticks(size = 50)
plt.yticks(size = 50)
plt.grid(True)
plt.show()

rawDescription: how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger

description: Make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger


rawDescription: Displaying frames from 2 separate videos according to timestamps stored in a text file


rawDescription: Pivoting pandas DataFrame -- AssertionError: Index length did not match values


code:
n = 5
a = range(0, 13*n, 13)
b = [ x + 12 for x in a]
a
b

rawDescription: Sequence Generation with Number applied to string


code:
import re
pat = re.compile('w=[0-9]+')  # or you can use \d+
s = pat.sub('', s)

rawDescription: Using a regexp to match my string content?


code:
my_form = MultiSelectForm(
    dynamic_field={'name': 'countries', 'choices': (mychoices), 'required': True})

rawDescription: Python/Django Forms: Dynamic variable creation and access for Form fields


code:
import test1
x = test1.Something()
test1.run()

rawDescription: python eval in "library" file

description: Python eval in "library" file


code:
file1 = ... # path to the first file
file2 = ... # path to the second file

with open(file1, "w") as fw:
    fw.write("c_id,name\n121210,abc\n121211,pqr")

with open(file2, "w") as fw:
    fw.write("121211,0,0\n121210,0,1")

rawDescription: Python Spark How to Map Fields of one rdd to another rdd


code:
from xml.sax.saxutils import escape, unescape
# escape() and unescape() takes care of &, < and >.
html_escape_table = {
    '"': """,
    "'": "'"
}
html_unescape_table = {v:k for k, v in html_escape_table.items()}

def html_escape(text):
    return escape(text, html_escape_table)

def html_unescape(text):
    return unescape(text, html_unescape_table)

rawDescription: Escape special HTML characters in Python


rawDescription: Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone


code: [' '.join(x) for x in ngrams('a b c d', 2)] # ['a b', 'b c', 'c d']

rawDescription: Computing N Grams using Python

description: Computing N Grams using Python


code:
X,Y = np.meshgrid(np.arange(0,100), np.arange(0,100))
result = np.vstack((Y.ravel(), X.ravel())).T
result
# array([[ 0,  0],
#        [ 0,  1],
#        [ 0,  2],
#           ...,

rawDescription: Efficient way of creating a permutated 2D array with a range of integers


code:
class Institution(models.Model):
    name = models.CharField(_('Name'), max_length=150, db_index=True)
    slug = models.SlugField(_('Domain name'), unique=True)

    class Meta:
        abstract = True

rawDescription: Model Many to Many relations with Abstract Class


code:
grouped = df.groupby('time_group')

for group_number, group_data in grouped:
    print(group_data.head())
    # Could also do group_data.to_csv() here if you want
    # to save the individual pieces as separate files

rawDescription: parsing pandas data frame base on conditions and save it to a csv

description: Parsing pandas data frame base on conditions and save it to a csv


rawDescription: Counting similarities among two pandas dataframes


code:
counts = collections.Counter()
counts[(1, 2, 4)] += 1

rawDescription: adding item to dictionary python with a variable name key

description: Adding item to dictionary python with a variable name key


code:
from numpy.core.umath_tests import inner1d
Z = inner1d(X,Y)

rawDescription: find the dot product of sub-arrays in numpy

description: Find the dot product of sub-arrays in numpy


rawDescription: Python SQLITE3 SELECT query with datetime calculated string not working


code:
def horner(coeffs, x):
    acc = 0
    for c in coeffs:
        acc = acc * x + c
    return acc
horner((1,1,0), myarray)

rawDescription: Obtaining Legendre polynomial form once Legendre coefficients are determined


code:
L1 = [["cat","dog","apple"],
      ["orange","green","red"],
      ["hand","cat","red"]]
L2 = ["cat","red"]
generate_edges(L1, L2)

rawDescription: Search a list of list of strings for a list of strings in python efficiently


code:
i = iter(lst)
dict(zip(i,i))

rawDescription: Retrieve a 2 items from a list at a time in loop?


code: dict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] )

rawDescription: "Adding" Dictionaries in Python?

description: "Adding" Dictionaries in Python


code: list_of_lines = [next(f) for _ in range(chunk_len)]

rawDescription: Pythonic way to ignore for loop control variable


code:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))

rawDescription: How to get time of a python program execution?

description: Get time of a python program execution


rawDescription: Pandas writing to excel: 1) blank row from index; 2) keep index daily


code:
x = testWindow()
path = x.openFileDialog()

rawDescription: How to read an attribute in another class?

description: Read an attribute in another class


code:
script2
launch1.VBS
# count 1

script2
launch4.VBS
# count 1

script5
launch1.VBS
# count 1

script8
launch3.VBS
# count 3

rawDescription: Python counting occurrences across multiple lines using loops


code:
any(x > 5 for x in range(4))  # => False
all(isinstance(x, int) for x in range(10))  # => True
any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])  # => True
all([True, True, True, False, True])  # => False

rawDescription: python using any() and all() to check if a list contains one set of values or another

description: Python using any() and all() to check if a list contains one set of values or another


code: from Indicators.Stochastics import *

rawDescription: How to organize a Python Project?

description: Organize a Python Project


rawDescription: How can I correctly pass Content-MD5 headers when putting files on S3 using boto's Key.generate_url method?

description: Correctly pass Content-MD5 headers when putting files on S3 using boto's Key.generate_url method


code: df.xs('C', copy = False)['x']=10

rawDescription: Set value for particular cell in pandas DataFrame


rawDescription: How to increase the number of tweets read using python for sentiment analyser

description: Increase the number of tweets read using python for sentiment analyser


code: index_of_min_index_map = {key: 0 for key in test}

rawDescription: python find minimum value in dictionary iteratively

description: Python find minimum value in dictionary iteratively


code:
a
b
a0 = a[:,0]
np.true_divide(a[:,1],b[np.searchsorted(a0,b[:,0],sorter=a0.argsort()),1])

rawDescription: Checking to see if array elements are equal


code: from wholeproject.database import dbfunctions

rawDescription: Best way to import database in python project

description: Import database in python project


code:
from distutils.core import setup
import py2exe

setup(console=['hello.py'])

rawDescription: making exe file from python that uses command line arguments

description: Making exe file from python that uses command line arguments


rawDescription: Attempting a Nested Scrape Using BeautifulSoup


code:
items = load_file(filename)

# Get input for 'code' from user
code = int(input(">> "))

# Get the position in the list where the item with this code is
try:
    list_position = [item[0] for item in items].index(code)
    # Do whatever you need to (ask for more input?)
    # If you have to overwrite the element, just reassign its
    # position in the list with
    # items[list_position] = (code, blah, blah)
except IndexError:
    # This means that the user's entered code wasn't entered
    # Here you do what you need to (maybe add a new item to the list),
    # but I'm just going to pass
    pass

rawDescription: Replacing data in files with new inputs

description: Replacing data in files with new inputs


rawDescription: Dictionary key count

description: Dictionary key count


code:
lines = open("input.txt", 'rt')
for line in lines:
    if not line.strip():
        break
open("output.txt", 'wt').writelines(lines)

rawDescription: How to delete parts of a file in python?

description: Delete parts of a file in python


code:
DENIED_PATTERN = re.compile(r'''
    :\s+?                                   # Start with leading white space
    (?P<protocol>[A-Z]*?)                   # Capture "<protocol>" start
    \saccess\s+denied\s+by\s+ACL\s+from\s+  # Matches literal string
    (?P<src>[0-9a-f\.:]*)/.*?:              # Captures "<src>" plus extra text
    (?P<dst>[0-9a-f\.:]*)                   # Captures "<dst>"
    (?:/(?P<dst_port>[0-9]*?))?\s           # Optional captures "/<dst_port>"
    ''', re.X)

rawDescription: Python program and regex

description: Python program and regex


code:
unique-ID,person_1,person,_2,person_3,person_4,...,person_20
12,Tom,Sally,Mike
16,Joe,Mike
5,Joe,Sally
1,Sally,Mike,Tom
6,Sally,Tom,Mike
2,Jared,Joe,Mike,John,...,Carl

rawDescription: Extracting Groups

description: Extracting Groups


code:
import random
random.sample(s, 1)[0]

rawDescription: How to get an arbitrary element from a frozenset?

description: Get an arbitrary element from a frozenset


rawDescription: Select from pandas dataframe using boolean series/array


code:
if docstring is not None and docstring.strip():
    func_list[docstring.partition('\n')[0].strip()] = rule.rule

rawDescription: How to interchange the key value output of app.url_map.iter_rules function

description: Interchange the key value output of app.url_map.iter_rules function


code:
line = raw_input()
while(line):
    # process line
    line=raw_input()

rawDescription: how to get a series of numbers and don't know how many is in python

description: Get a series of numbers and don't know how many is in python


code:
import multiprocessing as mp
import time
import random
import subprocess
import logging
logger = mp.log_to_stderr(logging.WARN)

SENTINEL = None
def popen_wrapper(inqueue, outqueue):
    for i in iter(inqueue.get, SENTINEL):
        logger.warn('echo "hi"')
        outqueue.put(i)

if __name__ == '__main__':

    num_to_run = 15
    max_parallel = 3

    inqueue = mp.Queue()
    outqueue = mp.Queue()
    procs = [mp.Process(target=popen_wrapper, args=(inqueue, outqueue))
             for i in range(max_parallel)]

    for p in procs:
        p.start()
    for i in range(num_to_run):
        inqueue.put(i)
    for i in range(max_parallel):
        # Put sentinels in the queue to tell `popen_wrapper` to quit
        inqueue.put(SENTINEL)

    for p in procs:
        p.join()

    results = [outqueue.get() for i in range(num_to_run)]
    logger.warn(results)

rawDescription: python multiprocessing - select-like on running processes to see which have one have finished

description: Python multiprocessing - select-like on running processes to see which have one have finished


code:
u4 = u3.fillna(method='ffill').fillna(0)
u4

rawDescription: How to get an accumulative counting of rows in a data frame?

description: Get an accumulative counting of rows in a data frame


code: ts.apply(lambda y: direction_day(y))

rawDescription: Applying complex function to several timeseries


code:
from copy import deepcopy

dictB = deepcopy(dictA)

rawDescription: Setting dictionarys equal in Python

description: Setting dictionarys equal in Python


code: my_expr = And(map(Literal, "The quick brown fox jumps over the lazy dog".split()))

rawDescription: Pyparsing - literal text with line breaks in varying locations


code:
import constants

class Question(...):
    ...
    help_text = constants.HELP_TEXT

rawDescription: Django help_text line length convention

description: Django help_text line length convention


code:
from lettuce import *

@step('I have to add the numbers (\d+) and (\d+)')
def have_to_add(step, number1, number2):
    world.number1 = int(number1)
    world.number2 = int(number2)

@step('I have to substract (?P<subtrahend>) from (?P<minuend>)')
def have_to_substract(step, minuend, subtrahend):
    world.minuend = int(minuend)
    world.subtrahend = int(subtrahend)

@step('I compute their difference')
def compute_difference(step):
    world.number = world.minuend - world.subtrahend

@step('I compute their sum')
def compute_sum(step):
    world.number = world.number1 + world.number2

@step('I see the number (\d+)')
def check_number(step, expected):
    expected = int(expected)
    assert world.number == expected, "Got %d" % world.number

rawDescription: pass in multiple arguments in lettuce test step

description: Pass in multiple arguments in lettuce test step


code:
img = pygame.image.load('images/Background_Logo.png')
WHITE = ( 255, 255, 255)
BLACK = ( 0, 0, 0)

rawDescription: Files only importing if opened from certain place


code:
def search(current_item, number):
    if current_item == number: return True
    return isinstance(current_item, list) \
        and any(search(item, number) for item in current_item)

rawDescription: Python nested list recursion search

description: Python nested list recursion search


rawDescription: How to make this simple string function "pythonic"

description: Make this simple string function "pythonic"


rawDescription: How to combine two dicts by key in python?

description: Combine two dicts by key in python


code:
ax.imshow(your_image, aspect='normal')
fig.savefig(fname, dpi)

rawDescription: scipy: savefig without frames, axes, only content

description: Scipy: savefig without frames, axes, only content


code:
from collections import Counter
List = ['s', 'b' , 's', 'd', 'h', 'a', 'h', 'e', 'h', 'a']
pair_counts = Counter(zip(List, List[1:]))
pair_counts.most_common()
pair_counts.most_common(1)

rawDescription: Find the letters in a python list that follow each other most frequently


code:
api_tok = 'api_token=e27e901c196b8f0399bc79'
scanjob = requests.get('http://10.0.0.127:4242/scanjob/1?%s'  % api_tok)

rawDescription: Using Python Variables in one Instance

description: Using Python Variables in one Instance


rawDescription: Spark: Use same OneHotEncoder on multiple dataframes


code:
sql_statements = {
    'select': {'select', '*', 'from', 'where', 'and'},
    'delete': {'delete', 'from', 'where', 'and'},
    'update': {'update', 'index', 'set', 'where', 'and'},
    'insert': {'insert', 'into', 'source'},
}

rawDescription: Python list is not being appended to if value found in another list


rawDescription: Compare & manipulate strings with python


code: sorted(example, key=lambda x: (-x[1], x[0]))

rawDescription: How to sort list depending on values in sublists?

description: Sort list depending on values in sublists


rawDescription: Python can i access a class method from another class without passing it as a parameter?


code:
total_rect = pygame.rect.Rect(0, 0, total_level_width, total_level_height)

ship = Ship(total_rect)

rawDescription: Adding scrolling to a top/down shooter

description: Adding scrolling to a top/down shooter


code:
with open("file.txt", "r") as file:
    lines = file.readlines()

rawDescription: Python: How to 'write' on the second line of a text file ignoring the first line


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977)

# Generate some data with different ranges
x = np.linspace(0, 8.8, 1000)
ydata = np.random.normal(0, 1, (4, x.size)).cumsum(axis=1)
ydata *= np.array([1e-3, 1e3, 10, 1e-2])[:,None]

fig, axes = plt.subplots(nrows=4)
for y, ax in zip(ydata, axes):
    ax.plot(x, y, color='salmon')
plt.show()

rawDescription: Python Numpy 2D plot set total number of y-tics with autoscaling


rawDescription: Pandas/matplotlib bar chart with colors defined by column


code:
from paste.httpserver import serve
from pyramid.response import Response
from pyramid.view import view_config

@view_config()
def hello(request):
    return Response('Hello')

if __name__ == '__main__':
    from pyramid.config import Configurator
    config = Configurator()
    config.scan()
    app = config.make_wsgi_app()

    # Put middleware
    app = LoggerMiddleware(app)

    serve(app, host='0.0.0.0')

rawDescription: How do I write a logging middleware for pyramid/pylons 2?

description: Write a logging middleware for pyramid/pylons 2


code:
if created_at.tzinfo is None:
    created_at = utc.localize(created_at)
return created_at

rawDescription: How do I handle "out of range" warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy

description: Handle "out of range" warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy


rawDescription: Convert/Reshape 3D Matrix to a 2D Matrix


code:
import turtle
def draw_sierpinski(length,depth):
    if depth==0:
        for i in range(0,3):
            t.fd(length)
            t.left(120)
    else:
        draw_sierpinski(length/2,depth-1)
        t.fd(length/2)
        draw_sierpinski(length/2,depth-1)
        t.bk(length/2)
        t.left(60)
        t.fd(length/2)
        t.right(60)
        draw_sierpinski(length/2,depth-1)

window = turtle.Screen()
t = turtle.Turtle()
draw_sierpinski(500,1)
window.exitonclick()

rawDescription: Sierpinski triangle recursion with python using turtle


code:
import pandas as pd

# read in a fixed-width file
df = pd.read_fwf("crime.tsv", widths=[14] + [10]*8, header=None)
# clean up the strings
df = df.applymap(lambda x: x.strip() if isinstance(x, basestring) else x)

# make a new column
df["County"] = None
# move over the county information
df["County"][df[5] == "COUNTY"] = df[6]
# fill the county info forwards into the empty places
df["County"].fillna(method='ffill', inplace=True)

# fill the crime information forwards
df[0].fillna(method='ffill', inplace=True)

# reset the columns from one of the examples
df.columns = ["Crime"] + list(df.ix[3,1:-1]) + ["County"]
# get rid of any of the headings left in the table
df = df[~(df["Gender"] == "Gender")]

# toss anything which still has empty cells
df = df.dropna()

# reset the index, and fix the types
df = df.set_index(["Crime", "Gender", "County"]).astype(int)
df = df.reset_index()

rawDescription: copy and paste part of the tab-type data to create new document

description: Copy and paste part of the tab-type data to create new document


rawDescription: Mapping Odd/Even to nested lists

description: Mapping Odd/Even to nested lists


code:
def foo(indict: dict(apple=None, pear=None, extra_items=...)) -> int:
    if any(x not in indict for x in ('apple', 'pear')):
        raise ValueError('message here...')
    print(indict)
    return 3

foo({})
foo({'apple':6, 'pear':4})
foo({'apple':6, 'pear':4, 'carrot':30000})

rawDescription: Dictionary with some mandatory keys as function input


code:
for line in text:
    array= line.strip().split(",")
    print(array[6][0:5])
    if int(array[6][0:5]) in KFCFzip:
        print("yes")

rawDescription: Python: Not finding value in list that should be there


code:
import random

import tkinter as tk

# --- constants --- # UPPERCASE name

RES_X = 800
RES_Y = 600

# --- classes --- # CamelCase name

class Enemy(object):
    '''single enemy'''

    def __init__(self, canvas):

        # access to canvas
        self.canvas = canvas

        self.radius = 12.5 # random

        self.color = random.choice( ('black', 'red', 'green', 'blue', 'yellow') )

        self.x = random.uniform(self.radius, RES_X-self.radius)
        self.y = random.uniform(self.radius, RES_Y-self.radius)

        self.x1 = self.x-self.radius
        self.y1 = self.y-self.radius

        self.x2 = self.x+self.radius
        self.y2 = self.y+self.radius

        self.oval = self.canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill=self.color, outline=self.color)

        self.moving = True

        self.start()

    def start(self):
        '''start moving'''

        self.moving = True

        # move this enemy after random time
        random_time = random.randint(150, 3000)
        root.after(random_time, self.move)

    def stop(self):
        '''stop moving'''

        self.moving = False

    def move(self):

        if self.moving: # to stop root.after

            direction = random.randint(1,4)

            if direction == 1: # up
                self.y -= self.radius
                self.y1 -= self.radius
                self.y2 -= self.radius
            elif direction == 2: # down
                self.y += self.radius
                self.y1 += self.radius
                self.y2 += self.radius
            elif direction == 3: # left
                self.x -= self.radius
                self.x1 -= self.radius
                self.x2 -= self.radius
            elif direction == 4: # right
                self.x += self.radius
                self.x1 += self.radius
                self.x2 += self.radius

            self.canvas.coords(self.oval, self.x1, self.y1, self.x2, self.y2)
            # move this enemy after random time
            random_time = random.randint(150, 3000)
            root.after(random_time, self.move)

# --- functions --- # lower_case name

def add_new_enemy():

    enemies.append(Enemy(canvas))

    # add next enemy after random time
    timer = random.randint(150, 3000)
    root.after(random_time, add_new_enemy)

# --- main ---

root = tk.Tk()
root.title("")

canvas = tk.Canvas(root, width=RES_X, height=RES_Y, bg="white")
canvas.pack()

# 5 enemies at the beginning
enemies = list()

for _ in range(5):
    enemies.append(Enemy(canvas))

# add new enemy after random time
random_time = random.randint(150, 3000)
root.after(random_time, add_new_enemy)

root.mainloop()

rawDescription: appending code to create multiple random moving sprites - python tkinter

description: Appending code to create multiple random moving sprites - python tkinter


code:
import inspect

class Foo(object):
    pass

if inspect.isclass(Foo):
   print("Yep, it's class")

rawDescription: How to check if module attribute is a Class

description: Check if module attribute is a Class


code:
import itertools

def union(it1, it2):
    return (item for pair in itertools.izip(it1, it2) for item in pair)

rawDescription: Union of two iterators

description: Union of two iterators


code: pd.read_csv("toolong.csv", converters={"b": lambda x: x[:5]})

rawDescription: Truncating column width in pandas

description: Truncating column width in pandas


code:
from collections import Counter
fruits = ["orange", "orange", "mango", "mango", "orange", "orange", "banana", "mango", "banana"]
[fruit for fruit, count in Counter(fruits).most_common(2)]

rawDescription: comparing two lists and finding most preferred pairs

description: Comparing two lists and finding most preferred pairs


code: print('"')

rawDescription: Python print " character

description: Python print " character


code:
with open(...) as f:
    instance.inorder(f)

rawDescription: Writing traversals to a file in python3.x issue


code:
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()

rawDescription: Django Staticfiles not being served on Azure


rawDescription: Subtracting seconds from int with no formatting


rawDescription: How to hide a Widget when the program starts in PyQt?

description: Hide a Widget when the program starts in PyQt


code:
BtnName = Tkinter.Button (RegBox, text="Back", command=back)
BtnName.pack()

rawDescription: Register username and password

description: Register username and password


code:
new_dir = "path/to/dir/"
for file1, file2 in zip(files_in_folder_1, files_in_folder_2):
    with open(file1) as f1, open(file2) as f2:
        dftask = pd.read_csv(file2)
        dfresource = pd.read_csv(file1)

    dftask.to_csv(os.path.join(new_dir, file2.name))
    dfresource.to_csv(os.path.join(new_dir,file1.name))

rawDescription: Different file name when saving in loop python/pandas


code:
tuple((str(color), str(color)) for color, in colors)
tuple((color.encode(), color.encode()) for color, in colors)

rawDescription: Two Column Data Structure - Python

description: Two Column Data Structure - Python


rawDescription: converters option in numpy genfromtxt not accepting -ve indexing of columns

description: Converters option in numpy genfromtxt not accepting -ve indexing of columns


code:
username = raw_input('Please enter your name: ')
print('Your name is: {}'.format(username))

rawDescription: I Don't Know What is argv and what's diffrent with raw_input()?


code: self.btn_a1 = Button(Form)

rawDescription: Custom button PyQT4

description: Custom button PyQT4


code:
from fractions import Fraction
summed = sum((2, 1, Fraction(3, 4), Fraction(2, 3)))
whole = int(summed)
remainder = summed - whole
'{} and {}'.format(whole, remainder)

rawDescription: adding fractions class python

description: Adding fractions class python


code:
im = plt.imshow(Z, cmap='hot')
plt.colorbar(im, orientation='horizontal')
plt.show()

rawDescription: matplotlib - 3d surface from a rectangular array of heights

description: Matplotlib - 3d surface from a rectangular array of heights


rawDescription: Python Looping Entire Dictionary

description: Python Looping Entire Dictionary


code: found = (i for i in array1 if i in array2)

rawDescription: Python intersection of two lists keeping duplicates


code:
try:
    import argparse
    parser = argparse.ArgumentParser()
    for arg in args:
        parser.add_argument(*arg['args'], **arg['kwargs'])
except:
    import optparse
    parser = optparse.OptionParser()
    for arg in args:
        parser.add_option(*arg['args'], **arg['kwargs'])

rawDescription: Python: how to write code that looks nicely and works with argparse or optparse?


code:
import itertools as IT
import multiprocessing as mp

q = mp.Queue()
for i in range(22):
    q.put(i)
q.put("END")

iterator = iter(q.get, 'END')
for chunk in iter(lambda: list(IT.islice(iterator, 10)), []):
    print(chunk)

rawDescription: How to get chunks of elements from a queue?

description: Get chunks of elements from a queue


code:
from enum import IntEnum
import re

class AutoNumber(IntEnum):
    def __new__(cls, *args):
        numberList = re.findall(r'\d+', str(cls._member_map_))
        if len(cls.__members__) > 0 and not args:
            prevMax = max(map(int, numberList))
            value = prevMax + 1
            print(format(value, '#04x'))
        else:
            value = args[0]
            print(format(value, '#04x'))

        integer = int.__new__(cls)
        integer._value_ = value
        return integer

class EnumClass(AutoNumber):
   NONE = 0
   HEARTBEAT = () # 0x1
   FLUID_TRANSFER_REQUEST = ()
   # ...

   # Camera App Messages
   START_SENDING_PICTURES = 0x010000
   STOP_SENDING_PICTURES = ()
   START_RECORDING_VIDEO_REQ = ()
   # ...

   # Sensor Calibration
   VOLUME_REQUEST = 0x020000
   START_CAL = ()
   # ...

   # File Mananger
   NEW_DELIVERY_REQ = 0x30000
   GET_DELIVERY_FILE_REQ = ()
   GET_FILE_REQ = ()
   # ...

rawDescription: Creating C like Enum in Python

description: Creating C like Enum in Python


code:
username : james
nodelist : [('localhost', 27017)]
database : test
connection : None
password : brewer
options : {}

rawDescription: Pymongo MongoClient: if you put a database in via URI, how do you get it back out?


rawDescription: Sklearn SVM: SVR and SVC, getting the same prediction for every input


code: client = RBClient('server_url')

rawDescription: How can I disable SSL verification with Reviewboards Python API?

description: Disable SSL verification with Reviewboards Python API


code:
class GroupedAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        group,dest = self.dest.split('.',2)
        groupspace = getattr(namespace, group, argparse.Namespace())
        setattr(groupspace, dest, values)
        setattr(namespace, group, groupspace)

rawDescription: argparse subcommands with nested namespaces

description: Argparse subcommands with nested namespaces