code:
email_pattern = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
str = "Name <emailaddress@example.com>"
str2 = "Another email emailexample@domain.com"
lst = ["email1@example.com", "email2@yahoo.com", "email3@mail.com", "emailaddress@example.com"]
import re
set(re.findall(email_pattern, str)).intersection(lst)
set(re.findall(email_pattern, str2)).intersection(lst)

rawDescription: How to search string members of a list in another string in Python 2

description: Search string members of a list in another string in Python 2


code:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

tdata = np.linspace(0, 10)
timeSeries = np.sin(tdata) + .4*np.random.random(tdata.shape)

def createSinFromFit(x, freq, amplitude, phase, offset):
    return np.sin(x * freq + phase) * amplitude + offset

def sinRegr(tdata, series):
    tfit = np.linspace(0, 6*np.pi, len(series))
    guess_freq = .2
    guess_amplitude = 3*np.std(series)/(2**0.5)
    guess_phase = 0
    guess_offset = np.mean(series)
    p0=[guess_freq, guess_amplitude, guess_phase, guess_offset]
    fit = curve_fit(createSinFromFit, tdata, series, p0=p0)   # use tdata to create the fit
    results = createSinFromFit(tfit,*fit[0])                  # use tfit to generate a new curve
    return tfit, results

tfit, plotThis = sinRegr(tdata, timeSeries)

plt.plot(tfit, plotThis)
plt.plot(tdata, timeSeries, "ro")
plt.show()

rawDescription: predicting values given a sinusouidal fit

description: Predicting values given a sinusouidal fit


code:
import numpy as np
b = np.array([[2,3,4,5], [7,6,8,10]])
indices = np.array([2, 3])
b[np.arange(len(indices)), indices]

rawDescription: Vectorised code for selecting elements of a 2D array


code: max(list, key=len)

rawDescription: How to get max lengthed item of item in list

description: Get max lengthed item of item in list


code: [(i,j) for i,j in ((a-1,b), (a+1,b), (a,b-1), (a,b+1)) if 0<=i<MAXX and 0<=j<MAXy and X[i][j] is not None ]

rawDescription: Creating a list comprehension to find orthogonal neighbours in 2D list


code:
blacklist = set(['thumbnails', 'quraan', 'cache'])

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        if line.strip() in blacklist: continue  # if you want to match the full line
        # if any(word in line for word in blacklist): continue  # if you want to check if a word exists on a line
        outfile.write(line)

rawDescription: how to copy content of file to another file with deleting some lines in a TXT file based on some strings with python

description: Copy content of file to another file with deleting some lines in a TXT file based on some strings with python


code:
def __del__(self):
    self.conn.close()

rawDescription: Unable to close a stream opened with pycurl


code: os.path.join("/whatever", "/else")

rawDescription: Unable to save InMemoryUploadedFile to model in Django


code:
from operator import itemgetter
L = ['ABC', 'DEF', 'GHIJ']
map(itemgetter(0), L)

rawDescription: Python: function that gets n-th element of a list


code:
import csv
import string

results = []
mappings = [
             [(string.ascii_uppercase[i-2], i) for i in range(2, 7)],
             [(string.ascii_uppercase[i-2], i) for i in range(7, 10)]]

with open(input_file, 'rU') as control_file:
    reader = csv.DictReader(control_file)
    for row in reader:
        row_data = {}
        row_data['key1'] = row['key1']
        row_data['key2'] = row['key2']
        row_data['key3'] = {k:row[v] for k,v in mappings[0]}
        row_data['key4'] = {k:row[v] for k,v in mappings[1]}
        results.append(row_data)

rawDescription: More pythonic way of iteratively assigning csv rows to dictionary values?


code:
import sqlite3
conn = sqlite3.connect('/tmp/test.db')
cur = conn.cursor()
cur.execute('CREATE TABLE foo (a text, b text)')
strA = "069-888888"
strB = "069777777"
cur.execute('INSERT INTO foo (a,b) values (?,?)', (strA, strB))
cur.execute('select * from foo;')
cur.fetchall()

rawDescription: Python sqlite3: force to bind a parameter as string?


code:
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

rawDescription: Is it possible to detect if a file has been moved in Python?


code:
import cherrypy

class HelloWorld(object):
    @cherrypy.expose
    def default(self, *args, **kwargs):
        return "Hello world!" + cherrypy.url()

cherrypy.quickstart(HelloWorld())

rawDescription: How to get name of a required page in CherryPy?

description: Get name of a required page in CherryPy


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.view = View(self)
        self.button = QtGui.QPushButton('Clear View', self)
        self.button.clicked.connect(self.handleClearView)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        layout.addWidget(self.button)

    def handleClearView(self):
        self.view.scene().clear()

class View(QtGui.QGraphicsView):
    def __init__(self, parent):
        QtGui.QGraphicsView.__init__(self, parent)
        self.setScene(QtGui.QGraphicsScene(self))
        self.setSceneRect(QtCore.QRectF(self.viewport().rect()))

    def mousePressEvent(self, event):
        self._start = event.pos()

    def mouseReleaseEvent(self, event):
        start = QtCore.QPointF(self.mapToScene(self._start))
        end = QtCore.QPointF(self.mapToScene(event.pos()))
        self.scene().addItem(
            QtGui.QGraphicsLineItem(QtCore.QLineF(start, end)))
        for point in (start, end):
            text = self.scene().addSimpleText(
                '(%d, %d)' % (point.x(), point.y()))
            text.setBrush(QtCore.Qt.red)
            text.setPos(point)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: Drawing a line consisting of multiple points using PyQt


rawDescription: how to select column values to display in pandas groupby

description: Select column values to display in pandas groupby


rawDescription: How to use win32 extensions from network location for python

description: Use win32 extensions from network location for python


code: flaskapp.run(host='0.0.0.0', debug=True, static_files={'/static': '/path/to/static'})

rawDescription: Flask development server with X-Sendfile


code:
def execute(access):
  return access.getTree(SystemTree.Geographic).resolve(path).getDisplayName()

name = connection.runReadAction(readActionResult=execute)

rawDescription: Jython equivalent of Java Code

description: Jython equivalent of Java Code


code:
import unittest
import mock

def check():
    return test()
def test():
    return "test"

class CheckTest(unittest.TestCase):
    @mock.patch('__main__.test')
    def test_test(self, mocked):
        mocked.return_value = "mocked"
        self.assertEqual(check(), "mocked")

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

rawDescription: Mocking a function using unittest

description: Mocking a function using unittest


code:
v = fd.values()
v.sort()
count = sum(v[-10:])

rawDescription: Sum up the number of words frequency using FreqDist, python


code:
import pexpect
import time,sys
telconn = pexpect.spawn('telnet 192.168.100.85')
time.sleep(20)
telconn.logfile = sys.stdout
telconn.expect(":")
time.sleep(20)
telconn.send("usr" + "\r")
telconn.expect(":")
telconn.send("Pass@123" + "\r")
telconn.send("\r\n")
time.sleep(20)
telconn.expect(">")

rawDescription: Python:Telnet password is not taking via script using pexpect


code: m.imshow(im, extent=extent, alpha=0.6)

rawDescription: how to display a image over a map with imshow?

description: Display a image over a map with imshow


code:
import datetime
df = pd.read_csv('your_csv.csv')
df.time = pd.Series([datetime.time(0, int(val[:2]), int(val[3:5]), int(val[6:])*100000)
                     for val in df.time], index = df.index)

rawDescription: Pandas read_csv reading time offset strings


code:
import logging
logger = logging.getLogger('weasyprint')
logger.handlers = []  # Remove the default stderr handler
logger.addHandler(logging.FileHandler('/path/to/weasyprint.log'))

rawDescription: Silent WeasyPrint script run

description: Silent WeasyPrint script run


code:
encoded = pd.get_dummies(pd.concat([train,test], axis=0))
train_rows = train.shape[0]
train_encoded = encoded.iloc[:train_rows, :]
test_encoded = encoded.iloc[train_rows:, :]

rawDescription: Problems with a binary one-hot (one-of-K) coding in python


code:
graphical_test = unittest.skipIf(
    os.environ.get('GRAPHICAL_TESTS', False), 'Non graphical tests only'
)

rawDescription: How to skip python unittest with a global parameter

description: Skip python unittest with a global parameter


code:
if a > 1:
    params = dict(module_path=a, playbook=b)
elif b < 1:
    params = dict(playbook=b)
else:
    params = dict(host_list=c, playbook="playbook")

PlayBook(**params) # ** for keyword arguments

rawDescription: How to pass named parameters to function after if Statements?

description: Pass named parameters to function after if Statements


code:
class MyRequestHandler(webapp.RequestHandler):
    def get(self, page):
        self.response.headers['Content-Type'] = 'text/plain'
        if not page:
            self.response.out.write('Hello, webapp World!')
        else:
            self.response.out.write('page is ' + page)

url_map = [('/(\d+)', MyRequestHandler)]
application = webapp.WSGIApplication(url_map, debug=True)

rawDescription: Google appengine rewrite question

description: Google appengine rewrite question


code:
def getHome():
  if hasattr(sys, "frozen"):
    if sys.platform == "darwin": # OS X
      return os.path.join(os.path.dirname(os.path.dirname(sys.executable)), "Resources")
    return os.path.dirname(sys.executable)
  else:
    return os.path.dirname(__file__)

rawDescription: accessing files after setup.py install

description: Accessing files after setup.py install


code: bytes([initialValue])*width

rawDescription: Most pythonic way to create bytes() of size N with non-zero initial value?


code:
with lock:
    numpyArray[:,0] = 1
    a += 2

rawDescription: Is it possible to lock a columnor row of a ctypes array using get_lock() using numpy?


code:
for row in file1:

    ...

    for key in key_words:
        if key in row:
            writer.writerow([key, row])
    if not any(key in row for key in key_words):
        writer2.writerow([row])

rawDescription: Comparing two csv files in Python

description: Comparing two csv files in Python


code:
def main():
    done = False
    while not done:
        limit = ask_limit()
        speed = ask_speed()
        findfine(speed, limit)

        done = raw_input("Done? ") == "yes"

rawDescription: Speeding Ticket Fine Calulation

description: Speeding Ticket Fine Calulation


code:
def normal():
    four_digit = str(four_digit_number)
    while True: # Data Validation
        try:
            guess = str(int(input("Please enter your guess: ")))
            assert len(guess) == 4
        except (ValueError, AssertionError):
            print("Please enter a 4 digit number as your guess not a word or a different digit number")
        else:
            break
    correct = sum(a == b for a, b in zip(four_digit, guess))
    if correct == 4:
        print("You got the number correct!")
    else:
        print("You got " + str(correct) + " digits correct")

rawDescription: IndexError: string index out of range, the index is in the range


code:
def delete(node, inheritLeft=True):
    child = node.left if inheritLeft else node.right
    node.value = child.value
    node.left = child.left
    node.right = child.right

rawDescription: Delete a root from a tree in python

description: Delete a root from a tree in python


code:
import os
from bs4 import BeautifulSoup

def clean_up_folder(dir):
    for root, dirs, files in os.walk(dir):
        for f in files:
            clean_up_file(os.path.join(root, f))

