code: chart.set_x_axis({'name_font': {'bold': True, 'italic': True}})

rawDescription: Change angle of text on axis

description: Change angle of text on axis


code: [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]

rawDescription: How to get a dict lookup by adjacent value

description: Get a dict lookup by adjacent value


code: return len([x for x in myList if x in myDict]) > 0

rawDescription: Dict has key from list

description: Dict has key from list


code:
def comboBoxIndexChanged(index):
  #Do something based on the index
  if somethingBasedOnTheIndex:
    self.line_edit_widget.setEnabled(true)
  else:
    self.line_edit_widget.setEnabled(false)

rawDescription: pyqt - combobox item enabling/disabling line_edit item based on state

description: Pyqt - combobox item enabling/disabling line_edit item based on state


code:
def get_run_mru():
    import _winreg
    regKey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
        r'Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU')
    recent = _winreg.QueryValueEx(regKey,'MRUList')[0]
    recent_list = []
    for subkey in recent:
        recent_list.append(_winreg.QueryValueEx(regKey,subkey)[0])
    return recent_list

rawDescription: Access Most Recently Used (MRU) entries via Python on Windows?


code:
#!/usr/bin/env python

from smtplib import SMTP              # sending email
from email.mime.text import MIMEText  # constructing messages

from jinja2 import Environment        # Jinja2 templating

TEMPLATE = """
<html>
<head>
<title>{{ title }}</title>
</head>
<body>

Hello World!.

</body>
</html>
"""  # Our HTML Template

# Create a text/html message from a rendered template
msg = MIMEText(
    Environment().from_string(TEMPLATE).render(
        title='Hello World!'
    ), "html"
)

subject = "Subject Line"
sender= "root@localhost"
recipient = "root@localhost"

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient

# Send the message via our own local SMTP server.
s = SMTP('localhost')
s.sendmail(sender, [recipient], msg.as_string())
s.quit()

rawDescription: Building Dynamic HTML Email Content with Python


code:
import json
url = 'http://text-processing.com/api/sentiment/'
payload = {'text': 'great'}
r = requests.post(url, data=json.dumps(payload))

rawDescription: SImple http post using python

description: SImple http post using python


rawDescription: How do I get multiple values from checkboxes in Django

description: Get multiple values from checkboxes in Django


code: globals()['yourvariables'] = variable

rawDescription: how to assign a python variable whose name is generated on-the-fly?

description: Assign a python variable whose name is generated on-the-fly


code:
from curses import wrapper

def display_world(world, stdscr):
    for y in range(0, 10):
        for x in range(0, 10):
            stdscr.addch(y+1, 2*x, world[y*10+x])
            stdscr.addch(y+1, 2*x+1, "|")
    stdscr.refresh()
    key = stdscr.getkey()
    stdscr.addnstr(0, 3, key, 10)
    stdscr.refresh()
    if key is "q":
        exit(0)

def update_world(world, stdscr):
    while True:
        display_world(world, stdscr)
        sleep(0.1)

def main(stdscr):
    stdscr.clear()
    world = new_world()
    world = spawn_spinos(world)
    world = spawn_player(world)
    update_world(world, stdscr)

wrapper(main)

rawDescription: Need Help Updating Screen

description: Need Help Updating Screen


code:
from collections import defaultdict
d = defaultdict(lambda: 'MyDefault', {'a':1, 'b':2})
d['c']
map(d.get, ['a', 'c'])
map(d.__getitem__, ['a', 'c'])

rawDescription: Getting a few values out of dictionary with default different than None (Python)


code:
Blue =  RGBint & 255
Green = (RGBint >> 8) & 255
Red =   (RGBint >> 16) & 255

rawDescription: RGB Int to RGB - Python

description: RGB Int to RGB - Python


code:
from django.template.loaders.app_directories import Loader
from shpaml import convert_text

class SHPAMLLoader(Loader):
    def load_template_source(self, *args, **kwargs):
        shpaml_source = super(SHPAMLLoader, self).load_template_source(*args, **kwargs)
        html = convert_text(shpaml_source)
        return html

rawDescription: Preprocess SHPAML in Django's template loader?


code:
import math
from random import gauss

my_mean = 0
my_variance = 10

random_numbers = [gauss(my_mean, math.sqrt(my_variance)) for i in range(100)]

rawDescription: Random number with specific variance in Python


code:
lst1 = ['l1_el1', 'l1_el2', 'l1_el3']
lst2 = ['l1_el4', 'l1_el5', 'l1_el6']

with open('file.txt', 'w') as fh:
    for l in (lst1, lst2):
        fh.write('\t'.join(l) + '\n')

rawDescription: Write multiple lists to a file with tabs between items and newlines between lists


code: self.session.mount('https://', adapter)

rawDescription: Python Requests, warning: urllib3.connectionpool:Connection pool is full


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

num_samples = 400

# The desired mean values of the sample.
mu = np.array([5.0, 0.0, 10.0])

# The desired covariance matrix.
r = np.array([
        [  3.40, -2.75, -2.00],
        [ -2.75,  5.50,  1.50],
        [ -2.00,  1.50,  1.25]
    ])

# Generate the random samples.
y = np.random.multivariate_normal(mu, r, size=num_samples)

# Plot various projections of the samples.
plt.subplot(2,2,1)
plt.plot(y[:,0], y[:,1], 'b.')
plt.plot(mu[0], mu[1], 'ro')
plt.ylabel('y[1]')
plt.axis('equal')
plt.grid(True)

plt.subplot(2,2,3)
plt.plot(y[:,0], y[:,2], 'b.')
plt.plot(mu[0], mu[2], 'ro')
plt.xlabel('y[0]')
plt.ylabel('y[2]')
plt.axis('equal')
plt.grid(True)

plt.subplot(2,2,4)
plt.plot(y[:,1], y[:,2], 'b.')
plt.plot(mu[1], mu[2], 'ro')
plt.xlabel('y[1]')
plt.axis('equal')
plt.grid(True)

plt.show()

rawDescription: Generate correlated data in Python (3.3)


code:
from sklearn.feature_extraction.text import CountVectorizer, WordNGramAnalyzer
v = CountVectorizer(analyzer=WordNGramAnalyzer(min_n=1, max_n=2))
X = v.fit_transform(files)

rawDescription: Is there a way to convert nltk featuresets into a scipy.sparse array?


code:
class AutoCompleteInputDialog(QtGui.QDialog):

    def __init__(self, *args, **kwargs):
        super(AutoCompleteInputDialog, self).__init__(*args, **kwargs)
        self.comboBox = AutoCompleteComboBox(self)
        self.va = QtGui.QVBoxLayout(self)
        self.va.addWidget(self.comboBox)
        self.box = QtGui.QWidget(self)
        self.ha = QtGui.QHBoxLayout(self)
        self.va.addWidget(self.box)
        self.box.setLayout(self.ha)
        self.OK = QtGui.QPushButton("OK",self)
        self.OK.setDefault(True)
        self.cancel = QtGui.QPushButton("Cancel",self)
        self.ha.addWidget(self.OK)
        self.ha.addWidget(self.cancel)
        self.OK.clicked.connect(self.accept)
        self.cancel.clicked.connect(self.reject)

rawDescription: PySide: How to overload classes with static functions


rawDescription: Python 3.3 - Formatting Information in a Table


rawDescription: Linked time axes (x-axis) in a matplotlib figure


code: f = open('/tmp/output', 'wb')

rawDescription: Python Write bytes to file

description: Python Write bytes to file


code:
import datetime

with open("output.txt", 'a+') as textfile:
    while True:
        input = raw_input("Enter: ")
        if input == 'done':
            break
        textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n')

rawDescription: save the user input to existing text file everytime running the script python?

description: Save the user input to existing text file everytime running the script python


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

col_names = ["a","b","c","d","e","f"]
my_dict = {}

for item in range(0, 6):
    my_dict[col_names[item]] = []

with open("myfile.csv","r") as f:
    spamreader = csv.reader(f,delimiter=";")
    for row in spamreader:
        for col in range(2 , len(row)):
            my_dict[col_names[col-2]].append([row[0],row[col]])
f.close()

for key, data_list in my_dict.items():
    dates_str, values = zip(*data_list)
    dates = [dt.datetime.strptime(d,'%d.%m.%Y').date() for d in dates_str]
    plt.plot(dates, values, label=key)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gcf().autofmt_xdate()

rawDescription: Python, plotting all columns vs the first column (date) in a csv file


code:
s = slice(1,3)
b[s,s]

ds = (s,s)
b[ds]

rawDescription: Numpy slicing from variable

description: Numpy slicing from variable


code:
from glob import iglob
import os.path
import pymongo
import json

for fname in iglob(os.path.expanduser('~/Tweets/*.txt')):
    with open(fname) as fin:
        tweets = json.load(fin)
        for tweet in tweets:
            db.tweets.insert(tweet)

rawDescription: Loading Several Text Files into MongoDB using PyMongo


rawDescription: No cv.Point in Python OpenCV on latest stable Debian


code:
import tempfile, shutil, os
def create_temporary_copy(path):
    temp_dir = tempfile.gettempdir()
    temp_path = os.path.join(temp_dir, 'temp_file_name')
    shutil.copy2(path, temp_path)
    return temp_path

rawDescription: how to concisely create a temporary file that is a copy of another file in python

description: Concisely create a temporary file that is a copy of another file in python


code:
a = [1, 5, 2, 5, 1]
from collections import Counter
[k for k, c in Counter(a).iteritems() if c == 1]

rawDescription: Filter list, only unique values - with python


code:
from itertools import combinations
route = ['Ayr', 'Newton', 'Troon', 'Paisley', 'Glasgow']
[(route[0],)+x+(route[-1],) for i in range(len(route)-1) for x in combinations(route[1:-1],i)]

rawDescription: Find all possible combinations of tuple pairs merging each into new sequences


code:
def insert(self,head,data):
    new_node = Node(data)
    if head is not None:
        current = head
        new_node.next = current
    return new_node

rawDescription: Trouble with implementing a linked list in Python


code: self._semaphores = [Semaphore(0) for _ in range(size + 1)]

rawDescription: Process synchronization in Python

description: Process synchronization in Python


code:
class Answer(models.Model):
    answer_text = models.CharField(...)

class Question(models.Model):
    """What all questions have in common"""
    title = models.CharField(...)
    text = models.CharField(...)
    answer = models.ForeignKey(Answer)

class PythonQuestion(Question):
    """What specifics a python question might have"""
    python_version = models.CharField(...)

rawDescription: How to make admin page of django do this particular thing?

description: Make admin page of django do this particular thing


code:
import codecs
with codecs.open(filename, encoding="utf-8") as inp:
    text = inp.read()

rawDescription: C# / Python Encoding difference

description: C# / Python Encoding difference


code: [FruitValues[i] for i in SortOrder]

rawDescription: Sort of dictionary values from keys in an ordered list


code:
docs=[[0,1],[0,0],[1,0,1]]
D=len(docs)
z_d_n=[[0 for _ in xrange(len(d))] for d in docs]
l_d_n=[[0 for _ in xrange(len(d))] for d in docs]

V=2
T=2
S=2
n_m_j_k=numpy.zeros( (V,T,S) )
n_j_k_d=numpy.zeros( (T,S,D) )
n_j_k=numpy.zeros( (T,S) )
n_k_d=numpy.zeros( (S,D) )
n_d=numpy.zeros( (D) )

beta=.1
alpha=.1
gamma=.1

for d, doc in enumerate(docs): #d: doc id
    for n, m in enumerate(doc): #i: index of the word inside document, m: id of the word in the vocabulary
        # j is the topic
        j = z_d_n[d][n]
        # k is the sentiment
        k = l_d_n[d][n]
        n_m_j_k[m][j][k] += 1
        n_j_k_d[j][k][d] += 1
        n_j_k[j][k] += 1
        n_k_d[k][d] += 1
        n_d[d] += 1

