code:
('bee', 'foo', 'zee', 'bar', 'bee')
('bee', 'foo', 'zee', 'bar', 'BETA')
('bee', 'foo', 'ZETA', 'bar', 'bee')
('bee', 'foo', 'ZETA', 'bar', 'BETA')
('BETA', 'foo', 'zee', 'bar', 'bee')
('BETA', 'foo', 'zee', 'bar', 'BETA')
('BETA', 'foo', 'ZETA', 'bar', 'bee')
('BETA', 'foo', 'ZETA', 'bar', 'BETA')

rawDescription: Generate all possible replacements

description: Generate all possible replacements


code: x = Bunch(d)

rawDescription: Python: load variables in a dict into namespace


code: [x.translate(translation_table).strip() for x in bucket_list ]

rawDescription: Python -unicode- translate table doesn't remove chars


code: "Description: "

rawDescription: Removing first appearance of word from a string?


code:
import IAPW2_1995

x = IAPW2_1995.dAr_ddelta( arg1, arg2, arg3, arg4, arg5 )

rawDescription: Class scope vs module scope attributes in Python


rawDescription: Add value from drop down list to tkinter GUI once item is selected? Python


code:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtGui
from example_Ui import Ui_MainWindow
from filler_Ui import Form

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

    tab_index = 1 # 1 because we already made a default tab in QtDesigner

    def LineEditChanged(self):
        findWidget = self.tabWidget.widget(self.tabWidget.currentIndex()).findChild(QtGui.QLineEdit, "lineEdit")
        if findWidget.isModified() == True:
            print("LineEdit contents edited in tab page!")
        print("Name of page edited :", "'", self.tabWidget.tabText(self.tabWidget.currentIndex()),"'")

    def TabButtonPressed(self):
        print("YOU DID IT!")
        print("Current Tab Index = ", self.tabWidget.currentIndex())

    def CreateNewTab(self, tabNum):
        tab_title = "New Tab : " + str(self.tab_index)
        self.tabWidget.addTab(Form(), tab_title)

    def MainButtonPressed(self):
        self.CreateNewTab(self.tab_index)
        findWidget = self.tabWidget.widget(self.tab_index).findChild(QtGui.QPushButton, "tabButton")
        findWidget.clicked.connect(self.TabButtonPressed)
        findWidget = self.tabWidget.widget(self.tab_index).findChild(QtGui.QLineEdit, "lineEdit")
        findWidget.editingFinished.connect(self.LineEditChanged)
        self.tab_index += 1

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

rawDescription: How to see signals from QWidgets inside dynamically created QTabWidget pages?

description: See signals from QWidgets inside dynamically created QTabWidget pages


code:
def edited(r):
    # make your changes to r
    return new_r

with open("SFU.txt") as inf, open("edited.txt", "w") as outf:
    # set up iterators
    cfg, res = tee(inf)
    for i in range(4):
        next(cfg)

    # iterate through in tandem
    for c, r in zip(cfg, res):
        if "configuration" in c:
            r = edited(r)
        outf.write(r)

    # reached end - write out remaining queued values
    for r in res:
        outf.write(r)

rawDescription: print a previous line based on a condition in python

description: Print a previous line based on a condition in python


code:
import numpy as np
import pandas as pd
np.random.seed(2016)

row=['a','b','c']
col=['A','B','C','D']

prevstate = pd.DataFrame([[i+j for j in col] for i in row], index=row, columns=col)
prob = pd.DataFrame(np.random.uniform(0, 1, size=(len(row), len(col))).round(4),
                    index=row, columns=col)
print(prevstate)
#     A   B   C   D
# a  aA  aB  aC  aD
# b  bA  bB  bC  bD
# c  cA  cB  cC  cD

print(prob)
#         A       B       C       D
# a  0.8967  0.7302  0.7833  0.7417
# b  0.4621  0.6426  0.2249  0.7085
# c  0.7471  0.6251  0.5800  0.2426

rawDescription: Python: Pandas DataFrame for tuples

description: Python: Pandas DataFrame for tuples


code:
class Foo(object):
    __slots__ = ('spam',)

dir(Foo())
Foo().spam
Foo.spam
type(Foo.spam)

rawDescription: How does __slots__ avoid a dictionary lookup?


code: unidecode("é") == "e"

rawDescription: Regex - match a character and all its diacritic variations (aka accent-insensitive)


code:
from Crypto.Cipher import AES
import base64

def rpad(s, fill='=', multiple=8):
    """
    Pad s with the fill char so the length of the string
    is a multiple of `multiple` (default 8).
    """
    return s + fill * (-len(s) % multiple)

key = """
4e 99 06 e8  fc b6 6c c9  fa f4 93 10  62 0f fe e8
f4 96 e8 06  cc 05 79 90  20 9b 09 a4  33 b6 6c 1b
"""
key = key.replace(" ","").replace("\n","").decode('hex')

mode = AES.MODE_CBC
iv = "\x00"*16
enc = AES.new(key, mode, iv)

password = "j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw"
decoded = base64.b64decode(rpad(password, multiple=4))

o = enc.decrypt(decoded)
print(o[:-ord(o[-1])].decode('utf16'))

rawDescription: Python Crypto - example script explanation


code:
self.menu_left_upper.pack(side="top", fill="both", expand=True)
self.menu_left_lower.pack(side="top", fill="both", expand=True)

rawDescription: Tkinter: grid or pack inside a grid?

description: Tkinter: grid or pack inside a grid


code:
from __future__ import print_function

# compute monthly payment
def pmt(rate, nper, pv):
    """
    rate    - annual interest rate
    nper    - # of periodic payments
    pv      - present value (principal loan amount)
    """
    return (rate * pv) / (1 - (1 + rate)**(-nper))

# compute future value (remaining balance)
def fv(rate, nper, pmt, pv):
    """
    rate    - annual interest rate
    nper    - # of periodic payments
    pmt     - monthly payment
    pv      - present value (principal loan amount)

    r1 = (1 + interest_rate) - will be used a few times below
    """
    r1 = 1 + rate
    return pv * r1**nper - pmt * (r1**nper -1) / rate

amount = 1000
int_rate = 4.5/100
term = 5
nper = 12
mtly_pmt = round(pmt(int_rate/nper, term*nper, amount), 2)

fmt = 'year {0:2d} {1:8.2f} {2:8.2f}'

for y in range(1, term + 1):
    print(fmt.format(
            y,
            fv(int_rate/nper, y*nper, mtly_pmt, amount),
            mtly_pmt * y * nper,
          )
    )

rawDescription: Python 3.5 - Yearly balance on loan

description: Python 3.5 - Yearly balance on loan


code: [zip(*[m4c[j][i] for j in range(len(m4c))]) for i in range(len(m4c[0]))]

rawDescription: Transposing a 3d list (Python)

description: Transposing a 3d list (Python)


code: run('cd $TEST && program')

rawDescription: Using environment variables in Fabric

description: Using environment variables in Fabric


code:
# ...
start_response(status, response_headers)
return ResponseIterator(iter(queue.get, None),
     on_finish=lambda: Processor.connections.remove(queue))

rawDescription: Implementing a WSGI Streaming Service: (how to detect client disconnects)


code:
with open('students.csv', 'w') as st_file:
    reader = csv.reader(st_file)
    for row in reader:
        event = Event.objects.get(id=row[0])
        event.student_attendees.add(Student.objects.get(row[2]))

rawDescription: Move /migrate django data into new table


rawDescription: Better replacement for a huge "if x==2 / if x==3 / if x==4" chain adding prefixes and suffixes?


code:
df['StateInitial'] = df['state'].str[:2]
df

rawDescription: how to do a left,right and mid of a string in a pandas dataframe

description: Do a left,right and mid of a string in a pandas dataframe


code: win32api.ShellExecute(0, 'open', 'gsprint.exe', '-printer "\\\\' + self.server + '\\' + self.printer_name + '" ' + file, '.', 0)

rawDescription: Print PDF document with python's win32print module?


rawDescription: Python OOP: How do I link multiple classes objects to one object


code:
x = MyClass()
x.foo(10) # OK, but `cls` is unused
x.bar(10) # OK!
x.baz(10) # Crash!!

MyClass.foo(10) # Ok, but `cls` is unused
MyClass.bar(10) # OK!
MyClass.baz(10) # OK!

rawDescription: Difference between calling classmethod or regular method from another classmethod


rawDescription: Update value in Dictionary with multiple values per key


code:
with MySession() as session:
    response = session.get(url)

rawDescription: How to override the .get() method in requests?

description: Override the .get() method in requests


code:
def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, str):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

print(flatten(["junk",["nested stuff"],[],[[]]]))

rawDescription: Python 3 replacement for deprecated compiler.ast flatten function


code:
xx = [[[10,20,30]],[[44], [55,66]]]
for chosen in choose_from_2d_lol(xx):
    print(chosen)

rawDescription: How to generate a permutation list of lists in python

description: Generate a permutation list of lists in python


rawDescription: Nested dictionaries in python with error when accessing non-existent key


code:
import ast
l = ast.literal_eval(j)

rawDescription: How to parse this json in Python

description: Parse this json in Python


code:
from sklearn.cross_validation import train_test_split
from sklearn import datasets

# Use Age and Weight to predict a value for the food someone chooses
X_train, X_test, y_train, y_test = train_test_split(table['Age', 'Weight'],
                                                    table['Food Choice'],
                                                    test_size=0.25)

# Another example using the sklearn pre-loaded datasets:
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
X, y = X_iris[:, :2], y_iris
X_train, X_test, y_train, y_test = train_test_split(X, y)

rawDescription: Equivalent of R's createDataPartition in Python


code: MyModel.objects.filter(X | Y)

rawDescription: Django: extend queryset or exclude from exclude method


code:
uni = u"but\u014dden"
repr(uni)
repr(u'Latin 1 and a newline: å\n')
repr(u'Quoting 1: \'')
repr(u'Quoting 2: \'\"')

rawDescription: Python 2.7, how to assign the "unicode literal representation" of a unicode instance to an str instance?


code:
splitter=QtGui.QSplitter()
iniFile=os.path.join(os.path.expanduser('~'),'myAppName/myAppNameSettings.ini')
settings=QtCore.QSettings(iniFile, QtCore.QSettings.IniFormat)
splitterSettings=splitter.saveState()
if splitterSettings:
    settings.setValue("splitterSettings", splitter.saveState())

rawDescription: How to get QSplitter index and position

description: Get QSplitter index and position


code:
@div.register(str)
def _(x, y):
    return x % y

rawDescription: Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins


code:
class CubicBSpline(object):
    [...]
    def clamped(self):
        new_points = [self.points[0]] * 3 + self.points + [self.points[-1]] * 3
        return CubicBSpline(new_points)

rawDescription: Drawing a clamped uniform cubic B-spline using Cairo


rawDescription: Format hex string to MAC string

description: Format hex string to MAC string


code:
dct = {'a': 1, 'b': '2'}
','.join('{}={!r}'.format(k, v) for k, v in dct.items())
','.join("{}='{}'".format(k, v) for k, v in dct.items())

rawDescription: How to convert a dict to string?

description: Convert a dict to string


code:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/path/to/socket")

rawDescription: Can I open UNIX POSIX ports from Python?

description: Open UNIX POSIX ports from Python


code:
import random

def applyNoise(bytes, bitFlipProbability):

  def applyByteNoise(byte):
    noisedByte = byte
    for bitPos in range(8):
      if random.random() < bitFlipProbability:
        noisedByte ^= 1 << bitPos
    return noisedByte

  return (applyByteNoise(byte) for byte in bytes)