def clean_up_file(original_file):
    with open(original_file) as orig_f2:
        soup = BeautifulSoup(orig_f2.read())

    title = soup.new_tag('title')
    td = soup.find('td', class_='title')
    if td is not None and td.string is not None:
        title.string = td.string

    head = soup.find('head')
    if head is not None:
        head.append(title)

    with open(original_file, 'w') as orig_f:
        if soup.original_encoding is not None:
            orig_f.write(soup.prettify().encode(soup.original_encoding))

clean_up_folder('Test')

rawDescription: How can I duplicate an element in Beautiful Soup?

description: Duplicate an element in Beautiful Soup


code:
p = Process(target=graphic, args=())
p1 = Process(target=connect, args=())

rawDescription: How to run different child process independently in python?

description: Run different child process independently in python


code:
A_decorated = decorator(A)

def C():
    # some code
    A_decorated()
    # some code

rawDescription: Can we apply python decorator at function invoke?


rawDescription: permanently replace values in a list using Python

description: Permanently replace values in a list using Python


code:
import pygtk
import gtk
import gobject

def window_delete_event(*args):
	return False

def window_destroy(*args):
	gtk.main_quit()

if __name__ == '__main__':
	win = gtk.Window()

	# combo's model
	model = gtk.ListStore(gobject.TYPE_STRING)
	for n in xrange(100):
		model.append([str(n)])

	# combo
	combo = gtk.ComboBoxEntry(model)
	win.add(combo)

	# combo's style
	style = gtk.rc_parse_string('''
		style "my-style" { GtkComboBox::appears-as-list = 1 }
		widget "*.mycombo" style "my-style"
	''')
	combo.set_name('mycombo')
	combo.set_style(style)

	win.show_all()
	win.connect('delete-event', window_delete_event)
	win.connect('destroy', window_destroy)
	gtk.main()

rawDescription: How do I put a scrollbar inside of a gtk.ComboBoxEntry?

description: Put a scrollbar inside of a gtk.ComboBoxEntry


code:
import os

modules = {
    'EGO_sgn': 'EgoMotion',
    'FSD_sgn': 'FreeSpace',
    'CAL_sgn': 'Calibration',
}

path_to_csv = os.path.join("path", "to", "your", "csv", "directory")
founded_files = []
key_file = None

def is_modules_in_filename(filename):
    for module_key, module_value in modules.items():
        if module_key in filename:
            return "key"
        if module_value in filename:
            return "value"

    return False

for f in os.listdir(path_to_csv):
    if not f.endswith(".csv"):
        continue

    filename = os.path.splitext(f)
    in_modules = is_modules_in_filename(filename[0])
    filename_with_path = os.path.join(path_to_csv, f)

    if in_modules == "key":
        key_file = filename_with_path

    if in_modules == "value":
        founded_files.append(filename_with_path)

print(key_file)
print(founded_files)

rawDescription: Find all csv files in the directory and add found file to the proper list by its name


code:
from setuptools import setup
setup(
    name='one-file',
    version='1.0',
    py_modules=['one_file'],
    entry_points={'console_scripts': ['one-file = one_file:main']}
)

rawDescription: What's the minimal directory structure to make setuptools work with one_file.py?


code:
from collections import OrderedDict
x= [('a',1),('b', 2)]
x_1 = OrderedDict(x)
for key in x_1:
    print(key)

rawDescription: Tuples into a dictionary

description: Tuples into a dictionary


code:
message = 'HelloWorld'
encoded = ''.join(chr(ord(letter) - 3) for letter in message)
decoded = ''.join(chr(ord(letter) + 3) for letter in encoded)

rawDescription: A Simple Message Decoder

description: A Simple Message Decoder


rawDescription: Pandas read_sql function produces binary column names


code:
# create all threads
ts = [MyThread(i) for i in range(10)]

# start all threads
for t in ts:
    t.start()

# wait for all threads
for t in ts:
    t.join()

rawDescription: How I can execute code pararelly or multithread


code:
import csv
import json
import time
import urllib2

PAGE_DELAY = 5.    # time between loading pages
PAGE_LOAD  = 0.3   # how long it takes to load a page
INFILE     = 'outputrows2.csv'
OUTFILE    = 'step3_desired_output.txt'

make_url = 'http://www.imdb.com/title/tt{}/'.format

def get_csv_column(csv_fname, col, **kwargs):
    with open(csv_fname, 'rb') as inf:
        incsv = csv.reader(inf, **kwargs)
        column = [row[col] for row in incsv]
    return column

def get_data_by_id(id):
    url = make_url(id)
    return urllib2.urlopen(url).read()

def delayed(delay, fn, *args):
    time.sleep(delay)
    return fn(*args)

def human_time(seconds):
    if seconds >= 86400:
        return '{:0.1f} days'.format(seconds / 86400.)
    elif seconds >= 3600:
        return '{:0.1f} hours'.format(seconds / 3600.)
    elif seconds >= 60:
        return '{:0.1f} minutes'.format(minutes / 60.)
    else:
        return '{:0.1f} seconds'.format(seconds)

def main():
    ids = get_csv_column(INFILE, 0)

    expected = (PAGE_DELAY + PAGE_LOAD) * len(ids)
    print('This will take about {}.'.format(human_time(expected)))

    results = (delayed(PAGE_DELAY, get_data_by_id, id) for id in ids)
    with open(OUTFILE, 'w') as outf:
        for res in results:
            outf.write(res)

if __name__=="__main__":
    main()

rawDescription: pulling data from a 'created' url

description: Pulling data from a 'created' url


rawDescription: Concatenating a list of xml strings into a single xml file using Python


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'),
                  index=pd.Series([2,5], name='b'))
print(df)
#    a  b  c
# b
# 2  1  2  3
# 5  4  5  6
print(np.where(df.index==5)[0])
# [1]
print(np.where(df['c']==6)[0])
# [1]

rawDescription: Getting the integer index of a Pandas DataFrame row fulfilling a condition?


code: a.transpose(1, 2, 0).ravel()

rawDescription: Ravel() 3D array in a peculiar order - Python


code:
def SD(numLists):
    def singleSD(numList):
      cntN=len(numList)
      sumN=0
      for i in numList:
          sumN+=i
      avgVal=float(sumN)/float(cntN)
      sumVar=0.0
      for i in range(cntN):
          sumVar+=float((numList[i]-avgVal)**2)
      return ((float(sumVar)/float((cntN-1)))**0.5)
    return [singleSD(l) for l in numLists]

rawDescription: finding the standard deviation of each list in a list of lists

description: Finding the standard deviation of each list in a list of lists


code:
__author__ = 'shivendra'
from flask import Flask, make_response, request
import io
import csv

app = Flask(__name__)

def transform(text_file_contents):
    return text_file_contents.replace("=", ",")

@app.route('/')
def form():
    return """

Transform a file demo

                <form action="/transform" method="post" enctype="multipart/form-data">
                    <input type="file" name="data_file" />
                    <input type="submit" />
                </form>

    """

@app.route('/transform', methods=["POST"])
def transform_view():
    f = request.files['data_file']
    if not f:
        return "No file"

    stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
    csv_input = csv.reader(stream)
    #print("file contents: ", file_contents)
    #print(type(file_contents))
    print(csv_input)
    for row in csv_input:
        print(row)

    stream.seek(0)
    result = transform(stream.read())

    response = make_response(result)
    response.headers["Content-Disposition"] = "attachment; filename=result.csv"
    return response

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)

rawDescription: Not able to parse a .csv file uploaded using Flask


code:
g = df.groupby(['person', 'classes', ..., 'varY', 'states'])

g.apply(lambda stateData: do_stuff(stateData))

rawDescription: The more elegant way to code an arbritrary number of for imbrication levels


code: pd.concat([df.apply(lambda x: some_function(x, p)) for p in parameters])

rawDescription: Pandas, build new dataframe with for loop


rawDescription: How to get the filesystem of a directory or drive in Python

description: Get the filesystem of a directory or drive in Python


code: ["not " * (1 - x) + y.obj_dict['self'].get_topic() for x,y in zip(comb, self.parents)]

rawDescription: use boolean list as mask

description: Use boolean list as mask


code:
def register(self, model_or_iterable, admin_class=None, **options):
    """
    Registers the given model(s) with the given admin class.

    The model(s) should be Model classes, not instances.

    If an admin class isn't given, it will use ModelAdmin (the default
    admin options). If keyword arguments are given -- e.g., list_display --
    they'll be applied as options to the admin class.

    If a model is already registered, this will raise AlreadyRegistered.

    If a model is abstract, this will raise ImproperlyConfigured.
    """

rawDescription: Why does one need to register both app name and app admin name in Django admin?


code:
@inline_requests
def parse_course(self, response):

    # ...

    for link in grade_links:
        try:
            response = yield Request(link)
        except Exception as e:
            # handle the exception here
            pass
        else:
            # extract the data here
            pass

     # at the end yield the item

rawDescription: Scrapy - merging results from N pages originating from single page


code:
if filepath.lower().startswith(drive.lower() + '/'):
    result = filepath[len(drive)+1:]

rawDescription: How to extract a string from another string wihout changing a characters case

description: Extract a string from another string wihout changing a characters case


code:
frame = bytearray(frame)
for i in range(len(mask)):
    frame[i] ^= mask[i]

rawDescription: Python: 'Unmask' a long XOR'd string of data


code: mydialog.setFixedSize(width, height)

rawDescription: PyQt: Prevent Resize and Maximize in QDialog?


code: re.sub(r'.*I', 'I', stri)

rawDescription: How to remove all characters before a specific character in Python?

description: Remove all characters before a specific character in Python


code:
import os, time

filelist = ['file1','file2','file3']

while True:
    list1 = []

    for file in filelist:
        list1.append(os.path.isfile(file))

    if all(list1):
        # All elements are True. Therefore all the files exist. Run %run commands
        break
    else:
        # At least one element is False. Therefore not all the files exist. Run FTP commands again
        time.sleep(600) # wait 10 minutes before checking again

rawDescription: Checking if a list of files exists before proceeding?


code:
import itertools
d = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], }
for a, b in itertools.combinations(d, 2):
    common = set(d[a]) & set(d[b])
    print('{}&{}: {}'.format(a, b, common))

rawDescription: dictionary operation using python

description: Dictionary operation using python


rawDescription: Python Turtle Graphics Window only Opens Briefly then Closes


code:
import nmap
nm = nmap.PortScanner()

hostlist = ' '.join(nm.all_hosts())
nm.scan(hosts=hostlist, arguments='-n -sP -PE')

rawDescription: Using python nmap module to scan hosts generated from a previous scan


code: total = sum(int(v) for name,v in table)

rawDescription: Finding a sum in nested list using a lambda function


rawDescription: regex groups to find a range

description: Regex groups to find a range


code:
from ggplot import *
my_theme = theme_seaborn()
p = ggplot(aes(x='wt', y='mpg'), data=mtcars) + geom_point()
print(p + my_theme)
p2 = ggplot(aes(x='date', ymin='beef - 1000',
            ymax='beef + 1000'), data=meat) + geom_area()
print(p2 + my_theme)

rawDescription: Where does python ggplot take its default values from


code:
s = '1234ab'
numbers = [int(x) for x in s if x.isdigit()]
total = sum(numbers)
avg = float(total) / len(numbers)
avg

rawDescription: How can I get the avg of a string of numbers without any modules in Python?