for d, doc in enumerate(docs): #d: doc id
    for n, m in enumerate(doc): #i: index of the word inside document, m: id of the word in the vocabulary
        # j is the topic
        j = z_d_n[d][n]
        # k is the sentiment
        k = l_d_n[d][n]
        n_m_j_k[m][j][k] -= 1
        n_j_k_d[j][k][d] -= 1
        n_j_k[j][k] -= 1
        n_k_d[k][d] -= 1
        n_d[d] -= 1

        # sample a new topic and sentiment label jointly
        # T is the number of topics
        # S is the number of sentiments
        p_left = (n_m_j_k[m] + beta) / (n_j_k + V * beta) # T x S array
        p_mid = (n_j_k_d[:,:,d] + alpha) / numpy.tile(n_k_d[:,d] + T * alpha, (T,1) )
        p_right = numpy.tile(n_k_d[:,d] + gamma,(T,1)) /  numpy.tile(n_d[d] + S * gamma,(T,S))
        p = p_left * p_mid * p_right
        p /= numpy.sum(p)
        new_jk = numpy.random.multinomial(1, numpy.reshape(p, (T*S) )).argmax()
        j=new_jk/T
        k=new_jk%T

        z_d_n[d][n]=j
        l_d_n[d][n]=k
        n_m_j_k[m][j][k] += 1
        n_j_k[j][k] += 1
        n_k_d[k][d] += 1
        n_d[d] += 1

rawDescription: Implementing Topic Model with Python (numpy)


code:
import sys
sys.path.insert(0, r'C:\Modules\Module1')
import module

rawDescription: In interactive Python, how to unambiguously import a module


rawDescription: Range in Python

description: Range in Python


code:
import re

list_of_dicts = []
with open('thefile.txt') as f:
    for line in f:
        d = dict()
        list_of_dicts.append(d)
        tokens = line.strip().split()
        for i in range(0, len(tokens), 2):
            where, what = tokens[i:i+2]
            mo = re.search(r'(\d+)-(\d+)', where)
            if mo:
                start = int(mo.group(1))
                end = int(mo.group(2)) + 1
            else:
                mo = re.search(r'(\d+)', where)
                if mo:
                    start = int(mo.group(1))
                    end = start + 1
                else:
                    msg = 'cannot parse {} in {}'.format(where, tokens)
                    raise ValueError(msg)
            for i in range(start, end):
                d['Fruit{}'.format(i)] = what

rawDescription: python loop thru unstructured data with different possibilities

description: Python loop thru unstructured data with different possibilities


code:
import myapp
from pyramid.paster import get_appsettings
from webtest import TestApp
app, conf = myapp.init(get_appsettings('settings.ini#appsection'))
rend = conf.testing_add_renderer('template.pt')
test_app = TestApp(app)
resp = test_app.get('/my/view/url')
rend.assert_(key='val')

rawDescription: Create pyramid request for testing, so that events are triggered


code: df.last_3 = df.key_pressed.shift(1) + ', ' + df.key_pressed.shift(2) + ', ' + df.key_pressed.shift(3)

rawDescription: How to get last N rows RELATIVE to another row in pandas (vector solution)?

description: Get last N rows RELATIVE to another row in pandas (vector solution)


rawDescription: Overwrite portions of some rows of a numpy array with portions of other rows


rawDescription: Average RMS value of an 3D audio signal in Python


code:
x = 170
Dataset.objects.filter(i_end_int__gte=x,i_begin_int__lte=x)

rawDescription: Django: Filter objects by integer between two values


code:
from scrapy.item import Item, Field
from scrapy.spider import Spider
from scrapy.selector import Selector

class MyItem(Item):
    content = Field()

class StockSpider(Spider):
    name = "stock_spider"
    allowed_domains = ["www.hamshahrionline.ir"]
    start_urls = ["http://www.hamshahrionline.ir/details/261730/Health/publichealth"]

    def parse(self, response):
        sel = Selector(response)
        paragraphs = sel.xpath("//div[@class='newsBodyCont']/p/text()").extract()
        for p in paragraphs:
            item = MyItem()
            item['content'] = p
            yield item

rawDescription: How to extract exact tags in scrapy

description: Extract exact tags in scrapy


code:
def runCounter(L):
  answer = []
  start = 0
  end = 1
  while end < len(L):
    if L[end] < L[end-1]:
      answer.append(end-start)
      start, end = end, end+1
    end += 1
  answer.append(end-start)
  return answer

L = [6, 12, 9, 10, 1, 2, 3, 4]
runCounter(L)

rawDescription: counting runs in a list, how?

description: Counting runs in a list, how


code:
counts = pd.value_counts(series).to_dict()
[{u: v} for (u, v) in counts.iteritems()]

rawDescription: Convert Series to list of dict in pandas


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

def get_dots(width, height, pitch):
    xs, ys = [], []
    for y in range(height // pitch):
      for x in range(width // pitch):
          xs.append((x + random()) * pitch)
          ys.append((y + random()) * pitch)
    return xs, ys

def main():
    xs, ys = get_dots(20, 20, 2)
    plt.scatter(xs, ys, c="r")
    plt.axis((0., 20., 0., 20.))
    plt.show()

if __name__=="__main__":
    main()

rawDescription: random position that knows previous position

description: Random position that knows previous position


code:
def getvalue():
    print(int(popcorn.get()) * 9)

rawDescription: How can I use the value from a spin box (or other Tkinter widget) properly in a calculation?

description: Use the value from a spin box (or other Tkinter widget) properly in a calculation


code:
import os
import glob
import shutil

outputDir = os.getcwd()

for fpath in glob.glob('*.tif'):  # this returns a list of the CURRENT contents. Therefore, there is no need to sanitize for the directories that we will later create
    year = os.path.basename(fpath)[9:13]
    if not os.path.isdir(os.path.join(outputDir, year)):
        os.mkdir(os.path.join(outputDir, year))
    shutil.move(fpath, os.path.join(outputDir, year))

rawDescription: Copying files to new folder based on string within filename


code:
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want

rawDescription: Key Presses in Python

description: Key Presses in Python


code:
def find_last(x,y):
  if x.find(y) == -1:
    return -1
  pos = x.find(y)
  next_y = x.find(y, pos + 1)
  while next_y != -1:
    pos = pos + next_y
    next_y = x.find(y, pos + 1)
  return pos

search = 'tom ran up but tom fell down'
target = 'tom'

print(find_last(search,target))

rawDescription: Python While Loop - Variable Not Updating?


code:
users = session.query(User).all()
for user in users:
    users_classes = ','.join([c.class_name for c in user.classes])
    print("{0} is {1} in {2}".format(user.user_firstName,
                                     user.role.role_name,
                                     users_classes))

rawDescription: Select many to many with Flask-SQLAlchemy


code:
mylist1 = [ 23,   13, None, 65,   None, 966, None, None]
mylist2 = [ None, 13, 98,   None, 61,   966, 13,   2]
mylis1 = [a if a else 0 for a in mylist1 ]
mylis1
mylis2 = [a if a else 0 for a in mylist2 ]
mylis2
output = [a | b for a, b in zip(mylis1, mylis2)]
output

rawDescription: how to combine two lists?

description: Combine two lists


code:
import re

if re.match(r'^.*_v\d+\.txt$', filename):
    pass  # valid
else:
    pass  # invalid

rawDescription: Test whether a file name has the correct naming convention in Python


code:
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

rawDescription: How to equalize the scales of x-axis and y-axis in Python matplotlib?

description: Equalize the scales of x-axis and y-axis in Python matplotlib


code:
import sys

sys.stdout.write("This will be first ")
sys.stdout.write("and this will be on the same line.")

rawDescription: Python Print Trailing Comma Behavior using sys.stdout


code:
def free_cells(table):
    free_cells = set([(x,y) for x in range(table.props.n_columns) for y in range(table.props.n_rows)])

    def func(child):
        (l,r,t,b) = table.child_get(child, 'left-attach','right-attach','top-attach','bottom-attach')
        used_cells = set([(x,y) for x in range(l,r) for y in range(t,b)])
        free_cells.difference_update(used_cells)

    table.foreach(func)

    return free_cells

rawDescription: PyGTK - polling GTK table for locations of widgets


code:
import os
def getwd():
    return os.path.dirname(__file__) if '__file__' in globals() else os.getcwd()

rawDescription: Doing smart things with __file__ in python (what are they talking about?)


rawDescription: convert groupby to dataframe, join the groups again

description: Convert groupby to dataframe, join the groups again


code:
import pygame
from pygame.locals import *
#init game engine with audio
pygame.init()
pygame.mixer.init()
#load a sound
sound = pygame.mixer.Sound("/path/to/WAVS/sample.wav")
#playback
sound.play()

rawDescription: Lightweight audio playback and image display for Raspberry Pi


code: print(nums[str(i)])

rawDescription: Iterating through keys in dictionaries

description: Iterating through keys in dictionaries


code:
import sys
import importlib

import __builtin__ as old_builtins

class ExampleImporter(object):
    old_import = __import__
    def __init__(self):
       self.count = 0
    def new_import(self, *args, **kwargs):
        self.count += 1
        print(args, kwargs)
        return self.old_import(*args, **kwargs)
importer = ExampleImporter()

old_builtins.__import__ = importer.new_import
assert __import__ == importer.new_import

# remove builtins from modules so as to force its reimport
del sys.modules["__builtin__"]
# in python3 the following bypasses __import__ entirely, but not in python2
new_builtins = importlib.import_module("__builtin__")
# restore initial state of __builtin__ module (will not delete new names
# added to __builtin__)
old_builtins.__dict__.update(new_builtins.__dict__)
# Replace new __builtin__ with old __builtin__ module. Otherwise you'll end up with a
# mess where different modules have different a __builtin__ module.
sys.modules["__builtin__"] = old_builtins
del new_builtins

assert __import__ == importer.old_import
assert importer.count == 1 # would be 0 in python3

rawDescription: Is it possible to recover __import__ after overwriting it?


code:
import turtle

#Create the player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0, -235)
player.setheading(90)

playerspeed = 15

#Move the player Left and Right
def move_left():
    x = player.xcor()
    x -= playerspeed
    if x < -200:
        x = - 200
    player.setx(x)

def move_right():
    x = player.xcor()
    x += playerspeed
    if x < -200:
        x = - 280
    player.setx(x)

#Create Keyboard Bindings
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")

#Start the main loop
turtle.mainloop()

rawDescription: python left and right arrow key event not working

description: Python left and right arrow key event not working


code:
from scipy.sparse import rand

x = rand(1000, 10, density=0.2, format='csr')
x.data[:] = 1

print(np.unique(x.todense().flat))
# [ 0.  1.]

rawDescription: Generate random sparse matrix filled with only values 0 or 1


code:
if inspect.isfunction(object):
    args, varargs, varkw, defaults = inspect.getargspec(object)
    argspec = inspect.formatargspec(
        args, varargs, varkw, defaults, formatvalue=self.formatvalue)
    if realname == '<lambda>':
        title = '%s lambda ' % name
        argspec = argspec[1:-1] # remove parentheses
else:
    argspec = '(...)'

rawDescription: Keyword-based documentation for CPython extensions


code:
import re
s = "String. New sentence. And again."
re.findall(r'[^ ].*?[.!?]', s)

rawDescription: Regular expression on Python to split string by symbol without deleting


code:
import click

class User(object):
    def __init__(self, username=None, password=None):
        self.username = username
        self.password = password

@click.group()
@click.option('--username', default='Naomi McName', help='Username')
@click.option('--password', default='b3$tP@sswerdEvar', help='Password')
@click.pass_context
def main(ctx, username, password):
    ctx.obj = User(username, password)
    print("This method has these arguments: " + str(username) + ", " + str(password))

@main.command()
@click.pass_obj
def do_thingy(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))

@main.command()
@click.pass_obj
def do_y(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))