print(list(applyNoise([ 1,2,3,4,5 ], 0.03)))

rawDescription: Binary bit flip generator in python

description: Binary bit flip generator in python


code:
foobars = ['big', 'small', 'medium', 'nice', 'ugly']
big_foobar = 'big'
any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, ...])

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

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


rawDescription: Inner join two list of list given indices


code:
def way7(theList, theDict):
    return list(theDict.viewkeys() & theList)

rawDescription: Finding all keys in a dictionary from a given list QUICKLY


code: print("The length of '{}' is {}".format(word, word_length))

rawDescription: How do I include quotation marks in a print statement if I am using a variable

description: Include quotation marks in a print statement if I am using a variable


code:
from rpy2.robjects.packages import importr
copula = importr('copula')
myCop_clayton = copula.archmCopula(family="clayton", dim =7, param=2)
from rpy2.robjects.vectors import StrVector, ListVector
from rpy2.robjects import r
myMvd = copula.mvdc(copula=myCop,
                    margins=StrVector(["norm", "norm"]),
                    paramMargins = r("""
                                     list(list(mean=0.66,sd = 0.1),
                                          list(mean=0.66,sd = 0.1))
                                     """))

rawDescription: rpy2, copula, How to import parameters? Python

description: Rpy2, copula, How to import parameters? Python


code:
def create_user_profile(strategy, details, user=None, is_new=False, *args, **kwargs):
    print(strategy.session_get('profile_type'))

rawDescription: Django: How to identifying through which link user done social authentication?


rawDescription: python - Looking up a dictionary key in another file with two criteria

description: Python - Looking up a dictionary key in another file with two criteria


code:
import json
data = {'egg':'green','ham':'yum','ran':{'out_of':'fake_words'}}
json.dumps(data)

rawDescription: Pandas/Python ruining JSON data in DataFrames


code:
import numpy as np

np.hstack(zip(A,B))

rawDescription: Concatenate two list based on the same index


code: all(row_a[1] == row_b[1] for row_a, row_b in zip(arr1, arr2))

rawDescription: How can I compare the column of two 2-dim array without any third-party libraries?

description: Compare the column of two 2-dim array without any third-party libraries


code:
import os
import paramiko

localpath = '~/pathNameForToday/'
os.system('mkdir ' + localpath)
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.get(remotepath, localpath)
sftp.close()
ssh.close()

rawDescription: Python script to get files from one server into another and store them in separate directories?


rawDescription: numpy boolean array with 1 bit entries

description: Numpy boolean array with 1 bit entries


rawDescription: How to keep PsychoPy object visual.Window the topmost (active) window on Windows 7?

description: Keep PsychoPy object visual.Window the topmost (active) window on Windows 7


code:
def total_wins(stocks):
    win = 0
    for block in stocks:
        purchase_date, purchase_price, shares, symbol, current_price = block
        win += (purchase_price - current_price) * shares
    return win

rawDescription: Understanding how to multiply specific values in tuples in Python


code:
A  # Different from the one posted in question to show variety
out

rawDescription: Inserting rows of zeros at specific places along the rows of a NumPy array


code:
{'Feedback': u'feedback', 'QueNo': 1, 'QueText': u'quetext', 'skillid': 1}
{'Feedback': u'feedback', 'QueNo': 2, 'QueText': u'quetext', 'skillid': 1}
{'Feedback': u'feedback', 'QueNo': 3, 'QueText': u'quetext', 'skillid': 1}

rawDescription: Python adding a number sequence in a list of dictionaries


code:
buttonBlue = Button(wind, text = 'Blue Planet', command = lambda: change(1))
buttonOrange = Button(wind, text = 'Blue Planet', command = lambda: change(0))
def change(newValue):
    global a
    a = newValue

rawDescription: How to avoid global variables in command function call

description: Avoid global variables in command function call


code:
def RealAppending(the_str):
    with lock:
        with open("test.txt", "a") as the_file:
            the_file.write(the_str) # write

rawDescription: Is this a thread-safe module, and actually how do you write one?


code:
with open('database.db', 'rb') as fh:
    db = pickle.load(fh)

rawDescription: Remember variables after code execution

description: Remember variables after code execution


code:
ints = data[data[1]=='INT']
exts = data[data[1]=='EXT']

rawDescription: Python 3.4 reading from CSV formats

description: Python 3.4 reading from CSV formats


code:
magicians = make_great(['Tom'])
print(magicians)

rawDescription: Modifying a list in python by passing it to a function


rawDescription: Matrix Approximation and Predicting Timeseries in Python/R with SVD


code: subf.ix[(t-60 < subf['Time']) & (subf['Time'] <= t), 'Value']

rawDescription: Customizing rolling_apply function in Python pandas


rawDescription: Change the value of a list's element

description: Change the value of a list's element


rawDescription: sorting the quintile output from qcut in pandas python

description: Sorting the quintile output from qcut in pandas python


code:
# construct 3D array with random data
# each data array will be a slice of this array, e.g. data[0], data[1], etc.
data = np.random.randint(0, 3, (3, 4, 5))
# make an empty array to store the results as before
result = np.empty_like(data[0], dtype=float)
# use broadcasting to test for equality
indices = np.all(data == data[0], axis=0)
# Do the assignment as before
result[indices] = data[0][indices]
result[~indices] = np.nan
result

rawDescription: Extraction of common element in given arrays to make a new array


code:
from itertools import izip_longest
not any(cmp(i, j) for i, j in izip_longest(x, y, fillvalue=object()))
not any(cmp(i, j) for i, j in izip_longest(x, z, fillvalue=object()))

rawDescription: Equality without using operator

description: Equality without using operator


code:
from pprint import pprint
pprint(query_dict)

rawDescription: python dictionary, make every odd number line to key and even number line to value from a file

description: Python dictionary, make every odd number line to key and even number line to value from a file


code:
{'fttcAvailable': False, 'phoneNumber': '01253873647'}
{'fttcAvailable': False, 'phoneNumber': '01253776535'}
{'fttcAvailable': True, 'phoneNumber': '01142726749'}

rawDescription: Scrape using multiple POST data from the same URL


code: map(str.split, config)

rawDescription: Iterate over a list to apply a method to each member


rawDescription: replacing node text using lxml.objectify while preserving attributes

description: Replacing node text using lxml.objectify while preserving attributes


code:
import matplotlib.pyplot as plt

def myplot(df, ilist, clist):
    df1 = df[df['I'].isin(ilist)][clist + ['t', 'I']].set_index('t')
    fig, ax = plt.subplots(len(clist))
    for I, grp in df1.groupby('I'):
        for j, col in enumerate(clist):
            grp[col].plot(ax=ax[j], sharex=True)

rawDescription: Pandas: interpolate missing rows and plot multiple series in dataframe


code:
with open("scores2.txt", "w") as f:
    for i in lst:
        f.write("{}\n".format(i[0]))

rawDescription: Reading a file to a dictionary and trying to rank


code:
import sys
sys.path.append(r'C:\Users\PyGuy\.virtualenvs\pyad\Lib\site-packages\python_ldap-2.4.15-py2.7-win32.egg')
import ldap

rawDescription: Searching LDAP with Python without LDAP library


rawDescription: How can I speed up my solution to this self-describing number puzzle?

description: Speed up my solution to this self-describing number puzzle


code:
class CSVFile(models.Model):
    ...
    file = models.FileField(...)

rawDescription: Django - User Uploaded CSV and JQueryCSVtoTable


code:
import pandas
import numpy as np

rawDescription: Need to create a median function that draws from a dictionary


code: "Wilbur Smith (son of John (Johnny, son of James), aka Billy), Eddie Murphy (John)"

rawDescription: How to split a string by commas positioned outside of parenthesis?

description: Split a string by commas positioned outside of parenthesis


code:
@contextlib.contextmanager
def strduping(buf):
    value = libc.strdup(buf)
    try:
        yield value
    finally:
        libc.free(value)

rawDescription: Memory leaks in Python when using an external C DLL


code:
import string
s = '\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'
printable = set(string.printable)
filter(lambda x: x in printable, s)

rawDescription: Remove all hex characters from string in Python


code: "".join([ch for ch in orig_string if ord(ch)<= 128])

rawDescription: Remove all characters from a string who's ordinals are out of range


rawDescription: Global variable in python is not edited

description: Global variable in python is not edited


code: Principal = start - end

rawDescription: Python: smarter way to calculate loan payments


code:
{
    'idx': 2,  # Index (position in vector)
    'name': 'x4',  # name
    'ord': False,  # is ordinal?
    # Mapping between value and label
    'vals': ['0.0', '1.0', '2.0', '3.0', '4.0']
}

rawDescription: How can I declare a Column as a categorical feature in a DataFrame for use in ml

description: Declare a Column as a categorical feature in a DataFrame for use in ml


code: test = lambda x:  num in [1, 2, 3]

rawDescription: Compare to multiple values in an if statement


code:
from datetime import datetime as dt

def speed(lat1, long1, time1, lat2, long2, time2):
    distance = haversine_distance(lat1, long1, lat2, long2)  # meter

    # here's the fun stuff
    time1 = dt.strptime(time1, "%m/%d/%Y %H:%M")
    time2 = dt.strptime(time2, "%m/%d/%Y %H:%M")
    delta_time = (time2 - time1).total_seconds() # second

    # continue with the rest of your code
    speed = (distance / delta_time) # speed in m/s
    speed = speed * 3.6 # speed in km/h

    return speed

rawDescription: Saving the amount of time between each time stamp in an array


code:
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
from sqlalchemy import Table, Column, Integer, String, MetaData
metadata = MetaData()

rawDescription: Dynamic Table Creation and ORM mapping in SqlAlchemy


code: B[B.searchsorted(A)] == A

rawDescription: Numpy.array indexing question

description: Numpy.array indexing question


code:
import os
import os.path
import shutil

os.mkdir('B') # Assuming `B` does not already exist.

for root, _dirs, files in os.walk('A'):
    for name in files:
        source_path = os.path.join(root, name)
        dest_path = os.path.join('B', name)
        shutil.copyfile(source_path, dest_path)

rawDescription: Manipulation of directories java/python

description: Manipulation of directories java/python


code: idxs = a[a['Invoice Number'].isin(b['Sold On Invoice Number'])].index

rawDescription: Overwrite field values based on membership in a set


code:
a
[i.tostring() for i in np.nditer(a)]
[i.tostring() for i in a.flatten()]

rawDescription: Converting a numpy.ndarray value from bytes to float


rawDescription: What data structure container can be sorted by date


code:
# yield_vs_append.py
data = range(1000)

def yielding():
    def yielder():
        for d in data:
            yield d
    return list(yielder())

def appending():
    lst = []
    for d in data:
        lst.append(d)
    return lst

rawDescription: Which is generally faster, a yield or an append?


code: {tuple(x.items): x.freq for x in result}

rawDescription: python 2.7 : create dictionary from list of sets

description: Python 2.7 : create dictionary from list of sets


rawDescription: What is the simplest way to remove phase angle discontinuities


code: sorted(json_reply['top']['sub'].items(), key=lambda i: int(i[0]))

rawDescription: Python 3.4 JSON sort by key as int

description: Python 3.4 JSON sort by key as int


code:
import base64
from_js_bin = base64.decode(from_js)
nonce = from_js_bin[:8]
ciphertext = from_js_bin[8:]