description: Get the avg of a string of numbers without any modules in Python


code:
pts = [(1,1), (3,4), (1,8), (7,6)]

def mk_distsq(a):
    def distsq(b):
        return ((b[0]-a[0])**2 + (b[1]-a[1])**2)**0.5
    return distsq

dist = [sorted(pts, key=mk_distsq(pt)) for pt in pts]

rawDescription: Custom sorting in for loop

description: Custom sorting in for loop


code:
import pandas as pd
selectColumns = ['h1','h2','h3']
table = pd.read_csv('test.csv')
tableNew = table[selectColumns]
pd.to_csv('tableNew')

rawDescription: selecting only relevant columns within a file - python

description: Selecting only relevant columns within a file - python


rawDescription: how to change a character by its position in a string python

description: Change a character by its position in a string python


code:
from nltk.corpus import wordnet as wn
vehicle = wn.synset('vehicle.n.01')
typesOfVehicles = list(set([w for s in vehicle.closure(lambda s:s.hyponyms()) for w in s.lemma_names]))

rawDescription: How to get all the hyponyms of a word/synset in python nltk and wordnet?

description: Get all the hyponyms of a word/synset in python nltk and wordnet


code:
import csv

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

rawDescription: Writing a Python list of lists to a csv file


code:
import re
text="www.cool.fr www.ham.edu www.stanford.com www.hack.ru"
print(re.findall(r"\S+\.(?:com|fr)\b",text))
# => ['www.cool.fr', 'www.stanford.com']

rawDescription: python regular expression : match one of listed substrings

description: Python regular expression : match one of listed substrings


code:
nums = newfile.split()
for num in nums:
    sum += int(num)

rawDescription: How to find sum of numbers from a file using a while loop?

description: Find sum of numbers from a file using a while loop


code: hrs, min, sec, msec = (int(group) for group in re.search('(\d+):(\d+):(\d+).(\d+)', current_line).groups())

rawDescription: searching multiple items with Python re

description: Searching multiple items with Python re


code:
s = '20130925'
dt = datetime.datetime.strptime(s, '%Y%m%d')
d = dt.date()
d

rawDescription: Easier way to create date object from string


code:
import requests
url = 'http://10.208.53.89:7778/UploadFiles'
multiple_files = [
   ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
   ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))
]
r = requests.post(url, files=multiple_files)

rawDescription: Uploading a file to Python bottle server without HTML form


code:
def strip_first_col(fname, delimiter=None):
    with open(fname, 'r') as fin:
        for line in fin:
            try:
               yield line.split(delimiter, 1)[1]
            except IndexError:
               continue

data = np.loadtxt(strip_first_col('myfilename'))

rawDescription: Numpy loadtxt skip first column

description: Numpy loadtxt skip first column


rawDescription: How to remove unicode character from a list in Django?

description: Remove unicode character from a list in Django


code:
import itertools
existing_sets = set(frozenset(x) for x in setslist)
new_sets = set(frozenset(x) for x in itertools.combinations(uniquenumbers, 2))
setslist = list(existing_sets | new_sets)

rawDescription: add unique unordered sets to list

description: Add unique unordered sets to list


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

class InteractiveCircle(object):
    def __init__(self):
        self.fig, self.ax = plt.subplots()
        self.ax.axis('equal')

        self.circ = Circle((0.5, 0.5), 0.1)
        self.ax.add_artist(self.circ)
        self.ax.set_title('Click to move the circle')

        self.fig.canvas.mpl_connect('button_press_event', self.on_click)

    def on_click(self, event):
        if event.inaxes is None:
            return
        self.circ.center = event.xdata, event.ydata
        self.fig.canvas.draw()

    def show(self):
        plt.show()

InteractiveCircle().show()

rawDescription: matplotlib: update position of patches (or: set_xy for circles)

description: Matplotlib: update position of patches (or: set_xy for circles)


code:
from chimpy import chimpy

chimp = chimpy.Connection('MAILCHIMP_APIKEY')
chimp.list_subscribe('your_list_id', self.request.GET['email'], {'FIRST': '', 'LAST': ''}, double_optin=False)

rawDescription: Add subscriber to mailchimp with python

description: Add subscriber to mailchimp with python


code:
#define cal_client:
self.cal_client = gdata.calendar.client.CalendarClient(source='Milosz-GCal-1.0')
#initiate calendar service (log in):
self.cal_client.ClientLogin(email, password, self.cal_client.source);
#get url for custom calendar (cal_index):
self.cal_url=self.cal_client.GetOwnCalendarsFeed().entry[self.cal_index].GetAlternateLink().href
#then, to read from the custom calendar:
self.feed=self.cal_client.GetCalendarEventFeed(self.cal_url)
#and to write to custom calendar:
new_event = self.cal_client.InsertEvent(event,self.cal_url)

rawDescription: How to create/list events in calendars other than default using Google's API for Python?

description: Create/list events in calendars other than default using Google's API for Python


code: loopindex[key]

rawDescription: Assign array value to local variable

description: Assign array value to local variable


code:
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Generate some random data
time = mdates.drange(datetime.datetime(2010, 1, 1),
                     datetime.datetime(2011, 1, 1),
                     datetime.timedelta(days=5))
y1 = np.cumsum(np.random.random(time.size) - 0.5)
y2 = np.cumsum(np.random.random(time.size) - 0.5)
y2 = y2 * 20 + 10

# Plot things up...
fig = plt.figure()
host = fig.add_subplot(111)
par = host.twinx()

host.set_ylabel('One Thing')
par.set_ylabel('Another')

line1, = host.plot(time, y1)
line2, = par.plot(time, y2, 'go')
host.legend([line1, line2], ['Item 1', 'Item 2'])

host.xaxis_date()

plt.show()

rawDescription: graphing multiple types of plots (line, scatter, bar etc) in the same window

description: Graphing multiple types of plots (line, scatter, bar etc) in the same window


code: result = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in l)]

rawDescription: python remove duplicate dictionaries from a list

description: Python remove duplicate dictionaries from a list


code:
def is_equal(floats_a, floats_b, precision=1e-15):
    return all((abs(a-b) < precision) for a, b in izip(floats_a, floats_b))

rawDescription: Compare Two Dictionaries - Floating Point


code:
# assuming your filters are stored in a list called all_filters
all_filter_image = zeros(10*28, 30*28)
for filter_num in range(300):
    # calculate start_x and start_y based on the size of your "large filter"
    # and the filter index
    all_filter_image[start_x:start_x + 28, start_y: start_y + 28] = all_filters[filter_num]

rawDescription: Neural network receptive field visualization in python


code:
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyMixin(object):
    id =  Column(Integer, primary_key=True)
    data = Column(String)

class MyModel1(MyMixin, Base):
    __tablename__ = 'models1'

class MyModel2(MyMixin, Base):
    __tablename__ = 'models2'

rawDescription: Flask-SQLAlchemy. Create several tables with all fields identical


code:
with Image(filename='file.pdf', resolution=200) as image:
    image.compression_quality = 99
    image.save(filename='file.jpg')

rawDescription: Improve quality of Wand conversion

description: Improve quality of Wand conversion


code:
linkInstructions = {
  "url1": {
    "title": lambda n: n.find('h4', 'title').text,
    "date": lambda n: n.find('li', 'when').em.text
  },
  "url2": {
    "title": lambda n: n.find('h3', 'title').text,
    "date": lambda n: n.find('li', 'when').strong.text
  }
  # and so forth
}

def parseNode(node, url):
  # let 'node' be the result of BeautifulSoup(html)
  # and 'url' be the url of the site

  result = {}

  for key,func in linkInstructions[url].iteritems():
    result[key] = func(node)

  # would return a dict with the structure {'title': <title>, 'date': <date>}
  return result

rawDescription: Store and reuse BeautifulSoup searches and node traversals


code: animals = {'pets': {'George': 'cat', 'Fred': 'dog'}}

rawDescription: What is a mult-dimensional dictionary?

description: What is a mult-dimensional dictionary


code:
def find_dt():
    x = int(input('enter a positive number: '))

    if x < 0:
        print ('not positive')
    ...

rawDescription: Python def function prints the prompt message when it is defined


code:
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

def plot_point_cov(points, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma ellipse based on the mean and covariance of a point
    "cloud" (points, an Nx2 array).

    Parameters
    ----------
        points : An Nx2 array of the data points.
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    pos = points.mean(axis=0)
    cov = np.cov(points, rowvar=False)
    return plot_cov_ellipse(cov, pos, nstd, ax, **kwargs)

def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma error ellipse based on the specified covariance
    matrix (`cov`). Additional keyword arguments are passed on to the
    ellipse patch artist.

    Parameters
    ----------
        cov : The 2x2 covariance matrix to base the ellipse on
        pos : The location of the center of the ellipse. Expects a 2-element
            sequence of [x0, y0].
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]

    if ax is None:
        ax = plt.gca()

    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))

    # Width and height are "full" widths, not radius
    width, height = 2 * nstd * np.sqrt(vals)
    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)

    ax.add_artist(ellip)
    return ellip

if __name__ == '__main__':
    #-- Example usage -----------------------
    # Generate some random, correlated data
    points = np.random.multivariate_normal(
            mean=(1,1), cov=[[0.4, 9],[9, 10]], size=1000
            )
    # Plot the raw points...
    x, y = points.T
    plt.plot(x, y, 'ro')

    # Plot a transparent 3 standard deviation covariance ellipse
    plot_point_cov(points, nstd=3, alpha=0.5, color='green')

    plt.show()

rawDescription: multidimensional confidence intervals

description: Multidimensional confidence intervals


code:
reps = {'1/2': 'half', '1/4': 'quarter', '3/4': 'three quarters'}
li = ['I own 1/2 bottle', 'Give me 3/4 of the profit']

map(lambda s: ' '.join([reps.get(w,w) for w in s.split()]),li)
Out[6]: ['I own half bottle', 'Give me three quarters of the profit']

#for those who don't like `map`, the list comp version:
[' '.join([reps.get(w,w) for w in sentence.split()]) for sentence in li]
Out[9]: ['I own half bottle', 'Give me three quarters of the profit']

rawDescription: Applying a dictionary of string replacements to a list of strings


code:
x1 = []
x2 = []
x3 = []

for y in range(1, 4):
    x = globals()['x' + str(y)]
    x.append("string")

rawDescription: Python Variable List Name in .Append

description: Python Variable List Name in .Append


code:
def do_some_work():
    plt.pause(3)

rawDescription: How to manipulate figures while a script is running in Python?

description: Manipulate figures while a script is running in Python


code:
COMMENTsRe = re.compile( r"""
                        //   |
                        \n   |
                        /\*  |
                        \*/
                        """, re.X )

def rm_comments( cut ):
  nocomment = 0 # no inside comment
  c = 1 # c-like comments, but nested
  cpp = 2 # c++like comments

  mode = nocomment
  clevel = 0 # nesting level of c-like comments
  matchesidx = []

  # in pure RE we cannot find nestesd structuries
  # so we are just finding all boundires and parse it here
  matches = COMMENTsRe.finditer( str(cut) )
  start = 0
  for i in matches:
    m = i.group()
    if mode == cpp:
      if m == "\n":
        matchesidx.append( ( start, i.end()-1 ) ) # -1 because without \n
        mode = nocomment
    elif mode == c:
      if m == "/*":
        clevel += 1
      if m == "*/":
        clevel -= 1
      if clevel == 0:
        matchesidx.append( ( start, i.end() ) )
        mode = nocomment
    else:
      if m == "//":
        start = i.start()
        mode = cpp
      elif m == "/*":
        start = i.start()
        mode = c
        clevel += 1

  cut.rm_and_save( matchesidx )