@main.command()
@click.pass_obj
def do_x(ctx):
    print("This method has these arguments: " + str(ctx.username) + ", " + str(ctx.password))

main()

rawDescription: How do I pass variables to other methods using Python's click (Command Line Interface Creation Kit) package

description: Pass variables to other methods using Python's click (Command Line Interface Creation Kit) package


code:
def function():
    steps = []

    if True:
        steps.append(1)

        if True:
            steps.append(2)

            if False:
                steps.append(3)
                return 'a', steps

            if False:
                steps.append(4)
                return 'b', steps

            steps.pop() #removes 2 from steps

        if True:
            steps.append(5)

            if True:
                steps.append(6)

                if False:
                    steps.append(7)
                    return 'a', steps

            steps.pop() #remove the 6

            if True:
                steps.append(8)
                return 'b', steps

        steps.pop() #remove the 5
    steps.pop() # removes the 1

rawDescription: conditions tree and backtrace

description: Conditions tree and backtrace


code: sorted(('{:08b}'.format(i) for i in xrange(256)), key=lambda x: x.count('1'))

rawDescription: Special counting

description: Special counting


code:
import Tkinter as tk

root = tk.Tk()

entry = tk.Entry(root, width=40)
entry.pack()
# Put text in the entrybox with the insert method.
# The 0 means "at the begining".
entry.insert(0, 'Please set the path of the file you want...')

text = tk.Text(root, width=45, height=5)
text.pack()
# Textboxes also have an insert.
# However, since they have a height and a width, you need to
# put 0.0 to spcify the beginning.  That is basically the same as
# x=0, y=0.
text.insert(0.0, 'Please set the path of the file you want...')

root.mainloop()

rawDescription: Python: is there a way to have default for Entry field?


code:
# This is a program that displays dimensions of a letter-size
# sheet of paper in millimeters.

WIDTH = 8.5
HEIGHT = 11

MILLIMETERS_IN_INCHES = 25.4

print("The dimentions of a letter-size sheet of paper in millimeters is : {} x {}", WIDTH * MILLIMETERS_IN_INCHES, HEIGHT * MILLIMETERS_IN_INCHES)

rawDescription: Sheet of paper in millimeters

description: Sheet of paper in millimeters


code:
id16 = vc.findViewByIdOrRaise('id/no_id/16')
for i in range(25):
    id16.backspace()

rawDescription: Erase text from Edit Text using AndroidViewClient


rawDescription: Find all Subgraphs using the reflexive transitive closure in Python


code:
A=0.000006
B=0.000009
S=0.0
C=0
with open('inputdatafile') as fin, open('outputfile','w') as fout:
  for line in fin:
    if line.startswith("#"):
      continue
    else:
      col = line.split()
      if col[1] == '1':
        val_6=float(col[-2])
        val_5=int(col[-3])
        if val_5 > A and val_5 < B:
          fout.write(" ".join(col) + "\n")
          s += val_6
          c += 1
  fout.write("Average 6th: %f\n" % (S/C))

rawDescription: how to extract a range of data in my special data structure in python

description: Extract a range of data in my special data structure in python


code: any(search in sublist for sublist in l)

rawDescription: How to test if a nested Python list contains a given string

description: Test if a nested Python list contains a given string


code:
inf = open("mydata.txt", "rb")
outf = gzip.open("file.txt.gz", "wb")
outf.write(inf.read())
outf.close()
inf.close()

rawDescription: How to compress a processed text file in Python?

description: Compress a processed text file in Python


code:
def inDisavow(url, disavowDomainList):
    for domain in disavowDomainList:
        if domain in url:
            return true
    return false

rawDescription: Compare string vs modified strings & partial strings


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

# define grid
nx, ny = 6, 5
x, y = np.arange(nx), np.arange(ny)
xx, yy = np.meshgrid(x, y)
z = np.maximum(xx, yy)

# create random points
npoints = 30
data_x = 10**(np.random.rand(npoints)*nx)
data_y = 10**(np.random.rand(npoints)*ny-1)

# plot grid then points
plt.pcolor(10.**x, 10.**(y-1), z, edgecolors='k')
plt.loglog(data_x, data_y, '.w')
plt.axis([1,10**5,0.1,10**3])
plt.show()

rawDescription: How do I use Matplotlib pyplot pcolor to provide distinct color to each grid in my plot

description: Use Matplotlib pyplot pcolor to provide distinct color to each grid in my plot


code:
db.test_collection.find({"data.Country": "ES"})
db.test_collection.find({"data.Count": {"$lt": 6}})

rawDescription: nested queries in pymongo using collection.find()

description: Nested queries in pymongo using collection.find()


code:
A = [-1, 1, 3, 3, 3, 2, 1, 0]
def indices(l):
    res = []
    for i in range(0,len(l)-2):
            diff = l[i+1] - l[i]
            for j in range(i+2,len(l)):
                    if (l[j] - l[j-1]) == diff:
                            res.append((i,j))
                    else:
                            break;
    return res
indices(A)

rawDescription: Arithmetic Sequences Slices in Python

description: Arithmetic Sequences Slices in Python


code: print('{:20} | {:20} {:5.2f} | {:20} {:5.2f}'.format(title, states[statemin], minimum, states[statemax], maximum))

rawDescription: Need Help on String Formatting

description: Need Help on String Formatting


code:
def explore(n, terms, seqs):

    if not terms:  # if all terms have been processed, you found a solution
        return {tuple(sum(sorted(seqs), []))}

    result = set()

    for ix, seq in enumerate(seqs):

        new_seqs = list(seqs)
        new_seqs[ix] = seq + [terms[0]]

        if len(seq) == 0:  # if you are adding to an empty sequence
            if ix == 0 or len(seqs[ix - 1]) > 0:  # be sure previous is not empty
                result.update(explore(n, terms[1:], new_seqs))
            break  # don't bother checking following seqs, they are empty

        elif len(seq) == 1:  # you can always add to 1-element seq
            result.update(explore(n, terms[1:], new_seqs))

        elif len(seq) < n and seq[-1] * 2 == seq[-2] + terms[0]:  # is arithmetic?
            result.update(explore(n, terms[1:], new_seqs))

    return result

m = int(raw_input())
terms = sorted(map(int, raw_input().split()))
seqs = [[] for _ in range(m)]

result = explore(len(terms) / m, terms, seqs)

for solution in result:
    print(" ".join(map(str, solution)))

rawDescription: Find M Arithmetic Sequences of N elements in a List containing M*N shuffled elements


code: set(i['id'] for i in items)

rawDescription: How to get all unique IDs from the list of dicts?

description: Get all unique IDs from the list of dicts


code:
import Tkinter

class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.master.minsize(width=512, height=256)
        self.master.config()
        self.pack()

        self.main_frame = Tkinter.Frame()
        self.main_frame.pack(fill='both', expand=True)

        self.data = {
            'Toyota': ['Camry', 'Corolla', 'Prius'],
            'Ford': ['Fusion', 'Focus', 'Fiesta'],
            'Volkswagen': ['Passat', 'Jetta', 'Beetle'],
            'Honda': ['Accord', 'Civic', 'Insight']
        }

        self.make_listbox = Tkinter.Listbox(self.main_frame)
        self.make_listbox.pack(fill='both', expand=True, side=Tkinter.LEFT)

        # here we bind the make listbox selection to our method
        self.make_listbox.bind('<<ListboxSelect>>', self.load_models)

        self.model_listbox = Tkinter.Listbox(self.main_frame)
        self.model_listbox.pack(fill='both', expand=True, side=Tkinter.LEFT)

        # insert our items into the list box
        for i, item in enumerate(self.data.keys()):
            self.make_listbox.insert(i, item)

    def load_models(self, *args):
        selection = self.make_listbox.selection_get()

        # clear the model listbox
        self.model_listbox.delete(0, Tkinter.END)

        # insert the models into the model listbox
        for i, item in enumerate(self.data[selection]):
            self.model_listbox.insert(i, item)

root = Tkinter.Tk()
app = Application(root)
app.mainloop()

rawDescription: populating listbox from selection, python

description: Populating listbox from selection, python


code:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min
X = np.random.randn(10, 4)
km = KMeans(n_clusters=2).fit(X)
closest, _ = pairwise_distances_argmin_min(km.cluster_centers_, X)
closest

rawDescription: Get nearest point to centroid, scikit-learn?


code:
import tkinter as tk
from tkinter import ttk

class ToggledFrame(tk.Frame):

    def __init__(self, parent, text="", *args, **options):
        tk.Frame.__init__(self, parent, *args, **options)

        self.show = tk.IntVar()
        self.show.set(0)

        self.title_frame = ttk.Frame(self)
        self.title_frame.pack(fill="x", expand=1)

        ttk.Label(self.title_frame, text=text).pack(side="left", fill="x", expand=1)

        self.toggle_button = ttk.Checkbutton(self.title_frame, width=2, text='+', command=self.toggle,
                                            variable=self.show, style='Toolbutton')
        self.toggle_button.pack(side="left")

        self.sub_frame = tk.Frame(self, relief="sunken", borderwidth=1)

    def toggle(self):
        if bool(self.show.get()):
            self.sub_frame.pack(fill="x", expand=1)
            self.toggle_button.configure(text='-')
        else:
            self.sub_frame.forget()
            self.toggle_button.configure(text='+')

if __name__ == "__main__":
    root = tk.Tk()

    t = ToggledFrame(root, text='Rotate', relief="raised", borderwidth=1)
    t.pack(fill="x", expand=1, pady=2, padx=2, anchor="n")

    ttk.Label(t.sub_frame, text='Rotation [deg]:').pack(side="left", fill="x", expand=1)
    ttk.Entry(t.sub_frame).pack(side="left")

    t2 = ToggledFrame(root, text='Resize', relief="raised", borderwidth=1)
    t2.pack(fill="x", expand=1, pady=2, padx=2, anchor="n")

    for i in range(10):
        ttk.Label(t2.sub_frame, text='Test' + str(i)).pack()

    t3 = ToggledFrame(root, text='Fooo', relief="raised", borderwidth=1)
    t3.pack(fill="x", expand=1, pady=2, padx=2, anchor="n")

    for i in range(10):
        ttk.Label(t3.sub_frame, text='Bar' + str(i)).pack()

    root.mainloop()

rawDescription: Expandable and contracting frame in Tkinter


code:
from flask import request

class Parser(object):

  sep = ';'

  # ...

  def filter_query(self, query):
    model_class = self._get_model_class(query) # returns the query's Model
    raw_filters = request.args.getlist('filter')
    for raw in raw_filters:
      try:
        key, op, value = raw.split(self.sep, 3)
      except ValueError:
        raise APIError(400, 'Invalid filter: %s' % raw)
      column = getattr(model_class, key, None)
      if not column:
        raise APIError(400, 'Invalid filter column: %s' % key)
      if op == 'in':
        filt = column.in_(value.split(','))
      else:
        try:
          attr = filter(
            lambda e: hasattr(column, e % op),
            ['%s', '%s_', '__%s__']
          )[0] % op
        except IndexError:
          raise APIError(400, 'Invalid filter operator: %s' % op)
        if value == 'null':
          value = None
        filt = getattr(column, attr)(value)
      query = query.filter(filt)
    return query

rawDescription: Dynamically constructing filters in SQLAlchemy


code:
def try_get(dic, default, *keys):
    for key in keys:
        try:
            dic = dic[key]
        except KeyError:
            return default
    return dic

e['a'] = try_get(d, 0, 'a')
e['d'] = try_get(d, 0, 'b', 'c', 'd')

rawDescription: Returning default value from a nested dict lookup in python


code:
import pygame

# you'll be able to shoot every 450ms
RELOAD_SPEED = 450

# the foes move every 1000ms sideways and every 3500ms down
MOVE_SIDE = 1000
MOVE_DOWN = 3500

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