rawDescription: Include nonce and block count in PyCrypto AES MODE_CTR


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

rawDescription: How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

description: Remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)


code: pd.core.format.header_style = None

rawDescription: pandas xlsxwriter, format header

description: Pandas xlsxwriter, format header


rawDescription: Diffing Binary Files In Python

description: Diffing Binary Files In Python


code:
parser.add_argument('--add-net',
                    action=ParseIPNets,
                    dest='user_nets',
                    help='Nets subnets for users. Can be used multiple times',
                    default = {})

args = parser.parse_args()
if len(args.user_nets) == 0:
    args.user_nets['user1'] = "198.51.100.0/24"

rawDescription: Custom parsing function for any number of arguments in Python argparse


code:
x.values
x.to_records()

rawDescription: loading a table in numpy as in R?

description: Loading a table in numpy as in R


code: hell.brick_list = [Brick() for _ in lister]

rawDescription: Accessing attributes of a list of objects in python


rawDescription: Refactoring if statements in python

description: Refactoring if statements in python


rawDescription: Why doesn't numpy.power act element-wise on arrays when the exponent is negative?


code:
# example 1
error_events = Event.objects.filter(event_type=Event.ERROR)

# example 2
if my_event.event_type == Event.Error:
    # this is an error event
    pass

rawDescription: Where to store color information in a web application?


code:
def get_or_create_or(cls, session, *args):
    instance = session.query(cls).filter(or_(*args)).first()
    # rest of stuff

rawDescription: How to make a get_or_create using OR with SQLAlchemy?

description: Make a get_or_create using OR with SQLAlchemy


code: [round(x) if x > 0.5 else x for x in lst]

rawDescription: Convert a list of floats to the nearest whole number if greater than x in Python


code:
from flask.ext.mongokit import MongoKit, Document

# import db below like this
from myapp import db

class User(Document):
    structure = {
    'name': unicode,
    'email': unicode,
}
use_dot_notation = True

# ok to do this below
db.register([User])

rawDescription: Implementing MVC in Python? (using Flask and MongoKit)


code: mark_emoticons('Hello ladies! How are you? Fantastic :) Look at your man ...')

rawDescription: translate by replacing words inside existing text

description: Translate by replacing words inside existing text


rawDescription: Python regex removing non alpha numeric characters from string except brackets


code:
genekeys = {}
tajvalues = {}
dictionaries = {}

for i in range(10):
    filename = sample+'_rand{0}.genes.tajD'.format(i)
    genekeys[i] = []
    tajvalues[i] = []
    with open(filename, 'r') as data:
        for line in data:
            line = line.strip().split('\t')
            gene, taj = line[0], line[3]
            genekeys[i].append(gene)
            tajvalues[i].append(taj)
    dictionaries[i] = dict(itertools.izip(genekeys[i],tajvalues[i]))

with open(sample+'_rand0.genes.tajD', 'r') as genes, open(outfilename, 'w') as outfile :
    for line in genes :
        values = {}
        line = line.strip().split('\t')
        mastergene = line[0]
        for i in range(10):
            values[i] = dictionaries[i][mastergene]
        allrand = [values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9]]
        avg = numpy.mean(allrand)
        outfile.write(mastergene + '\t' + values[0] + '\t' + values[1] + '\t' + values[2] + '\t' + values[3] + '\t' + values[4] + '\t' + values[5] + '\t' + values[6] + '\t' + values[7] + '\t' + values[8] + '\t' + values[9] + '\t' + avg + '\n')

rawDescription: Opening multiple files, creating lists, and dictionaries with for loop and range function in iPython


code:
def generate_student_dict(first_name=None, last_name=None , birthday=None, gender =None):
     # It's important to copy locals in first line of code (see @MuhammadTahir comment).
     args_passed = locals().copy()
     # some code
     return args_passed

generate_student_dict()

rawDescription: Python keyword arguments unpack and return dictionary


code:
my_list=["\tLocation\tNext Available Appointment: Date\n","\tLocation2\tNext Available Appointment: Date2\n"]
[re.findall(r'^\t(.*)\t.*: (.*)$',i) for i in my_list]

rawDescription: Use regex backreferences to create array


rawDescription: Accessing values in a list of nested dictionaries


code:
z = []
for k, v in b.iteritems():
    if v not in {"Supplementary", "Assignment", "Smith", "Bowen"}:
        z.append(k)

rawDescription: Python; Dictionary iteration

description: Python; Dictionary iteration


code:
for d in dimensions:
    dict = dict[d]

rawDescription: Get a value from multidimensional, with variable number of dimensions, dictionary in python


rawDescription: How to create series of pandas dataframe by iteration

description: Create series of pandas dataframe by iteration


code: hog[Y, X, angle]

rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


code:
def validate():
    while True:
        # begin inf. loop
        p = input("some prompt goes here")
        if some_validation:
            break
            # end inf. loop
        # therefore if the validation fails, it reprompts
    # once you're out of the inf. loop...
    return p

rawDescription: How do I check a value entered?? Python 3.4

description: Check a value entered?? Python 3.4


rawDescription: Delete specific spaces from a string Python


code:
import time
time.time()

rawDescription: Python record the time of typing

description: Python record the time of typing


rawDescription: Ordereddict Merge by Month, and Week python


code: anim.save("path.mp4", writer=mywriter)

rawDescription: Pixelated animations in Matplotlib

description: Pixelated animations in Matplotlib


code: seq_iter = x if isinstance(x, dict) else xrange(len(x))

rawDescription: Iterate over a dict or list in Python

description: Iterate over a dict or list in Python


code:
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(open("test.xml"))
print(soup.find("type").text)

rawDescription: Accessing child nodein an xml in python

description: Accessing child nodein an xml in python


code:
import pickle
myusername = "Hello"
mypassword = "World"
login = [myusername, mypassword]
pickle.dump(login, open("%s.p" % login[0], "wb")) #Saves credentials in Hello.p, because Hello is the username
#Exit

rawDescription: Python User Registration

description: Python User Registration


code:
import asyncio

async def async_foo():
    print("async_foo started")
    await asyncio.sleep(1)
    print("async_foo done")

async def main():
    asyncio.ensure_future(async_foo())  # fire and forget async_foo()

    # btw, you can also create tasks inside non-async funcs

    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: "Fire and forget" python async/await

description: "Fire and forget" python async/await


rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
import urllib2
urllib2_req = urllib2.Request(request.url, request.to_postdata())
response = urllib2.urlopen(urllib2_req)
response_body = response.read()    # in case you need it

rawDescription: python-oauth2 - issue Request objects

description: Python-oauth2 - issue Request objects


code: doc.xpath('//span[@class="graytext" and @style="font-size: 11px"]')

rawDescription: Parse the date string from html in lxml

description: Parse the date string from html in lxml


code:
# somescript.py
import myext
from myext import PySomeFeature
...

rawDescription: Using Cython To Link Python To A Shared Library


rawDescription: Change color of histogram after it was plotted


code: d

rawDescription: How to get the value of a value as a key of a dictionary

description: Get the value of a value as a key of a dictionary


rawDescription: Replacing string elements of a pandas DataFrame with integers


code:
search=es.search(
    q='The Query to ES.',
    index="*logstash-*",
    size=10,
    search_type="scan",
    scroll='5m',
)

rawDescription: Elasticsearch python API: Delete documents by query


code:
allstrings = [u'This', u'the third largest earthquake in recorded history', u'the third largest earthquake', u'recorded history', u'massive tsunamis , which caused widespread devastation when they hit land , leaving an estimated 230,000 people dead in countries around the Bay of Bengal and the Indian Ocean', u'massive tsunamis', u'widespread devastation', u'they', u'land', u'an estimated 230,000 people dead in countries around the Bay of Bengal and the Indian Ocean', u'an estimated 230,000 people', u'countries around the Bay of Bengal and the Indian Ocean', u'countries', u'the Bay of Bengal and the Indian Ocean', u'the Bay', u'Bengal and the Indian Ocean', u'Bengal', u'the Indian Ocean']
[s for s in allstrings if not any(t in s for t in allstrings if t != s)]

rawDescription: How to select the finest granularity of string items in a list

description: Select the finest granularity of string items in a list


code:
I=tree.query(a)
I

rawDescription: Python rounding of random floats to nearest points on a 2D uniform mesh grid


rawDescription: Which regex is more efficient?

description: Which regex is more efficient


rawDescription: Split list python

description: Split list python


code:
rs.Bar.append( pyxb.BIND( name='a'  ) )
rs.Bar[-1].code = '42'

rawDescription: PyXB : Creating More Rigid Instances of Anonymous Types


code:
def job_that_executes_once():
    # Do some work ...
    return schedule.CancelJob

schedule.every().day().at('14:38').do(job_that_executes_once)

rawDescription: Fire a python script at a specific time

description: Fire a python script at a specific time


rawDescription: Choosing and iterating specific sub-arrays in multidimensional arrays in Python


rawDescription: How to convert < into < in lxml, Python?

description: Convert < into < in lxml, Python


code:
original = sentence = 'I? am. cal?led ,bob. Wh,at. is your .name?.'
punc = ('!', '"', '£', '$', '%', '^', '&', '*', '(', ')', '¬', '`', '{', '}', '~', '@', ':', '?', '>', '<', ',', '.', '/', ';', '#', ']', '[', '/', '*')

sentence = list(sentence)
Dictionary = {}
seq = [] # list of all indices with any punctuation

for i, p in enumerate(sentence):
    if p in punc:
        seq.append(i)
        if p in Dictionary:
            Dictionary[p].append(i)
        else:
            Dictionary[p] = [i]

sentence = list(filter(lambda x: x not in punc, sentence))
for i in seq:
    for key, indices in Dictionary.items():
        if i in indices:
            sentence.insert(i, key)
            indices.remove(i)
assert(''.join(sentence) == original)

rawDescription: How to remove punctuation from a string and remember the position of it from the string

description: Remove punctuation from a string and remember the position of it from the string


code:
def copy(dst, src):
    """Copies the contents of src to dst"""
    pointer(dst)[0] = src

# alternately
def new_copy(src):
    """Returns a new ctypes object which is a bitwise copy of an existing one"""
    dst = type(src)()
    pointer(dst)[0] = src
    return dst

# or if using pointers
def ptr_copy(dst_ptr, src_ptr):
    dst_ptr[0] = src_ptr[0]

rawDescription: Python ctypes: copying Structure's contents


code:
http_proxy  = "http://10.10.1.10:3128"
https_proxy = "https://10.10.1.11:1080"
ftp_proxy   = "ftp://10.10.1.10:3128"

proxyDict = {
              "http"  : http_proxy,
              "https" : https_proxy,
              "ftp"   : ftp_proxy
            }

r = requests.get(url, headers=headers, proxies=proxyDict)

rawDescription: Proxies with Python 'Requests' module

description: Proxies with Python 'Requests' module


code:
class AThread(QtCore.QThread):
    trigger = QtCore.pyqtSignal(int)

rawDescription: How to emit signals with parameters

description: Emit signals with parameters


rawDescription: How can I select values along an axis of an nD array with an (n-1)D array of indices of that axis?

description: Select values along an axis of an nD array with an (n-1)D array of indices of that axis


code:
import re
regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line

rawDescription: Python string.replace regular expression


rawDescription: Finding the differences between two nested lists


code:
packet = IP(flags=2)  # alternatively, IP(flags='DF')
packet

rawDescription: Python: Scapy: How to read IP flags