rawDescription: Latex fractions to mathML in Python with regex


code:
years = [2012,2013,2011,2014,2015]
sessions = ["AC", "AB"]
periods = ["I", "II", "III"]

from itertools import product

list(product(years, sessions, periods))

rawDescription: Combine Multiple Lists one by one

description: Combine Multiple Lists one by one


rawDescription: Delete first three rows of a dataframe in pandas


code:
# import required to use randint
import random

# holds the last number to be randomly generated
previous_number = None
while True: # infinite loop
    # generates a random number between 1 and 6
    num = random.randint(1, 6)
    # check if the last number was 6 and current number is 6
    if previous_number == 6 and num == 6:
        # if the above is true then break out the loop
        break
    # store the latest number and start the loop again
    previous_number = num

rawDescription: how to tell an infinite loop to end once one number repeats twice in a row (in python 3.4)

description: Tell an infinite loop to end once one number repeats twice in a row (in python 3.4)


rawDescription: printing indexes of vector to names

description: Printing indexes of vector to names


code: parentFolder = models.ForeignKey('self', unique=False, related_name="childrenFolders")

rawDescription: Django models: One to one relationship between objects of the same model class


code:
def login():
    username = raw_input('username: ')

    if username != 'pi':
        # if 'pi' is not entered i want to print out 'restricted'
        return 'restricted'

    # if the correct user name is returned 'pi' I want to be
    # prompted to enter a password .
    password = raw_input('password: ')

    if password == '123':
        # if password is '123' want it to grant access
        # aka ' print out 'welcome'
        return 'welcome'

    if password == 'guest':
        # this is where the second password is , if 'guest'
        # is entered want it to grant access to different
        # program aka print 'welcome guest'
        return 'welcome guest'

    # wrong password. I believe you might want to return some other value

rawDescription: Python: login using 1 username but different passwords


code:
from itertools import izip
value = sum((x * y) for x, y in izip(weights, items))

rawDescription: Python; the most performant way to implement element-wise vector multiplication


rawDescription: Indices of matching elements given two lists of which one has redundant entries


code:
class InstitutionView(ModelView):
    ...

    # _handle_view called every request
    def _handle_view(self, name, **kwargs):
        if not flask_login.current_user.is_authenticated():
            return self.inaccessible_callback(name, **kwargs)

        # re-scaffold views every request
        self._refresh_cache()

        return super(InstitutionView, self)._handle_view(name, **kwargs)

    # _refresh_cache called once when view is added to admin interface
    def _refresh_cache(self):
        # do not _refresh_cache outside of a request context
        if not flask_login.current_user:
            # init members with empty tuples to avoid instantiation error
            self._list_columns = ()
            return
        super(InstitutionView, self)._refresh_cache()

rawDescription: Flask-Admin: Form scaffolding per-request


code:
def get_my_string():
    """Returns the file inputFn"""

    inputFn = "/home/Documents/text.txt"

    try:
        with open(inputFn) as inputFileHandle:
            return inputFileHandle.read()

    except IOError:
        sys.stderr.write( "[myScript] - Error: Could not open %s\n" % (inputFn) )
        sys.exit(-1)

rawDescription: Opening a .txt file in Python

description: Opening a .txt file in Python


code:
from collections import Mapping, Sequence, Set, deque

def count_leaves(nested):
    queue = deque([nested])
    count = 0
    while queue:
        node = queue.popleft()
        if isinstance(node, Mapping):
            queue.extend(node.values())
        elif isinstance(node, (Sequence, Set)) and not isinstance(node, basestring):
            queue.extend(node)
        else:
            count += 1

    return count

rawDescription: Counting JSON leaf nodes

description: Counting JSON leaf nodes


code:
def yielder():
    for i in range(2**100):
        yield i

@task
def report_progress():
    for progress in yielder():
        # set current progress on the task
        report_progress.backend.mark_as_started(
            report_progress.request.id,
            progress=progress)

def view_function(request):
    task_id = request.session['task_id']
    task = AsyncResult(task_id)
    progress = task.info['progress']
    # do something with your current progress

rawDescription: Reporting yielded results of long-running Celery task


code: [('-1' if item not in list_B else item) for item in list_A]

rawDescription: How to improve the following list-to-list look up in Python?

description: Improve the following list-to-list look up in Python


code: np.logical_or(df, vector[:, None])

rawDescription: How do I "or" each column in a DataFrame with a vector?


code:
data = b'''iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAIBJRE
          FUOMvN08ENgCAMheG/TGniEo7iEiZuqTeiUkoLHORK++Ul8ODPZ92XS2ZiADITmwI+sWHwi
          w2BGtYN1jCAZF1GMYDkGfJix3ZK8g57sJywteTFClBbjmAq+ESiGIBEX9nCqgl7sfyxIykt
          7NUUD9rCiupZqAdTu6yhXgzgBtNFSXQ1+FPTAAAAAElFTkSuQmCC'''

import base64
from PIL import Image
from io import BytesIO

im = Image.open(BytesIO(base64.b64decode(data)))
im.save('accept.jpg', 'JPEG')

rawDescription: python: convert base64 encoded png image to jpg

description: Python: convert base64 encoded png image to jpg


code:
for item in mylist:
    dir, filename = os.path.basename(os.path.dirname(item)), os.path.basename(item)
    txt.write(dir + ',' + filename + '\n')

rawDescription: Creating text file from two differerent folders in python


rawDescription: How to print the output of python code in Vim buffer?

description: Print the output of python code in Vim buffer


rawDescription: Python Logging, Not Writing Timestamp to Output File


code:
import oauth2 as oauth
import requests
import time

url = "https://rest.netsuite.com/app/site/hosting/restlet.nl?script=992&deploy=1"
token = oauth.Token(key="080eefeb395df81902e18305540a97b5b3524b251772adf769f06e6f0d9dfde5", secret="451f28d17127a3dd427898c6b75546d30b5bd8c8d7e73e23028c497221196ae2")
consumer = oauth.Consumer(key="504ee7703e1871f22180441563ad9f01f3f18d67ecda580b0fae764ed7c4fd38", secret="b36d202caf62f889fbd8c306e633a5a1105c3767ba8fc15f2c8246c5f11e500c")

http_method = "GET"
realm="ACCT123456"

params = {
    'oauth_version': "1.0",
    'oauth_nonce': oauth.generate_nonce(),
    'oauth_timestamp': str(int(time.time())),
    'oauth_token': token.key,
    'oauth_consumer_key': consumer.key
}