pygame.display.set_caption("Micro Invader")

# create a bunch of events
move_side_event = pygame.USEREVENT + 1
move_down_event = pygame.USEREVENT + 2
reloaded_event  = pygame.USEREVENT + 3

move_left, reloaded = True, True

invaders, colors, shots = [], [] ,[]
for x in range(15, 300, 15):
    for y in range(10, 100, 15):
        invaders.append(pygame.Rect(x, y, 7, 7))
        colors.append(((x * 0.7) % 256, (y * 2.4) % 256))

# set timer for the movement events
pygame.time.set_timer(move_side_event, MOVE_SIDE)
pygame.time.set_timer(move_down_event, MOVE_DOWN)

player = pygame.Rect(150, 180, 10, 7)

while True:
    clock.tick(40)
    if pygame.event.get(pygame.QUIT): break
    for e in pygame.event.get():
        if e.type == move_side_event:
            for invader in invaders:
                invader.move_ip((-10 if move_left else 10, 0))
            move_left = not move_left
        elif e.type == move_down_event:
            for invader in invaders:
                invader.move_ip(0, 10)
        elif e.type == reloaded_event:
            # when the reload timer runs out, reset it
            reloaded = True
            pygame.time.set_timer(reloaded_event, 0)

    for shot in shots[:]:
        shot.move_ip((0, -4))
        if not screen.get_rect().contains(shot):
            shots.remove(shot)
        else:
            hit = False
            for invader in invaders[:]:
                if invader.colliderect(shot):
                    hit = True
                    i = invaders.index(invader)
                    del colors[i]
                    del invaders[i]
            if hit:
                shots.remove(shot)

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]: player.move_ip((-4, 0))
    if pressed[pygame.K_RIGHT]: player.move_ip((4, 0))

    if pressed[pygame.K_SPACE]:
        if reloaded:
            shots.append(player.copy())
            reloaded = False
            # when shooting, create a timeout of RELOAD_SPEED
            pygame.time.set_timer(reloaded_event, RELOAD_SPEED)

    player.clamp_ip(screen.get_rect())

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

    for invader, (a, b) in zip(invaders, colors):
        pygame.draw.rect(screen, (150, a, b), invader)

    for shot in shots:
        pygame.draw.rect(screen, (255, 180, 0), shot)

    pygame.draw.rect(screen, (180, 180, 180), player)
    pygame.display.flip()

rawDescription: Pygame: Spaceinvaders: can't shoot bullets


code:
imhist
imhist * np.diff(bins)
(imhist * np.diff(bins)).sum()

rawDescription: How does numpy.histogram works with the normal=True option


code:
if n % 2 != 0:
    for l in axs[i/2-1,1].get_xaxis().get_majorticklabels():
        l.set_visible(True)
    f.delaxes(axs[i/2, 1])

f.show()

rawDescription: matplotlib with odd number of subplots

description: Matplotlib with odd number of subplots


code:
def __getattr__(self, name):
    try:
        return self._service_calls[name]
    except KeyError:
        raise AttributeError

rawDescription: Is it possible to maintain "boundness" of a method when passing it as an object outside its class


code:
seen_sets = []
to_write = []

with open('input.csv', 'rb') as fin:
    r = csv.reader(fin)
    for row in r:
        newset = set(r[1].split(',')).union(r[2].split(','))
        prev = any(len(s.intersection(newset)) > 1 for s in seen_sets)
        seen_sets.append(newset)
        row.append('1' if prev else '0')
        to_write.append(row)

with open('output.csv', 'wb') as fou:
    w = csv.writer(fou)
    w.writerows(to_write)

rawDescription: Python: count if items in a row appears in previous rows together


code:
textures_file = open('textures.txt', 'w')
decode_file = open('to_decode.txt', 'w')

textures_file.write("Username: " + username + " Textures: " + textures)
decode_file.write(textures)

rawDescription: How to write to multiple files in Python?

description: Write to multiple files in Python


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

post_save.connect(save_pet_handler, sender=Owner, dispatch_uid="my_unique_identifier")

def save_pet_handler(sender, instance, created, **kwargs):
    ...

rawDescription: Django: save a OneToOneField automatically from *related* model?


code:
df = pd.DataFrame({'a': [0,0,0,0,70,0,0,90,0,0,80,0,0],
                       'b': [0,0,0,50,0,60,0,90,0,80,0,0,0]})

fig, axs = plt.subplots(1,2,figsize=(10,4))

# plot the original, for comparison
df.plot(ax=axs[0])

for name, col in df.iteritems():
    col[col != 0].plot(ax=axs[1], label=name)

axs[1].set_xlim(df.index[0],df.index[-1])
axs[1].set_ylim(bottom=0)
axs[1].legend(loc=0)

rawDescription: plot pandas data frame but most columns have zeros

description: Plot pandas data frame but most columns have zeros


code:
from collections import Counter
x = [1, 2, 3, 2, 1, 8]
counts = Counter(x)
[item for item in x if counts[item] == 1]

rawDescription: Need help finding a way using a set that returns a list that occur only once in a while still preserving order?


code:
class Orb(object):
    def __init__(self,posorg,posdest):
        self.posx=posorg[0]
        self.posy=posorg[1]
        self.targ=posdest
        self.posorg=posorg
        self.bullet_vector=Move(self.targ[0],self.targ[1],self.posx,self.posy,20)
    def update(self):
        self.posx += self.bullet_vector[0]
        self.posy += self.bullet_vector[1]
        pygame.draw.circle(screen, ((0,0,255)), (int(self.posx),int(self.posy)), 5)

rawDescription: Make an object move in a direction constantly Pygame


code:
species = ['A', 'B', 'H', 'S', 'P', 'N']

data2 = data.set_index(['Species'])
data2.reindex(species).plot(kind='bar', stacked=True, figsize=(15, 10), fontsize=16, rot=0)

rawDescription: Change order of columns in stacked bar plot


code:
from itertools import product
n = 3
# generate product in reverse lexicographic order
bin_str = [''.join(p) for p in product('10', repeat=n)]
# ['111', '110', '101', '100', '011', '010', '001', '000']
# sort by number of ones
bin_str.sort(key=lambda s: s.count('1'))
# ['000', '100', '010', '001', '110', '101', '011', '111']

rawDescription: create list of binary strings (Python)

description: Create list of binary strings (Python)


code:
class Movement(EntityComponent):
    def __init__(self):
        # Default values
        self.speed = 0
        self.acceleration = 0

    serializable_fields = [
        ('speed', int),
        ('acceleration', int)
    ]

def load(object, source):
    for name, field_type in object.serialiable_fields:
        settarr(object, name, field_type(source[name]))

def save(object):
    target = PropertyTree()
    for name, field_type in object.serializable_fields:
         target[name] = str(getattr(object, name))
    return target

rawDescription: How should I refactor/redesign my code

description: How should I refactor/redesign my code


code:
for element in elements:
    if element.get_attribute('type') == 'datetime':
        element.send_keys('11/11/2011')

rawDescription: How to sort through WebElements

description: Sort through WebElements


rawDescription: Running both python 2.6 and 3.1 on the same machine


code:
df = pandas.DataFrame([1,2,3,4], columns=["data"])
df
df["desired"] = df["data"] > 2.5
df

rawDescription: Conditional Logic on Pandas DataFrame

description: Conditional Logic on Pandas DataFrame


code:
with open('list', 'rt') as list_file:
    values = [line.strip() for line in list_file]

with open('cluster', 'rt') as cluster_file, open('Table', 'wt') as table_file:
    for cluster in (set(line.split()) for line in cluster_file):
        row = ' '.join('01'[value in cluster] for value in values)
        table_file.write(row + '\n')

rawDescription: Making a presence/absence matrix from two files using python


code:
data = resp["color"]
i = 0
colors = []
sizes = []
while i<len(data)-1:
    d = data[i]
    if d.startwith("Color"):
        colors.append(data[i+1])
        i += 1
    elif d.startwith("Size"):
        sizes.append(data[i+1])
        i += 1
    i += 1

resp['color'] = colors
resp['size'] = sizes

rawDescription: how to create two new lists from this mix in python?

description: Create two new lists from this mix in python


code:
import inspect
import my_module
[m[0] for m in inspect.getmembers(my_module, inspect.isclass) if m[1].__module__ == 'my_module']

rawDescription: Python: get only classes defined in imported module with dir()?


code:
while True:
  REFERENCE = raw_input("Reference (*.shp):")
  SEGMENTED = raw_input("Segmented (*.shp):")
  METHOD = raw_input("Method (ke, pu, clinton):")
  if METHOD != "ke" and METHOD != "pu" and METHOD != "clinton":
    raise ValueError("%s is not a valid method" % METHOD)
  if METHOD == "ke" or METHOD == "clinton":
    THRESHOLD = input("Threshold (0.0 - 1.0):")
    if not check_threshold(THRESHOLD):
        raise AccuracyException("Threshold of %s is not valid" % THRESHOLD)
  else:
    THRESHOLD = None
  SEP = raw_input("Sep:")
  if SEP != "space" and SEP != "tab" and SEP != "comma" and SEP != "colon" and SEP != "semicolon" and SEP != "hyphen" and SEP != "dot":
    raise ValueError("%s is not valid" % SEP)
  HEADER = raw_input("Header (True/False):")
  if HEADER.strip() != "True" and HEADER.strip() != "False":
    raise ValueError("%s is not valid" % HEADER)
  # output
  OUTPUT = raw_input("Output (*.txt):")

rawDescription: How to reset the input stream in python?

description: Reset the input stream in python


code:
PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
PyObject* PyObject_GetItem(PyObject *o, PyObject *key)

rawDescription: How do I create an array slice using the NumPy C API?

description: Create an array slice using the NumPy C API


code:
import urlparse
urlparse.urljoin("ftp://domain.com/a/b/c/d/", "../..")
urlparse.urljoin("ftp://domain.com/a/b/c/d/e.txt", "../..")

rawDescription: How can I normalize/collapse paths or URLs in Python in OS independent way?

description: Normalize/collapse paths or URLs in Python in OS independent way


code:
ORDER_CHOICES_WITH_PRICES = [
    (key, "%s - %s€" % (val, ORDER_PRICES[key][0]))
    for key, val in ORDER_CHOICES
]

rawDescription: Django: How to customize a form ChoiceField display?


code: df = xl.parse("Sheet1", header=None)

rawDescription: How to specify column names while reading an Excel file using Pandas?

description: Specify column names while reading an Excel file using Pandas


code:
sqlalchemy.echo = true
sqlalchemy.echo_pool = true

rawDescription: Logging queries with sqlalchemy 0.6

description: Logging queries with sqlalchemy 0.6


code:
import csv
from collections import OrderedDict

data = OrderedDict()
with open('input.txt') as f:
    reader = csv.reader(f, delimiter='|')
    for row in reader:
        row = [e.strip() for e in row]
        person   = row[0]
        location = (row[1], row[2])

        if location not in data: data[location] = []

        data[location].append(person)

# Show voting places
print("Voting places (voting_place_id, voting_place):")
for (i,k) in enumerate(data):
    print("  %3d %s" % (i,k))
print("")

# Show voters
print("Voters (voting_place_id, person):")
for (i,k) in enumerate(data):
    for p in data[k]:
        print("  %3d %s" % (i,p))
print("")

rawDescription: How do I normalize a CSV list in to 2 or more separate files?

description: Normalize a CSV list in to 2 or more separate files


code:
def calculate_result(items):
    items = tuple(int(i) for i in items)
    result = sum(items) / 16500.0
    result = result / len(items)
    return '%i' % round(result) + '%'

result0 = calculate_result(item.start for item in exams)
result1 = calculate_result(item.s1 for item in exams)
result2 = calculate_result(item.s2 for item in exams)

rawDescription: Refactor this views code