description: Python: Scapy: How to read IP flags


rawDescription: Populating a list with elements from different lists in Python


code: yield old + ' ' + new

rawDescription: Bigram function using python

description: Bigram function using python


code: res = [ True if item in animal_list else False for item in your_list ]

rawDescription: List of Elements to Boolean Array

description: List of Elements to Boolean Array


code:
now = datetime.datetime.now()
jobs = Job.query(Job.published == "on", Job.expire <= now).fetch()
for job in jobs:
    job.published = "off"
    job.put()

rawDescription: Google App Engine: Using cron to expire (or 'unpublish') entities


code:
email_strings = email_string2.split(',')
for s in email_strings:
  s[s.find('<')+1:-1]

rawDescription: How to eliminate email formatting in received email?

description: Eliminate email formatting in received email


code:
class Monster(object):
    def __init__(self, health, name):
        print(name + " has been born!")
        self.name = name
        self.health = health
        self.stats()

    def stats(self):
        print(self.name + "  -  " + str(self.health) + " HP")

rawDescription: Pass variables set within a function to a method within a class


code:
from Tkinter import *
from PIL import Image,ImageTk
from urllib import urlopen
import io # try this

url1 = 'https://lh3.googleusercontent.com/-bnh6_0GlqbA/VUKUsl1Pp9I/AAAAAAACGoM/Vx9yu1QGIKQ/s650/Sunset.png'
url2 = 'https://lh3.googleusercontent.com/-_J57qf7Y9yI/VUPaEaMbp9I/AAAAAAACGuM/3f4551Kcd0I/s650/UpsideDawn.png'

window = Tk()

imagebytes = urlopen(url1).read()
imagedata = io.BytesIO(imagebytes) # use bytesio instead of stringio
imagePIL = Image.open(imagedata)
imageready = ImageTk.PhotoImage(imagePIL)

imagelabel = Label(window, image = imageready)
imagelabel.image = imageready

imagelabel.pack()
window.mainloop()

rawDescription: Tkinter being fickle with pictures, some are blank, others are not


rawDescription: Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row


code: user = User(**data_db_form)

rawDescription: Save dictionary to model object

description: Save dictionary to model object


code:
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper

def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

rawDescription: Cross-Origin Resource Sharing Multiple Sites


code:
atuple = (1, 2, 3)
list(atuple)
list = ['cheese', 'on', 'toast']
list(atuple)

rawDescription: Replacing multiple characters from an element in a list,


rawDescription: python if $_GET is empty do something & url path

description: Python if $_GET is empty do something & url path


code:
lastUrl, nextUrl = None, 'blah'

while nextUrl != lastUrl:
    # url gets consumed and becomes "old"
    info, lastUrl = request.get(nextUrl), nextUrl

rawDescription: Exit a while loop, when a certain string doesn't appear in Python


rawDescription: How to efficiently use a index array as a mask to turn a numpy array into a boolean array?

description: Efficiently use a index array as a mask to turn a numpy array into a boolean array


code: hexbin(x, y, C=w, alpha=0.5)

rawDescription: Generate Weight Map in Color with MatPlotLib?


rawDescription: Python - Parse text file and create lists based on some criteria


rawDescription: Get the printed length of a word by text width


rawDescription: Using split to populate a column in Pandas dataframe


code:
df[['birth_date_1', 'birth_date_2']].lt(df['date'], axis=0)
df[['birth_date_1', 'birth_date_2']].lt(df['date'], axis=0).sum(axis=1)

rawDescription: Pandas comparison with variable number of columns


code:
def __init__(self, firstname, lastname):
    self.firstname = firstname
    self.lastname = lastname

employee_data = ['John', 'Smith']
employee = Employee(*employee)
...

rawDescription: generalised insert into sqlalchemy using dictionary

description: Generalised insert into sqlalchemy using dictionary


rawDescription: How to get all grandchildren of a directory in python with only one OS call

description: Get all grandchildren of a directory in python with only one OS call


rawDescription: Performance issue in python with nested loop


code:
Solution
from StringIO import StringIO
import re
import pandas as pd

text = """adidas,,
USER_ID,USER_NAME
b012345,zaihan,Process
b212345,nurhanani,Check
b451234,nasirah,Call
c234567,ibrahim,Check
nike,,
USER_ID,USER_NAME
b842134,khalee,Call
h123455,shabree,Process
c234567,ibrahim,Process
c143322,zaihan,Check
b451234,nasirah,Call
"""

m = re.findall(r'(.*,,\n(.*([^,]|,[^,])\n)*)', text)

dfs = range(len(m))
keys = range(len(m))
for i, f in enumerate(m):
    lines = f[0].split('\n')
    lines[1] += ','
    keys[i] = lines[0].split(',')[0]
    dfs[i] = pd.read_csv(StringIO('\n'.join(lines[1:])))

df = pd.concat(dfs, keys=keys)
df = df.set_index(['USER_ID', 'USER_NAME'], append=True).unstack(0)

df.index = df.index.droplevel(0)
df.columns = df.columns.droplevel(0)

df = df.stack().unstack()

rawDescription: process data with header in rows in python csv

description: Process data with header in rows in python csv


code:
if (index % 2 == 0):
    data[counter][1][peak_counter][0] = float(buff2)
else:
    data[counter][1][peak_counter][1] = float(buff2)

rawDescription: Making my NumPy array shared across processes


code:
class SomeModel(ndb.Model):
  avatar = ndb.BlobProperty()

rawDescription: Store uploaded file data in Blob

description: Store uploaded file data in Blob


code:
Color(1)
Color(3)

rawDescription: How to convert int to Enum in python?

description: Convert int to Enum in python


code:
import re
pattern = re.compile("(Mo|Tu|We|Th|Fr|Sa|Su)+\s\d{2}:\d{2}(AM|PM)\s-\s\d{2}:\d{2}(AM|PM)")
pattern.match('MoWe 04:30PM - 05:50PM').group(0)
pattern.match('Fr 12:00PM - 01:20PM').group(0)

rawDescription: Regex match text starting with word in a set


code:
calculated_std = 0.0
absolute_avg = 1.0

rawDescription: python while loop iteration

description: Python while loop iteration


code:
with open("monthly.csv", "w") as f:
    p = pd.read_csv(next(glb), names=['Name', 'Date', 'Open', 'High',
                                      'Low', 'Close', 'Volume'], usecols=[0, 1, 2, 3, 4, 5, 6])
    p.to_csv(f)
    for files in glb:
        p = pd.read_csv(files, names=['Name', 'Date', 'Open', 'High',
                                      'Low', 'Close', 'Volume'], usecols=[0, 1, 2, 3, 4, 5, 6])
        p.to_csv(f, sep=',', header=False)

rawDescription: Pandas prints to screen corrently but saves only some data to csv


code:
def _requests_to_follow(self, response):
    if not isinstance(response, HtmlResponse):
        return
    seen = set()
    for n, rule in enumerate(self._rules):
        links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
        if links and rule.process_links:
            links = rule.process_links(links)
        seen = seen.union(links)
        for link in links:
            r = Request(url=link.url, callback=self._response_downloaded)
            r.meta.update(rule=n, link_text=link.text)
            yield rule.process_request(r)

rawDescription: Scrapy CrawlSpider rules with multiple callbacks


code:
import functools
import inspect

realgas = inspect.getargspec

lookaside = dict()

def fakegas(f):
    if f in lookaside:
        return lookaside[f]
    return realgas(f)

inspect.getargspec = fakegas

def deco(fn):
    @functools.wraps(fn)
    def x(*args, **kwargs):
        return fn(*args, **kwargs)
    lookaside[x] = realgas(fn)
    return x

@deco
def x(a, b=23):
  """Some doc for x."""
  return a + b

help(x)

rawDescription: How to keep help strings the same when applying decorators?

description: Keep help strings the same when applying decorators


rawDescription: How to copy files of a certain type in python

description: Copy files of a certain type in python


rawDescription: Apache spark taking average by key with python


code:
NET-216-58-192-0-1
{'Address': '1600 Amphitheatre Parkway',
 'CIDR': '216.58.192.0/19',
 'City': 'Mountain View',
 'Country': 'US',
 'NetHandle': 'NET-216-58-192-0-1',
 'NetName': 'GOOGLE',
 'NetRange': '216.58.192.0 - 216.58.223.255',
 'NetType': 'Direct Allocation',
 'OrgAbuseEmail': 'arin-contact@google.com',
 'OrgAbuseHandle': 'ZG39-ARIN',
 'OrgAbuseName': 'Google Inc',
 'OrgAbusePhone': '+1-650-253-0000',
 'OrgAbuseRef': 'http://whois.arin.net/rest/poc/ZG39-ARIN',
 'OrgId': 'GOGL',
 'OrgName': 'Google Inc.',
 'OrgTechEmail': 'arin-contact@google.com',
 'OrgTechHandle': 'ZG39-ARIN',
 'OrgTechName': 'Google Inc',
 'OrgTechPhone': '+1-650-253-0000',
 'OrgTechRef': 'http://whois.arin.net/rest/poc/ZG39-ARIN',
 'Organization': 'Google Inc. (GOGL)',
 'OriginAS': 'AS15169',
 'Parent': 'NET216 (NET-216-0-0-0-0)',
 'PostalCode': '94043',
 'Ref': 'http://whois.arin.net/rest/org/GOGL',
 'RegDate': '2000-03-30',
 'StateProv': 'CA',
 'Updated': '2013-08-07'}

rawDescription: re.split return None in function but normaly works OK

description: Re.split return None in function but normaly works OK


code:
new_dc_files = list()
for dc in dc_files:
    if 'NoCover' in dc:
         continue
    new_dc_files.append(dc)

rawDescription: Python Remove Item from list

description: Python Remove Item from list


code:
plot_table = df.pivot_table(index=['Year', 'LandUse'],
                            columns='Region',
                            values='Area', aggfunc='sum')

rawDescription: pandas complicated stacked barplot

description: Pandas complicated stacked barplot


rawDescription: How to get the coordinates of a graph drawn by specific layout algorithm in graph-tool?

description: Get the coordinates of a graph drawn by specific layout algorithm in graph-tool


code:
class A:
    pass
add_helpfunc(A)
help(A.helpfunc)
help(A().helpfunc)

rawDescription: Attribute added with setattr not showing up in help()


code:
from itertools import groupby

def f(lst):
    if_empty = ('ignored_key', ())
    k, v = next(groupby(lst), if_empty)
    return sum(1 for _ in v)

rawDescription: Finding the amount of equal elements in the beginning of a list


code:
from widgets.color_picker import ColorPicker
from widgets.fancy_window import FancyWindow

rawDescription: Python module importing

description: Python module importing


code:
class LoL(list):
    def __init__(self, *args):
        list.__init__(self, *args)
    def __getitem__(self, item):
        try:
            return list.__getitem__(self, item)
        except TypeError:
            rows, cols = item
            return [row[cols] for row in self[rows]]

lol = LoL([list(range(10)) for i in range(10)])
print(lol[1:4, 2:5])

rawDescription: Sub matrix of a list of lists (without numpy)


code: H2 = np.pad(H[:-2], (2, 0), mode='constant', constant_values=(np.nan,))

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code:
a = df.groupby("A")["C"]
newt = a.last() - a.first()
print(newt)

rawDescription: Pandas calculate year over year (or any other index) change in rows


rawDescription: Python 2.7 formatting data for writing as csv


code:
import urllib2
r = urllib2.urlopen(url)