req = oauth.Request(method=http_method, url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
header = req.to_header(realm)
headery = header['Authorization'].encode('ascii', 'ignore')
headerx = {"Authorization": headery, "Content-Type":"application/json"}
print(headerx)
conn = requests.get("https://rest.netsuite.com/app/site/hosting/restlet.nl?script=992&deploy=1",headers=headerx)
print(conn.text)

rawDescription: Looking for example Python code for Netsuite API using OAuth?


code:
myconfig = TransferConfig(

    multipart_threshold=9999999999999999, # workaround for 'disable' auto multipart upload
    max_concurrency=10,
    num_download_attempts=10,
)

connection = boto3.client(service_name='s3',
        region_name='',
        api_version=None,
        use_ssl=True,
        verify=True,
        endpoint_url=url,
        aws_access_key_id=access_key,
        aws_secret_access_key=secret_key,
        aws_session_token=None,
        config=None)
transfer=S3Transfer(connection,myconfig)

transfer.upload_file('/tmp/samplefile.tgz','mybucket','remotefile.tgz')

rawDescription: Boto3 - Disable automatic multipart upload


code:
import math
import sys

def almost_equal(a, b):
    d = a - b
    return math.sqrt(d.real ** 2 + d.imag ** 2) < sys.float_info.epsilon

rawDescription: How to recognize very close complex numbers as equal?

description: Recognize very close complex numbers as equal


code:
mylist = [5,4,9,2,7,'dog']
def list_split(l, element):
    if l[-1] == element:
        return l, []
    delimiter = l.index(element)+1
    return l[:delimiter], l[delimiter:]
list_split(mylist, 4)
list_split(mylist, 2)
list_split(mylist, 'dog')

rawDescription: How to to split a list at a certain value

description: To split a list at a certain value


code:
loader = unittest.TestLoader()
loader.testMethodPrefix = "test_prefix"# default value is "test"

suite1 = loader.discover('Test1', pattern = "Test*.py")
suite2 = loader.discover('Test2', pattern = "Test*.py")
alltests = unittest.TestSuite((suite1, suite2))
unittest.TextTestRunner(verbosity=2).run(alltests)

rawDescription: Specify specific testcases in python unit test TestLoader


code:
dates = rng.to_pydatetime()
print(dates[0])
print(dates[0].strftime('%Y-%m-%d'))

rawDescription: Pandas date_range from DatetimeIndex to Date format


code:
import re

def main():
    with open('INPUT_FILE.txt', 'r') as in_file:
        content = in_file.read()

    new_content = re.sub(
        r'OLD_TEXT_0([1-5])', r'NEW_TEXT_0\1', content, flags=re.MULTILINE
    )

    with open('OUTPUT_FILE.txt', 'w') as out_file:
        out_file.write(new_content)

if __name__ == '__main__':
    main()

rawDescription: How to use a looping operation while performing multiple text replacment using python regex

description: Use a looping operation while performing multiple text replacment using python regex


rawDescription: Replace multiple variable values in string using Python regex


code:
plt = nightlife_ratings_mean.plot(x = 'year', y = 'stars', style = 'o-', title = "Stars for each month and year")
plt.set_xlabel("[Year, Month]")
plt.set_ylabel("Stars")

rawDescription: How to plot after doing a groupby on pandas data frame

description: Plot after doing a groupby on pandas data frame


code:
import sys

def is_kernel():
    if 'IPython' not in sys.modules:
        # IPython hasn't been imported, definitely not
        return False
    from IPython import get_ipython
    # check for `kernel` attribute on the IPython instance
    return getattr(get_ipython(), 'kernel', None) is not None

rawDescription: Determine if we're in an IPython notebook session


code:
import bson

myrow = { att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"}

ref_id = bson.ObjectId()
db.collectionA.insert({att1:myrow['att1'], att2:myrow['att2'], _id:ref_id})
db.collectionB.insert({att3:myrow['att3'], att4:myrow['att4'], ref_id:ref_id})

rawDescription: How to split a row into different collections with each store the _id of the first collection as reference

description: Split a row into different collections with each store the _id of the first collection as reference


code:
# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)

# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)

rawDescription: Accessing Django's SQL Purifier Off-Line


code:
import pandas as pd

df1 = pd.DataFrame({'Languages': ['C++', 'C', 'Java', 'C#', 'Python', 'PHP'],
                    'Uses': ['computing', 'computing', 'application', 'application', 'application', 'web'],
                    'Type': ['Proprietary', 'Proprietary', 'Proprietary', 'Proprietary', 'Open-Source', 'Open-Source']})

df2 = pd.DataFrame({'Languages': ['C++', 'C', 'Java', 'C#', 'Python', 'PHP',
                                 'Perl', 'R', 'Ruby', 'VB.NET', 'Javascript', 'Matlab'],
                    'Uses': ['computing', 'computing', 'application', 'application', 'application', 'web',
                            'application', 'computing', 'web', 'application', 'web', 'computing'],
                    'Type': ['Proprietary', 'Proprietary', 'Proprietary', 'Proprietary', 'Open-Source',
                            'Open-Source', 'Open-Source', 'Open-Source', 'Open-Source', 'Proprietary',
                            'Open-Source', 'Proprietary']})

# OUTER JOIN
mergedf = pd.merge(df1, df2, on=['Languages'], how='outer')
# FILTER OUT LANGUAGES IN SMALLER THAT IS NULL
mergedf = mergedf[pd.isnull(mergedf['Type_x'])][['Languages', 'Uses_y', 'Type_y']]

#     Languages       Uses_y       Type_y
#6         Perl  application  Open-Source
#7            R    computing  Open-Source
#8         Ruby          web  Open-Source
#9       VB.NET  application  Proprietary
#10  Javascript          web  Open-Source
#11      Matlab    computing  Proprietary

# ISIN COMPARISON, RETURNING RECORDS IN LARGER NOT IN SMALLER
unequaldf = df2[~df2.Languages.isin(df1['Languages'])]

#     Languages         Type         Uses
#6         Perl  Open-Source  application
#7            R  Open-Source    computing
#8         Ruby  Open-Source          web
#9       VB.NET  Proprietary  application
#10  Javascript  Open-Source          web
#11      Matlab  Proprietary    computing

# CROSS JOIN
df1['key'] = 1                 # (REQUIRES A JOIN KEY OF SAME VALUE)
df2['key'] = 1
crossjoindf = pd.merge(df1, df2, on=['key'])
# FILTER FOR LANGUAGES IN LARGER NOT IN SMALLER (ALSO USING ISIN)
crossjoindf = crossjoindf[~crossjoindf['Languages_y'].isin(crossjoindf['Languages_x'])]\
                    [['Languages_y', 'Uses_y', 'Type_y']].drop_duplicates()

#   Languages_y       Uses_y       Type_y
#6         Perl  application  Open-Source
#7            R    computing  Open-Source
#8         Ruby          web  Open-Source
#9       VB.NET  application  Proprietary
#10  Javascript          web  Open-Source
#11      Matlab    computing  Proprietary

rawDescription: Inequality joins in Pandas?

description: Inequality joins in Pandas


code:
es = Elasticsearch(['http://localhost:9200/'], verify_certs=True)

if not es.ping():
    raise ValueError("Connection failed")

rawDescription: check elasticsearch connection status in python

description: Check elasticsearch connection status in python


rawDescription: How to configure fabric with SSH key on a Window machine

description: Configure fabric with SSH key on a Window machine


code:
b=Tix.Balloon(master,statusbar=statusbar)
for sub in b.subwidgets_all():
  sub.config(bg='grey')

rawDescription: How to change the background color for tix.Balloon message?

description: Change the background color for tix.Balloon message


code:
def checkTrapTransaction():
    try:
        logUtb(f, 'Checking if Transaction type is trapped, making payment with Transaction type as empty')
        browser.find_by_id('submitBtn').first.click()
        alert = browser.get_alert()
        x = str(alert.text)
        if x == 'Transaction Type is required.':
            logUtb(f, 'Transaction Type input is trapped')
        alert.accept()
        logUtb(f, "")

    except:
        logUtbE(f, "Exception: Please recheck your code")

def checkTrapEmail():
    try:
        logUtb(f, 'Checking if email is a valid email')
        browser.select('tranType','A')
        browser.find_by_id('submitBtn').first.click()
        alert = browser.get_alert()
        x = str(alert.text)
        if x == 'Please enter a valid email address.':
            logUtb(f, 'Proper email format is trapped')

        alert.accept()
        logUtb(f, "")

    except:
        logUtbE(f, "Exception: Please recheck your code")

rawDescription: Using alert.accept() multiple times does not function properly


code:
# To load only columns 1 (time), 19 (velocity x), and 21 (velocity z).
numpy.loadtxt('data.csv', delimiter=',', usecols=(1,19,21))

rawDescription: Is it efficent to use lists for data reading before assigning them to a numpy array?


code:
# urls.py
...
url(r'^dynamic-view/(?P<dynamic_view_url>.*)/$', 'dynamic_view')

# views.py
def dynamic_view(request, dynamic_view_url):
    url_parts = [p for p in dynamic_view_url.split("/") if p]
    if "feedback" in url_parts:
        return _view_for_feedback(request, url_parts)
    elif "news" in url_parts:
        return _view_for_news(request, url_parts)
    else:
        raise Http404

rawDescription: Django dynamic page functionality and url


rawDescription: Replacing an element from list after checking for condition in python: doing it the "pythonic way"


code:
import tarfile

f = open('archive.tar', 'rb')
print (f)
tar = tarfile.open(fileobj=f, mode='r:') # Unpack tar
for item in tar:
    print(item)

rawDescription: python tarfile recursive extract in memory

description: Python tarfile recursive extract in memory


code:
booking[start_date]
booking[start_time]
booking[adults]
booking[children]

rawDescription: Scrapy - Get data in Form

description: Scrapy - Get data in Form


rawDescription: How to parse dates for comparison time range comparison for specific value

description: Parse dates for comparison time range comparison for specific value


rawDescription: Split dictionary of lists into single lists


code:
indices = np.where(m > 0)
index_row, index_col = indices
dist = m[indices]
index_row
index_col
dist

rawDescription: Numpy extract row, column and value from a matrix


code:
def func1():
    pass

def func2():
    pass

switch = {
    "do1": func1,
    "do2": func2,
}

do_str = "do1"
switch[do_str]()

rawDescription: Python Use Switch Case?

description: Python Use Switch Case


code:
from random import choice
from string import digits, ascii_lowercase

chars = digits + ascii_lowercase
L = ["".join([choice(chars) for i in range(2)]) for j in range(100)]
print(L)

rawDescription: Generate a list of random string of fixed length in python


code:
import networkx as nx
import numpy as np
import string

dt = [('len', float)]
A = np.array([(0, 0.3, 0.4, 0.7),
               (0.3, 0, 0.9, 0.2),
               (0.4, 0.9, 0, 0.1),
               (0.7, 0.2, 0.1, 0)
               ])*10
A = A.view(dt)

G = nx.from_numpy_matrix(A)
G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),string.ascii_uppercase)))

G = nx.to_agraph(G)

G.node_attr.update(color="red", style="filled")
G.edge_attr.update(color="blue", width="2.0")

G.draw('/tmp/out.png', format='png', prog='neato')

rawDescription: Drawing a graph or a network from a distance matrix?


code:
directions = dict(
    white={'North':'East','East':'South','South':'West','West':'North'},
    black={'North':'West','West':'South','South':'East','East':'North'},
)

def orientation_and_colour_change(ant_row,ant_col,orientation):
    "Return new orientation, and change grid state as a side effect."
    color = grid[ant_row][ant_col]
    grid[ant_row][ant_col] = 'white' if color == 'black' else 'black'
    return directions[color][orientation]

rawDescription: Function not outputting as desired/expected


rawDescription: URL parsing in Python - normalizing double-slash in paths


code:
def product(i1, i2):
    for a in i1:
        j2, i2 = itertools.tee(i2)
        for b in j2:
            yield (a, b)

rawDescription: itertools product blocks, when using generators as parameters

description: Itertools product blocks, when using generators as parameters


code:
import json
json_string = json.dumps(qdict.dict())

rawDescription: Serialize python dataDict to json object


rawDescription: Equivalent of time.sleep from python in ruby


code:
from operator import itemgetter
lst = [["fileA",7],["fileB",4],["fileC",17],["fileD",15]]
min(lst, key=itemgetter(1))
min(lst, key=itemgetter(1))[0]

rawDescription: Return the smallest element value in a list of lists


code:
import urllib.request as urllib2
result = json.loads(urllib2.urlopen('...').read().decode('utf8'))
with open('example.txt', 'w', encoding='utf8') as f:
    print(result['captions'][0]['content'], file=f)

rawDescription: How to change encoding of a byte object in python 3?

description: Change encoding of a byte object in python 3


code:
def run(server_class=BaseHTTPServer.HTTPServer,
        handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
    server_address = ('0.0.0.0', 12123)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

rawDescription: How to make HTTP server with port not 80 available for network?

description: Make HTTP server with port not 80 available for network


code:
from collections import Iterable

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and any(isinstance(subel, Iterable) for subel in el):
            for sub in flatten(el):
                yield sub
        else:
            yield el

my_list = [[2,3,2,2], [[2,1,2,1], [2,1,1]], [1,1,1]]
print(sum(1 for el in flatten(my_list) if 2 in el))

rawDescription: Python iterate through list and count items of a certain value


rawDescription: How to count Combinations

description: Count Combinations


code:
def main():
    restart_file = config.get('some_section', 'restart_file')
    while True:
        checkReply = Reply()
        checkReply.time_to_reply()
        checkReply.search_db()
        time.sleep(10)
        if os.path.exists(restart_file):
            os.unlink(restart_file)
            if 0 == os.fork():
                os.execl(shlex.split('command to run the updated program'))
            sys.exit('restarting')

rawDescription: Restarting a python program during sleep safely?


code:
import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

rawDescription: Sending string via socket (python)

description: Sending string via socket (python)


code: ':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6)))

rawDescription: Is there any more compact way of writing that statement?


code:
for k,v in request.POST.items():
    if str(k)!="csrfmiddlewaretoken":
        setattr(user, k, v)
    user.save()

rawDescription: In db data is not inserting from django

description: In db data is not inserting from django


code:
def isPrime(n):
    def isSpsp(n, a):
        d, s = n - 1, 0
        while d % 2 == 0: d, s = d / 2, s + 1
        t = pow(a, d, n)
        if t == 1: return True
        while s > 0:
            if t == n - 1: return True
            t, s = (t * t) % n, s - 1
        return False
    ps = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
         43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    if n in ps: return True
    for p in ps:
        if not isSpsp(n, p): return False
    return True

rawDescription: Making my program faster using with compiling


code:
ax.xaxis.set_minor_locator( xLocator )
ax.xaxis.set_minor_formatter( xminorFormatter )

rawDescription: Plotting scientific format on the axis label and different size minor formatter text size


code:
import numpy

# create such a nested array
d = numpy.array([[[1, 2]]])

# test that we can access individual elements
assert d[0, 0, 0] == 1
assert d[0, 0, 1] == 2

rawDescription: Getting element from a certain numpy array returned from OpenCV?


code:
try:
    # Replace 7 with increasing variable if run in loop.
    if min(filter(lambda n: n > 7, arr_x + arr_y)) in arr_y:
        perform_some_action()
except IndexError:
    print('There is no next biggest integer.')

rawDescription: Finding the next biggest integer in two arrays


code:
# ------------------------ Setup work -------------------------------
_,idx1 = np.unique(np.append(A,B),return_inverse=True)
A_ID = idx1[:A.size]
B_ID = idx1[A.size:]

# ------------------------ Union work -------------------------------
# Get length of zc, which would be the max of ID+1.
lenC = idx1.max()+1

# Initialize output array zc and fill with NaNs.
zc1 = np.empty((lenC,3,))
zc1[:]=np.nan

# Fill first column with consecutive numbers starting with 0
zc1[:,0] = range(0,lenC)

# Most important part of the code :
# Set the cols-1,2 at places specified by IDs from A and B respectively
# with values from 0 to the extent of the respective IDs
zc1[A_ID,1] = np.arange(A_ID.size)
zc1[B_ID,2] = np.arange(B_ID.size)

# ------------------------ Intersection work -------------------------------
# Get intersecting indices between A and B
intersect_ID = np.argwhere(A_ID[:,None] == B_ID)

# Initialize output zd based on the number of interesects
lenD = intersect_ID.shape[0]
zd1 = np.empty((lenD,3,))
zd1[:] = np.nan

# Fill first column with consecutive numbers starting with 0
zd1[:,0] = range(0,lenD)
zd1[:,1:] = intersect_ID

rawDescription: Is there a better way to determine cross-mapping indicies for numpy arrays


code:
bashCommand = "sass --watch ./css/main.sass:./css/main.css"
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)