description: Refactor this views code


code:
def save_plain(self, *args):
    """
    A plain save function. If there's no preexisting file name,
    uses save_as() instead.
    Parameter:
        *args: may include an event
    """
    if self.savename: # if there's a name
        self.save(self.savename) # then use it
    elif self.save_as(): # else, use save_as instead
        return True # successful save returns True
    return False # else, return False

def save_as(self, *args):
    """
    A save as function, which asks for a name and only retains it if it was given
    (canceling makes empty string, which isn't saved).
    Parameter:
        *args: may include an event
    """
    temp = filedialog.asksaveasfilename(defaultextension=".txt", \
    filetypes=(('Text files', '.txt'),('All files', '.*'))) # ask for a name
    if temp: # if we got one,
        self.savename = temp # retain it
        self.save(temp) # and pass it to save()
        return True
    return False

def save(self, filename):
    """
    Does the actual saving business of writing a file with the given name.
    Parameter:
        filename (string): the name of the file to write
    """
    try: # write the movelist to a file with the specified name
        with open(filename, 'w', encoding = 'utf-8-sig') as output:
            for item in self.movelist:
                output.write(item + "\n")
        self.unsaved_changes = False # they just saved, so there are no unsaved changes
    except: # if that doesn't work for some reason, say so
        messagebox.showerror(title="Error", \
        message="Error saving file. Ensure that there is room and you have write permission.")

rawDescription: Creating Python button saves edited file


code:
for line in csvdata:
    multiplicity = max([len(datum.split(" ")) if isinstance(datum, str) else 0 for datum in line])
    for datum in line:
        if(not isinstance(datum, str)):
            datum = " ".join(["-1"]*multiplicity)

rawDescription: How to replace empty string in python

description: Replace empty string in python


code: face1 = imgg[y:y+height, x:x+width]

rawDescription: opencv and python: how to use cv2.surf() with mask

description: Opencv and python: how to use cv2.surf() with mask


rawDescription: Get the quotient when dividing a float in Python 2.7


code:
line = "ABC"
type(line)
line = line.decode("cp1252")
type(line)
line

rawDescription: What does a `line.decode()` do in Python 2?


code:
import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

rawDescription: How to write to an existing excel file without overwriting data?

description: Write to an existing excel file without overwriting data


code:
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxW
MessageBox(None, 'Hello', 'Window title', 0)

rawDescription: Ctypes Text Input Box Help Using Python

description: Ctypes Text Input Box Help Using Python


code:
import re
regex = re.compile('(.*)(?:India)')
with open("D:/txt_res/abc.txt") as f:
    for line in f:
        match = regex.search(line)
        if match is not None:
            print(match)

rawDescription: Grouping Output Pattern in Regex- Python


code:
query = self.dbObj.session.query(MaterialsTable)
for attr , val in interfaceCodesObject.filterNameDict.items():
    query = query.filter(and_(getattr(MaterialsTable,attr).like("%%%s%%" % val)))

# all result rows
query.all()

# count of rows
rowCounter = query.count()

rawDescription: sqlalchemy and how to count row

description: Sqlalchemy and how to count row


code:
import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("http://games.espn.go.com/ffl/signin")
#implement wait it is mandatory in this case
WebDriverWait(driver,1000).until(EC.presence_of_all_elements_located((By.XPATH,"(//iframe)")))
frms = driver.find_elements_by_xpath("(//iframe)")

driver.switch_to_frame(frms[2])
time.sleep(2)
driver.find_element_by_xpath("(//input)[1]").send_keys("username")
driver.find_element_by_xpath("(//input)[2]").send_keys("pass")
driver.find_element_by_xpath("//button").click()
driver.switch_to_default_content()
time.sleep(4)
driver.close()

rawDescription: Logging into ESPN using Selenium

description: Logging into ESPN using Selenium


code:
params = OrderedDict()
params['requestEnvelope.errorLanguage'] = 'en_US'
params['payKey'] = pay_key
res = requests.post('https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails/', headers=headers, data=params)
transaction_id = res.json()['paymentInfoList']['paymentInfo'][0]['senderTransactionId']

rawDescription: How to get transactionID from payment

description: Get transactionID from payment


code:
import requests
response = requests.head('http://example.com')
response.headers

rawDescription: Get file size using python-requests, while only getting the header


code:
import maya.cmds as cmds

def import_multiple_object_files():
    files_to_import = cmds.fileDialog2(fileFilter =  '*.obj', dialogStyle = 2, caption = 'import multiple object files', fileMode = 4)
    for file_to_import in files_to_import:
        names_list  = file_to_import.split('/')
        object_name = names_list[-1].replace('.obj', '')
        returnedNodes = cmds.file('%s' % file_to_import, i = True, type = "OBJ", rnn=True, ignoreVersion = True, options = "mo=0",  loadReferenceDepth  = "all"  )
        cmds.rename( returnedNodes[0], object_name)

rawDescription: importing and renaming multiple objects in maya with python

description: Importing and renaming multiple objects in maya with python


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

yy, zz = np.meshgrid(range(2), range(2))
xx = yy*0

ax = plt.subplot(projection='3d')
ax.plot_surface(xx, yy, zz)
plt.show()

rawDescription: How does one draw the X = 0 plane using matplotlib (mpl3d)?

description: Draw the X = 0 plane using matplotlib (mpl3d)


code:
"?" == True
"?" == False # it's not False either
bool("?")

rawDescription: How does "all" function in python works?

description: How does "all" function in python works


rawDescription: Modifying and creating sites in djangos admin app


code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox()
driver.get("http://www.saksoff5th.com/")

driver.implicitly_wait(10) # seconds

driver.find_element_by_css_selector(".sign-in > span").click()
driver.find_element_by_css_selector(".ui-dialog[style*='display: block'] .ui-icon-closethick").click()

# If you prefer explicit wait, you can do these
# WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_css_selector(".sign-in > span")).click()
# WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_css_selector(".ui-dialog[style*='display: block'] .ui-icon-closethick")).click()

rawDescription: Clicking visible close button inside a dialog


code:
f= a*b - b
y = sp.Wild('y', properties=[lambda x: isinstance(x, Symbol)])
x = sp.Wild('x', properties=[lambda x: isinstance(x, Symbol)])
f.replace(x*y, c)

rawDescription: Sympy: Replacement using Wild symbols

description: Sympy: Replacement using Wild symbols


code:
import datetime,  os

current_month = datetime.date.today().replace(day=1)
# this could be more concise if `start_month` were the month number rather than month name
possible_month = datetime.datetime.strptime('%s %s' % (start_month, start_year), '%B %Y').date()
while possible_month <= current_month:
    csv_filename = possible_month.strftime('%B %Y') + '.csv'
    if os.path.exists(csv_filename):
        CSVFile = True
        # do something cool here, and maybe break the loop if you like
    possible_month = (possible_month + datetime.timedelta(days=31)).replace(day=1)

rawDescription: Cycling through a list of months with years to check if file exists


code:
import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_save
from django.dispatch import receiver

class Uuidable(models.Model):
    uuid = models.CharField(_('uuid'), blank=True,
                            null=False, unique=True,
                            max_length=64, default=uuid.uuid4())

    class Meta:
        abstract = True

    @receiver(pre_save)
    def set_uuid_on_save(sender, instance, *args, **kwargs):
        if instance.pk is None:
            instance.uuid = uuid.uuid4()

rawDescription: Django fixtures save with default value

description: Django fixtures save with default value


code:
import bisect
position = bisect.bisect_left(range_list, your_input)
if position > 0:
    nearest_range = range_list[position - 1]
else:
    nearest_range = None

rawDescription: Python: getting the previous item from a list based on closeness


code:
from django.contrib import admin
from django.db import models
class MyModelAdmin(admin.ModelAdmin):

    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs.filter(date__year="2013")
        else:
            return qs

class MyModel(models.Model):
    date = models.DateField()

admin.site.register(MyModel, ModelAdmin)

rawDescription: How to display a query set in the django admin?

description: Display a query set in the django admin


code:
sys1 = __import__("sys")
import imp
sys2 = imp.load_module("sys2", *imp.find_module("sys"))
import sys
sys is sys1 is sys2

rawDescription: Python: Load module by its name

description: Python: Load module by its name


code:
import matplotlib.pyplot as plt
plt.loglog(range(100))
ax1 = plt.gca()
ax2 = ax1.twiny()
ax2.set_xticks([100,80,50])
ax2.set_xticklabels(['0','1','2'])
ax1.set_xlabel('redshift')
ax2.set_xlabel('age')
plt.show()

rawDescription: Multiple x-axis, which are nonlinear to each other


code:
fig, ax =  subplots()
ax.set_frame_on(False)

rawDescription: plot python figure with ticks only and not axes lines

description: Plot python figure with ticks only and not axes lines


code:
subprocess.Popen([setup.profile['NSISExe'], '/DON=' + setup.profile['DESC'],
                  '/DOD=' + setup.profile['InstallDir'],
                  '/DMT=' + app.machine_type.get(),
                  '/DSD=' + os.path.join(WinShellVar.LOCAL_APPDATA, 'MLC CAD', appname),
                  '/DXV=X6',
                  setup.profile['NSISScript']])

rawDescription: Run windows executable from python script with multiple arguments


code:
def writeYaml(data, filename):

  sections = data.keys()
  dump = yaml.dump(data, default_flow_style=False)

  # set 2 indent spaces in every line
  out = dump.replace('\n', '\n  ')
  # re-set indentation for sections only
  for i in sections:
      out = out.replace('\n  %s' % i, '\n%s' % i)

  with open(filename, 'w') as yaml_file:
      yaml_file.write(out)

rawDescription: How to parse and append to flexget yaml config file?

description: Parse and append to flexget yaml config file


code:
def download_paper(request, paper_pk):
     paper = get_object_or_404(Paper, pk=paper_pk) # get your model instance
     # also check permissions on paper, if necessary
     with paper.pdf_file_field.open("r") as fd:
         response = HttpResponse(fd.read(), content_type="application/pdf")
         response['Content-Disposition'] = 'attachment; filename="%s"' % paper.pdf_file_field.name
         return response

rawDescription: I need to be able to redownload a document that was submitted onto my django website


code:
text = "You don't have enough funds, please click -><a href='%s'> here </a><- go to your account to add funds." % reverse('add_funds')

raise forms.ValidationError(mark_safe(_(text)),
                                            code='insufficent_funds',
                                            )

rawDescription: Raising a validationerror in django with marksafe


code:
myfile = open('myfile.tar', 'wb')
shutil.copyfileobj(response.fp, myfile)
myfile.close()

rawDescription: Downloading file using post method and python


code:
import ExifTags
import Image

img = Image.open(filename)
print(img._getexif().items())
exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS)
if not exif['Orientation']:
    img=img.rotate(90, expand=True)
img.thumbnail((1000,1000), Image.ANTIALIAS)
img.save(output_fname, "JPEG")

rawDescription: PIL thumbnail is rotating my image?

description: PIL thumbnail is rotating my image


code:
class Territory(models.Model):
    name = models.CharField(max_length=150)

class Country(Territory):
    iso = models.CharField(max_length=2, primary_key=True)

class Region(Territory):
    iso = models.CharField(max_length=2, blank=True)
    country = models.ForeignKey('Country')

class City(Territory):
    region = models.ForeignKey('Region')

class Artist(models.Model):
    name = models.CharField(max_length=128)
    born_place = models.ForeignKey(Territory)
    dead_place = models.ForeignKey(Territory)
    live_places = models.ManyToManyField(Territory)
    work_places = models.ManyToManyField(Territory)

rawDescription: How to model a m2m relation where the related table can be a city, a region (state) or a country

description: Model a m2m relation where the related table can be a city, a region (state) or a country