In [29]: r = urllib2.urlopen(url)

In [30]: date = next(r).strip('# date=').rstrip()

In [31]: time = next(r).strip('# time=').rstrip()

In [32]: stamp = pd.to_datetime(x + ' ' + time)

In [33]: stamp
Out[33]: Timestamp('2013-11-12 00:00:00', tz=None)

rawDescription: Extracting metadata from comment fields using pandas


code:
def fillVacuum(toFill,MatchLengthOf):
    if len(toFill)<len(MatchLengthOf):
       [toFill.insert(i, np.nan) for i in range(len(MatchLengthOf)-len(toFill))]
    return()

def sortByAnthr(X,Y,Xindex):
    #intersect non-na column indexes between two datasets
    idx = np.intersect1d(X.notnull().nonzero()[0],Y.notnull().nonzero()[0])

    #order the subset of X.index by Y
    ordrX = [x for (x,y) in sorted(zip(Xindex[idx],Y[idx]), key=lambda pair: pair[1])]

    #due to molding that'll happen later in apply, it is necessary to fill removed indexes
    fillVacuum(ordrX, Xindex)

    return(ordrX)

def OrderRow(row,df):
    ordrd_row = df.ix[row.dropna().name,row.dropna().values].tolist()
    fillVacuum(ordrd_row, row)
    return(ordrd_row)

def r_selectr(dat2,dat1, n):
    ordr_cols = dat1.apply(lambda x: sortByAnthr(x,dat2.loc[x.name,:],x.index),axis=1).iloc[:,-n:]
    ordr_cols.columns = list(range(0,n)) #assign interpretable column names

    ordr_r = ordr_cols.apply(lambda x: OrderRow(x,dat1),axis=1)
    return([ordr_cols, ordr_r])

ordr_cols,ordr_r = r_selectr(dat2,dat1,5)

rawDescription: Sort dataframe rows independently by values in another dataframe


rawDescription: How to correctly parse a tiled map in a text file?

description: Correctly parse a tiled map in a text file


code:
fib_dec = memoize(fib_dec) # fully memoized
fib_undec_1 = memoize(fib_undec) # not fully memoized

print("Calling fib_dec(2)")
print(fib_dec(2))
print("Calling fib_dec(1)")
print(fib_dec(1))
print("Calling fib_undec_1(2)")
print(fib_undec_1(2))
print("Calling fib_undec_1(1)")
print(fib_undec_1(1))
print("Calling fib_undec_1(2)")
print(fib_undec_1(2))

rawDescription: Memoization python function

description: Memoization python function


rawDescription: What is difference between {:.4e} and {:2.4} in Python scientific notation


code:
class RandomResponder(object):
    choices = [A, B, C]

    @classmethod
    def which(cls):
        return random.choice(cls.choices)

    def __getattr__(self, attr):
        return getattr(self.which(), attr)

rawDescription: Need to route instance calls inside a python class


code:
groups.nth(n=0)  # the 0th items in each group
groups.nth(n=1)  # the 1st items in each group, NaNs if <=1

rawDescription: Accessing groups in Pandas

description: Accessing groups in Pandas


rawDescription: Pandas, order of groupby and projection

description: Pandas, order of groupby and projection


code:
for item in temp_list['data']:  # Add latest pulled data to our list
    members.append(item)

rawDescription: Python recursive function variable scope


code:
import Queue

log = Queue.Queue()
class Runner1(object):

    def run(self):
        log.put('First Warning')
        log.put('Second Warning')
        return 42

class Main1(object):

    def __init__(self):
        self._runner = Runner1()

    def log(self, message):
        print('Some object specific info: {0}'.format(message))

    def run(self):
        out=self._runner.run()
        while True:
            try:
                msg = log.get_nowait()
                self.log(msg)
            except Queue.Empty:
                break
        print(out)

e1 = Main1()
e1.run()

rawDescription: Thread-safe warnings in Python

description: Thread-safe warnings in Python


code:
from random import choice
''.join(choice(('0','1')) for _ in range(10))

rawDescription: Binary string in Python issues

description: Binary string in Python issues


code: clsmembers = [c for c in inspect.getmembers(sys.modules[__name__], inspect.isclass) if c[1].__module__ == __name__]

rawDescription: Get a list of classes, defined within a script


code:
from django.core.serializers.json import Serializer

class UserSerializer(Serializer):
    def get_dump_object(self, obj):
        mapped_object = {
            'user_name': obj.first_name,
            'salary': obj.salary,
            'dept_name': obj.dept_name
        }

        return mapped_object

rawDescription: using Django Rest framework to serialize custom data types and return response

description: Using Django Rest framework to serialize custom data types and return response


code:
choice = input('letter: ')
choice = choice.strip()
if choice == 'a':
    print ('that is an a')
    input('press any key to exit...')
else:
    print('that letter is not an a')
    input('press any key to exit')

rawDescription: Why does my code work in python shell but not when I double click the py file


rawDescription: How to make an action happen every minute in Python

description: Make an action happen every minute in Python


code:
from multiprocessing import Pool

input_list = []
for i in list1:
    for j in list2:
        input_list.append((i, j))

p = Pool()
result_list = p.map(do_something, input_list)

rawDescription: is synchronization needed with multiprocessor in python?

description: Is synchronization needed with multiprocessor in python


code:
import logging

import chromalog

logger = logging.getLogger('foo')

chromalog.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
fh = logging.FileHandler('foo.log')
logger.addHandler(fh)
logger.warning('warning!')

rawDescription: Adding chromalog to STDOUT and file logging


code:
def myview(request):
    result = subprocess.Popen(['ls', '/home/zurelsoft/R'], stdout=subprocess.PIPE).communicate()[0].splitlines()
    return render_to_response('thanks.html', {'res':result, 'res1':command}, context_instance=RequestContext(request))

rawDescription: Line break the list element in Python

description: Line break the list element in Python


code:
from itertools import takewhile, islice, count

def chunk(stream, size):
    return takewhile(bool, (list(islice(stream, size)) for _ in count()))

rawDescription: python: is there a library function for chunking an input stream?

description: Python: is there a library function for chunking an input stream


code:
import datetime
now = datetime.datetime.now()
date = '2014-02-19'
time = '10:08:13.61'
dt = datetime.datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M:%S.%f')
dt
now - dt

rawDescription: Calculate elapsed time

description: Calculate elapsed time


rawDescription: Filter out rows/columns with zero values in MultiIndex dataframe


rawDescription: Using BeautifulSoup to search html for string


code:
descriptionTextField("<KeyRelease-Up>", OnArrow)
descriptionTextField("<KeyRelease-Down>", OnArrow)
pnTextField("<KeyRelease-Up>", OnArrow)
pnTextField("<KeyRelease-Down>", OnArrow)
...
def OnArrow(event):
    widget = event.widget
    other = pnTextField if widget == descriptionTextField else descriptionTextField
    other.yview_moveto(widget.yview()[0])
    other.mark_set("insert", widget.index("insert"))

rawDescription: Python tkinter scrolling two TEXT widgets at the same time with arrow keys


code:
signin_data[u'email'] = 'your_email'
signin_data[u'password'] = 'your_password'

rawDescription: Unable to log in to Amazon using Python

description: Unable to log in to Amazon using Python


rawDescription: Optimize Class Simulation Code?

description: Optimize Class Simulation Code


code:
def out_loop():
    out = np.empty((arr1.size, arr2.size))
    for i in range(arr1.size):
        np.multiply(arr1[i], arr2, out=out[i].reshape((1, arr2.size)))
        out[i] *= 2
    return out

rawDescription: Why are for loops quicker than numpy for 2D array multiplication


code:
br.select_form(nr=0) # select index
controls = br.form.controls
controls[desired_index]._value = 'your_value'
...
br.submit()

rawDescription: differentiating between html form SELECT items with the same name

description: Differentiating between html form SELECT items with the same name


code: lst = []

rawDescription: How to convert column data from text file into list in Python?

description: Convert column data from text file into list in Python


code:
import itertools
def cycle_through_servers(*server_lists):
    zipped = itertools.izip_longest(*server_lists, fillvalue=None)
    chained = itertools.chain.from_iterable(zipped)
    return itertools.cycle(s for s in chained if s is not None)

rawDescription: cycle through multiple list using itertools.cycle()

description: Cycle through multiple list using itertools.cycle()


code:
import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-i", "--idMovie", dest="arg",
                  help="insertMovieIds", metavar="variable")
opt, args = parser.parse_args()
un_id = opt.arg
with open("out.txt") as f:
    names = next(f).rstrip().split(",")
    r = csv.DictReader(f, fieldnames=names)
    print(",".join(names))
    for d in r:
        if un_id == d["MovieID"]:
            print(",".join([d[n] for n in names]))

rawDescription: Python2.7 - Passing argument to command line to filter CSV according to parameter


code:
def __call__(self, parser, namespace, values, option_string=None):
    setattr(namespace, self.dest, values)

rawDescription: Neatly pass positional arguments as args and optional arguments as kwargs from argpase to a function


code:
aList = []
sDict = {}
for com in coms:
    for env in envs:
        for d in eval("{0}_{1}_stks".format(env, com)):
            aList.append(d["name"]) # add name from d to end of aList
            sDict[d["name"]] = {'component': com, 'environment': env}

rawDescription: creating a dict iterating through two nested loops and a JSON output

description: Creating a dict iterating through two nested loops and a JSON output


code:
from random import sample

with open("foo.fasta") as f:
    print(sample(list(zip(f, f)), 2))

rawDescription: How to randomly extract FASTA sequences using Python?

description: Randomly extract FASTA sequences using Python


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

n = 100000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
plt.hexbin(x,y)

plt.show()

rawDescription: Python: Creating a 2D histogram from a numpy matrix


code:
with open('output.txt', 'w+') as new_file:
    new_file.write(variable)

rawDescription: How do I save the output I have to a new text file?

description: Save the output I have to a new text file


code:
def addition_range(start, end):
    res = [(lambda x, i=i: x + i) for i in range(start, end)]
    return res or None

rawDescription: Generator and actual variable values

description: Generator and actual variable values


code:
while True:
    if time.time() > future:
        break
    # do other stuff

rawDescription: Stopwatch In Python

description: Stopwatch In Python


code: permission_classes = (IsAuthenticated, IsOwner)

rawDescription: Use request.user for model deserialization in django rest framework


code:
with open('a.txt', 'r') as infile:
    with open('b.txt', 'w') as outfile:
        for line in infile:
            line = line.split()
            new_line = '{0} "yyy" {1} "xxx"\n'.format(line[0], line[3])
            outfile.write(new_line)

rawDescription: python program - modify columns in text file

description: Python program - modify columns in text file


code:
def proxy(bridge):
    def proxyfy(cls):
        def __getattr__(self, attr):
            target = getattr(self, bridge)
            if attr.startswith('__') and not attr.endswith('__'):
                # unmangle
                attr = '_{}{}'.format(type(target).__name__, attr)
            return getattr(target, attr)
        setattr(cls, '__getattr__', __getattr__)
        return cls
    return proxyfy

rawDescription: Using closure to decorate a class's methods


code: 'this is a sentence.'.capitalize()

rawDescription: Title case for a paragraph

description: Title case for a paragraph


rawDescription: Python, Pairwise 'distance', need a fast way to do it


code:
import time

device1 = '04/12/2012 14:17'
device2 = '14:16:13'
device3 = '134941'