rawDescription: How to Convert SASS on the fly to CSS in Python?


code:
import csv
from itertools import islice
from collections import defaultdict

dd = defaultdict(list)
with open('input') as fin:
    pipe_in = csv.reader(fin, delimiter='|')
    for key, val in islice(pipe_in, 3, None):
        dd[key].append(val)

with open('output', 'wb') as fout:
    pipe_out = csv.writer(fout, delimiter='|')
    pipe_out.writerows([k, ', '.join(v)] for k, v in sorted(dd.iteritems()))

# 1|648
# 2|25, 305, 307, 569
# 3|354, 450, 573
# 4|293, 449
# 5|25, 73

rawDescription: Importing data with multiple IDs

description: Importing data with multiple IDs


code: d = dict((m.get(k, k), v) for (k, v) in d.items())

rawDescription: One-line expression to map dictionary to another


code:
n_max = y.argmax()
plt.plot(x[n_max],y[n_max],'o')
n_min = y.argmin()
plt.plot(x[n_min],y[n_min],'x')

rawDescription: Plot max of graph using python

description: Plot max of graph using python


code:
def press_newgame(self):
    a = tkinter.simpledialog.askinteger('Inputz', 'Enter the gameboard size')
    self.create_grid(a)

rawDescription: How can I call a "command" with tkinter.simpledialog?

description: Call a "command" with tkinter.simpledialog


code:
ax1 = fig.add_subplot(111)

ax1.xlim(-.5,2) # Set it in axis 1 coords

ax1.plot(x1, y1,'b--')
ax2 = ax1.twiny()
ax2.plot(x2, y1, 'go')
ax2.set_xlabel('Temperature')
ax2.invert_xaxis()

ax2.xlim(-2, 3) # Set it in axis 2 coords

rawDescription: How do I manipulate multiple x-axes to correspond to each other, while on different scales?

description: Manipulate multiple x-axes to correspond to each other, while on different scales


code:
class SignalReceiver(QtCore.QObject):
    def __init__(self):
        self.eventLoop = QEventLoop(self)

    @PySide.QtCore.Slot(str)
    def stop_waiting(self, text):
        self.text = text
        eventLoop.exit()

    def wait_for_input(self):
        eventLoop.exec()
        return self.text

class MainWindow(...):
     ...
     def __init__(self):
        ...
        self.helper_signal.connect(self.worker.signalReceiver.stop_waiting)

class WorkerThread(PySide.QtCore.QThread):
    def __init__(self):
        self.signalReceiver = SignalReceiver()
        # After the following call the slots will be executed in the thread
        self.signalReceiver.moveToThread(self)

    def get(self,  *args, **kwargs):
        result = requests.get(*args, **kwargs)
        while result.history:
            ...
            self.result = self.signalReceiver.wait_for_input()

rawDescription: PySide wait for signal from main thread in a worker thread


code:
def Score(guess, solution):
    solution = list(solution)
    c = 0
    for g in guess:
        if g in solution:
            c += 1
            solution.remove(g)

    return c

rawDescription: Number Of Matching Elements In Two Lists


code:
OPTIONS = 0
BALLS = 1

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

def sub(u, v):
    return [ u[i]-v[i] for i in range(len(u)) ]

def dot(u, v):
    return sum(u[i]*v[i] for i in range(len(u)))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

class Ball(object):
    def __init__(self, path):
        self.x, self.y = (0, 0)
        self.img = pygame.image.load('/home/wastl/Documents/DSC_0051.JPG')
        self.speed = 2.5
        self.color = (200, 200, 200)
        self.path = cycle(path)
        self.set_target(next(self.path))
        #self.sound = pygame.mixer.music.load('yeah.mp3')

    @property
    def pos(self):
        return self.x, self.y

# for drawing, we need the position as tuple of ints
# so lets create a helper property
    @property
    def int_pos(self):
        return map(int, self.pos)

    @property
    def target(self):
        return self.t_x, self.t_y

    @property
    def int_target(self):
        return map(int, self.target)

    def next_target(self):
        self.set_target(self.pos)
        self.set_target(next(self.path))

    def set_target(self, pos):
        self.t_x, self.t_y = pos

    def update(self):
    # if we won't move, don't calculate new vectors
        if self.int_pos == self.int_target:
            return self.next_target()

        target_vector = sub(self.target, self.pos)

    # a threshold to stop moving if the distance is to small.
    # it prevents a 'flickering' between two points
        if magnitude(target_vector) < 2:
            return self.next_target()

    # apply the balls's speed to the vector
        move_vector = [c * self.speed for c in normalize(target_vector)]

    # update position
        self.x, self.y = add(self.pos, move_vector)

    def draw(self):
        screen.blit(self.img, self.int_pos)
        #pygame.mixer.music.play()

class Option:

    def __init__(self, text, pos):
        self.hovered = False
        self.text = text
        self.pos = pos
        self.set_rect()
        self.draw()

    def draw(self):
        self.set_rend()
        screen.blit(self.rend, self.rect)

    def set_rend(self):
        self.rend = menu_font.render(self.text, True, self.get_color())

    def get_color(self):
        if self.hovered:
            return (255, 255, 255)
        else:
            return (100, 100, 100)

    def set_rect(self):
        self.set_rend()
        self.rect = self.rend.get_rect()
        self.rect.topleft = self.pos

pygame.init()
quit = False
path = [(26, 43),(105, 110),(45, 225),(145, 295),(266, 211),(178, 134),(250,5),(147,12)]

path2 = [(26, 43),(105, 10),(45, 125),(150, 134),(150, 26),(107, 12)]

ball = Ball(path)

ball.speed = 1.9

ball2 = Ball(path2)

ball2.color = (200, 200, 0)

balls = [ball, ball2]

screen = pygame.display.set_mode((480, 320))

menu_font = pygame.font.Font(None, 40)

options = [Option("NEW GAME", (140, 105)), Option("LOAD GAME", (135, 155)),
       Option("OPTIONS", (145, 205))]

STATE = OPTIONS

while not quit:

    pygame.event.pump()
    screen.fill((0, 0, 0))

    if STATE == OPTIONS:

        for option in options:
            if option.rect.collidepoint(pygame.mouse.get_pos()):
                option.hovered = True
                if pygame.event.get([pygame.MOUSEBUTTONDOWN]) and option.text == "NEW GAME":
                    STATE = BALLS
            else:
                option.hovered = False
            option.draw()
            pygame.display.update()

    elif STATE == BALLS:
        map(Ball.update, balls)

        screen.fill((0, 0, 0))

        map(Ball.draw, balls)

        pygame.display.flip()

    quit = pygame.event.get(pygame.QUIT)
    pygame.event.poll()

    clock.tick(60)

rawDescription: Start event when button is clicked with pygame


code:
from xlrd import *
def main():
    '''This Program reads input (A:clone name, B:sequence, C:elisa) from an
    Excel file and makes a cross comparison of each sequence pair'''
    book = open_workbook("mtask.xlsx")
    Input = book.sheet_by_index(0)

# naming of input data
a = (Input.col_values(0,0))
b = (Input.col_values(1,0))
c = (Input.col_values(2,0))

# make dictionary: keys are seq numbers; values are residues
y = {}
for i in range(Input.nrows):
    x = []
    for j in b[i]:
        x.append(j)
    y[a[i]] = x

# comparison of sequences and extraction of mutations for each sequence pair
List = []
for shit in range(Input.nrows):
    for seq in range(Input.nrows):
        seq12 = []
        z = 0
        for i in y[a[seq]]:
            try:
                for j in y[a[shit]][z]:
                     if i == j:
                         seq12.append(i.lower()+j.lower())
                     else:
                         seq12.append(i+j)
                z = z+1
            except IndexError:
                 print("oops")

        lib = [a[seq],a[shit],c[seq],c[shit]]
        for position, item in enumerate(seq12):
            if item.isupper():
                x = (str(item[0])+str(position+1)+str(item[1]))
                lib.append(x)
        List.append(lib)

# comparison of sequences and extraction of mutations for each sequence pair
dic = {}
for i in range(Input.nrows*Input.nrows):
    x = []
    for j in List[i]:
        x.append(j)
    dic[i] = x

# sort
a = []
for i in dic.values():
    a.append(i)