code:
def build_filters(self, filters=None):

    """
    Adds support for negation filtering
    """
    if not filters:
        return filters

    applicable_filters = {}
    self.filters = filters

    # Normal filtering
    filter_params = dict([(x, filters[x]) for x in filter(lambda x: not x.endswith('!'), filters)])
    applicable_filters['filter'] = super(MainBaseResource, self).build_filters(filter_params)

    # Exclude filtering
    exclude_params = dict([(x[:-1], filters[x]) for x in filter(lambda x: x.endswith('!'), filters)])
    applicable_filters['exclude'] = super(MainBaseResource, self).build_filters(exclude_params)

    return applicable_filters

def apply_filters(self, request, applicable_filters):

    """
    Adds support for:
    1. negation filtering: value_date__year!=2013
    2. multiple filtering value_date__year=2013,2012
    """

    from django.db.models import Q
    import operator
    from types import *

    objects = self.get_object_list(request)

    f = applicable_filters.get('filter')

    if f:
        # Q Filters for multiple values (1,2,3 etc)
        q_filters = []
        for key, val in f.iteritems():
            string = str(val)
            if ',' in string:
                for excl_filter in string.split(','):
                    q_filters.append((key, excl_filter))

        q_list = [Q(x) for x in q_filters]
        for x in q_filters:
            try:
                del f[x[0]]
            except:
                pass
        if q_list:
            objects = objects.filter(reduce(operator.or_, q_list), **f)
        else:
            objects = objects.filter(**f)

    e = applicable_filters.get('exclude')
    if e:
        objects = objects.exclude(**e)
    return objects

rawDescription: How do I construct an AND query on the same field in the URL of TastyPie?

description: Construct an AND query on the same field in the URL of TastyPie


code:
s = Series(pd.to_timedelta(['756 days','2 days', '3 days 5 min']))
s
s.astype('timedelta64[D]')
s / np.timedelta64(1,'D')

rawDescription: Pandas: Cast datetime column as int

description: Pandas: Cast datetime column as int


code:
from struct import pack

def pack_message(content):
    magic = [0xb1, 0x02, 0x00, 0x00]
    return pack("I", len(content)) + \
           pack("%dI" % len(magic), *magic) + \
           pack("s I", bytearray(content, 'utf-8'), 0)

print(pack_message("Hello, world!\n"))

rawDescription: Converting a few lines of Java code into python. (struct.pack)


code:
Post.objects.raw("""
    SELECT DISTINCT post FROM
        (SELECT appname_post.post_id AS post, appname_recommendation.submit_time
        FROM appname_post
        INNER JOIN appname_recommendation
        ON appname_post.post_id = appname_recommendation.post_id
        ORDER_BY appname_recommendation.submit_time)
    """)

rawDescription: Django - sort QuerySet by backwards related model's field


code:
class Shape(object):
    def __init__(self, sides=4):
        self.sides = sides

rawDescription: Class accepts varying arguments Python

description: Class accepts varying arguments Python


rawDescription: My regex is not working properly

description: My regex is not working properly


code:
answer_disp.clicked.connect(
    lambda ca=current_answer, a=answer: self.ap.parse_answer(ca, a))

rawDescription: PyQt connect() call affecting multiple widgets


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

iMax = N = 500
theta = np.linspace(0, 6*np.pi, N)
x = np.cos(theta)
y = np.sin(theta)
z = np.linspace(0, 1, N)
step = 10
dati = np.column_stack(
    [theta, x, np.roll(x, -step), np.roll(x, -2*step)
     , y, np.roll(y, -step), np.roll(y, -2*step)
     , z, np.roll(z, -step), np.roll(z, -2*step)])

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
seg, = plt.plot([], [])

ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(0, 1)

def init():
    return seg,

def updateFigure(t):
    p1 = dati[t, 1:4]
    p2 = dati[t, 4:7]
    p3 = dati[t, 7:10]
    seg._verts3d = (p1, p2, p3)
    return seg,

ani = animation.FuncAnimation(
    fig, updateFigure
    , init_func=init
    , frames=iMax
    , interval=5, blit=True)
plt.show()

rawDescription: Animate a segment in a 3d space

description: Animate a segment in a 3d space


code:
import copy
import cProfile

def main():
    # ...your earlier code goes here
    num = 5
    list =  list1
    list1 = [copy.deepcopy(x) for item in list for x in repeat(item, num)]
    for i, val in enumerate(list1):
        list1[i]['account']['id'] = randint(2,10)
        list1[i]['account']['name'] = 'name' + randint(2,10)
        list1[i]['account']['FullName'] = 'statusName' + randint(2,10)
        list1[i]['account']['login'] = 'login'  + randint(2,10)
        list1[i]['account']['contract']['id']= randint(2,10)

if __name__ == "__main__":
    cProfile.run("main()", sort="cumulative")

rawDescription: python add copy element of the list to list

description: Python add copy element of the list to list


code:
def PrintProductsBelowNumber(number):
    number1 = 1
    while number1 <= number:
        number2 = 1
        while number2 <= number:
            print(number1, "*", number2, "=", number1 * number2)
            number2 += 1
        number1 += 1

PrintProductsBelowNumber(2)

rawDescription: What is wrong with my nested loops in Python?


code:
regex = re.compile('{}(.*){}'.format(re.escape(''), re.escape('')))
regex.findall('Text')

rawDescription: Regex to extract between two strings (which are variables)


code:
def unpair(iterable):
    p = iter(iterable)
    return chain(next(p, []), (x[1] for x in p))

rawDescription: Reverse the `pairwise` generator

description: Reverse the `pairwise` generator


code:
def find_closest(A, target):
    #A must be sorted
    idx = A.searchsorted(target)
    idx = np.clip(idx, 1, len(A)-1)
    left = A[idx-1]
    right = A[idx]
    idx -= target - left < right - target
    return A[idx]

arr2.sort()
closest = find_closest(arr2, arr1)
closest = np.where(abs(closest - arr1) < .375, closest, np.nan)

rawDescription: Speed up minimum search in Numpy/Python

description: Speed up minimum search in Numpy/Python


code:
def numVowels(a):
    vowels = "aeuioAEUIO"
    result = 0
    for char in a:
        if char in vowels:
            result = result + 1
    return result

numVowels("ajdgejfifhou")

rawDescription: Count vowels in a string

description: Count vowels in a string


code:
a = [1, 2]
b = a[:]  # slice with all the elements, produces a *copy*
b
a.pop()  # remove an element from a won't change b
b
a

rawDescription: Function which removes the first item in a list (Python)


code:
from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options, using_table_options, GenericProperty
from sqlalchemy.orm import relation
from sqlalchemy import ForeignKeyConstraint

class Company(Entity):
    using_options(tablename='company')

    company_id = Field(Unicode(32), primary_key=True)
    display_name = Field(Unicode(255))
    pages = OneToMany('Page')

class Page(Entity):
    using_options(tablename='page')

    company = ManyToOne('Company', colname='company_id', primary_key=True)
    url = Field(Unicode(255), primary_key=True)
    attrs = OneToMany('Attr')

class Attr(Entity):
    using_options(tablename='attr')

    page = ManyToOne('Page', colname=['company_id', 'url'], primary_key=True)
    attr_key = Field(Unicode(255), primary_key=True)

    using_table_options(ForeignKeyConstraint(['company_id'], ['company.company_id']))
    company = GenericProperty(relation(Company))

rawDescription: Elixir (SqlAlchemy): relations between 3 tables with composite primary keys


code:
with open('sampled_data.csv', 'w') as f:
  while True:
    f.write(','.join(str(adc.read(AIN0)*1800)))
    time.sleep(T)

rawDescription: Analog sampling on the Beaglebone Black only reads noise


code:
parser.add_option('-M', '--module-first', action='store_true',
                  dest='modulefirst',
                  help='Put module documentation before submodule '
                  'documentation')

rawDescription: Can Sphinx emit the 'module contents' first and the 'submodules' last?


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

x_points = np.random.rand(100)
y_points = np.random.rand(100)

bp.figure(title='My Title', x_axis_label='X axis', y_axis_label='Y axis', \
    title_text_font_size='8pt')

bp.scatter(x_points, y_points)
bp.show()

rawDescription: Adjust title font size for a Bokeh figure


code:
self.list_widget = QListWidget()
files = glob.glob('YourDirectory/*.jpg') #Get all jpegs in your directory
for i in files:
    self.list_widget.addItem(QListWidgetItem(QIcon(i),'your text here'))
self.list_widget.setIconSize(QSize(400,300)) #Set your image size

rawDescription: Configuring a custom scrollbar in PyQt

description: Configuring a custom scrollbar in PyQt


code:
def save_currencies(_fetch_currencies, filename):
    with open(filename, 'w') as my_csv:
        my_csv.write('code,name\n')   # add header line
        csv_writer = csv.writer(my_csv, delimiter=',')
        csv_writer.writerows(_fetch_currencies)

rawDescription: How to save data to a specific folder and add header line in csv file

description: Save data to a specific folder and add header line in csv file


code:
import readline
import shlex

print('Enter a command to do something, e.g. `create name price`.')
print('To get help, enter `help`.')

while True:
    cmd, *args = shlex.split(input('> '))

    if cmd=='exit':
        break

    elif cmd=='help':
        print('...')

    elif cmd=='create':
        name, cost = args
        cost = int(cost)
        # ...
        print('Created "{}", cost ${}'.format(name, cost))

    # ...

    else:
        print('Unknown command: {}'.format(cmd))

rawDescription: Python Interactive Shell Type Application


code:
time = datetime.datetime.strptime("04:35:45", "%H:%M:%S").time()
time
day = datetime.datetime.now().date()
day
datetime.datetime.combine(day, time)

rawDescription: What's the best way to create datetime from "%H:%M:%S"


code:
# Choose some default value
default = 0
# Prepare dict with defaults
defaults = {k: default for k in chain(*(x.keys() for x in dc.values()))}

# Fill gaps if needed and construct data frame
df = pd.DataFrame(
    {k: dict(defaults.items() + v.items()) for k, v in dc.items()},
    index=['a', 'b', 'c','d'], dtype=np.uint8)

rawDescription: how to fill the missing value when constructing a DataFrame?

description: Fill the missing value when constructing a DataFrame


code:
from collections import Counter
l = ['html', 'header', 'title', 'body', 'div', 'div', 'div', 'div', 'div', 'ul', 'li', 'li', 'li']
[item for item, cnt in Counter(l).items() if cnt > 2]

rawDescription: In python how to count occurance of elements in list


code:
s1 = wb.add_sheet("Test")

s1.write(0, 0, "Col 1")
s1.write(0, 1, "Col 2")
s1.write(0, 2, "Col 3")
s1.write(0, 3, "Col 4")
s1.write(0, 4, "Col 5")

test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
list2 = []
for val in test_list:
    list2.append(str(val))

# Generator for column
def next_c_index():
    c = [1, 2, 3, 4]
    while True:
        for i in c:
            yield i

# Generator for row
def next_r_index(ncolumns=5):
    """
    Assumes you start from writing from 2nd row.
    :ncolumns = number of columns (default 5)
    Eg. 1, 1, 1, 1, 2, 2, 2, 2
    """
    n = 0
    r = 0
    while True:
        # In every cycle of 4
        if (n)%(ncolumns-1)==0:
            r += 1
        n += 1
        yield r

# Since you have 5 columns I pass 5 while calling row generator
row = next_r_index(ncolumns=5)
col = next_c_index()
for val in list2:
    s1.write(row.next(), col.next(), val)

rawDescription: Adding iterated array values to xlwt sheet


code:
span = browser.find_element_by_xpath("//div[@class='video-details-inside']/table//span[@class='added-time']")
td = span.find_element_by_xpath('..')
views = td.text.replace(span.text, '').strip()

rawDescription: Python crawler not finding specific Xpath


rawDescription: Mapping dummy variables in pandas data frame


rawDescription: Numpy: expanding subarray of a larger array