time1 = time.strptime(device1, '%m/%d/%Y %H:%M')
time2 = time.strptime(device2, '%H:%M:%S')
time3 = time.strptime(device3, '%H%M%S')

rawDescription: Matching up differing timestamp conventions across device data


code: A.__getitem__((slice(None, None, None), 1, 2))

rawDescription: Index a numpy array using a tuple (or list) when len < ndim?


code:
from django.db import models
from localflavor.us.us_states import US_STATES
class StateChoice(models.Model):
    state = forms.ChoiceField(choices=US_STATES)

rawDescription: How to read a data file containing survey form options into models.py

description: Read a data file containing survey form options into models.py


code: ref = { key: d[key] }

rawDescription: Retrieve a key-value pair from a dict as another dict


code:
@functools.total_ordering
class Foo:
    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def __lt__ (self, other):
        if self.a == other.a:
            return self.b < other.b
        return self.a < other.b

    def __eq__ (self, other):
        return self.a == other.b and self.b == other.b

rawDescription: Python equivalent of Java's compareTo()

description: Python equivalent of Java's compareTo()


code:
fa = lambda: a**3-a-2
fb = lambda: b**3-b-2
fc = lambda: c**3-c-2
fa
fb
fc
fc()  # calling a function executes the expression, each time
c += 2
fc()

rawDescription: Python Variables and Equations

description: Python Variables and Equations


code: first = next((d for d in L if 'firstname' in d and 'lastname' in d), None)

rawDescription: Get to nested dictionary in list

description: Get to nested dictionary in list


code: {{ user.my_proxy.keywords }}

rawDescription: Getting Proxied user object in django templates


rawDescription: Is there another better way to get file ext from a given path in python


code:
for pi in open('pi.txt'):
    pi = pi.upper()
    words = [word.rstrip() for word in open('wordlist.txt') if word.rstrip().upper() in pi]

rawDescription: Find words from a sequence of random letters?


code:
df = pd.DataFrame({'a': a, 'b': b})
df.groupby(['a', 'b']).groups

rawDescription: find index of similar values

description: Find index of similar values


code:
res.index = res.index.droplevel(0)
res

rawDescription: Python: indexing pandas series by datetime


rawDescription: Python Compare overlap of multiple dictionaries of ranges


code:
_dictkeys = "y", "z"

def __iter__(self):
    for key in self._dictkeys:
        yield key, getattr(self, key)

rawDescription: How can I make a custom conversion from an object to a dict?

description: Make a custom conversion from an object to a dict


code:
sl_i = slice(i_min, i_max)
sl_j = slice(j_min, j_max)
sl_k = slice(k_min, k_max)
M_selection = M[sl_i, sl_j, sl_k]

rawDescription: How to extract a sub-array in numpy efficiently?

description: Extract a sub-array in numpy efficiently


code:
a_sep = [x.split('/')[1] for x in a]
idxs = [i for i, x in enumerate(a_sep) if x in b]

rawDescription: Cross-list comprehension in Python

description: Cross-list comprehension in Python


code:
from matplotlib.backends.backend_pdf import PdfPages

# create df2
with PdfPages('foo.pdf') as pdf:
    for key, group in df2:
        fig = group.plot().get_figure()
        pdf.savefig(fig)

rawDescription: Plot and save multiple figures of group by function as pdf


code:
import os
import sys
sys.path.insert(0, os.path.expanduser('~/lib'))

rawDescription: How to setup environemnt to load python library?

description: Setup environemnt to load python library


code:
from PIL import Image, ImageChops

def is_there_a_border(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    return bbox != (0,0,im.size[0],im.size[1])

rawDescription: Detect if an image has a border, programmatically (return boolean)


rawDescription: Split string by hyphen

description: Split string by hyphen


code:
Solution
for i in range(len(data_sets_a)):
    cols = ['col_a', 'col_b', 'col_c']
    gb = data_sets_a[i].groupby(cols)
    data_sets_a[i] = gb.agg(funcs, inplace=1).reset_index()

rawDescription: How do I apply transformations to list of pandas dataframes?

description: Apply transformations to list of pandas dataframes


code:
def deleteButton():
    b = layout.takeAt(2)
    buttons.pop(2)
    b.widget().deleteLater()

rawDescription: PySide: Removing a widget from a layout

description: PySide: Removing a widget from a layout


code: dictPass = {i.split()[0]:i.split()[1] for i in users}

rawDescription: How to check if the second list element on a line in a file contains 'x'?

description: Check if the second list element on a line in a file contains 'x'


code:
import requests
response = requests.get('https://websitewithfile.com/text.txt',verify=False, auth=('user', 'pass'))
print(response.text)

rawDescription: HTTP Error 401: Authorization Required while downloading a file from HTTPS website and saving it


rawDescription: Numpy - add row to array

description: Numpy - add row to array


code:
import numpy as np
labels = np.arange(0, 10) % 2
from sklearn.cross_validation import LeaveOneLabelOut
cv = LeaveOneLabelOut(labels)

rawDescription: How to customize sklearn cross validation iterator by indices?

description: Customize sklearn cross validation iterator by indices


code:
new_list =[] # A list which holds the numbers
for a in range(1111,10000):
    for b in str(a):
        if int(b) % 2 == 0:
            break
    else:
        # only executed if the loop wasn't broken out of
        new_list.append(a)

rawDescription: How to check if all the digits of a number are odd in python?

description: Check if all the digits of a number are odd in python


code:
ldap_host = 'example.com'
ldap_port = 389
...

rawDescription: web2py application configuration file

description: Web2py application configuration file


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(3,3))
ax.pcolormesh(trans.values, cmap=plt.get_cmap('Blues'), vmin=0, vmax=1)
ax.invert_yaxis()
ax.set_yticks(np.arange(0, len(trans.index))+0.5)
ax.set_xticks(np.arange(0, len(trans.columns))+0.5)
ax.set_yticklabels(trans.index, fontsize=16, color='k')
ax.set_xticklabels(trans.columns, fontsize=16, color='k')
ax.tick_params(direction='out', pad=10)
ax.set_frame_on(True)

for tk1, tk2 in zip(ax.xaxis.get_major_ticks(), ax.yaxis.get_major_ticks()):
    tk1.tick1On, tk2.tick1On, tk1.tick2On, tk2.tick2On = [False]*4

plt.show()

rawDescription: Estimating transition probabilities (pandas)


Header: MakeModeChange

rawDescription: Getting the Response value of an XMLHttpRequest in Polymer


code:
from importlib import import_module

name = 'xml.etree.ElementTree.ElementTree'
parts = name.rsplit('.', 1)
ElementTree = getattr(import_module(parts[0]), parts[1])
tree = ElementTree()

rawDescription: How do you map a fully qualified class name to its class object in Python?

description: Map a fully qualified class name to its class object in Python


code:
event_buffer = ctypes.create_string_buffer(BUFFER_SIZE)
nbytes = ctypes.wintypes.DWORD()
overlapped_read_dir = OVERLAPPED()
call2pass = RDCW_CALLBACK_F(dir_change_callback)

hand = get_directory_handle(os.path.abspath("/test/"))

def docall():
    ReadDirectoryChangesW(hand, ctypes.byref(event_buffer),
                          len(event_buffer), False,
                          WATCHDOG_FILE_NOTIFY_FLAGS,
                          ctypes.byref(nbytes),
                          ctypes.byref(overlapped_read_dir), call2pass)

print("Waiting!")
docall()

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code:
def bar():
    return [[x for x in y] for z in spam]

dis.dis(bar)

rawDescription: Why does locals() return a strange self referential list?


code:
s = "A string with "
d = s.encode("utf-8")
print(len(s)) # outputs 15
print(len(d)) # outputs 18

rawDescription: The reason of foo.__x__ and x(foo) in Python (i.e. len and __len__)


code:
from itertools import product

d1 = {(i, j): {} for i, j in product(range(4), repeat=2)}

rawDescription: Dictionary assignment to tuple-keys in other dictionary with map() function


code:
from myApp.models import Key, Value # where myApp is your app name

key = Key.objects.get(key='my_key')
values = key.values.all()

rawDescription: How to design Django models where one key have multiple corresponding values?

description: Design Django models where one key have multiple corresponding values


code:
vocabulary = {}  # map terms to column indices
data = []        # values (maybe weights)
row = []         # row (document) indices
col = []         # column (term) indices

for i, doc in enumerate(documents):
    for term in doc:
        # get column index, adding the term to the vocabulary if needed
        j = vocabulary.setdefault(term, len(vocabulary))
        data.append(1)  # uniform weights
        row.append(i)
        col.append(j)

A = scipy.sparse.coo_matrix((data, (row, col)))

rawDescription: How to convert co-occurrence matrix to sparse matrix

description: Convert co-occurrence matrix to sparse matrix


code:
in_between_dates = []
for d in dt_dates:
    if d >= start_date and d <= end_date:
        in_between_dates.append(d)

rawDescription: How do I filter a python list containing dates according to the given start date and end date?

description: Filter a python list containing dates according to the given start date and end date


rawDescription: How to change matplotlib line color in scipy.spatial.delaunay_plot_2d

description: Change matplotlib line color in scipy.spatial.delaunay_plot_2d


code: y = np.concatenate([y, N[None,:]], axis=0)

rawDescription: Simpler code to combine multiple lists into one array? I actually wish "lists" are still "lists" in that array


code:
lis1 = [['a', 2], ['b',1], ['b',5]]
lis2 = [['b', 2], ['c', 1], ['a', 10]]
from itertools import chain
from collections import Counter
c = sum((Counter(dict([x])) for x in chain(lis1, lis2)), Counter())
c.most_common()

description: Any pythonic way to do "[['a', 2], ['b',1]] + [['b', 2], ['c', 1]] = [['b', 3], ['a', 2], ['c', 1]]"


code:
noprimes = []
for i in range(2,8):
   for j in range(i*2, 50, i):
     noprimes.append(j)

rawDescription: No Primes list Comprehension

description: No Primes list Comprehension


code: df.groupby('User')['X'].filter(lambda x: x.sum() == 0).index

rawDescription: How to subset a data frame using Pandas based on a group criteria?

description: Subset a data frame using Pandas based on a group criteria


code:
connection = pymongo.Connection('mymongohostname.com')
connection.my_database.my_collection.insert({
    'created_at': dt,
    # ... other info about the tweet ....
}, safe=True)

rawDescription: How do I compare dates from Twitter data stored in MongoDB via PyMongo?

description: Compare dates from Twitter data stored in MongoDB via PyMongo


code: P(r, R, n).diff(r)

rawDescription: How to overload the fdiff method of a personal function inheriting from the Function class?

description: Overload the fdiff method of a personal function inheriting from the Function class


code:
new_stats = {
    'NumberOfHealthPickups': 99
    # ...
}
updated_stats = {}
for stat in new_stats:
    updated_stats[stat] = models.F(stat) + new_stats[stat]
PlayerStats.objects.filter(user=user).update(**updated_stats)

rawDescription: Update multiple columns using django F() object


code:
url(r'$', 'display', name='dyn_dysplay')
reverse('dyn_display')

rawDescription: pass kwargs for the view in reverse; django 1.5

description: Pass kwargs for the view in reverse; django 1.5


code:
import urllib.request
import xml.etree.ElementTree as ET
url=urllib.request.urlopen('http://www.tcmb.gov.tr/kurlar/201501/02012015.xml').read()
f=open('data.xml','w+b')
f.write(url)
f.close()
tree = ET.parse('data.xml')
root = tree.getroot()
for i in range(len(root[0])):
           print(root[0][i].text)