# collect number of mutations in data files
import csv
null = []
one = []
two = []
three = []
four = []
five = []
six = []
seven = []
eight = []
nine = []
ten = []
for i in range(Input.nrows*Input.nrows):
    if len(a[i]) <= 4:
        null.append(a[i])
        with open("no_mut.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(null)
    elif len(a[i]) == 5:
        one.append(a[i])
        with open("one.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(one)
    elif len(a[i]) == 6:
        two.append(a[i])
        with open("two.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(two)
    elif len(a[i]) == 7:
        three.append(a[i])
        with open("three.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(three)
    elif len(a[i]) == 8:
        four.append(a[i])
        with open("four.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(four)
    elif len(a[i]) == 9:
        five.append(a[i])
        with open("five.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(five)
    elif len(a[i]) == 10:
        six.append(a[i])
        with open("six.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(six)
    elif len(a[i]) == 11:
        seven.append(a[i])
        with open("seven.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(seven)
    elif len(a[i]) == 12:
        eight.append(a[i])
        with open("eight.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(eight)
    elif len(a[i]) == 13:
        nine.append(a[i])
        with open("nine.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(nine)
    elif len(a[i]) == 14:
        ten.append(a[i])
        with open("ten.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(ten)

main()

rawDescription: Compare multiple lists with the output being the number and identity of each missmatch between every pair of lists


code:
import urllib.request as net
from html.parser import HTMLParser
import re

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0",
}

def unescape(items):
    html = HTMLParser()
    unescaped = []
    for i in items:
        unescaped.append(html.unescape(i))

    return unescaped

def getItemsFromPage(url):
    request = net.Request(url, headers=headers)
    response = str(net.urlopen(request).read())
    # --------------------------
    # FIX AMPERSANDS - unescape
    # --------------------------
    links = re.findall('(http://www.charitynavigator.org/index.cfm\?bay=search\.summary&orgid=[\d]+)', response)
    unescaped_links = unescape(links)

    return unescaped_links

url = 'http://www.charitynavigator.org/index.cfm?bay=search.alpha&ltr=1'
item_urls = getItemsFromPage(url)
request = net.Request(item_urls[0], headers=headers)
print(item_urls)
response = net.urlopen(request)

# DEBUG RESPONSE
print(response.url)
print(80 * '-')

print("<title>Charity Navigator Rating - 10,000 Degrees</title>" in (response.read().decode('utf-8')))

rawDescription: Is there way to ignore 302 Moved Temporarily redirection or find what it is caused by?


code:
a
b
np.array([np.dot(a,row) for row in b]).reshape(-1,2)

rawDescription: Python Matrix multiplication; numpy array


code:
A = np.arange(10)
np.add.reduceat(A, np.arange(0, A.shape[0], 5.0), axis=0)
np.add.reduceat(A, np.arange(0, A.shape[0], 5), axis=0)

rawDescription: Error when trying to sum an array by block's


code:
import numpy as np

def closest_center(x, clist):
    return clist[np.argmin(np.abs(x - clist))]

rawDescription: update elements using numpy array function

description: Update elements using numpy array function


code:
value = ''
while not value.strip().isdigit():
     value = input("Please enter the value")

rawDescription: Loop until an input is of a specific type


code:
import subprocess
import sys
command = 'MyWork.exe %s' % (sys.argv[1])
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.wait()
output = (proc.stdout.read(), proc.stderr.read())

rawDescription: Python pipe and command line arguments

description: Python pipe and command line arguments


rawDescription: Index a 3D numpy array

description: Index a 3D numpy array


code:
import random
from datetime import datetime
random.seed(datetime.now())

rawDescription: Python: Random System time seed

description: Python: Random System time seed


code:
from collections import defaultdict

graph = defaultdict(list)

with open(txtFile) as file:
    for line in file:
        s_line = line.split()
        graph[s_line[0]].append(s_line[1])

rawDescription: How can I add key values into a dictionary from reading in each line of a .txt file and update values?

description: Add key values into a dictionary from reading in each line of a .txt file and update values


code:
class Matrix:
    def __init__ (self, columns):
        self.columns = columns
        self.rows = []

    def push (self, row):
        nRow = []
        row = dict (row)
        for key in self.columns:
            nRow.append (row [key] if key in row else 0)
        self.rows.append (nRow)

    def result (self): return self.rows

    def colNames (self): return self.columns

word_list = ["a", "b","c","d", "e"]
input1 = [("b",20),("a",10)]
input2 = [("c",9)]
input3 = [("d",70)]

m = Matrix (word_list)
m.push (input1)
m.push (input2)
m.push (input3)
print (m.result () )
print (m.colNames () )

rawDescription: Merge several lists with different length into a matrix


code:
writeLoc = 0
readLoc = 0
with open( "filename" , "r+" ) as f:
    while True:
        line = f.readline()

        #manual EOF check; not sure of the correct
        #Python way to do this manually...
        if line == "":
            break

        #save how far we've read
        readLoc = f.tell()

        #if we need this line write it and
        #update the write location
        if isRequired(line):
            f.seek( writeLoc )
            f.write( line )
            writeLoc = f.tell()
            f.seek( readLoc )

    #finally, chop off the rest of file that's no longer needed
    f.truncate( writeLoc )

rawDescription: How do I remove lines from a big file in Python, within limited environment

description: Remove lines from a big file in Python, within limited environment


code:
# project/urls.py
from django.conf.urls import url
from django.contrib import admin

from project.admin import foo_site

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(foo_site.urls)),
)

#project/app/admin.py
from project.admin import foo_site
from project.app.models import Bar

foo_site.register(Bar)

rawDescription: Django 1.4 - Manually import admin models


code:
import numpy, random

flips = numpy.array([0,0])

for i in range(10):
    flips[random.randint(0,1)] += 1

rawDescription: How would I remove an element from an array at a specific position in Python, using NumPy?


code:
e1['Image DateTime']
str(e1['Image DateTime'])

tag = time.strptime(str(e1['Image DateTime']),"%Y:%m:%d %H:%M:%S")
tag
time.strftime("%Y-%m-%d %H:%M:%S", tag)

rawDescription: python time problem

description: Python time problem


code:
# ...
with open(filename) as f:
    for line in f:
        tok = line.split()
        op = tok[0]
        qty = int(tok[1])
        # ...
# ...

rawDescription: How to read file line by line in file?

description: Read file line by line in file


code:
file_path = "C:\\temp\\test.pdf"
p = subprocess.Popen(["C:\\Ghostgum\\gsview\\gsprint.exe", "-printer", printer_name, "-colour",  file_path],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate() # waits for the gs process to end
os.remove(file_path) # now the file can be removed

rawDescription: Print a PDF and delete the file when printing has finished


code: list_of_objects = db.get(list_of_keys)

rawDescription: What is the best way to get the objects from a list of keys?


code:
feature1 = Point((45, 45));
feature2 = Point((-45, -45));

features = [feature1, feature2];

collection = FeatureCollection(features);

rawDescription: geoJSON: How to create FeatureCollection with dynamic number of Features?

description: GeoJSON: How to create FeatureCollection with dynamic number of Features


code:
import itertools
import os

dirs = [["Weights", "No_Weights"],
        ["Male", "Female"],
        ["Caucasian", "African-American", "Asian", "Hispanic", "Indo", "Other", "Unknown"],
        ["B20", "20", "30", "40", "50", "60", "70"]]

for item in itertools.product(*dirs):
    os.makedirs(os.path.join(*item))

rawDescription: Creating/making directories in python (complex)


code:
import gtk

class PlaceholderEntry(gtk.Entry):

    placeholder = 'Username'
    _default = True

    def __init__(self, *args, **kwds):
        gtk.Entry.__init__(self, *args, **kwds)
        self.connect('focus-in-event', self._focus_in_event)
        self.connect('focus-out-event', self._focus_out_event)

    def _focus_in_event(self, widget, event):
        if self._default:
            self.set_text('')
            self.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('black'))

    def _focus_out_event(self, widget, event):
        if gtk.Entry.get_text(self) == '':
            self.set_text(self.placeholder)
            self.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('gray'))
            self._default = True
        else:
            self._default = False

    def get_text(self):
        if self._default:
            return ''
        return gtk.Entry.get_text(self)

if __name__ == '__main__':
    w = gtk.Window()
    vbox = gtk.VBox()
    w.add(vbox)
    vbox.pack_start(PlaceholderEntry())
    quitbtn = gtk.Button(stock=gtk.STOCK_QUIT)
    quitbtn.connect('clicked', gtk.main_quit)
    vbox.pack_start(quitbtn)
    w.connect('destroy', gtk.main_quit)
    w.show_all()
    gtk.main()

rawDescription: Pygtk entry placeholder

description: Pygtk entry placeholder


code:
class MyModelAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
           'fields': ('field1', 'field2', 'field3')
        }),
        ('Advanced options', {
            'fields': ('field4', 'field5'),
        }),
    )

rawDescription: Group fields in Django's admin forms

description: Group fields in Django's admin forms


code: a,b = b,a

rawDescription: Is this a correct interpretation of Python code?


code:
from random import shuffle, choice

#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
    word_dict = {}
    for line in f:
        # split into two parts, word and description
        word, hint = line.split(":")
        word_dict[word] = hint

def intro():
    print('Welcome to the scramble game\n')
    print('I will show you a scrambled word, and you will have to guess the word\n')

#Picks a random key from the dictionary b
def pick_word():
    word = choice(list(word_dict.keys()))
    return word

#Gives a hint to the user
def give_hint(word):
    # return the definition of the word
    descrip = word_dict[word]
    return descrip

#Below - Retrieves answer from user, rejects it if the answer is not alpha
def get_answer():
    while True:
        answer = input('Please enter a guess: ')
        if answer.isalpha():
            return answer
        else:
            print("Only letters in the word")

def main():
    intro()
    word = pick_word()
    # give user lives/tries
    tries = 3
    shffled_word = list(word)
    # shuffle the word
    shuffle(shffled_word)
    # rejoin shuffled word
    shffled_word = "".join(shffled_word)
    # keep going for three tries as most
    while tries > 0:
        inp = input("Your scrambled word is {}\nEnter h if you want to see your hint or any key to continue".format(shffled_word))
        if inp == "h":
            print("The word definition is {}".format(give_hint(word)))
        ans = get_answer()
        if ans == word:
            print("Congratulations you win!")
            break
        tries -= 1
    # ask user if they want to play again, restarting main if they do
    play_again = input("Press 'y'  to play again or any key to exit")
    if play_again == "y":
        main()
    # else the user did not press y so say goodbye
    print("Goodbye")
main()

rawDescription: Python - Word Scramble Game

description: Python - Word Scramble Game


code:
from collections import defaultdict

y = defaultdict(list)

for key, values in x.items():  # .iteritems() in Python 2
    for value in values:
        y[value].append(key)

rawDescription: efficiently swap a python dict's keys and values where the values contain one or more elements

description: Efficiently swap a python dict's keys and values where the values contain one or more elements


code:
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()

rawDescription: Quick and easy file dialog in Python?

description: Quick and easy file dialog in Python


code:
from ast import literal_eval
s = "['a',['b','c','d'],'e']"
print(literal_eval(s))

rawDescription: How to convert array string to an array in python

description: Convert array string to an array in python


code:
import urllib2
import json

url = 'https://hooks.slack.com/services/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'
values = {"username": "webhookbot", "text": "This is posted to #general and comes from a bot named webhookbot.", "icon_emoji": ":ghost:"}

data = json.dumps(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()

rawDescription: Having problems with Post via python

description: Having problems with Post via python


code:
resp = urllib.urlopen(url)
for i in range(10):
    line = resp.readline()

rawDescription: Python urllib download only some of a webpage?


code:
d = [

    {

    "title":"SOme title",
   "date":2007,
    "link":"somelink"
    },

    {

    "title":"SOme2 title",
    "date":2007,
    "link":"somelink"
    }

]

rawDescription: Python unhashable dict

description: Python unhashable dict


code:
str1 = "blah"
str2 = "new"
"testblah".replace(str1, str1+str2)
"testblahtest".replace(str1, str1+str2)
"test".replace(str1, str1+str2)
"blahtestblah".replace(str1, str1+str2)

rawDescription: Insert substring if found

description: Insert substring if found


code:
class SolicitanteForm(ModelForm):

    class Meta:
        model = Solicitante
        fields = '__all__'

rawDescription: Django: How can I render a ModelForm partially editable fields and show other fields as label items?


code:
# Build the network yourself
inputs = InputLayer(shape=(None, 2))
network = DenseLayer(inputs, num_units=1, nonlinearity=None, b = None)

net1 = NeuralNet(
network,
#We don't need any of these parameters since we provided them above
# layer parameters:
#input_shape=(None,2), # 2 inputs
#hidden_num_units=200, # number of units in hidden layer
#output_nonlinearity=None, # output layer uses identity function
#output_num_units=1, # 1 target value

# optimization method:
update=nesterov_momentum,
update_learning_rate=0.01,
update_momentum=0.9,

regression=True,  # flag to indicate we're dealing with regression problem
max_epochs=400,  # we want to train this many epochs
verbose=1,
bias = None
)

rawDescription: removing bias from neural network layer

description: Removing bias from neural network layer


code:
N = 10000

# initialize an array of flags
is_prime = [1 for num in xrange(N)]
is_prime[0] = 0 # this is because indexing starts at zero
is_prime[1] = 0 # one is not a prime, but don't mark all of its multiples!

def set_prime(num):
    "num is a prime; set all of its multiples in is_prime to zero"
    for x in xrange(num*2, N, num):
        is_prime[x] = 0

# iterate over all integers up to N and update the is_prime array accordingly
for num in xrange(N):
    if is_prime[num] == 1:
        set_prime(num)

primes = [num for num in xrange(N) if is_prime[num]]

rawDescription: Optimization of prime number code

description: Optimization of prime number code


code:
@app.route('/search')
def search():
    # If it's a GET request, the data will be provided as request.args.  In case
    # of POST or PUT you'll have to use request.data or request.json (depends on
    # how the plugin is sending the data).
    query = request.args.get('query')
    # Perform the search here.
    results = ...
    # What to return here depends on what the plugin expects, consult the docs
    # to figure this out.  Most likely it'll be some JSON encoded data structure.
    return jsonify(results=results)

rawDescription: jQuery AJAX plugins with Flask

description: JQuery AJAX plugins with Flask


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

x, y, z = zip(*data)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z)
plt.show()

rawDescription: 3D plots in Python

description: 3D plots in Python


code:
st = "SELECT name_key,address_key FROM file WHERE foreign_key = $1"
pst = plpy.prepare(st, [ "integer" ])
rv = plpy.execute(pst, [ param_key ])

rawDescription: how to parameter-ize a query's WHERE clause within pl/python?

description: Parameter-ize a query's WHERE clause within pl/python


code:
#define you functions
def move_ant(grid,row,col,orientation):
    row,col,orientation = orientation_and_color_change(row,col,orientation)#run function and return values.

    row,col,orientation = movement(row,col,orientation)#run function and return changed vals

    return row,col,orientation

def orientation_and_color_change(changeRow,changeCol,changeOrientation):
    #do stuff with the variables you've inputted
    return changeRow,changeCol,changeOrientation

def movement(moveRow,moveCol,moveOrientation):
    #do stuff with variables
    return changeRow,changeCol,changeOrientation
#RUN THE FUNCTION
#not sure how you have you're vars set up
grid = [10,30]#random numbers! Yay!
row = 1
col = 1
orientation = 0
row,col,orientation = move_ant(grid,row,col,orientation)

rawDescription: Running a couple functions inside another one


code: new3dmat = np.array([func2dmat(slice) for slice in my3dmat])

rawDescription: Numpy Vectorized Function Over Successive 2d Slices


code:
if not os.path.exists(os.path.join(template_path, page)):
    self.abort(404)

rawDescription: Show 404 when specific route matches

description: Show 404 when specific route matches


code:
done = False
while not done:
    print('Good evening sir, I am Tippos! Please, tell me the price of your meal and how much you would like to tip and I\'ll do the math for you!')
    bill_amt = input('First sir, what was the price of your meal?(Please do not use signs such as "$"):')

    tax = 1.13
    x = float(bill_amt)
    tip_amt = input('And how much would you like to tip? 10, 15, or maybe 20% Go on, any number sir!(Please do not use signs such as "%"):')
    y = float(tip_amt)

    tip_amt = x * (y / 100)
    print('Your tip will cost you an extra' ,tip_amt, 'dollars.')
    total_amt = (x + y) * tax
    print('Your total cost will be' ,total_amt, 'dollars, sir.')
    if 'yes' != input('Do you want to start over?').lower():
        done = True

rawDescription: How do I loop a program back to the start from a user input?

description: Loop a program back to the start from a user input


code:
import matplotlib.pyplot as pl

def test(x):
    pl.figure()
    pl.plot(x)
    pl.show()

for i in range(1,3):
    eje = range(i*10)
    test(eje)

rawDescription: Plot a matplotlib figure within a for loop at each step


rawDescription: Combine columns in a Pandas DataFrame to a list in a DataFrame


code:
l1, = plt.plot(x_series, y_series_1, 'r-')
l2, = plt.plot(x_series, y_series_2, 'c--')

# Some time later...
l1.set_color('b')
l2.set_color('g')

rawDescription: How to I change line color after calling matplotlib plot?


code:
import re
re.match('a', 'abc')
re.match('a', 'bac')
re.search('a', 'bac')

rawDescription: python Regex match exact word

description: Python Regex match exact word


code:
COLORS = ['blue', 'green', 'yellow', 'red']

word = COLORS[0]

def stimulus(same):

    global word

    if same:  # return the previous color
        return (word)

    colors = list(COLORS)

    colors.remove(word)

    word = choice(colors)  # chose a different color & remember it

    return word

def next_selected():
    global word
    word = stimulus(choice((True, False)))

    label1.config(text=word)
    label1.update()

rawDescription: The random choice for a word from a list doesn't work properly (Python/Tkinter)


code:
dts = [datetime(2016,2,1), datetime(2016,3,31)]

import pandas as pd

a = pd.DatetimeIndex(dts)

# a: <class 'pandas.tseries.index.DatetimeIndex'>
#    [2016-02-01, 2016-03-31]
#    Length: 2, Freq: None, Timezone: None

# b stores the first day of month for each of the datetime in the list a.

b = a.map(lambda x: x.replace(day=1))

# b: array([Timestamp('2016-02-01 00:00:00'),
#           Timestamp('2016-03-01 00:00:00')], dtype=object)

# c stores just the month number for each datetime in a.

c = a.month

# c: array([2, 3], dtype=int32)

rawDescription: Python obtaining list of first days in a month from list of datetime


code: out.write('%s:\t%s\n' %(name,len(s)))

rawDescription: Counting patterns in sequences

description: Counting patterns in sequences


code:
class MyFigure(Figure):
    pass

fig, ax = matplotlib.pyplot.subplots(FigureClass=MyFigure)

rawDescription: How do I subclass matplotlib's figure class?

description: Subclass matplotlib's figure class


code:
def __init__(self):
    self.bar = 1
    self.run()

rawDescription: Best way to call Python class methods automatically upon instantiation

description: Call Python class methods automatically upon instantiation


code: itertools.product(range(0,6), [True,False], range(1,3), ...)

rawDescription: Generating a dictionary in python with all possible cominations of given variables


code:
def F(a, b=None):
    if b is None:
        b = []
    b.append(a)
    return b

rawDescription: Optional parameters in Python functions and their default values


code:
import ast

class LatexVisitor(ast.NodeVisitor):

    def prec(self, n):
        return getattr(self, 'prec_'+n.__class__.__name__, getattr(self, 'generic_prec'))(n)

    def visit_Call(self, n):
        func = self.visit(n.func)
        args = ', '.join(map(self.visit, n.args))
        if func == 'sqrt':
            return '\sqrt{%s}' % args
        else:
            return r'\operatorname{%s}\left(%s\right)' % (func, args)

    def prec_Call(self, n):
        return 1000

    def visit_Name(self, n):
        return n.id

    def prec_Name(self, n):
        return 1000

    def visit_UnaryOp(self, n):
        if self.prec(n.op) > self.prec(n.operand):
            return r'%s \left(%s\right)' % (self.visit(n.op), self.visit(n.operand))
        else:
            return r'%s %s' % (self.visit(n.op), self.visit(n.operand))

    def prec_UnaryOp(self, n):
        return self.prec(n.op)

    def visit_BinOp(self, n):
        if self.prec(n.op) > self.prec(n.left):
            left = r'\left(%s\right)' % self.visit(n.left)
        else:
            left = self.visit(n.left)
        if self.prec(n.op) > self.prec(n.right):
            right = r'\left(%s\right)' % self.visit(n.right)
        else:
            right = self.visit(n.right)
        if isinstance(n.op, ast.Div):
            return r'\frac{%s}{%s}' % (self.visit(n.left), self.visit(n.right))
        elif isinstance(n.op, ast.FloorDiv):
            return r'\left\lfloor\frac{%s}{%s}\right\rfloor' % (self.visit(n.left), self.visit(n.right))
        elif isinstance(n.op, ast.Pow):
            return r'%s^{%s}' % (left, self.visit(n.right))
        else:
            return r'%s %s %s' % (left, self.visit(n.op), right)

    def prec_BinOp(self, n):
        return self.prec(n.op)

    def visit_Sub(self, n):
        return '-'

    def prec_Sub(self, n):
        return 300

    def visit_Add(self, n):
        return '+'

    def prec_Add(self, n):
        return 300

    def visit_Mult(self, n):
        return '\\;'

    def prec_Mult(self, n):
        return 400

    def visit_Mod(self, n):
        return '\\bmod'

    def prec_Mod(self, n):
        return 500

    def prec_Pow(self, n):
        return 700

    def prec_Div(self, n):
        return 400

    def prec_FloorDiv(self, n):
        return 400

    def visit_LShift(self, n):
        return '\\operatorname{shiftLeft}'

    def visit_RShift(self, n):
        return '\\operatorname{shiftRight}'

    def visit_BitOr(self, n):
        return '\\operatorname{or}'

    def visit_BitXor(self, n):
        return '\\operatorname{xor}'

    def visit_BitAnd(self, n):
        return '\\operatorname{and}'

    def visit_Invert(self, n):
        return '\\operatorname{invert}'

    def prec_Invert(self, n):
        return 800

    def visit_Not(self, n):
        return '\\neg'

    def prec_Not(self, n):
        return 800

    def visit_UAdd(self, n):
        return '+'

    def prec_UAdd(self, n):
        return 800

    def visit_USub(self, n):
        return '-'

    def prec_USub(self, n):
        return 800
    def visit_Num(self, n):
        return str(n.n)

    def prec_Num(self, n):
        return 1000

    def generic_visit(self, n):
        if isinstance(n, ast.AST):
            return r'' % (n.__class__.__name__, ', '.join(map(self.visit, [getattr(n, f) for f in n._fields])))
        else:
            return str(n)

    def generic_prec(self, n):
        return 0

def py2tex(expr):
    pt = ast.parse(expr)
    return LatexVisitor().visit(pt.body[0].value)

rawDescription: Converting a python numeric expression to LaTeX


code:
with open("pe_ratio.csv","wb") as f: # or open("pe_ratio.csv", "w", newline="") in Py3
    writer = csv.writer(f)

    # do other stuff here, staying indented until you're done writing to the file

rawDescription: Python DictWriter /n

description: Python DictWriter /n


code:
import pandas as pd
df = pd.read_html("https://www.google.com/finance?q=NYSE%3AIBM&fstype=ii&ei")

rawDescription: web scraping data from tables

description: Web scraping data from tables


code: sents=["I am x","I am Y"]

rawDescription: incremental training SGD Classifier of Sklearn with sentences

description: Incremental training SGD Classifier of Sklearn with sentences


code:
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('peak.txt', dtype = float)

fig = plt.figure(figsize=(6,8))
ax = fig.add_subplot(111)

for i in range(1, data.shape[1]):
    y = data[..., i] + 0.1*i
    ax.plot(data[..., 0], y)

plt.show()

rawDescription: separate peaks from each other equidistantly

description: Separate peaks from each other equidistantly


code: p = ui.get('padding', 0)

rawDescription: Shortest way to get a value from a dictionary or a default if the key is not present