rawDescription: What does os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) mean? python


rawDescription: How to pad a string to a fixed length with spaces in Python?

description: Pad a string to a fixed length with spaces in Python


rawDescription: Replacing leading and trailing hyphens with spaces?


code: [v[2] for v in dictionary1.values()]

rawDescription: Possible to extract a List from a Dictionary of Lists in Python?


code:
import requests
r = requests.post('http://httpbin.org/post', json={"key": "value"})
r.status_code
r.json()

rawDescription: Post JSON using Python Requests

description: Post JSON using Python Requests


code:
#CTimer

import os;
import time

#vl

repeater = 2

sleeptime = 0.00

#code

while repeater==2:
    print("-CTimer-")
    print("\n")
    print("Set time")
    print("Use preset")
    print("Exit")
    print("\n")
    var1 = input(">>>")

    if var1=="set time":

        sleeptime = float(input("Set time:"))  #<-- add float()

        start = input("Start")

        time.sleep(sleeptime)

        os.system("C:/Python34/Scripts/alsctimer64an.bat")

    if var1=="use preset":

        print("1min")
        print("5min")
        print("10min")
        print("20min")
        print("30min")
        print("45min")
        print("1hour")
        print("\n")
        usepreset = input("Use preset:")

        if usepreset=="1min":

            start = input("Start")

            time.sleep(60)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

        if usepreset=="5min":

            start = input("Start")

            time.sleep(300)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

        if usepreset=="10min":

            start = input("Start")

            time.sleep(600)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

        if usepreset=="20min":

            start = input("Start")

            time.sleep(1200)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

        if usepreset=="30min":

            start = input("Start")

            time.sleep(1800)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

        if usepreset=="45min":

            start = input("Start")

            time.sleep(2700)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

        if usepreset=="1hour":

            start = input("Start")

            time.sleep(3600)

            os.system("C:/Python34/Scripts/alsctimer64an.bat");

    if var1=="exit":

        print("Exiting...")

        time.sleep(5)

        exit()

rawDescription: I'm trying to create a countdown timer, but it doesn't work


code:
import time
from multiprocessing import Process, Pipe

import numpy as np
import matplotlib.pyplot as plt

class DataStreamProcess(Process):
    def __init__(self, connec, *args, **kwargs):
        self.connec = connec
        Process.__init__(self, *args, **kwargs)

    def run(self):
        random_gen = np.random.mtrand.RandomState(seed=127260)
        for _ in range(30):
            time.sleep(0.01)
            new_pt = random_gen.uniform(-1., 1., size=2)
            self.connec.send(new_pt)

def main():
    conn1, conn2  = Pipe()
    data_stream = DataStreamProcess(conn1)
    data_stream.start()

    plt.gca().set_xlim([-1, 1.])
    plt.gca().set_ylim([-1, 1.])
    plt.gca().set_title("Running...")
    plt.ion()

    pt = None
    while True:
        if not(conn2.poll(0.1)):
            if not(data_stream.is_alive()):
                break
            else:
                continue
        new_pt = conn2.recv()
        if pt is not None:
            plt.plot([pt[0], new_pt[0]], [pt[1], new_pt[1]], "bs:")
            plt.pause(0.001)
        pt = new_pt

    plt.gca().set_title("Terminated.")
    plt.draw()
    plt.show(block=True)

if __name__ == '__main__':
    main()

rawDescription: Matplotlib figure not responding when used with multiprocessing


rawDescription: Replacing Celery Beat "CELERYBEAT_SCHEDULE" with a dynamic source (database)


rawDescription: matplotlib's colormap

description: Matplotlib's colormap


code:
arc = open('file_name.txt').readlines()[0].split('\r')

#Do what you want with the 7th line i.e. arc[6]

new_arc = open('file_name.txt','w')
for line in arc:
    new_arc.write(line)
    new_arc.write('\n')

new_arc.close()

rawDescription: Remove Space from Particular line In Textfile Python


code:
import sys
from PyQt5 import QtCore, QtWidgets

class Thread(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)

    def run(self):
        thread_func()
        self.exec_()

timers = []

def thread_func():
    print("Thread works")
    timer = QtCore.QTimer()
    timer.timeout.connect(timer_func)
    timer.start(1000)
    print(timer.remainingTime())
    print(timer.isActive())
    timers.append(timer)

def timer_func():
    print("Timer works")

app = QtWidgets.QApplication(sys.argv)
thread_instance = Thread()
thread_instance.start()
sys.exit(app.exec_())

rawDescription: QT Timers not calling function

description: QT Timers not calling function


code:
from PIL import Image

im = Image.open('image-to-modify.jpg')

source = im.split()

R, G, B = 0, 1, 2
constant = 1.5 # constant by which each pixel is divided

Red = source[R].point(lambda i: i/constant)
Green = source[G].point(lambda i: i/constant)
Blue = source[B].point(lambda i: i/constant)

im = Image.merge(im.mode, (Red, Green, Blue))

im.save('modified-image.jpeg', 'JPEG', quality=100)

rawDescription: Low the brightness of an Image using Pillow


code:
d = g.degree_property_map("out", weight)   # weight is an edge property map
bins = linspace(d.a.min(), d.a.max(), 40)  # linear bins
h = vertex_hist(g, d, bins)

rawDescription: Weighted Degree Distribution in Python's graph_tool


code:
import pymongo
client = pymongo.MongoClient()

client.copy_database('foo', 'bar')

assert set(client['foo'].collection_names()) == set(client['bar'].collection_names())

for collection in client['foo'].collection_names():
    assert client['foo'][collection].count() == client['bar'][collection].count()

client.drop_database('foo')

rawDescription: How to rename a mongodb database using pymongo?

description: Rename a mongodb database using pymongo


code:
from functools import partial

with open('sample.txt', 'rb') as inputfile, open(outputfilename, 'wb') as output:
    for chunk in iter(partial(inputfile.read, 23), ''):
        # chunk is 23 bytes small
        output.write(chunk + '\n')

rawDescription: reading a line from a file and splitting it - python

description: Reading a line from a file and splitting it - python


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
norm.cdf(1.96)

def solve(m1,m2,std1,std2):
  a = 1/(2*std1**2) - 1/(2*std2**2)
  b = m2/(std2**2) - m1/(std1**2)
  c = m1**2 /(2*std1**2) - m2**2 / (2*std2**2) - np.log(std2/std1)
  return np.roots([a,b,c])

m1 = 2.5
std1 = 1.0
m2 = 5.0
std2 = 1.0

#Get point of intersect
result = solve(m1,m2,std1,std2)

#Get point on surface
x = np.linspace(-5,9,10000)
plot1=plt.plot(x,norm.pdf(x,m1,std1))
plot2=plt.plot(x,norm.pdf(x,m2,std2))
plot3=plt.plot(result,norm.pdf(result,m1,std1),'o')

#Plots integrated area
r = result[0]
olap = plt.fill_between(x[x>r], 0, norm.pdf(x[x>r],m1,std1),alpha=0.3)
olap = plt.fill_between(x[x<r], 0, norm.pdf(x[x<r],m2,std2),alpha=0.3)

# integrate
area = norm.cdf(r,m2,std2) + (1.-norm.cdf(r,m1,std1))
print("Area under curves ", area)

plt.show()

rawDescription: Overlapping probability of two normal distribution with scipy


code:
db.core_pid.update({"_id": current_id},
                   {"$set": {
                       "status": "Completed",
                       "endtime": datetime.now(pytz.timezone('EST'))}})

rawDescription: How to update multiple values in Mongodb using pymongo?

description: Update multiple values in Mongodb using pymongo


code:
from bs4 import BeautifulSoup as Soup

with open("sample.xml", "r") as f:
    target_xml = f.read()

# create a `Soup` object
soup = Soup(target_xml, "xml")

# loop through all <driver> returned as a list and prints all
for d in soup.find_all("driver"):
    print(d)

rawDescription: printing child nodes along with their xml tags in python

description: Printing child nodes along with their xml tags in python


code: execute(ssh_keygen, 'jbloggs', '/home/jbloggs', host="server1")

rawDescription: Fabric - Passing arguments to tasks via execute


code:
p = Popen(["command", "args"], stdout=PIPE, universal_newlines=True)
tmp = ""
delims = {"#", "!"}
for ch in iter(lambda: p.stdout.read(1), ""):
    if ch in delims:
        print(tmp)
        tmp = ""
    else:
        tmp += ch

rawDescription: how to read subprocess stdout using a different separator from line break

description: Read subprocess stdout using a different separator from line break


rawDescription: How do I remove a specific number of files using python (version 2.5)?

description: Remove a specific number of files using python (version 2.5)


code:
import urlparse
base_url = "http://example.com/foo/"
urlparse.urljoin(base_url, "../bar")
urlparse.urljoin(base_url, "/baz")

rawDescription: BeautifulSoup How to get url from img src when it has ../..?


code:
from random import randint
from pickle import dump, load
from os.path import isfile

if isfile('state.bin'):
    with open('state.bin', 'rb') as fh:
        state = load(fh)
else:
    state = {'counter' : 0, 'iterations' : 1}

if state['counter'] == 0 and state['iterations'] == 100:
    print('a string*')
else:
    if randint(0, 100) < 3 and state['counter'] < 3:
        print('a string*')
        state['counter'] += 1
state['iterations'] += 1

with open('state.bin', 'wb') as fh:
    dump(state, fh)

rawDescription: random and certainty in python?

description: Random and certainty in python


code:
def perfect_tree_partition(n):
    """find the point to partition n keys for a perfect binary tree"""
    x = 1

    # find a power of 2 <= n//2
    # while x <= n//2:  # this loop could probably be written more elegantly :)
    #     x *= 2
    x = 1 << (n.bit_length() - 1)   # indeed you can

    if x//2 - 1 <= (n-x):
        return x - 1      # case 1
    else:
        return n - x//2   # case 2 == n - (x//2 - 1) - 1

rawDescription: Create a complete binary search tree from list


code: os.system("start application-name")

rawDescription: Start a Windows Run command in Python (Browser protocol)


code: from pylab import *

rawDescription: Comparison of Python and R vocabularies

description: Comparison of Python and R vocabularies


code:
buffer_size = 720 * 288 * ctypes.sizeof(ctypes.c_float)
rgb_buffer = ctypes.create_string_buffer(buffer_size)
ctypes.memmove(rgb_buffer, getRgbBuffer(), buffer_size)

rawDescription: Using python ctypes to get buffer of floats from shared library into python string


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

x = np.random.randint(1, 10, 10)
y = np.random.randint(1, 100, 10)

fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True)
# do simple plot here, replace barplot yourself
axes[0].plot(x)
axes[1].plot(y)

rawDescription: Pandas: Splitting a Graph into many sub graphs while maintaining scale


code:
import re
re.sub(' [A-Z]* ', ' ', "John D Smith")
re.sub(' [A-Z]* ', ' ', "Robert B Johnson")

rawDescription: How do you remove a middle initial from a name in python?

description: Remove a middle initial from a name in python


code:
from tkinter import *

def onObjectClick(event):
    print('Got object click', event.x, event.y)
    print(event.widget.find_closest(event.x, event.y))

root = Tk()
canv = Canvas(root, width=100, height=100)
obj1Id = canv.create_line(0, 30, 100, 30, width=5, tags="obj1Tag")
obj2Id = canv.create_text(50, 70, text='Click', tags='obj2Tag')

canv.tag_bind(obj1Id, '<ButtonPress-1>', onObjectClick)
canv.tag_bind('obj2Tag', '<ButtonPress-1>', onObjectClick)
print('obj1Id: ', obj1Id)
print('obj2Id: ', obj2Id)
canv.pack()
root.mainloop()

rawDescription: How do I attach event bindings to items on a canvas using Tkinter?

description: Attach event bindings to items on a canvas using Tkinter


rawDescription: Community detection in Python

description: Community detection in Python