rawDescription: Web Mining with Python

description: Web Mining with Python


code:
def third_factorial(X):
    x = 1
    for position in range(3, X + 1, 3):
        x = factorial_recurrence(
                factorial_recurrence(
                    factorial_recurrence(
                        x,
                        position - 2
                    ),
                    position - 1
                ),
                position
            )
    return x

rawDescription: Issues with Recursion using Python 3

description: Issues with Recursion using Python 3


code:
timeit('f(r())', 'from __main__ import random_dict as r, original as f', number=100)
timeit('f(r())', 'from __main__ import random_dict as r, zip_and_max as f', number=100)

rawDescription: normalise list data in range (0.0, 1.0)

description: Normalise list data in range (0.0, 1.0)


rawDescription: Selecting and sorting on unique foreign key with Django


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

month = ["dec-09", "jan", "feb"]
n = len(month)

air = np.array([383.909, 395.913, 411.714])

ind = np.arange(n)
width = 0.35

fig, ax = plt.subplots()
ax.bar(ind, air, width, color=["yellow", 'cornflowerblue', 'darkgreen'])

ax.set_ylabel("KWH")
ax.set_title("winter")
ax.set_xticks(ind+width/2)
ax.set_xticklabels(("dec-09", "jan", "feb"))

rawDescription: Specify color type for bar graph pylab

description: Specify color type for bar graph pylab


code:
import subprocess
bashCommand = lambda url, filename: "wget -O %s.csv %s" % (filename, url)
save_locations = {'http://someurl/path/to/file.csv': 'test.csv'}
for url, filename in save_locations.items():
    process = subprocess.Popen(bashCommand(url, filename).split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]

rawDescription: How to save many CSV files from URL

description: Save many CSV files from URL


code:
ax.set_xlim(20, 40)
fig

rawDescription: Redisplaying modified plot in subsequent IPython notebook cells


code:
import Tkinter as tk

def main():

    root = tk.Tk()

    message = tk.Label(root, text="Hello World")
    message.pack()

    button = tk.Button(root, text="exit", command=root.destroy)
    button.pack()

    tk.mainloop()

main()

rawDescription: Alternative to using global parameters in Tkinter


code:
lines = []
with open('jag.txt') as f:
    lines = [ line.split('\t') for line in f.read().splitlines() ]
print(lines)

rawDescription: python text files

description: Python text files


code: group_rows = df.groupby('ID').groups

rawDescription: pandas DataFrame to list of dict using columns as key

description: Pandas DataFrame to list of dict using columns as key


rawDescription: For Kasiski Test,How to implement 26x26 table in Python


code:
from datetime import datetime
my_time = '05:43:34'

my_time = datetime.strptime('%H:%M:%S', my_time)

rawDescription: Structure representing time without date in Python


code:
tempdict=dict()
f=open(textfile, 'r')
while 1:
    x=f.readline().strip()
    if x=='':
        f.close()
        break
    x=[x[i] for i in range(len(x))]
    for node in x:
        tempdict[node]=''

rawDescription: Python. Import specific characters from a .txt file