code: {{ post_obj.text|urlize }}

rawDescription: Make user-submitted links live (i.e. clickable) in a django app


code:
to_json = {"accountId":accountId,
    "emailSubject":customData.emailSubject,
    "emailBlurb":customData.emailBlurb,
    "customFields":customFields,
    "status":customData.status,
    "messageLock":customData.messageLock}

if james is not None:
  to_json['james'] = james

requestBody = json.dumps(to_json)

rawDescription: add a variable conditionally in python code

description: Add a variable conditionally in python code


code: url(r'^yadda/$', None)

rawDescription: reverse() throws AttributeError on call

description: Reverse() throws AttributeError on call


code:
class PictureSerialiser(serializers.ModelSerializer):

    image_url = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = Picture
        fields = ('field', 'image', 'image_url')

    def get_image_url(self, obj):
        return obj.image.url

rawDescription: Return image url in Django Rest Framework


code:
from random import shuffle

myList = ["file1", "file2", "file3", "file4"]
longList = []

for x in range(0,10):
    shuffle(myList)
    longList.append(myList[:])

rawDescription: Append to list after shuffle (Python)

description: Append to list after shuffle (Python)


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

ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

def graphRawFX (axes1) :

    date=mdates.strpdate2num('%Y%m%d%H%M%S')
    bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
    delimiter=',',
    converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
    fig = plt.figure(figsize=(10,7))

    axes1.plot(date,bid)
    axes1.plot(date,ask)

graphRawFX(ax1)

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

plt.grid(True)
plt.show()

rawDescription: Python 2.7 NameError: name 'ax1' is not defined


code: ssh.exec_command("/sbin/reboot -f > /dev/null 2>&1 &")

rawDescription: Executing reboot command over SSH using Paramiko


rawDescription: Python sample without replacement and change population


rawDescription: Python Tuple within a Tuple

description: Python Tuple within a Tuple


code:
mykey = '/path/to/ssl_key_file'
mycert = '/path/to/ssl_cert_file'
opener = urllib2.build_opener(HTTPSClientAuthHandler(mykey, mycert))
opener.add_handler(urllib2.HTTPBasicAuthHandler()) # add HTTP Basic Authentication information...
opener.add_password(user=settings.USER_ID, passwd=settings.PASSWD)

rawDescription: Modifying Python code to use SSL for a REST call


code: foo.values()[not foo.keys().index(key)]

rawDescription: Generic way to select "other value"

description: Generic way to select "other value"


rawDescription: return a list containing elements of another list

description: Return a list containing elements of another list


code:
n = number

def primesfrom2to(n):
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
    for i in xrange(1,int(n**0.5)/3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[       k*k/3     ::2*k] = False
            sieve[k*(k-2*(i&1)+4)/3::2*k] = False
    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]

primes = primesfrom2to(n).tolist()  # list of primes.
primes = map(int, primes)
factors = {}
for prime in primes:
    n = number
    factor = 0
    while True:
        if n%prime == 0:
            factor += 1
            n /= prime
            factors[prime] = factor
        else: break

rawDescription: How to find multiplicity of prime factors in order to get number of divisors

description: Find multiplicity of prime factors in order to get number of divisors


code: d = { t[0]:t[1:] for t in arr }

rawDescription: Converting a list of tuples of different sizes into a dictionary


rawDescription: How do I turn this into a numpy matrix?

description: Turn this into a numpy matrix


code:
from Tkinter import *
import tkMessageBox

def getInfo():
    #This function gets the entry of the text area and shows it to the user in a message box
    tkMessageBox.showinfo("User Input", E1.get())

def quit():
    #This function closes the root window
    root.destroy()

root = Tk() #specify the root window

label1 = Label( root, text="User Input") #specify the label to show the user what the text area is about
E1 = Entry(root, bd =5) #specify the input text area

submit = Button(root, text ="Submit", command = getInfo) #specify the "submit" button that runs "getInfo" when clicked
quit_button = Button(root, text = 'Quit', command=quit) #specify the quit button that quits the main window when clicked

#Add the items we specified to the window
label1.pack()
E1.pack()
submit.pack(side =BOTTOM)
quit_button.pack(side =BOTTOM)

root.mainloop() #Run the "loop" that shows the windows

rawDescription: Show user a message in python

description: Show user a message in python


code:
sshot = QPixmap.grabWidget(self)
sshot.save('sshot.png')

rawDescription: Printing main window in PyQt

description: Printing main window in PyQt


code:
from SOAPpy import *

def hello(_SOAPContext = None):
    return "Your IP address is %s" % _SOAPContext.connection.getpeername()[0]

if __name__ == "__main__":
  server = SOAPServer( ( '10.3.40.104', 8080 ) )
  server.registerFunction( MethodSig(hello, keywords=0, context=1) )
  server.serve_forever()

rawDescription: When using soappy SOAPServer, how do I read the request's headers?


rawDescription: Writing array in single csv column

description: Writing array in single csv column


code:
from collections import defaultdict, namedtuple
from pulp import *

User = namedtuple('User', ('coverage', 'price'))

def solvesetcover(users):
    vars = [LpVariable('x{}'.format(i), 0, 1, cat='Binary') for i, user in enumerate(users)]
    prob = LpProblem()
    totals = defaultdict(int)
    for user, var in zip(users, vars):
        prob += user.price * var
        for elt in user.coverage:
            totals[elt] += var
    for total in totals.values():
        prob += total >= 1
    GLPK(msg=0).solve(prob)
    return [user for user, var in zip(users, vars) if value(var)]

if __name__ == '__main__':
    users = []
    users.append(User({1, 2, 3, 4, 5, 6, 7}, 1.16))
    users.append(User({8, 9, 10, 11, 12, 13, 14}, 1.08))
    users.append(User({1, 8}, 1.04))
    users.append(User({2, 3, 9, 10}, 1.02))
    users.append(User({4, 5, 6, 7, 11, 12, 13, 14}, 1.01))
    print(solvesetcover(users))

rawDescription: Doing constraint-satisfaction in Python

description: Doing constraint-satisfaction in Python


code:
from distutils.core import setup

setup(
    name='TowelStuff',
    version='0.1dev',
    packages=['towelstuff',],
    license='Creative Commons Attribution-Noncommercial-Share Alike license',
    long_description=open('README.txt').read(),
)

rawDescription: Python 3.2: How to setup versioning for a project


code:
keyset = set()
for k in d:
    keyset.update(d[k])

for k in d:
    for kk in keyset:
        d[k].setdefault(kk, 0)

rawDescription: how to get all the keys in a 2d dict python

description: Get all the keys in a 2d dict python


code:
import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://yahoo.com').read()
soup = BeautifulSoup(page)
counter = 0
for img in soup.find_all('img'):
    with open("image" + str(counter),'wb') as f:
        f.write(urllib2.urlopen(img['src']).read())
    counter += 1

rawDescription: Download an image using Python

description: Download an image using Python


code:
open_file.write(data)
open_file.flush()

rawDescription: python multiprocessing writing to shared file

description: Python multiprocessing writing to shared file


code:
from nltk.corpus import PlaintextCorpusReader
import os.path
import sys

basepath = os.path.dirname(__file__)
corpus_root= os.path.abspath(os.path.join(basepath, "corpus"))
wordlists=PlaintextCorpusReader(corpus_root, '.*')

rawDescription: Finding path for corpus in NLTK

description: Finding path for corpus in NLTK


code: s1_t = map(lambda e: [e], s_1)

rawDescription: Transpose result of sum

description: Transpose result of sum


code:
class mainWindow(QtGui.QWidget):
    def __init__(self):
        super(mainWindow, self).__init__()
        self.layout = QtGui.QVBoxLayout()

        self.label1 = QtGui.QLabel()
        self.label1.setText("Name")
        self.lineEdit1 = QtGui.QLineEdit()
        self.lineEdit1.setToolTip("This is a ToolTip")

        self.label2 = QtGui.QLabel()
        self.label2.setText("Age")
        self.lineEdit2 = QtGui.QLineEdit()
        self.lineEdit2.setToolTip("This is another ToolTip")

rawDescription: Detect being hovering over specific widgets in PyQt4


code:
for i in range(len(unique_example)):
        for j in range(len(unique_example[i])):

            # stores as { "attribute": value, "predicate_value[0]": occurrence, "predicate_value[1]": occurrence}
            attribute_frequency_dict = {name_of_attributes[i]: unique_example[i][j]}

            for k in range(len(goal_predicate_list)):

                frequency = len([x for x in examples if x['Predicate'] == goal_predicate_list[k] and
                                 x[name_of_attributes[i]] == unique_example[i][j]])

                attribute_frequency_dict[goal_predicate_list[k]] = frequency

            attribute_frequency_list.append(attribute_frequency_dict)

rawDescription: making a list of dictionary in python

description: Making a list of dictionary in python


code:
from copy import deepcopy
from random import shuffle
from json import dumps     # for pretty printing of results

bowlers2balls = {
    1:0,2:1,3:0,4:0,5:0,6:1,7:2,8:2,9:3,10:0,11:0,12:0,13:0,
    14:0,15:0,16:1,17:0,18:0,19:0,20:0,21:2,22:3,23:0
}

Lanes = 6
Schedule = {}
min_turns = (len(bowlers2balls) - 1) / Lanes + 1

# Create a list of lists. Bowlers with a shared ball are all in the
# same sublist. Each bowler without a shared ball gets their own
# sublist. Ball numbers do not appear here.

shared = [[tup[0] for tup in bowlers2balls.items() if tup[1] == ball]
          for ball in set(bowlers2balls.values()) if ball]
for grp in shared:
    shuffle(grp)
unshared = [[tup[0]] for tup in bowlers2balls.items() if not tup[1]]
full_bgroups = shared + unshared

# Generate random schedules until we get one with minimum turns. It
# often happens that we get a suboptimal one because the bowlers with
# shared balls aren't used up.

while True:
    for lane in xrange(1,Lanes+1):
        Schedule['Lane{}'.format(lane)] = []

    bgroups = deepcopy(full_bgroups)
    while bgroups:
        shuffle(bgroups)
        for i, lane in enumerate(Schedule.keys()):
            if i >= len(bgroups):
                break
            bowler = bgroups[i].pop()
            Schedule[lane].append(
                ('{:2d}'.format(bowler),
                 bowlers2balls[bowler]))
        # Remove emptied lists from bgroups
        bgroups = filter(None, bgroups)

    turns = max([len(s) for s in Schedule.values()])
    if turns <= min_turns:
        break

print (dumps(Schedule, sort_keys=True)
       .strip('{}')
       .replace(']], ', ']],\n'))

rawDescription: Bowling scheduler

description: Bowling scheduler


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

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots(1, 1)

ax.scatter(x, y)
ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
ax.grid(b=True, which='major', color='w', linewidth=1.0)
ax.grid(b=True, which='minor', color='w', linewidth=0.5)

rawDescription: Add minor gridlines to matplotlib plot using seaborn


code:
import subprocess
import sys
import os
args = [sys.executable] + sys.argv
new_environ = os.environ.copy()

if hasattr(subprocess, 'CREATE_NEW_CONSOLE'):
    popen = subprocess.Popen(args, env=new_environ, creationflags=subprocess.CREATE_NEW_CONSOLE)
    exit_code = popen.wait()
else:
    #On Linux, CREATE_NEW_CONSOLE is not available, thus, we use xterm itself.
    args = ['xterm', '-e'] + args
    popen = subprocess.Popen(args, env=new_environ)
    popen.wait() #This exit code will always be 0 when xterm is executed.

rawDescription: Pydev: Send stdout to a real (tty) terminal


rawDescription: Importing large integers from a mixed datatype file with numpy genfromtxt


code:
import configparser

parser = configparser.ConfigParser(delimiters=('?', '*'))

rawDescription: Python escape delimiter in configuration file using ConfigParser