code:
import lxml.html
data = ["
test	help
", "
data1	data2
"]
[lxml.html.fromstring(tr).xpath(".//text()") for tr in data]

rawDescription: Parsing an html table

description: Parsing an html table


rawDescription: Print strings with line break Python

description: Print strings with line break Python


code:
df['quant'] = np.nan

for q in [0.75, 0.5, 0.25]:
    df.loc[(df.fudge <= df.fudge.quantile(q + 0.25)) & (df.fudge > df.fudge.quantile(q)), 'quant'] = q

df.quant.fillna(0.0, inplace=True)

rawDescription: Getting quartiles in pandas when data has low variance


code:
@increment_counter('A')
def do_something_1(self):
    ...

rawDescription: How can I increase counter properties of class when a instance is called?

description: Increase counter properties of class when a instance is called


code: f = Button(win, text=a, command=lambda d=d: openWindowR(str(d)))

rawDescription: Opening windows from other windows in tkinter


rawDescription: Connecting to remote PostgreSQL database with SQLAlchemy using SSH tunneling with public key and passphrase, all that from a Windows machine


rawDescription: How to construct a dictionary which contain keys which are invalid keyword arguments, not using {}

description: Construct a dictionary which contain keys which are invalid keyword arguments, not using {}


code:
print(header('rr', 'Test table'))
print(line('First', 'Second'))
print(line(12, 27))
print(line(31, 9))
print(footer())

rawDescription: making a table in python

description: Making a table in python


code:
import datetime

data = ["2014-04-11 08:00:00.000000", "2014-04-11 09:35:00.000000", "2014-04-11 09:35:00.000000", "2014-04-11 09:40:00.000000", "2014-04-11 11:00:00.000000"]

delta = datetime.timedelta(minutes=10)
result = []
bucket = []
current = None
for item in data:
    datetime_obj = datetime.datetime.strptime(item, '%Y-%m-%d %H:%S:%M.%f')
    if current is None:
        current = datetime_obj
        bucket = [current]
        continue
    if (datetime_obj - current) <= delta:
        bucket.append(datetime_obj)
    else:
        result.append(bucket)
        current = datetime_obj
        bucket = [current]

if bucket:
    result.append(bucket)

for bucket in result:
    print(bucket)

rawDescription: Merge list of timestamps in Python

description: Merge list of timestamps in Python


code:
import numpy as np
bins = np.linspace(0,9,10)
bincount = np.zeros(9)
import random
for i in range(1000000):
    bincount += np.histogram(random.randrange(9), bins)[0]

bincount

rawDescription: Counts in bins using loop

description: Counts in bins using loop


code:
try:
    foo = 1
    guessfoo = int(input('Guess my number: '))
    if foo == guessfoo:
        print('Well done, You guessed it!')
    else:
        print('haha, fail.')
except ValueError:
    # cannot cast your input
    pass

rawDescription: Guessing a number, true or false? Python


code:
def get_table_list(self, cursor):
        "Returns a list of table names in the current database."
        cursor.execute("""
            SELECT c.relname
            FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relkind IN ('r', 'v', '')
                AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
                AND pg_catalog.pg_table_is_visible(c.oid)""")
        return [row[0] for row in cursor.fetchall()]

rawDescription: Django syncdb - How does it know if it previously created the tables or if I did?


code:
def sweep(g, k):
    g = np.asarray(g)
    n = g.shape[0]
    if g.shape != (n, n):
        raise ValueError('Not a square array')
    if not np.allclose(g - g.T, 0):
        raise ValueError('Not a symmetrical array')
    if k >= n:
        raise ValueError('Not a valid row number')
    #  Fill with the general formula
    h = g - np.outer(g[:, k], g[k, :]) / g[k, k]
    # h = g - g[:, k:k+1] * g[k, :] / g[k, k]
    # Modify the k-th row and column
    h[:, k] = g[:, k] / g[k, k]
    h[k, :] = h[:, k]
    # Modify the pivot
    h[k, k] = -1 / g[k, k]
    return h

rawDescription: Python implementation of statistical Sweep operator


code:
hd = os.path.expanduser('~')
os.mkdir(os.path.join(hd, '.my-config'))

rawDescription: Is there a Python idiom for creating dot folders in home directory?


rawDescription: Finding partial matches in an href tag

description: Finding partial matches in an href tag


code: c = (a < 3).astype(int)

rawDescription: Replacing Numpy elements if condition is met


rawDescription: python: how to create list of/iterate through multiple instances of a variable

description: Python: how to create list of/iterate through multiple instances of a variable


rawDescription: How do you express binary literals in Python?

description: Express binary literals in Python


code: [(key, list(group)) for key, group in groupby(L, key=bool)]

rawDescription: Make a new sublist of preceding characters every time there's a zero in a list, excluding the zero


code:
h1,h2,h3
a,b,c
d,e,f
g,h,i
j,k,l

rawDescription: How to Delete Rows CSV in python

description: Delete Rows CSV in python


code:
from django.db import connections

class DBRouter(object):
    """A router to control all database operations on models in
    the contrib.auth application"""

    def db_for_read(self, model, **hints):
        m = model.__module__.split('.')
        try:
            d = m[-1]
            if d in connections:
                return d
        except IndexError:
            pass
        return None

    def db_for_write(self, model, **hints):
        m = model.__module__.split('.')
        try:
            d = m[-1]
            if d in connections:
                return d
        except IndexError:
            pass
        return None

    def allow_syncdb(self, db, model):
        "Make sure syncdb doesn't run on anything but default"
        if model._meta.app_label == 'myapp':
            return False
        elif db == 'default':
            return True
        return None

rawDescription: Multiple Database Config in Django 1.2

description: Multiple Database Config in Django 1.2


code:
def group_splitter(it, key=None):
    if key is None:
        key = lambda x: x
    group = []
    for item in iter(it):
        if key(item) and group:
            yield group
            group = []
        group.append(item)
    if group:
        yield group

rawDescription: Split a list into sublists on a value and keep the value


code:
def check_lists(list1, list2):
    return list1 == list2

rawDescription: How to check if two lists have the same objects in the same order?

description: Check if two lists have the same objects in the same order


code:
p = Parent(
    parent_id='A3333', name='with a child',
    children=[Child(name='will not work')]
)
session.add(p)
session.commit()  # this will fail

rawDescription: relationship with a sliced and casted value of the column in SQLAlchemy

description: Relationship with a sliced and casted value of the column in SQLAlchemy


rawDescription: Can some one explain me what does np.log do?


code:
b=a.split(',')
b

rawDescription: Slicing a python string with intervals?

description: Slicing a python string with intervals


code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class ZeroSpinBox(QSpinBox):
    atzero = pyqtSignal(int)

    zeros = 0

    def __init__(self):
        super(ZeroSpinBox, self).__init__()
        self.valueChanged.connect(self.checkzero)

    def checkzero(self):
        if self.value() == 0:
            self.zeros += 1
#             self.emit(SIGNAL("atzero(int)"), self.zeros)
            self.atzero.emit(self.zeros)

class Form(QDialog):

    def __init__(self):
        super(Form, self).__init__()

        dial = QDial()
        dial.setNotchesVisible(True)
        zerospinbox = ZeroSpinBox()
        layout = QHBoxLayout()
        layout.addWidget(dial)
        layout.addWidget(zerospinbox)
        self.setLayout(layout)

        dial.valueChanged.connect(zerospinbox.setValue)
        zerospinbox.valueChanged.connect(dial.setValue)
        zerospinbox.atzero.connect(self.announce)
#         self.connect(zerospinbox, SIGNAL("atzero(int)"), self.announce)

        self.setWindowTitle("Signals")

    def announce(self, zeros):
        print("zerospinbox has been at zero " + str(zeros) + " times.")

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

rawDescription: How to connect custom signal to slot in pyside with the new syntax?

description: Connect custom signal to slot in pyside with the new syntax


code: [list(it) for key, it in groupby(sorted(L))]

rawDescription: How to sort like values in Python

description: Sort like values in Python


code:
[
    ('', 'bg.APDS.UnitTests.vbproj')
    ('', 'bg.DatabaseAPI.UnitTests.vbproj')
    ('', 'bg.DataManagement.UnitTests.vbproj')
    ('', 'bg.FormControls.UnitTests.vbproj')
]

rawDescription: Getting rid of empty strings in a tuple

description: Getting rid of empty strings in a tuple


code:
def short3(gen,X):
    return next(x for x in gen if x > X)

rawDescription: Elegant way to calculate first generator result larger than X


code:
import csv

with open('input.csv', 'rb') as fin, open('output.csv', 'wb') as fout:
    rows = list(csv.DictReader(fin, skipinitialspace=True))
    schemes = range(1, max(int(row['scheme']) for row in rows) + 1)
    fieldnames = ['Ip'] + ['scheme {}'.format(i) for i in schemes] + ['Sentence_id']
    csvout = csv.DictWriter(fout, fieldnames=fieldnames, extrasaction='ignore', restval='NA')
    csvout.writeheader()
    for row in rows:
        row['scheme {}'.format(row['scheme'].strip())] = row['Tag']
        csvout.writerow(row)

rawDescription: Python - csv column restructuring

description: Python - csv column restructuring


code:
class Foo(object): pass

first_class = Foo()
first_class.second_class = Foo()
first_class.second_class.third_class = Foo
first_class.second_class.third_class.id = 'baz'
resolve_object('first_class.second_class.third_class.id')

rawDescription: Resolving a Python object in global namespace by string look up


code:
def handle_change_username(self):
  user = ...  # get the user who wants to change their username
  username = self.request.get('username')
  uniq = 'User.username:%s' % username
  ok = User.unique_model.create(uniq)
  if ok:
    user.username = username
    user.put()
  else:
    # notify them that this username
    # is already taken
    ...

rawDescription: Adding a username property to webapp2 User model after entity has been created (with Simpleauth)


code: data['character2']['health'] = 50

rawDescription: Overwrite flags in a file python

description: Overwrite flags in a file python


code: struct.pack('>H', values)

rawDescription: Python3 editing hex string

description: Python3 editing hex string


code:
def format_time(seconds):
    return time.strftime('%H:%M:%S', time.gmtime(seconds))

rawDescription: How to list latest modification time of contents of some directories?

description: List latest modification time of contents of some directories


code:
def allowed(*allowed_methods):
    @auto_adapt_to_methods
    def wrapper(func):
        def wrapped(request):
            if request not in allowed_methods:
                raise ValueError("Invalid method %s" % request)
            return func(request)
        return wrapped
    return wrapper

rawDescription: Using the same decorator (with arguments) with functions and methods


code:
for x in _list:
    if is_list(x):
        new_list.append(process_list(x))
    else:
        new_list.append(x+1)

rawDescription: matching list structure other than map() in python

description: Matching list structure other than map() in python


code:
n = 0
i = li.index(n)     # returns the first location of n (0 in your case)
left = li[:i]       # gives the left part of the list
right = li[i+1:]    #     and the right part
lsum = sum(left)
rsum = sum(right)

rawDescription: Find sum of right and left hand of list element in python


code: dict(y, **x)

rawDescription: Union of dict objects in Python

description: Union of dict objects in Python


code:
range_list=[]
for number in my_list:
    if x <= number < y:
        range_list.append(number)

rawDescription: Getting Python range() to recognise a decimal eg. 70.555555


code:
for i, df in enumerate(dfs, start=1):
    df.rename(columns={col:'{}_df{}'.format(col, i) for col in ('items', 'spend')},
              inplace=True)

rawDescription: Pandas: merge multiple dataframes and control column names?


code:
from collections import Counter

Counter(map(tuple, multi)).most_common()

rawDescription: How do I compose a frequency list from unique arrays of different length in numpy

description: Compose a frequency list from unique arrays of different length in numpy


rawDescription: Why isn't read_csv() parsing my dates?

description: Why isn't read_csv() parsing my dates


code:
import numpy as np

def find_chain(mat):
  locs=np.column_stack(np.nonzero(mat))
  chain=[np.array([0,0])]
  while locs.shape[0]>0:
    dists=((locs-np.vstack([chain[-1]]*locs.shape[0]))**2).sum(axis=1)
    next=dists.argmin()
    if dists.min()<=2 or len(chain)==1:
      chain.append(locs[next,:])
      locs=locs[np.arange(locs.shape[0])!=next,:]
    else:
      chain=[chain[0]]+chain[1::][::-1]
  return np.vstack(chain[1::]),((chain[1]-chain[-1])**2).sum()<=2

rawDescription: Converting an open curve to a list of ordered pixels: a Python test code with numpy


code:
import re

text = '15" approx. length from waist to hem, 26" waist#Measured from Small#Shell: 100% Polyester, Lining: 100% Polyester#Machine wash cold, tumble dry low#Imported'
line_re = re.compile('#[^#]*%[^#]*#')
matches = line_re.findall(text)

rawDescription: Python non-greedy regex match with pattern in between


rawDescription: How to retrieve the exact HTML as in a browser

description: Retrieve the exact HTML as in a browser


rawDescription: How to map a function to every item in every sublist of a list

description: Map a function to every item in every sublist of a list


code:
from numpy import arange, newaxis
arange(2**4)[:,newaxis] >> arange(4)[::-1] & 1

rawDescription: Convert decimal range to Numpy array, with each bit being an array element


rawDescription: Calculation and construction of two dimensional array with nested loop


code:
{'api_error': {'list': [{'converted_value': 'invalid email',
                         'field': 'email',
                         'value': 'EMAIL_INVALID'},
                        {'converted_value': 'No special characters allowed',
                         'field': 'name',
                         'value': 'NAME_INVALID'}],
               'status': 'ERROR'},
 'email': 'EMAIL_INVALID',
 'email_label': 'invalid email',
 'name': 'NAME_INVALID',
 'name_label': 'No special characters allowed',
 'status': 'ERROR'}

rawDescription: create a python dictionary based on another dictionary

description: Create a python dictionary based on another dictionary


rawDescription: Obtaining a value from a list of dictionaries


code:
class EntryTemplate(Entry):
    def __init__(self, master, status):
        Entry.__init__(self, master)
        Entry.insert(self, 0, status)
        Entry.bind(self, "<FocusIn>", lambda event: self.clickOnEntry(event, status))
        Entry.bind(self, "<FocusOut>", lambda event: self.clickOffEntry(event, status))

    def clickOnEntry(self, event, defaultText):
        if self.get() == defaultText:
            self.delete(0, END)

    def clickOffEntry(self, event, defaultText):
        if len(self.get()) == 0:
            Entry.insert(self, 0, defaultText)

rawDescription: How can I use the get() function to turn the answer in the entry() box into a string

description: Use the get() function to turn the answer in the entry() box into a string


code:
l=[]
y=[]
for x in f.readlines():
    l.append(x.split()[0])   #list of ip addresses
    y.append(x.split()[1])   #list of ports

rawDescription: Dividing a text file into 2 lists using python


rawDescription: Align a matplotlib figure to the text in LaTeX


code: ('Phoenix', 'Phoenix')

rawDescription: Dataframe Indexing Issue?

description: Dataframe Indexing Issue


code:
#!/usr/bin/env python
import wx

app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
sizer = wx.BoxSizer(wx.HORIZONTAL)

menu = wx.Menu()
menu.Append(wx.ID_ABOUT, 'About')

search = wx.SearchCtrl(frame)
search.ShowCancelButton(True)
search.SetMenu(menu)

sizer.Add(search, 0)
frame.SetSizer(sizer)
frame.SetAutoLayout(1)
sizer.Fit(frame)
frame.Show()
app.MainLoop()

rawDescription: SearchCtrl in wxPython looks different

description: SearchCtrl in wxPython looks different


code: img.setTo(Vec3b(b, g, r));

rawDescription: the equivalent of python's [:] in c++

description: The equivalent of python's [:] in c++


rawDescription: how to import module from other directory in python?

description: Import module from other directory in python


code: new_dict = old_dict.copy()

rawDescription: How do I change an element in a list, and keep a copy of the original list?

description: Change an element in a list, and keep a copy of the original list


rawDescription: How to find floating point numbers in binary file with Python?

description: Find floating point numbers in binary file with Python


code: result = [value + x if flag else value for value, flag in zip(mylist, ix)]

rawDescription: Concatenating some string elements in a list with a given string


code:
import pandas as pd
import numpy as np

n = int(1e6)
np.random.seed(0)
df = pd.DataFrame({
    'uid': np.arange(n),
    'catid': np.repeat('foo bar baz', n),
})

rawDescription: How to make "value is in dateframe column" quicker

description: Make "value is in dateframe column" quicker


code:
def drop_keys(recursive_dict,keep_list):
    key_list=recursive_dict.keys()
    for key in key_list:
        if(type(recursive_dict[key]) is dict):
            drop_keys(recursive_dict[key], keep_list)
        elif(key not in keep_list):
            del recursive_dict[key]

rawDescription: Recursive dictionary modification in python


rawDescription: Class attribute overriding: keep parent class changes


rawDescription: How to sum elements of a list corresponding to elements of another list in python

description: Sum elements of a list corresponding to elements of another list in python


code: y[mask][:, mask] = other

rawDescription: Restricting a sparse matrix to a subspace in scipy


rawDescription: __getitem__ for a list vs a dict

description: __getitem__ for a list vs a dict


code:
import math
x = "3.5"
math.floor(float(x)) # returns FP; still needs to be wrapped in int()
math.ceil(float(x)) # same
math.trunc(float(x)) # returns an int; essentially the same as int(float(x))

rawDescription: Python: Convert '3.5' to integer

description: Python: Convert '3.5' to integer


code:
def gcd(a, b):
    count = 0
    while b:
        a, b = b, a%b
        count += 1
    print(count)
    return a

rawDescription: counting-steps Euclidean algorithm program in python

description: Counting-steps Euclidean algorithm program in python


code:
mean = sy / n
std = np.sqrt(sy2/n - mean*mean)

rawDescription: Mean values depending on binning with respect to second variable


code:
def home(request):
     content = posts.objects.all()[:5]
     form = postForm()
     if request.POST:
         form = postForm(request.POST)
         if form.is_valid():
             form.save()
     return render_to_response('index.html',{'posts' : content, 'form' : form}, context_instance=RequestContext(request))

rawDescription: Python and Django Blog Sample Project

description: Python and Django Blog Sample Project


code:
import csv
from collections import defaultdict

mydict = defaultdict(dict)
with open('inventory.csv', 'rb') as inf:
    for row in csv.DictReader(inf, fieldnames=['Product', 'Part Number',
                                               'Category']):
        mydict[row['Category']][row['Product']] = row['Part Number']

import json  # for pretty-printing result
print(json.dumps(mydict, indent=4))

rawDescription: Creating nested dict using csv.DictReader


rawDescription: python re.search (regex) to search words who have pattern like {{world}} only

description: Python re.search (regex) to search words who have pattern like {{world}} only


code:
gl = dict(globals())
gl.update({'f':f})

rawDescription: Exec, closures and scopes

description: Exec, closures and scopes


code:
#!/usr/bin/python

import sys
import csv

infile = sys.argv[1]

Z = [ ]

with open( infile ) as f_in:
    lines = csv.reader( f_in, delimiter=' ', skipinitialspace=True )
    for n, line in enumerate( lines ):
        if n > 6:
            re = float( line[11] )
            im = float( line[12] )

            Z.append( complex( re, im ) )

print( Z )

rawDescription: Python: convert frequency response to impulse response


rawDescription: Element to Element addition of two lists in python


code:
import os
p1+'/'+os.path.basename(p2)

rawDescription: Is there any smart way to combine overlapping paths in python?


rawDescription: Python:reduce list but keep details

description: Python:reduce list but keep details


rawDescription: Python: How exactly can you take a string, split it, reverse it and join it back together again?