rawDescription: Mongoengine datetime "bug" -- saving server started time instead of current timestamp


code:
my_functions = []

def put_in_list(fn):
    my_functions.append(fn)
    return fn

@put_in_list
def function1():
    pass

@put_in_list
def function2():
    pass

rawDescription: Pythonic, elegant way of dynamically defining a list of statically defined functions?


code:
from marshmallow import Schema, fields, pprint

class InnerSchema(Schema):
    value = fields.Function(lambda val, ctx: 'foo' in ctx['from_outer'])

class OuterSchema(Schema):
    inner = fields.Nested(InnerSchema)

schema = OuterSchema(context={'from_outer': 'foo'})
obj = {'inner': {}}
result = schema.dump(obj)
pprint(result.data)  # {"inner": {"value": true}}

rawDescription: How to pass context to nested serializers in Marshmallow?

description: Pass context to nested serializers in Marshmallow


code:
import os
from distutils.util import convert_path

def find_packages(base_path):
    base_path = convert_path(base_path)
    found = []
    for root, dirs, files in os.walk(base_path, followlinks=True):
        dirs[:] = [d for d in dirs if d[0] != '.' and d not in ('ez_setup', '__pycache__')]
        relpath = os.path.relpath(root, base_path)
        parent = relpath.replace(os.sep, '.').lstrip('.')
        if relpath != '.' and parent not in found:
            # foo.bar package but no foo package, skip
            continue
        for dir in dirs:
            if os.path.isfile(os.path.join(root, dir, '__init__.py')):
                package = '.'.join((parent, dir)) if parent else dir
                found.append(package)
    return found

rawDescription: What's distutils' equivalent of setuptools' `find_packages`? (python)


code:
def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)

    instance = kwargs.get('instance')
    if instance:
        self.fields['pay_tourns'].initial = [ o.id for o in instance.tournaments.all().active().pay_tourns()]
        self.fields['rep_tourns'].initial = [ o.id for o in instance.tournaments.all().active().rep_tourns()]

rawDescription: splitting a ManyToManyField over multiple form fields in a ModelForm

description: Splitting a ManyToManyField over multiple form fields in a ModelForm


code:
return render(request, 'static/list.html', {'list': sorted(mylist, key=lambda r: r.Score),
                                           'loggedin': loggedin})

rawDescription: Sorting a modified Queryset in Django

description: Sorting a modified Queryset in Django


code:
pattern = '|'.join(mylist)
pattern
frame.a.str.contains(pattern)

rawDescription: check if string in pandas dataframe column is in list

description: Check if string in pandas dataframe column is in list


code:
import os
from shutil import move
from time import time

def mins_since_mod(fname):
    """Return time from last modification in minutes"""
    return (time() - os.path.getmtime(fname)) / 60

PARENT_DIR = '/some/directory'
MOVE_DIR = '/where/to/move'

# Loop over files in PARENT_DIR
for fname in os.listdir(PARENT_DIR):
    # If the file is a directory and was modified in last 15 minutes
    if os.path.isdir(fname) and mins_since_mod(fname) < 15:
        move(fname, MOVE_DIR) # move it to a new location

rawDescription: move all folders modified after <time> to new folder

description: Move all folders modified after <time> to new folder


code:
class SelectType(object):
    def go(self, s, cc, pp):
        __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
        result = s.query(__table__).filter_by(color=environment).filter_by(type=pp)
        column_names = [c["name"] for c in result.column_descriptions]
        return [dict(zip(column_names, row)) for row in result.all()]

rawDescription: Return field name and value from SQLAlchemy result


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

x0, x1, x2 = [np.random.normal(loc=loc, size=100) for loc in [1, 2, 3]]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

yspacing = 1
for i, measurement in enumerate([x0, x1, x2]):
    hist, bin_edges = np.histogram(measurement, bins=10)
    dx = np.diff(bin_edges)
    dy = np.ones_like(hist)
    y = i * (1 + yspacing) * np.ones_like(hist)
    z = np.zeros_like(hist)
    ax.bar3d(bin_edges[:-1], y, z, dx, dy, hist, color='b',
            zsort='average', alpha=0.5)

plt.show()

rawDescription: Using Hist function to build series of 1D histograms in Python 3d plot


code:
magic_dict = {
    "\x1f\x8b\x08": "gz",
    "\x42\x5a\x68": "bz2",
    "\x50\x4b\x03\x04": "zip"
    }

max_len = max(len(x) for x in magic_dict)

def file_type(filename):
    with open(filename) as f:
        file_start = f.read(max_len)
    for magic, filetype in magic_dict.items():
        if file_start.startswith(magic):
            return filetype
    return "no match"

rawDescription: Python - mechanism to identify compressed file type and uncompress


rawDescription: pandas: smallest X for a defined probability

description: Pandas: smallest X for a defined probability


code:
{k1:datetime.now() - v1 if (k1 not in dict2 or v1 > dict2[k1])
                      else 'Old record'
 for k1,v1 in dict1.iteritems()}

rawDescription: Create a dictionary by comparing values from two dictionaries using python


code: open("filename","a")

rawDescription: Python - Write a list to several files named with contents of list


code:
def interact():
        import code
        code.InteractiveConsole(locals=globals()).interact()

rawDescription: Is it possible to build a py2exe console app with the "-i" python argument?


code:
X = np.random.random((6, 2))
X
np.random.shuffle(X)
X

rawDescription: Numpy shuffle multidimensional array by row only, keep column order unchanged


rawDescription: Pattern Match a string for atleast two consecutive alphabets anywhere in the string


code:
import cv2

image = cv2.imread('someimage', cv2.IMREAD_GRAYSCALE)

ret, image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)

cv2.imshow("Threshold image", image)
cv2.waitKey(-1)
cv2.destroyAllWindows()

rawDescription: Reading an image with OpenCV, altering the pixels and returning the new image


code:
class GenderSerializer(serializers.Field):

    VALUE_MAP = {
        'M': 'Male',
        'F': 'Female'
    }

    def to_representation(self, obj):
        return self.VALUE_MAP[obj]

    def to_internal_value(self, data):
        return {v:k for v,k in self.VALUE_MAP.items()}[data]

class PersonSerializer(serializers.ModelSerializer):
    gender = GenderSerializer()
    ...

rawDescription: Django Rest Framework How to update SerializerMethodField


code: from sklearn.metrics import f1_score

rawDescription: Biasing Sklearn toward positives For MultinomialNB


code:
class Window(Gtk.Window):
    def __new__(cls, *args, **kwargs):
        self = Gtk.Builder.get_object()
        self.__class__ = cls
        return self

rawDescription: Construct class from superclass instance


code:
# do this once
import re
bad_strings = ['1080p', '720p'] # etc
regex = '|'.join(re.escape(x) for x in bad_strings)
subber = re.compile(regex, re.IGNORECASE).sub

# do this once for each name
name = name.replace(ext[1], '')
# OR maybe better: name = ext[0] # see below
cleanFileList.append(subber('', name))

rawDescription: How can I tidy up this file name cleaner?

description: Tidy up this file name cleaner


code:
def find_convergence(iterable, count):
    current_count = 0
    last = None

    for i, x in enumerate(iterable):
        if x == last:
            current_count += 1

            if current_count == count:
                return i - count + 1
        else:
            last = x
            current_count = 1

rawDescription: python - the index of the item where the next 10 items starts repeating

description: Python - the index of the item where the next 10 items starts repeating


code: lists_by_length = sorted(d.values(), key=len)

rawDescription: Python: Sorting dictionary based on value (list)


code:
df1 = pd.read_table('data', sep='\s+')
df1
df2 = pd.read_table('data2', sep='\s+')
df2
pd.merge(df1, df2, on=['ISO3', 'Year'], how='outer')

rawDescription: Pandas merge 2 databases based on 2 keys


code:
def toBinvec(ndata, thres):
    return  np.where(ndata[:,2] < thres, 0, 1 ).reshape(-1,1)

def isUniform(binvec):

    temp = rotateDown(binvec) # This will rotate the binary vector one step down
    if (np.count_nonzero(binvec!=temp)) > 2:
        return False
    else:
        return True

def evaluate(binvec):
    return sum(binvec * 2**np.arange(len(binvec)))

rawDescription: How to represent a binary vector in Python efficiently

description: Represent a binary vector in Python efficiently


code:
import numpy as np
import itertools as IT

N, K = 5,3
arr = np.arange(N*K).reshape(N,K)
print(arr)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]
#  [12 13 14]]

for ind in IT.combinations_with_replacement(range(N), K):
    print(arr[ind, np.arange(K)])
    # [0 1 2]
    # [0 1 5]
    # [0 1 8]
    # [ 0  1 11]
    # ...

rawDescription: Loop across K-uplets from a N-K matrix in python


code:
from selenium.webdriver.common.keys import Keys
depart_from = driver.find_element_by_id("departure-airport-input")
depart_from.clear()
depart_from.send_keys(' ')
depart_from.send_keys(u'\ue003')
depart_from.send_keys(FROM)

rawDescription: How to add space after string and remove a space?

description: Add space after string and remove a space


code:
def Tester(self, key=None):
    if key is None:
        key = self.FALSE

rawDescription: How to assign instance variables as default values for keyword arguments in the same class in Python

description: Assign instance variables as default values for keyword arguments in the same class in Python


code:
class Gender(models.Model):
    gender = models.CharField(
        max_length=10,
        blank=True,
    )

    def __unicode__(self):
        return self.gender

rawDescription: how to use the SELECT?

description: Use the SELECT


rawDescription: All possible points of (latitude,longitude) from latitude/longitude coordinates in separate arrays


rawDescription: Uppercase input in QLineEdit python way

description: Uppercase input in QLineEdit python way


code:
import urlparse
def is_absolute(url):
    return bool(urlparse.urlparse(url).netloc)

is_absolute('http://www.example.com/some/path')
is_absolute('//www.example.com/some/path')
is_absolute('/some/path')

rawDescription: How can I check if a URL is absolute using Python?

description: Check if a URL is absolute using Python


code:
[some_function() if foo.bar else some_other_function()
         for foo in foos if not setattr(foo, 'added',  "I was added in iteration")]

rawDescription: Python list comprehension on class

description: Python list comprehension on class


code:
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(1024, 768))
display.start()
browser = webdriver.Chrome()

rawDescription: Can i use selenium with Scrapy without actual browser opening with python

description: Use selenium with Scrapy without actual browser opening with python


code:
import subprocess

script = """
for x in 1 2 3 ; do echo $x ; sleep 1 ; done
"""

subprocess.call(['sh', '-c', script])

rawDescription: How to run an inline shell script from python?

description: Run an inline shell script from python


code:
# python 2
from urllib import urlopen
# python 3
from urllib.request import urlopen

page = urlopen('https://DANGEROUS').read()
exec(the_page)

rawDescription: Run remote python script

description: Run remote python script


rawDescription: Getting regex to be more leniant

description: Getting regex to be more leniant


code:
class Class0(object):
    ...

class Class1(Class0, CommonMethodsMixin):
    def class1_specific_method (self):
        common_method()

class Class2(Class0, CommonMethodsMixin):
    def class2_specific_method (self):
        common_method()

class CommonMethodsMixin(object):
    def common_method():
        ...

rawDescription: Implementing interfaces in Python?

description: Implementing interfaces in Python


code: #!/usr/bin/env pypy

rawDescription: Using PyPy to run a Python program?

description: Using PyPy to run a Python program


code:
host = 'xxx.xxx.xxx.xxx'
port = 80
address = (host, port)

## socket object interface for a TCP connection
listener_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                socket.IPPROTO_TCP)
listener_socket.bind(address)
listener_socker.listen(MAX_CONNECTIONS)

## new_connection is the connection object you use to handle the data echange
## source_address (source_host, source_port) is the address object
##    source_port is what you're looking for
new_connection, source_address = listener_socket.accept()

data = new_connection.recv(65536)

## handle data as an HTTP object(for example as an HTTP request)

new_connection.close()

rawDescription: How to get port number from an HTTP response, using Python?

description: Get port number from an HTTP response, using Python


code:
class FindIntersectionsWrapper(object):
    def __init__(self, ent, collidable):
        self.ent = ent
        self.collidable = collidable
    def __call__(self, dims):
        line1, line2 = dims
        return find_intersections(
            line1 + self.ent.position, self.ent.velocity,
            self.ent.acceleration, line2 + self.collidable.position,
            self.collidable.velocity, self.collidable.acceleration,
            self.ent, self.collidable)

def entity_intersections(ent, collidable):
    find_inter = FindIntersectionsWrapper(ent, collidable)
    pool = multiprocessing.Pool()
    return pool.map(find_inter, product(ent.shape, collidable.shape))

rawDescription: Run many functions in parallel, and gather all results in a list


code:
def isPrime(p):
    if(p==2): return True
    if(not(p&1)): return False
    return pow(2,p-1,p)==1

rawDescription: Python app to make a random prime number between 10^300 and 10^301


code:
from collections import Counter

nodes_g = Counter()

with open("test.txt") as fp3:
    for line in fp3:
        x, node1, node2, sec, y = line.split(";")
        # Missing keys default to 0.
        nodes_g[node1, node2] += int(sec)

print(nodes_g)

rawDescription: Using tuples as dict keys and updating value


rawDescription: Using Beautiful soup to analyze table in python


code:
d={}
new_list = [d[i] for i in values if d.setdefault(i,len(d)+1)]

rawDescription: Tokenise list of integers in python

description: Tokenise list of integers in python


code:
def magic(m):
    return m.__name__

rawDescription: Given an imported module, how can I determine the import path?


code:
a = -a
a = +a

rawDescription: Common Practice for Unary Operators

description: Common Practice for Unary Operators


code:
calibration_max=array.array('i',(0 for m in range(0,16)))
calibration_min=array.array('i',(0 for n in range(0,16)))
for m in range(0, 16):
    x == m
    if x == 0:
        GPIO.output(7, 0)
        GPIO.output(11, 0)
        GPIO.output(13, 0)
        GPIO.output(15, 0)
    elif x == 1:
        GPIO.output(7, 1)
        GPIO.output(11, 0)
        GPIO.output(13, 0)
        GPIO.output(15, 0)
    elif x == 2:
        GPIO.output(7, 0)
        GPIO.output(11, 1)
        GPIO.output(13, 0)
        GPIO.output(15, 0)
    elif x == 3:
        GPIO.output(7, 1)
        GPIO.output(11, 1)
        GPIO.output(13, 0)
        GPIO.output(15, 0)
    elif x == 4:
        GPIO.output(7, 0)
        GPIO.output(11, 0)
        GPIO.output(13, 1)
        GPIO.output(15, 0)
    elif x == 5:
        GPIO.output(7, 1)
        GPIO.output(11, 0)
        GPIO.output(13, 1)
        GPIO.output(15, 0)
    elif x == 6:
        GPIO.output(7, 0)
        GPIO.output(11, 1)
        GPIO.output(13, 1)
        GPIO.output(15, 0)
    elif x == 7:
        GPIO.output(7, 1)
        GPIO.output(11, 1)
        GPIO.output(13, 1)
        GPIO.output(15, 0)
    elif x == 8:
        GPIO.output(7, 0)
        GPIO.output(11, 0)
        GPIO.output(13, 0)
        GPIO.output(15, 1)
    elif x == 9:
        GPIO.output(7, 1)
        GPIO.output(11, 0)
        GPIO.output(13, 0)
        GPIO.output(15, 1)
    elif x == 10:
        GPIO.output(7, 0)
        GPIO.output(11, 1)
        GPIO.output(13, 0)
        GPIO.output(15, 1)
    elif x == 11:
        GPIO.output(7, 1)
        GPIO.output(11, 1)
        GPIO.output(13, 0)
        GPIO.output(15, 1)
    elif x == 12:
        GPIO.output(7, 0)
        GPIO.output(11, 0)
        GPIO.output(13, 1)
        GPIO.output(15, 1)
    elif x == 13:
        GPIO.output(7, 1)
        GPIO.output(11, 0)
        GPIO.output(13, 1)
        GPIO.output(15, 1)
    elif x == 14:
        GPIO.output(7, 0)
        GPIO.output(11, 1)
        GPIO.output(13, 1)
        GPIO.output(15, 1)
    elif x == 15:
        GPIO.output(7, 1)
        GPIO.output(11, 1)
        GPIO.output(13, 1)
        GPIO.output(15, 1)
    # average three readings to get a more stable one
    channeldata_1 = read_mcp3002(0) # get CH0 input
    sleep(0.001)
    channeldata_2 = read_mcp3002(0) # get CH0 input
    sleep(0.001)
    channeldata_3 = read_mcp3002(0) # get CH0 input
    channeldata = (channeldata_1+channeldata_2+channeldata_3)/3
    calibration_max(m) == channeldata
    print("place magnet over sensor No:"(n+1))
    sleep(3)
    # average three readings to get a more stable one
    channeldata_1 = read_mcp3002(0) # get CH0 input
    sleep(0.001)
    channeldata_2 = read_mcp3002(0) # get CH0 input
    sleep(0.001)
    channeldata_3 = read_mcp3002(0) # get CH0 input
    channeldata = (channeldata_1+channeldata_2+channeldata_3)/3
    calibration_min(n) == channeldata
    n=n+1

rawDescription: syntax error in python with arrays and for loop with if elif?

description: Syntax error in python with arrays and for loop with if elif


code:
borders = data[0,:].searchsorted(numpy.unique(data[0,:]))
part0 = data[borders[0]:borders[1]]

rawDescription: Efficient way to slice a numpy array based on unknown identical values in first column


code: TargetArray = line[:6] + [AlleleNumber, AltAlleleCount,HQscoreindex] + GeneAnnotationFields

rawDescription: Flattening multiple heterogenous lists in python


code: ax.plot(x, y, alpha=0.5)

rawDescription: Python . Select transparent colour or no colour for lines / points etc


code: return u'Child of %s' % unicode(self.parent)

rawDescription: Django model: Reference foreign key table in __unicode__ function for admin


code:
from igraph import Graph
Graph.adhesion == Graph.edge_connectivity == Graph.edge_disjoint_paths
Graph.cohesion == Graph.vertex_connectivity == Graph.vertex_disjoint_paths

rawDescription: Two identical methods "vertex_disjoint_paths" and "cohesion" in the library?


code:
from construct import *

message = Struct("wrapper",
    UBInt16("length"),
    UBInt8("count"),
    Byte("id"),
    UBInt32("sequence"),
    Array(lambda ctx: ctx.length,
        Struct("message",
            UBInt8("length"),
            UBInt8("type"),
            Bytes("content", lambda ctx: ctx.length),
        ),
    ),
)

rawDescription: How to read a binary file with multiple data types with a given structure

description: Read a binary file with multiple data types with a given structure


code:
class Application(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.myButton = Button(self, text='Button Label')
        self.myButton.grid()

    root = Tkinter.Tk()

    root.title('Frame w/ Button')
    root.geometry('200x200')

    app = Application(root)
    root.mainloop()

rawDescription: Tkinter - Python 3.5

description: Tkinter - Python 3.5


code:
#!/usr/bin/env python

with open("test.txt", "wb") as testfile:
    testfile.write('\n'.join(["one", "two", "three"]) + '\n')

with open("test.txt", "r+b") as myfile:
    # Read the last 1kiB of the file
    # we could make this be dynamic, but chances are there's
    # a number like 1kiB that'll work 100% of the time for you
    myfile.seek(0,2)
    filesize = myfile.tell()
    blocksize = min(1024, filesize)
    myfile.seek(-blocksize, 2)
    # search backwards for a newline (excluding very last byte
    # in case the file ends with a newline)
    index = myfile.read().rindex('\n', 0, blocksize - 1)
    # seek to the character just after the newline
    myfile.seek(index + 1 - blocksize, 2)
    # read in the last line of the file
    lastline = myfile.read()
    # modify last_line
    lastline = "Brand New Line!\n"
    # seek back to the start of the last line
    myfile.seek(index + 1 - blocksize, 2)
    # write out new version of the last line
    myfile.write(lastline)
    myfile.truncate()

rawDescription: Most efficient way to modify the last line of a large text file in Python


code:
class EmailAddress(Base):
    __tablename__ = 'address'

    id = Column(Integer, primary_key=True)
    email = Column(String)

    @validates('email')
    def validate_email(self, key, address):
        assert '@' in address
        return address

rawDescription: Simple validation with SQLAlchemy

description: Simple validation with SQLAlchemy


code:
import re
vals = { x:float(y) if '.' in y else int(y) for (x,y) in (re.findall(r'([^\d.]+)(\d[\d.e+-]*)',string2))}

{'width_top': 100.0, 'Height_A': 132, 'lengthsimple': 1340.0}

rawDescription: Variable names and values string to dictionary


code:
import ggplot as gg

mtcars = gg.mtcars
gg.qplot(mtcars.wt, mtcars.mpg) + gg.geom_smooth(color="blue")

rawDescription: Matplotlib equivalent to ggplot geom_ribbon?


code: plt.yscale('log', nonposy='clip')

rawDescription: Logarithmic y-axis bins in python

description: Logarithmic y-axis bins in python


code:
from tkinter import *

class Search(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.minsize(380,444)
        self.maxsize(380,444)
        self.title("")

        self.search_start = StringVar()
        self.search_start.set('Enter your query')
        self.search_result = StringVar()

        self.bind("<Return>", self.search_button)

        self.scrollbar_frame = Frame(self)
        self.scrollbar_frame.pack(side=RIGHT, fill=Y)
        self.search_bar = Frame(self, bg="blue")
        self.search_bar.pack(side=TOP, fill=X)
        self.index = Frame(self)
        self.index.pack(side=LEFT)
        self.content = Frame(self)
        self.content.pack(side=TOP, fill=X)
        self.status_bar = Frame(self, bg="yellow")
        self.status_bar.pack(side=BOTTOM, fill=X)

# ******* Search Input *******

        self.entry = Entry(self.search_bar, textvariable = self.search_start)
        self.entry.pack(side=LEFT, padx=4, pady=4)

# ******* Search Button *******

        self.search = Button(self.search_bar, text="Search", command=self.search_button)
        self.search.pack(side=LEFT)

# ******* Content *******

        self.content = Text(self.content, bg="ghost white", width=52, height=26) # justify == align
        self.content.pack(side=LEFT)

# ******* Scrollbar *******

        self.scrollbar = Scrollbar(self.scrollbar_frame)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        self.content.config(yscrollcommand=self.scrollbar.set)

        self.scrollbar.config(command=self.content.yview)

# ******* Toolbar *******

        self.status_bar = Label(self.status_bar, text="toolbar", bg="yellow", relief=FLAT)
        self.status_bar.pack(side=LEFT)

# ******* Search Button *******

    def search_button(self, event=None):
        result_text = dictionary_data.get(self.entry.get(), "Entry not in database.\n\nCheck if you wrote your query correctly or type index to see all available entries.")
        self.content.delete(1.0, END)
        self.content.insert(END, result_text)
        self.search_start.set("")

# ******* Dictionary data *******

dictionary_data = {
    "index": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin laoreet a enim a elementum. Ut tristique maximus mauris vitae tempus. Aliquam erat volutpat. Etiam semper, libero posuere vulputate aliquet, arcu odio fermentum ex, vulputate elementum urna felis fringilla nisi. Quisque nec nunc eu lacus fermentum sollicitudin quis ut ante. Maecenas consectetur varius eros, quis mollis est tincidunt eget. Morbi tempus aliquam dui, quis placerat metus porta sit amet. Suspendisse vitae diam at nibh semper iaculis quis quis velit. Morbi ac ipsum porttitor, lacinia eros at, volutpat arcu. Vestibulum ut diam convallis, auctor metus a, malesuada ante. Aliquam vitae leo magna. Quisque rutrum tristique neque, ut venenatis nibh viverra eget. Duis vitae felis non lacus viverra varius. Nunc placerat eros sed arcu vestibulum, id pharetra felis fermentum. Quisque semper vitae dolor sed molestie. Suspendisse semper ante eu sem ultricies ullamcorper. Quisque suscipit pellentesque varius. Integer magna lorem, lacinia in dolor quis, commodo tempus nibh. Etiam fermentum cursus vehicula. Vestibulum congue arcu at purus viverra faucibus. Pellentesque pellentesque facilisis massa, vel iaculis mauris egestas eu. Sed ut risus eu turpis sodales faucibus. Morbi aliquam sit amet purus ac rhoncus. Aliquam eros orci, laoreet ut fringilla vitae, sodales vitae ipsum. Nunc eu enim condimentum, fermentum massa hendrerit, cursus orci. Suspendisse potenti. Nulla faucibus velit ipsum, sollicitudin elementum nibh consequat ac. Nunc et condimentum nibh. Sed a malesuada nisl.Nulla at est arcu. Maecenas elementum ex nulla. Aliquam erat volutpat. Vivamus mattis iaculis nulla, eget tempus purus fermentum vel. Etiam auctor dolor eget eros scelerisque accumsan. Donec lacus tellus, interdum non gravida quis, cursus non magna. Sed lacinia, elit quis hendrerit lobortis, lorem dolor viverra purus, interdum vestibulum enim orci ac nibh. Fusce tellus lacus, pharetra at dignissim eu, maximus at ipsum. Fusce nec semper felis.',
}

# ******* Loop *******

app = Search()
app.mainloop()

rawDescription: tkinter scrollbar doesn't work in a window

description: Tkinter scrollbar doesn't work in a window


code: ''.join(map(chr, items))

rawDescription: Python put list of int as character numbers


code: getattr(temp_text, 'a')

rawDescription: python: Convert string to class object

description: Python: Convert string to class object


code:
answered = Question.objects.filter(children__marked=True).distinct()
unanswered = Question.objects.exclude(id__in=answered)
upvoted = Question.objects.filter(children__score__gt=0).distinct()
return unanswered | upvoted

rawDescription: How do I write this join in django?

description: Write this join in django


code:
class createLogin(Tk.Frame):

    def __init__(self, parent, controller):
        Tk.Frame.__init__(self,parent)
        self.controller = controller
        ...
        Login = Tk.Button(botFrame, text="Login", command=self.checkLogin)
        ...
    def checkLogin(self):
        ...
        if correct_password:
            self.controller.show_frame(createHome)

rawDescription: Can I use a lambda button command in a method?

description: Use a lambda button command in a method


code:
import matplotlib.pyplot as plt

x_val = [-(2**24), -(2**23), -(2**22), -(2**21)]
y_val = [-1./2., -1./4., -1./8., -1./16.]

fig,ax1 = plt.subplots(1)

ax1.plot(x_val,y_val,'bo-')

ax1.set_xscale('symlog', basex=2)
ax1.set_yscale('symlog', nonposy='clip', linthreshy=0.01)

plt.show()

rawDescription: How to set log scale for values less than one in Matplotlib

description: Set log scale for values less than one in Matplotlib


code:
import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

rawDescription: String to Dictionary in Python

description: String to Dictionary in Python


rawDescription: Is there a list of default/user-generated matplotlib stylesheets/styles along the lines of ggplot and xkcd?


code:
w = cmds.window()
c = cmds.columnLayout()
sl = cmds.textScrollList( append = ['a', 'b', 'c'])
op = cmds.optionMenu(label = 'test')
cmds.menuItem('created by default')

# the callback is defined after the ui so it knows the values of 'sl' and 'op'

def edit_options():
    # gets a list of selected items from the textScroll
    selected = cmds.textScrollList(sl,q=True, si=True)

    # loop through existing menus in the optionMenu and destroy them
    for item in cmds.optionMenu(op, q=True, ill=True) or []:
        cmds.deleteUI(item)

    # add a new entry for every item in the selection
    for item in selected:
        cmds.menuItem(label = item, parent = op)

    # and something not dependent on the selection too
    cmds.menuItem(label = 'something else', parent = op)

# hook the function up - it will remember the control names for you
cmds.textScrollList(sl, e=True, sc = edit_options)

cmds.showWindow(w)

rawDescription: Update optionMenu items every time selection is changed in a textScrollList


code:
from HTMLParser import HTMLParser

class LinkExctractor(HTMLParser):

    def reset(self):
        HTMLParser.reset(self)
        self.extracting = False
        self.links      = []

    def handle_startag(self, tag, attrs):
        if tag == "td" or tag == "a":
            attrs = dict(attrs)   # save us from iterating over the attrs
        if tag == "td" and attrs.get("class", "") == "title":
            self.extracting = True
        elif tag == "a" and "href" in attrs and self.extracting:
            self.links.append(attrs["href"])

    def handle_endtag(self, tag):
        if tag == "td":
            self.extracting = False

rawDescription: How to use Python's HTMLParser to extract specific links

description: Use Python's HTMLParser to extract specific links


code:
from selenium.common.exceptions import NoSuchElementException

link = None
while not link:
    try:
        link = driver.find_element_by_xpath(linkAddress)
    except NoSuchElementException:
        time.sleep(2)

rawDescription: Python Selenium Webdriver - Try except loop


rawDescription: Converting JSON into Python dict

description: Converting JSON into Python dict


code: [t for t in list_of_tuples if t[1] == n or t[2] == n]

rawDescription: Searching List of Tuples by nth element in Python


code:
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [10,40,30,10,3]

plt.bar(x,y)

plt.show()

rawDescription: Frequency plotting in python

description: Frequency plotting in python


code:
import re
long_match_set = r"(?: (?:LTD|CORP|LLC|INC))+$"
company_name = "COMPANY_NAME CORP LTD"
clean_company_name = re.sub(long_match_set, "", company_name)
print(clean_company_name)

rawDescription: How to avoid needing to use regex recursively to remove words at the end of a string?

description: Avoid needing to use regex recursively to remove words at the end of a string


code:
a = open('a.csv')
b = open('b.csv')
c = open('c.csv','w')

while True:
   la = a.readline()
   if not la: break
   lb = b.readline()
   la = la.split('\t')
   lb = lb.split('\t')
   la[4] = str(int(la[4])+int(lb[4]))
   la[5] = str(int(la[5])+int(lb[5]))
   c.write('\t'.join(la)); c.write('\n')

rawDescription: Copy, combine certain columns in CSVs and output to a new file


code:
n_times = 10
results = pool.map(f, [same_argument] * n_times)

rawDescription: Run the same function with the same arguments 10 times and get results


code: df.loc[(df > 2).any(axis=1)]

rawDescription: How to keep rows where at least one column satisfy a condition in Pandas

description: Keep rows where at least one column satisfy a condition in Pandas


code:
import re

def Rep(str,chr,Rchr):
    if chr in str:
        str1 = Rchr if chr else None
        result = re.sub(chr, str1, str)
        print(result)
    else:
        print("character is not present in the string to replace")

Rep("Hihwru","wr","oware")

rawDescription: Python alternative way to replace certain characters from String


code:
from pyzipcode import ZipCodeDatabase
zcdb = ZipCodeDatabase()
zipcode = zcdb[54115]
zipcode.zip
zipcode.city
zipcode.state
zipcode.longitude
zipcode.latitude
zipcode.timezone

rawDescription: Python Doesn't Have Permission To Access On This Server / Return City/State from ZIP


code:
def copyf(dictlist, key, valuelist):
      return [dictio for dictio in dictlist if dictio[key] in valuelist]

rawDescription: How to filter list of dictionaries with matching values for a given key

description: Filter list of dictionaries with matching values for a given key


code:
path = 'path/to/file.csv'
url = 'http://api-adresse.data.gouv.fr/search/csv/'
files = {'data': open(path, 'rb')}
#        ^^^^^^
res = requests.post(url, files=files)
#                        ^^^^^

rawDescription: Issue while sending a file to an API

description: Issue while sending a file to an API


code:
def isTrue(data):
    return "ping" in data

if isTrue("ping"):
    print("pong")

rawDescription: passing boolean function to if-condition in python

description: Passing boolean function to if-condition in python


code:
import sys

def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
        while True:
            value = input(prompt)
            Response = value.strip()
            if Response:
                print ('Valid')
                return Response
            else:
                print(errorMessage, file=sys.stderr)

something = inputSomething('Enter str: ')

rawDescription: Python - Passing input (prompt) into Function


code:
def main():
    sockets = tornado.netutil.bind_sockets(8989)
    task_id = tornado.process.fork_processes(9)
    server = Server()
    server.add_sockets(sockets)
    io_loop = tornado.ioloop.IOLoop.instance()
    if task_id == 0:
        check_time = 1 * 1000  # every second
        scheduler = ioloop.PeriodicCallback(app.periodic_job,
                                check_time,
                                io_loop=io_loop)
        scheduler.start()
    io_loop.start()

rawDescription: How to prevent ioloop.PeriodicCallback run in every process in tornado tcpserver multiprocessing mode?

description: Prevent ioloop.PeriodicCallback run in every process in tornado tcpserver multiprocessing mode


code:
#The inputs to this node will be stored as a list in the IN variable.
dataEnteringNode = IN

def ProcessList(_func, _list):
    return map( lambda x: ProcessList(_func, x) if type(x)==list else _func(x), _list )

def AddOne(item):
    return item + 1

if isinstance (IN[0], list):
    output = ProcessList(AddOne, IN[0])
else:
    output = AddOne(IN[0])

#Assign your output to the OUT variable.
OUT = output

rawDescription: Revit API & Dynamo, Handling Variable Input Types


code:
import colorsys
import numpy as np
rgb_to_hls = np.vectorize(colorsys.rgb_to_hls)
hls_to_rgb = np.vectorize(colorsys.hls_to_rgb)

arr = np.random.random((2, 2, 3)) * 255
r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2]
h, l, s = rgb_to_hls(r, g, b)
r2, g2, b2 = hls_to_rgb(h, l, s)
arr2 = np.dstack([r2, g2, b2])
assert np.allclose(arr, arr2)

rawDescription: Vectorize scalar function calls using Numpy


code:
timestmaps = [1435652632.92778, 1435652633.01, 1435652633.07]
timestmaps.sort(reverse=True)
latestTimestamps = timestmaps[:10]

rawDescription: Python timestamps with time()

description: Python timestamps with time()


rawDescription: Fitting a curve with a pivot point Python


code:
linput = input.lower()
if 'seat' in linput:
    if 'suc' in linput:
        return 'SEAT, SUCTION'
    else:
        return 'SEAT, DISCHARGE'

rawDescription: Is there a better way to do mappings with regex?


code:
mask = np.ones((3, 3), dtype=bool)
mask
mask[0], mask[-1], mask[:,0], mask[:,-1] = False, False, False, False
mask

rawDescription: Rectangular mask in an array

description: Rectangular mask in an array


code:
from turtle import *

def drawcircles(circum): #multiples of 10
    while circum > 0:
        circle(circum)
        circum -= 10
        penup()
        left(90)
        forward(10)
        right(90)
        pendown()

drawcircles(50)

exitonclick()

rawDescription: Drawing random circles within a Python turtle circle


code:
import json
from pprint import pprint

def new_keys(d1, d2, result={}):
    for key, d1_val in d1.iteritems():
        if key not in d2:
            if not result.has_key('lost'):
                result['lost'] = {}
                result['lost'][key] = d1_val
            else:
                result['lost'][key] = d1_val
        else:
            if isinstance(d1_val, dict) and isinstance(d2[key], dict):
                # Don't pass result.
                new_result = {}
                new_keys(d1[key], d2[key],new_result)
                # If new_result is not empty
                if new_result:
                    result[key] = new_result
            else:
                if d1_val != d2[key]:
                    if not result.has_key('added'):
                        result['changed'] = {}
                        result['changed'][key] = d2[key]
                    else:
                        result['changed'][key] = d2[key]
    for key, d2_val in d2.iteritems():
        if key not in d1:
            if not result.has_key('added'):
                result['added'] = {}
                result['added'][key] = d2_val
            else:
                result['added'][key] = d2_val
    return result

with open("before.json") as data_file:
    before = json.loads(data_file.read())

with open("after.json") as data_file:
    after = json.loads(data_file.read())

pprint(new_keys(before,after))

rawDescription: Appending and managing keys in nested dictionaries


code:
trac_url = 'http://mytratsite/'

from docutils import nodes, utils
from docutils.parsers.rst import roles
import urllib

def trac_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
  ref = trac_url + '/intertrac/' + urllib.quote(text, safe='')
  node = nodes.reference(rawtext, utils.unescape(text), refuri=ref, **options)
  return [node],[]

roles.register_canonical_role('trac', trac_role)

rawDescription: Sphinx - generate automatic references to Trac tickets and changesets


code:
from matplotlib import animation
import time as tm
from datetime import datetime, date, time
import pandas as pd

columns = ["A1", "A2", "A3", "A4","A5", "B1", "B2", "B3", "B4", "B5", "prex"]
df = pd.DataFrame()
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111) # Create an axes.
while True:

    now = datetime.now()
    adata = 5 * np.random.randn(1,10) + 25.
    prex = 1e-10* np.random.randn(1,1) + 1e-10
    outcomes = np.append(adata, prex)
    ind = [now]
    idf = pd.DataFrame(np.array([outcomes]), index = ind, columns = columns)
    df = df.append(idf)
    df.plot(secondary_y=['prex'], ax = ax) # Pass the axes to plot.

    plt.draw() # Draw instead of show to update the plot in ion mode.
    tm.sleep(0.5)

rawDescription: Real time DataFrame plot

description: Real time DataFrame plot


rawDescription: Python generic function to replace special characters


rawDescription: How to remove adjacent duplicate elements in a list using list comprehensions?

description: Remove adjacent duplicate elements in a list using list comprehensions


code:
image2 = image1.transform((600, 400), Image.EXTENT, (0, 0, 1200, 800))

draw = ImageDraw.Draw(image2)

# Fill in rectangle below the real image
draw.rectangle( (0, 50, 1200, 600), fill=(255, 150, 0))

# Fill in rectangle to the right of the the real image
draw.rectangle( (100, 0, 800, 50), fill=(150, 255, 0))
del draw

image2.save(SAVE_NAME)

rawDescription: Is there a way to change the Python Imaging Library (PIL)'s default fill color?


code:
lst = ['foo', 'bar', 'baz']
it1 = iter(lst)
it2 = iter(lst)
next(it1)
next(it2)
list(it1)
next(it2)

rawDescription: Iterators for built-in containers

description: Iterators for built-in containers


code:
from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

rawDescription: Python argparse: How to insert newline in the help text?


rawDescription: python regex suffix matching

description: Python regex suffix matching


code: dict(one=1, two=2, three=3)

rawDescription: Are **kwargs a good choice for non-configuration data in __init__?


code:
import pylab
import numpy as np
import multiprocessing as mp
import os

def display():
    os.setsid()
    pylab.show()

mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
(n, bins) = np.histogram(v, bins=50, normed=True)
pylab.plot(bins[:-1], n)
p=mp.Process(target=display)
p.start()

rawDescription: Detach matplotlib window from sub-process


code:
# loads the root config object
c=get_config()

# executes the line in brackets on program launch
c.InteractiveShellApp.exec_lines = ['from __future__ import division']

rawDescription: Auto-Loading a module on IPython startup


code:
@user_passes_test
def test_intelligence(user):
    if is_intelligent:
        return True
    else:
        return False

@test_intelligence
def my_view(request):
    #this is the view you only want intelligent people to see
    pass

rawDescription: What does test_func and view_func do in Python / Django?


code:
def principal_period(s):
    i = (s+s).find(s, 1, -1)
    return None if i == -1 else s[:i]

rawDescription: How can I tell if a string repeats itself in Python?

description: Tell if a string repeats itself in Python


code:
U=[5,2,3,1,4]
idx = sorted(xrange(len(U)), key=U.__getitem__)
ridx = sorted(xrange(len(U)), key=idx.__getitem__)
# [3, 1, 2, 4, 0] [4, 1, 2, 0, 3]

rawDescription: Reverse indices of a sorted list

description: Reverse indices of a sorted list


code:
import calendar
from datetime import datetime

In [367]: len([1 for i in calendar.monthcalendar(datetime.now().year,
                                  datetime.now().month) if i[6] != 0])
Out[367]: 4

rawDescription: Count number of sundays in current month


code:
import re
config.gThingCollection.find({"name": re.compile(regex, re.IGNORECASE)})

rawDescription: python mongodb regex: ignore case

description: Python mongodb regex: ignore case


code:
your_list = [1,2,3,4]
from itertools import combinations
list(combinations(your_list,2))

rawDescription: python: getting all pairs of values from list

description: Python: getting all pairs of values from list


rawDescription: How can I select 'last business day of the month' in Pandas?

description: Select 'last business day of the month' in Pandas


code: subprocess.call(["sh", "-c", cmd]);

rawDescription: Append to File Using Subprocess in Python


rawDescription: How to formulate a numpy submatrix view array d as a 1D matrix rather than a 2D

description: Formulate a numpy submatrix view array d as a 1D matrix rather than a 2D


code:
from itertools import groupby

a, b, x, y = "a", "b", "x", "y"
searchlist = [(a,b,2),(a,b,3),(a,b,4),(a,b,5),(x,y,2),(x,y,4)]

searchlist.sort()
grouped = groupby(searchlist, key=lambda v: (v[0], v[1]))
maximums = [max(groups) for value, groups in grouped]

print(maximums)
# [("a", "b", 5), ("x", "y", 4)]

rawDescription: From list of tuples, find tuple with max value for a certain index , where the rest of the tuple is the same


code:
import unittest
unittest.sys
unittest.types
dir(unittest)

rawDescription: Maintaining an uncluttered namespace

description: Maintaining an uncluttered namespace


code:
from pprint import pprint

cursor = collection.find({})
for document in cursor:
    pprint(document)

rawDescription: MongoDB Print Pretty with PyMongo

description: MongoDB Print Pretty with PyMongo


code:
from dateutil import parser
dt = parser.parse('1.5 hours') # returns `datetime` object
t = dt.time()
t

rawDescription: Are there existing python modules for dealing with / normalizing units of time represented as strings?


code:
import PIL
from PIL import Image
from PIL import ImageChops # used for multiplying images

# open images
painting = Image.open("painting.bmp")
mask     = Image.open("mask.bmp")

def black_onto(img1, img2):
    # create blank white canvas to put img2 onto
    resized = Image.new("RGB", img1.size, "white")

    # define where to paste mask onto canvas
    img1_w, img1_h = img1.size
    img2_w, img2_h = img2.size
    box = (img1_w/2-img2_w/2, img1_h/2-img2_h/2, img1_w/2-img2_w/2+img2_w, img1_h/2-img2_h/2+img2_h)

    # multiply new mask onto image
    resized.paste(img2, box)
    return ImageChops.multiply(img1, resized)

out = black_onto(painting, mask)
out.show() # this gives the output image shown above

rawDescription: Overlaying just black pixels from an image over another using Python Imaging Library


code:
import pylab as pl
import numpy as np

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

dx = np.diff(x)
dy = np.diff(y)

x2 = np.linspace(0, 2*np.pi, 10)
y2 = np.sin(x2)

dx = np.zeros_like(x2) + 1e-12
dy = np.sin(x2+dx) - y2

length = np.sqrt(dx**2 + dy**2)
dx /= length
dy /= length

fig, ax = pl.subplots()
ax.set_aspect("equal")
ax.plot(x, y, lw=4)

size = 20
ax.quiver(x2, y2, -dy, dx, headaxislength=size, headlength=size, headwidth=size, color="blue")
pl.margins(0.2)

rawDescription: Sawtooth line style in matplotlib?

description: Sawtooth line style in matplotlib


code:
class ThumbListWidget(QtGui.QListWidget):
    def __init__(self, type, parent=None):
        super(ThumbListWidget, self).__init__(parent)
        self.setIconSize(QtCore.QSize(124, 124))
        self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
        self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            super(ThumbListWidget, self).dragEnterEvent(event)

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            super(ThumbListWidget, self).dragMoveEvent(event)

    def dropEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            links = []
            for url in event.mimeData().urls():
                links.append(str(url.toLocalFile()))
            self.emit(QtCore.SIGNAL("dropped"), links)
        else:
            event.setDropAction(QtCore.Qt.MoveAction)
            super(ThumbListWidget, self).dropEvent(event)

rawDescription: How to Drag and Drop from One QListWidget to Another


code:
input = ['a;1,2,3\n', 'b;abc\n']
filter(lambda item:item.find('b;') == 0 ,input)

rawDescription: check if item is in list and then return the item

description: Check if item is in list and then return the item


code:
if key == '\\':
        ctypes.windll.user32.keybd_event(0x11, 0, 0, 0) # should be left control
        ctypes.windll.user32.keybd_event(0x12, 0, 0, 0) # should be alt
        ctypes.windll.user32.keybd_event(0xDB, 0, 0, 0) # should be alt ß
        ctypes.windll.user32.keybd_event(0x11, 0, KEYEVENTF_KEYUP, 0)
        ctypes.windll.user32.keybd_event(0x12, 0, KEYEVENTF_KEYUP, 0)
        ctypes.windll.user32.keybd_event(0xDB, 0, KEYEVENTF_KEYUP, 0)
        return

rawDescription: encoding of backslash in pythons pyautogui

description: Encoding of backslash in pythons pyautogui


code:
# ... do setup work
os.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path)

rawDescription: Python script opening a bash prompt terminating the script


code:
import json

with open(json_file) as json_file:
    json_decoded = json.load(json_file)

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

with open(json_file, 'w') as json_file:
    json.dump(json_decoded, json_file)

rawDescription: How to add a key-value to JSON data retrieved from a file with Python?

description: Add a key-value to JSON data retrieved from a file with Python


code:
def srch(item, myList, i=0):
  if i < len(myList):
    return myList[i] == item or srch(item, myList, i+1)
  return -1

rawDescription: Searching through a list using recursion in Python?


rawDescription: How to save computational time by using built-in functions and avoid looping over for loops for large numpy arrays in python?

description: Save computational time by using built-in functions and avoid looping over for loops for large numpy arrays in python


code:
nq = Notifications.objects.filter(userid__iexact=q)
for string in nq:
    string.markType = "Read"
    string.save()
results = Notifications.objects.filter(Q(userid__iexact=q)).order_by('-id')

rawDescription: Django Python ... Updating multiple elements in database


code:
import re
text = "Games & Fun"
re.sub(r'\W+', '-', text)

rawDescription: python replace all special characters and spaces with single '-'

description: Python replace all special characters and spaces with single '-'


rawDescription: Hex-decimals in C strings

description: Hex-decimals in C strings


code:
a = np.arange(6).reshape(2,3)
a
for x in np.nditer(a, op_flags=['readwrite']):
    x[...] = 2 * x
a

rawDescription: Iterate and modify array with NumPy

description: Iterate and modify array with NumPy


code:
from cms.models.pagemodel import Page
...
p = Page.objects,get(...)
...
t.save()
p.save()

rawDescription: updating djangocms database entry via script not working with cronjob

description: Updating djangocms database entry via script not working with cronjob


code:
import xml.dom.minidom as minidom

#open the input csv/xml file
inputPath = '/path/to/xml.csv'
xml_csv = open(inputPath)

#open a output file in write mode
outputPath = '/path/to/contributors.xml'
outxml = open(outputPath,'w')

#create a new xml document and top level element
impl = minidom.getDOMImplementation()
newxml = impl.createDocument(None,'contributors',None)
top = newxml.documentElement

#loop through each line in the file splitting on commas
for line in xml_csv:
    xmlFields = line.split(',')

    for fldxml in xmlFields:
        #double double quotes caused the parser to choke, I'm replacing them here
        fldxml = fldxml.replace('""','"')

        #parse the xml data from each field and
        #find all contributor elements under the top level
        dom = minidom.parseString(xmlfld)
        contributors = entry.getElementByTagName('contributor')

        #add each contributor to the new xml document
        for contributor in contributors:
            top.appendChild(contributor)

#write out the new xml contributors document in pretty XML
outxml.write(newxml.toprettyxml())
outxml.close()

rawDescription: parsing a text/csv file containing XML entries in Python

description: Parsing a text/csv file containing XML entries in Python


code:
# create some sample data
x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x) * 120

fig, ax = plt.subplots()

# plot only the outline of the polygon, and capture the result
poly, = ax.fill(x, y, facecolor='none')

# get the extent of the axes
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()

# create a dummy image
img_data = np.arange(ymin,ymax,(ymax-ymin)/100.)
img_data = img_data.reshape(img_data.size,1)

# plot and clip the image
im = ax.imshow(img_data, aspect='auto', origin='lower', cmap=plt.cm.Reds_r, extent=[xmin,xmax,ymin,ymax], vmin=y.min(), vmax=30.)

im.set_clip_path(poly)

rawDescription: Set a colormap under a graph

description: Set a colormap under a graph


code:
class NoteSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username')

    def restore_object(self, attrs, instance=None):
        instance = super(NoteSerializer, self).restore_object(attrs, instance)
        instance.owner = self.context['request'].user
        return instance

    class Meta:
        model = Note
        fields = ('note', 'owner')

rawDescription: Django rest framework populate fields of nested objects programmatically


code: db[dbName].update( { 'pId' : publisher, 'oId' : offer.id },  {"$inc" : {'payout':1.22}}, True)

rawDescription: How to add value to existing value using PyMongo

description: Add value to existing value using PyMongo


rawDescription: PyQT - setting the text color for a QTabWidget


rawDescription: removing weird double quotes (from excel file) in python string

description: Removing weird double quotes (from excel file) in python string


code:
condition = (df.ID=='a1') & (df.geo=='DE')
df.ix[condition, 'value'] = 9999

rawDescription: Modify data in pandas

description: Modify data in pandas


code:
class Point(namedtuple('Point', ['x', 'y'])):
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

rawDescription: Simple addition and subtraction for tuples of X and Y coordinates


code:
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)

rawDescription: Python and SQLite: insert into table

description: Python and SQLite: insert into table


code:
from os import stat
from pwd import getpwuid

def find_owner(filename):
    return getpwuid(stat(filename).st_uid).pw_name

rawDescription: how to find the owner of a file or directory in python

description: Find the owner of a file or directory in python


rawDescription: Python Firebase - User authentication?

description: Python Firebase - User authentication


code:
table = Table('anExistingTable', Base.metadata, autoload=True, autoload_with=Session.bind)
Extension = type('Extension', (BaseClass,), {
    '__table__' : table,
    '__mapper_args__' : {
        'inherits': BaseClass,
        'polymorphic_identity': 'extension'
    }
})

rawDescription: Model Creation by SQLAlchemy database reflection


code:
countries = [ "us", "fr", "de", "ca", "nl" ]
for co in countries:
    controller.set_conf("ExitNodes", "{" + co + "}")

    # make request using Tor socks proxy for site here
    # some check to determine if site is blocking country or not

rawDescription: Scan tor exit nodes to access blocked site


code:
def rsearch(x, found=[]):
    if goal(x):
        raise PathFound
    for y in neighbors(x) and y not in found:
        found.append(y)
        path.insert(0, y)    # switch to depth-first search
        rsearch(y, found)
        path.pop()

rawDescription: Python Search Algorithm from Implied Graphs


code:
from Xlib.display import Display
from Xlib.Xatom import WINDOW
display = Display()
root = display.screen().root
active_id = root.get_full_property(_NET_ACTIVE_WINDOW, WINDOW).value[0]
window = display.create_resource_object('window', active_id)
title = window.get_full_property(_NET_WM_NAME, UTF8_STRING).value

rawDescription: how do i keep track of title changes for firefox in ubuntu?

description: Keep track of title changes for firefox in ubuntu


code:
with open('file.csv') as file:
    second_line = list(file)[1]

with open('out.csv', mode = 'w') as file:
    file.write(second_line)

rawDescription: Start reading and writing on specific line on CSV with Python


code:
ex = "/Volumes/Obelix/5215.tif, /Volumes/Gemeinsam/25.tif, /Volumes/Obelix/5100.tif"
newex = re.sub(r'/Volumes/Gemeinsam/.+?,?(\s|$)', '', ex)

rawDescription: Replace wildcard from string

description: Replace wildcard from string


code:
import os
BASE_DIR = os.path.dirname(__file__)
key = os.path.join(BASE_DIR, "secrets.json")

rawDescription: Django settings SECRET_KEY

description: Django settings SECRET_KEY


code:
@admin.register(SubscriptionApp)
class SubscriptionAppAdmin(admin.ModelAdmin):
    form = autocomplete_light.modelform_factory(model=SubscriptionApp)

class SubscriptionAppInline(admin.TabularInline):
    model = SubscriptionApp

@admin.register(Subscription)
class SubscriptionAdmin(admin.ModelAdmin):
    model = Subscription
    ordering = ('name',)

rawDescription: Django admin + autocomplete_light for many-to-many field with large data-set


code:
class Vote(models.Model):
    VOTE_ENUM = (
        (VoteEnum.DOWN_VOTE, VoteEnum.toString(VoteEnum.DOWN_VOTE)),
        (VoteEnum.NONE, VoteEnum.toString(VoteEnum.NONE)),
        (VoteEnum.UP_VOTE, VoteEnum.toString(VoteEnum.UP_VOTE)),

    )
    question = models.ForeignKey(Question, null=False, editable=False, blank=False)
    voter = models.ForeignKey(User, blank=False, null=False, editable=False)
    vote_type = models.SmallIntegerField(default=0, null=False, blank=False, choices=VOTE_ENUM)

    class Meta:
        abstract = True

    def is_upvote(self):
        return self.vote_type > 0
    def is_downvote(self):
        return self.vote_type < 0

class VoteAnswer(Vote):
    answer = models.ForeignKey(Answer, null=False, editable=False, blank=False)

    class Meta:
        unique_together = (("voter", "answer"),) # to prevent user from voting on the same question/answer/comment again

    def __unicode__(self):
        vote_type = "UP" if vote_type > 0 else ("DOWN" if vote_type < 0 else "NONE")
        return u"{0}: [{1}] {2}".format(user.username, vote_type, answer.text[:32])

    def is_upvote(self):
        return "FOO! "+str(super(VoteAnswer, self).is_upvote())

class VoteComment(Vote):
    comment = models.ForeignKey(Comment, null=False, editable=False, blank=False)

    class Meta:
        unique_together = (("voter", "comment"),) # to prevent user from voting on the same question/answer/comment again

    def __unicode__(self):
        vote_type = "UP" if vote_type > 0 else ("DOWN" if vote_type < 0 else "NONE")
        return u"{0}: [{1}] {2}".format(user.username, vote_type, comment.text[:32])

    def is_upvote(self):
        return "BAR!"

rawDescription: How to store functions in django models

description: Store functions in django models


code:
a = [1, 2, 3]
b = [4, 5, 6]
c = a # c is a reference to the list in a
c

a[:] = b
a # a will have a copy of the list in b
c # and c will keep having the same value as a
b = [7, 8, 9]
a = b[:]
a # a has the new value
c # c keeps having the old value

rawDescription: Assigning to vs. from a slice

description: Assigning to vs. from a slice


code:
jsScript = '''
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

text = getSelectionText(); alert(text)
'''

driver.execute_script(jsScript)

rawDescription: executing Javascript using Selenium in python (Tkinter as GUI)

description: Executing Javascript using Selenium in python (Tkinter as GUI)


code:
try:
  import readline
except ImportError:
  import pyreadline as readline

rawDescription: Readline functionality on windows with python 2.7


code:
class CliProfileManager(models.Manager):
   def get_subscribed_clients(self, shop):
       return self.get_queryset().exclude(unsubscriptions__shop=shop)

class CliProfile(...):
     objects = CliProfileManager()

profiles = CliProfile.objects.filter(...)
subscribed = profiles.get_subscribed_clients()

subscribed = profiles.objects.get_subscribed_clients()

rawDescription: Django: using filter() with Many To Many field


code:
pv_test_A.loc[:,[2015]].rename(columns={2015: "New Label A"}).plot(ax=axes)
pv_test_B.loc[:,[2015]].rename(columns={2015: "New Label B"}).plot(ax=axes)

rawDescription: Change plot label when plotting different dataframes in pandas


code:
from decimal import *
getcontext().prec = 50
Decimal(1)/Decimal(7)

rawDescription: Increase Accuracy of float division (python)


rawDescription: Python/Numpy: Divide array

description: Python/Numpy: Divide array


rawDescription: newline in text extraction from pdf

description: Newline in text extraction from pdf


code: nonzero = numpy.where( (hist > 0) & (binDist < max_dist) )

rawDescription: How to calculate the numpy.histogramdd bins coordinates

description: Calculate the numpy.histogramdd bins coordinates


code:
game = Game.objects.get(name="testb")
game.likes = 5
game.save()

rawDescription: Changing model field within the Django Shell


code:
class Reference:
    def __init__(self, value):
        self.value = value
    def __mul__(self, other):
        return Reference(self.value * other.value)

rawDescription: How to make different variables refer to same value, while still allowing operations directly?

description: Make different variables refer to same value, while still allowing operations directly


code: from __future__ import absolute_import

rawDescription: Python: Disabling relative import

description: Python: Disabling relative import


code:
l # assume you already read the list of numbers from the file.
from collections import Counter
Counter(l).most_common()

rawDescription: to display the maximum count of numbers

description: To display the maximum count of numbers


code:
import random

print("Welcome to the coin flipper!")

start = input('Press enter to flip the coin')
count = 0
while True:
    coin_flip = random.randint(1,2)
    count+=1

    if count >100:
        break

    if coin_flip == 1:
        print('Heads')

    elif coin_flip == 2:
        print("Tails")

rawDescription: random.randint function not working

description: Random.randint function not working


code:
mylist  = [[1,2,3,4], [] , [1,2,3,4] , []]
[i for i,x in enumerate(mylist) if not x]

rawDescription: How to find all indexes of a list that are empty in Python

description: Find all indexes of a list that are empty in Python


code:
return "".join("  {} -> {}\n".format(key, d[key])
               for key in sorted(d, key=key, reverse=reverse))

rawDescription: How to write this as 1 line return Python

description: Write this as 1 line return Python


code:
from tokenize import generate_tokens
from cStringIO import StringIO
list(generate_tokens(StringIO('hello this is a test string').readline))

rawDescription: Python how to work with tokens

description: Python how to work with tokens


rawDescription: boto.ec2.connection.EC2Connection.request_spot_instances() does not return boto.ec2.spotinstancerequest.SpotInstanceRequest

description: Boto.ec2.connection.EC2Connection.request_spot_instances() does not return boto.ec2.spotinstancerequest.SpotInstanceRequest


code:
def save_embed(request):
    if request.method == "POST":
        form = SubmitEmbed(request.POST)
        if form.is_valid():
            url = form.cleaned_data['url']
            proxies = {
                "http": "http://123.123.123.123:1234",
                "https": "https://123.123.123.123:1234",
            }
            r = requests.get('http://api.embed.ly/1/oembed?key=' + settings.EMBEDLY_KEY + '&url=' + url, proxies=proxies)

rawDescription: Django - how to make requests with proxies?


code:
#!/usr/bin/env

def first(flist, default=None):

    """ Try each function in `flist` until one does not throw an exception, and
    return the return value of that function. If all functions throw exceptions,
    return `default`

    Args:
        flist - list of functions to try
        default - value to return if all functions fail

    Returns:
        return value of first function that does not throw exception, or
        `default` if all throw exceptions.

    TODO: Also accept a list of (f, (exceptions)) tuples, where f is the
    function as above and (exceptions) is a tuple of exceptions that f should
    expect. This allows you to still re-raise unexpected exceptions.
    """

    for f in flist:
        try:
            return f()
        except:
            continue
    else:
        return default

# Testing.

def f():
    raise TypeError

def g():
    raise IndexError

def h():
    return 1

# We skip two exception-throwing functions and return value of the last.
assert first([f, g, h]) == 1

assert first([f, g, f], default='monty') == 'monty'

rawDescription: How to write multiple try statements in one block in python?

description: Write multiple try statements in one block in python


code:
a = [1, 2, 3]
del a[0] # should delete 1
a
del a[1] # This use to be the index for 2, but now `3` is at this index
a

rawDescription: Slicing List Confusion in Python

description: Slicing List Confusion in Python


code:
import numpy as np
dataINeed = np.arange(3)
dataINeed
data = np.array([5,7,9,1,5,3,7,1,2,0])
dataINeedset = set(dataINeed)
np.array([x in dataINeedset for x in data])

rawDescription: Yet for array indexing

description: Yet for array indexing


code: _fred = None

rawDescription: Global name is not defined for second unittest


code:
import subprocess
def copy2clip(txt):
   cmd='echo '+txt.strip()+'|clip'
   return subprocess.check_call(cmd, shell=True)
copy2clip('now this is on my clipboard')

rawDescription: how can I copy a string to the windows clipboard? python 3

description: Copy a string to the windows clipboard? python 3


code:
if "select count(*) from scan where prefix = ? and code_id = ? and ..." == 0:
    execute("insert into scan....")

rawDescription: Python: Checking if field exists in table


code:
car = Car.objects.filter(product__id=product_id).extra(
        select={'is_top': " brand='BMW'"})
car = car.extra(order_by = ['is_top'])

rawDescription: Custom Order by in django

description: Custom Order by in django


code:
ccc = defaultdict( lambda: defaultdict( list ) )
for row in cursor.fetchall():
    country, county, city = row
    ccc[country][county].append(city)

rawDescription: python convert sql result to tree hierarchy

description: Python convert sql result to tree hierarchy


code: driver.find_element_by_xpath("//strong[contains(preceding-sibling::text(), 'Last updated: ')]").text

rawDescription: Selenium parse data into a variable

description: Selenium parse data into a variable


code: plt.plot(x, y, 'o', clip_on=False)

rawDescription: Markers at the border of the fig cannot show completely using matplotlib


code:
import struct
def pack_floats(*args):
    return struct.pack('%df' %len(args), *args)

pack_floats(0.1,1.2,2.3)

rawDescription: using *args in struct.pack

description: Using *args in struct.pack


code:
ax.set_xticklabels(df[0])
ax.set_yticklabels(df[1])
ax.set_xticks(df["x"])
ax.set_yticks(df["y"])
ax.set_xlabel("Source IP")
ax.set_ylabel("Destination IP")

rawDescription: IP addresses as x and y labels in a pandas scatter plot


code: df.filter(regex=r'(?i)hdgfl1', axis=0)

rawDescription: Case insensitive selecting row in Pandas Data Frame (grep -i)


code:
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('a', '').replace('b', ''))
f1.close()
f2.close()

rawDescription: Python: Filter in File I/O

description: Python: Filter in File I/O


code:
my_2d_list_of_rows = [row.split() for row in my_file]
my_2d_list_of_columns = zip(*my_2d_list_of_rows)

rawDescription: How do I split a data array in python into two seperate groupings of variables?

description: Split a data array in python into two seperate groupings of variables


code:
def first2(s):
    return s[:2]

rawDescription: How to get the first 2 letters of a string in Python?

description: Get the first 2 letters of a string in Python


code:
message = "blabla df qdsf dqsf \"fqdfdqsfsdf  fdqs fqdsf\""
pattern = "(\w+|'.*[^']'|\".*[^\"]\")"
re.findall(pattern, message)

rawDescription: Python regular expressions

description: Python regular expressions


code:
from io import StringIO
txt = '''
1, 2, 3
4, 5, 6
7, 8, 9'''

xs = np.loadtxt(StringIO(txt), delimiter=',')
xs

x, y = xs[:, 1:], xs[:, 0]
x
y

rawDescription: Read several numpy array from csv in one line


code:
from rest_framework.fields import CurrentUserDefault

class ClientSearchSerializer(serializers.ModelSerializer):

    client = serializers.SlugRelatedField(
        many=False,
        queryset=Client.objects.filter(user=CurrentUserDefault()),
        slug_field='id'
    )

rawDescription: Django Rest Framwork get user in serializer


rawDescription: Python 3 - What is ">>"

description: Python 3 - What is ">>"


code:
line = object()
line,

rawDescription: Difference between `return line, ` and `return line`


code:
import glob, os
glob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))

rawDescription: Python: How to Access Linux Paths

description: Python: How to Access Linux Paths


code:
from BeautifulSoup import BeautifulSoup, CData, Tag
source = """
<title>The end of the world as we know it</title>
<category><![CDATA[Planking Dancing]]></category>
<pubDate><![CDATA[Sun, 16 Sep 2012 12:00:00 EDT]]></pubDate>
<dc:creator><![CDATA[Bart Simpson]]></dc:creator>
"""
soup = BeautifulSoup(source)
for navstr in soup(text=True):
    if isinstance(navstr, CData):
        tag = Tag(soup, "myTag")
        tag.insert(0, navstr[:])
        navstr.replaceWith(tag)

soup

rawDescription: Replacing CDATA NavigableStrings with Tags in BeautifulSoup


code:
def rate():
    rate = 1
    if var.get() =='GBP' and var2.get() =='USD':
        rate=float(1.63452)
    if var.get() == 'GBP' and var2.get()=='EUR':
        rate=float(1.19529)
    ## TODO:: add other convertion conditions
    return rate

def convert():
    converted=Label(root, text=(var.get(), entarr.get(),">>>", (entarr.get()*rate()), var2.get()))
    converted.pack(expand=1)
    return convert

rawDescription: How do I correct this function to create a label in Tkinter Python?

description: Correct this function to create a label in Tkinter Python


code:
a = [11, 10, (12, 52)]
sorted(a, key=lambda x: x[0] if isinstance(x, tuple) else x)

rawDescription: Sorting With Tuples and Intergers in the Same List


code:
df.plot(x='bnw_Value', y='bnw_Percent', title='BNW', kind='bar', ax=ax1)
df.plot(x='php_Value', y='php_Percent', title='PHP', kind='bar', ax=ax2)

rawDescription: Subplots with Pandas

description: Subplots with Pandas


code:
inp="""System MA
user id =  2084
username =  XYZ90
selection =  pnq
decimal =  6.000
Percentage =  19.1176470588 %

System NA
user id =  2086
username =  pron1
selection =  abc
decimal =  13.000
Percentage =  13.1147540984 %

System M
user id =  1664
username =  Chrisod
selection =  pleader
decimal =  15.000
Percentage =  16.091954023 %"""

inp=inp.split('\n\n')

rss_start="""<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0">

<channel>
  <title>Your title</title>
  <link>http://yoursite.com</link>
  <description>Your discription</description>
"""

rss_end="""</channel>

</rss> """

def description(item):
    return item

def title(item):
    return item.split('\n')[0]

def link(item):
    return 'http://mysite.com/' + item.split('\n')[0]

rss_items=[]
for counter, item in enumerate(inp):
    rss_items.append("""
  <item>
    <title>%s</title>
    <link>%s</link>
    <description>%s</description>
    <guid>counter</guid>
  </item>""" % (title(item),description(item),link(item)))

rss_output=rss_start+''.join(rss_items)+rss_end

rawDescription: Generating simple RSS feed from parsed data


code:
class Player():
    def __init__(self, master, radius, xcoordinate=100, ycoordinate=100):
        self.master=master
        self.xcoordinate = xcoordinate
        self.ycoordinate = ycoordinate
        self.radius = radius
        self.master.title("World")
        self.master.bind('<Right>', self.moveRight)
        self.master.bind('<Left>', self.moveLeft)
        self.draw()  ## called once

    def moveRight(self, event):
        self.canvas.move(self.oval_id, 25, 0)
        print("Right key pressed")
        print("x: " + str(self.xcoordinate))

    def moveLeft(self, event):
        self.canvas.move(self.oval_id, 0, 25)
        print("Left key pressed")
        print("y: " + str(self.ycoordinate))

    def draw(self):
        self.canvas = Canvas(self.master, width=200, height=200,
                 borderwidth=0,highlightthickness=0, bg="black")
        self.canvas.grid()
        self.oval_id=self.canvas.create_oval(self.xcoordinate-self.radius,
                                        self.ycoordinate-self.radius,
                                        self.xcoordinate+self.radius,
                                        self.ycoordinate+self.radius,
                                        fill="red")

master=Tk()
p1 = Player(master, 50)
master.mainloop()

rawDescription: Redraw circle - python

description: Redraw circle - python


rawDescription: How to query data rows with id is specified by another query with Django queryset

description: Query data rows with id is specified by another query with Django queryset


code:
# Used to check if myfunc is running in current program
running_here = False

# Set 'running' variable inside database to 'false' if myfunc was running
# inside current program at the time of exiting or don't do anything otherwise
atexit.register(lambda: set_var('running', 'false') if running_here else None)
# Call atexit handler when SIGTERM is recieved by calling sys.exit
signal.signal(signal.SIGTERM, lambda x, frame: sys.exit(0))

def myfunc():
    global running_here

    # Don't do anything if there's an instance already
    if get_var('running') == 'true':
         return

    # Don't let multiple instances to run at the same time
    set_var('running', 'true')
    running_here = True

    do_something()
    do_something_else()

    # Allow other instances to run
    set_var('running', 'false')
    running_here = False

rawDescription: Execute code at exit

description: Execute code at exit


code: np.repeat(np.arange(c.size), c)

rawDescription: Inverse of numpy's bincount function

description: Inverse of numpy's bincount function


code:
from django.contrib import admin
from django.apps import apps

app_config  = apps.get_app_config('myapp')
models = app_config.get_models()

for Model in models:
    fieldnames = [f.name for f in Model._meta.get_fields() if f.name != 'id']
    ModelAdmin = type('ModelAdmin', (admin.ModelAdmin,), {'list_filter': fieldnames})
    admin.site.register(Model, ModelAdmin)

rawDescription: How can I automatically create list_filters for all my models in a django admin page?

description: Automatically create list_filters for all my models in a django admin page


code:
import matplotlib.pyplot as plt
from scipy import *
from scipy import integrate
from scipy.integrate import ode
import numpy as np

fig = plt.figure(num=1)
ax=fig.add_subplot(111)

## Vector field function
def vf(t,x):
  dx=np.zeros(2)
  dx[0]=1
  dx[1]=x[0]**2-x[0]-2
  return dx

#Solution curves
t0=0; tEnd=10; dt=0.01;
r = ode(vf).set_integrator('vode', method='bdf',max_step=dt)
ic=[[-3.5,-10], [-3,-10], [-2.5,-10]]
color=['r','b','g']
for k in range(len(ic)):
    Y=[];T=[];S=[];
    r.set_initial_value(ic[k], t0).set_f_params()
    while r.successful() and r.t +dt < tEnd:
        r.integrate(r.t+dt)
        Y.append(r.y)

    S=np.array(np.real(Y))
    ax.plot(S[:,0],S[:,1], color = color[k], lw = 1.25)

#Vector field
X,Y = np.meshgrid( np.linspace(-5,5,20),np.linspace(-10,10,20) )
U = 1
V = X**2-X-2
#Normalize arrows
N = np.sqrt(U**2+V**2)
U2, V2 = U/N, V/N
ax.quiver( X,Y,U2, V2)

plt.xlim([-5,5])
plt.ylim([-10,10])
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")
plt.show()

rawDescription: Drawing directions fields

description: Drawing directions fields


rawDescription: pyQt4 - How to select table rows and disable editing cells

description: PyQt4 - How to select table rows and disable editing cells


code:
if title is None:
    title= ''

rawDescription: How do you fill a variable with an empty space in Python?

description: Fill a variable with an empty space in Python


code:
from sqlalchemy.sql.expression import func

(db.session.query(User, func.ts_rank('{0.1,0.1,0.1,0.1}', User.textsearchable_index_col, func.to_tsquery('smit:* | ji:*')).label('rank'))
    .filter(User.authentication_method != 2)
    .filter(User.textsearchable_index_col.op('@@')(func.to_tsquery('smit:* | ji:*')))
    .order_by('rank desc')
).all()

rawDescription: Returning ranked search results using gin index with sqlalchemy


rawDescription: Find a specific point on diagram (vectors) in Python


code:
course_info = [
               ['Course Code' , c.course_code] ,
               ['Course Title' , c.course_name],
               ['Prerequisites by Course(s) and Topics', c.pre_reqs],
               ['Assessment Instruments with Weights (some desc)', c.grade_distribution]
            ]

for k in course_info:
    headpara = Paragraph(k[0], styleN)
    datas.append([headpara , Paragraph(clean_string(k[1]), styleN)])

rawDescription: Reportlab bold and normal text in one paragraph


code:
import re

with open('php_file.txt', 'r') as f:
    html = re.sub('<\?.*?\?>', '', f.read(), re.MULTILINE)

with open('html_file.txt', 'w') as f:
    f.write(html)

rawDescription: Removing PHP Lines from an HTML File Using Python


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

x = np.linspace(0, 1, 10)
y = x**2

plt.rc('text', usetex=True)
plt.rc('text', **{'latex.preamble':
              '\\usepackage[bitstream-charter]{mathdesign}'})

plt.figure(dpi=200)
plt.plot(x, y, c='green')
line1 = Line2D(range(10), range(10), marker='_', color="blue")
line2 = Line2D(range(10), range(10), marker='_',color="green")
leg = plt.legend((line1,line2),('',''),numpoints=1, loc=1)
leg.get_frame().set_alpha(0.2)
plt.text(0.955, 0.925, "$T^*_s$")
plt.text(0.955, 0.865, "$T^*_g$")
plt.show()

rawDescription: Python legend marker location changes when using alternative font


code:
class silence(object):

    def __init__(
        self,
        stdout = None,
        stderr = None
        ):
        if stdout == None and stderr == None:
            devnull = open(os.devnull, "w")
            # Assign devnull to stdout and stderr
            stdout = devnull
            stderr = devnull
        self._stdout = stdout or sys.stdout
        self._stderr = stderr or sys.stderr

rawDescription: Why does devnull not work at hiding console output when it is defined within this context manager?


code:
import win32gui
import re

class WindowMgr:
    """Encapsulates some calls to the winapi for window management"""
    def __init__ (self):
        """Constructor"""
        self._handle = None

    def find_window(self, class_name, window_name = None):
        """find a window by its class_name"""
        self._handle = win32gui.FindWindow(class_name, window_name)

    def _window_enum_callback(self, hwnd, wildcard):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd

    def find_window_wildcard(self, wildcard):
        self._handle = None
        win32gui.EnumWindows(self._window_enum_callback, wildcard)

    def set_foreground(self):
        """put the window in the foreground"""
        win32gui.SetForegroundWindow(self._handle)

w = WindowMgr()
w.find_window_wildcard(".*Hello.*")
w.set_foreground()

rawDescription: Python Window Activation

description: Python Window Activation


code:
import json

# your variables are already assigned before this
data = {'url': url, 'address': address, 'name': name}
sent = json.dumps(data)
result = firebase.post("/businesses", sent)

rawDescription: POST data to Firebase using Python

description: POST data to Firebase using Python


code:
from bs4 import BeautifulSoup

with open('input.xml') as infile:
    soup = BeautifulSoup(infile, 'lxml')
    for e in soup.find_all('div', attrs={'xml:lang': lambda value: value != 'English'}):
        _ = e.extract()

with open('output.xml', 'w') as outfile:
    outfile.write(soup.prettify(soup.original_encoding))

rawDescription: Python parse xml file

description: Python parse xml file


code: l_id = [d[key] for key in ['id1', 'id2'] for d in l_data]

rawDescription: Merge multiple list comprehensions

description: Merge multiple list comprehensions


code:
cherrypy.server.socket_host = '192.168.0.147'
cherrypy.server.socket_port = 8080

rawDescription: How to deploy a CherryPy app locally

description: Deploy a CherryPy app locally


code:
df.groupby('count_id')["AMV"].transform('min')
df["AMV"] - df.groupby('count_id')["AMV"].transform('min')
df["AMV_norm"] = df["AMV"] - df.groupby('count_id')["AMV"].transform('min')

rawDescription: Pandas data frame - lambda calculus and minimum value per series


code:
requirements = open("requirements.txt", "r")
shell_script = open("pip.sh", "w+")
shell_script.write("sudo apt-get install python-pip\n")
for line in requirements:
    shell_script.write("sudo pip install -I " + line)

rawDescription: Python Dependency Management on EMR

description: Python Dependency Management on EMR


code:
from Script1 import func1 # only for option 2
from Script2 import func2 # only for option 2

def value():
    ...
    if user_input == "Script1":
        func1()
    else:
        func2()

def func1(): # only for option 1
    ...

def func2(): # only for option 1
    ...

value() # call value

rawDescription: How to redirect from a python script to another scripts taking user input

description: Redirect from a python script to another scripts taking user input


code:
def reformat(fin, fout):
    fout.write(next(fin)) # just copy the first line (the header) to output
    for line in fin:
        fields = line.split(' ')

        # Make a format header specific to the number of fields
        fmt = '%6.2f' + ('%10.6f' * (len(fields)-1)) + '\n'

        fout.write(fmt % tuple(map(float, fields)))

basenames = os.listdir(indir)  # get a list of input ASCII files to be processed
for basename in basenames:
    input_filename = os.path.join(indir, basename)
    output_filename = os.path.join(outdir, basename)
    with open(input_filename, 'r') as fin, open(output_filename, 'w') as fout:
        reformat(fin, fout)

rawDescription: Python: Concise / elegant way to reformat a set of text files?


code:
def is_similar(image1, image2):
    return image1.shape == image2.shape and not(np.bitwise_xor(image1,image2).any())

rawDescription: OpenCV - Fastest method to check if two images are 100% same or not


code:
from selenium.webdriver.common.action_chains import ActionChains

N = 5  # number of times you want to press TAB

actions = ActionChains(browser)
for _ in range(N):
    actions = actions.send_keys(Keys.TAB)
actions.perform()

rawDescription: Send multiple tab key presses with selenium


code: max(len(k.split()) for k in d.keys())

rawDescription: Python - Find longest (most words) key in dictionary


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.priceline.com/")
driver.find_element_by_id("hotel-btn-submit-retl").click()
driver.close()

rawDescription: Clicking in a online js button with python


code:
import sys
from PyQt4 import QtCore, QtGui

# import pyuic generated user interface file
from ui_mainwindow import Ui_MainWindow

class MyMainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        # connect myaction_logic to myaction.toggled signal
        self.myaction.toggled.connect(self.myaction_slot)

    def myaction_slot(self):
        pass # do something here

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyMainWindow()
    myapp.show()
    sys.exit(app.exec_())

rawDescription: Qt designer: Custom code for custom actions


code:
tup = ... # some sequence/tuple of unknown length
sql = 'SELECT * FROM table WHERE word IN (%s)' % ', '.join('?' for a in tup)
c.execute(sql, tup)

rawDescription: How to get variable length placeholders in a Python call to SQLite3

description: Get variable length placeholders in a Python call to SQLite3


code:
most_viewed_videos = Video.objects.filter(
        videowatch__created__month=today.month,
        viewing__status="D"
    ).annotate(
        count=Count("videowatch"),
        viewing_count=Sum("viewing")
    .extra(
        select={'total': 'COUNT(videowatch)+SUM(viewing)'}
    )
    ).values("count", "viewing_count").order_by(
        "-viewing_count",
        "-count"
)

rawDescription: Calculate annotated fields together

description: Calculate annotated fields together


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

def fun(x, y):
  return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: surface plots in matplotlib

description: Surface plots in matplotlib


code:
rate, num_samples, dur, num_chans = extract_vars(blks)

# your code here

rawDescription: Passing Variable from Function in Python


code:
@classmethod
def attributes(cls, create=False, extra=None):
    if extra:
        if 'profile__first_name' in extra and 'username' not in extra:
            extra['username'] = extra['profile__first_name'].lower()
        elif 'username' in extra and 'profile__first_name' not in extra:
            extra['profile__first_name'] = extra['username'].title()

    return super().attributes(create, extra)

rawDescription: FactoryBoy overriding Attributes

description: FactoryBoy overriding Attributes


code:
def my_decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        f(*args, **kwargs)
    return wrapper

rawDescription: PySide: multiple decorators for widget slots


code:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

rawDescription: how do i write to a python subprocess' stdin

description: Write to a python subprocess' stdin


rawDescription: python xarray concat groupby in datetime64 dimensions

description: Python xarray concat groupby in datetime64 dimensions


code:
import matplotlib.pylab as plt

dims = 4
fig, axes = plt.subplots(1, dims-1 + 1, sharey=False)

plt.subplots_adjust(wspace=0)

ax1 = axes[0]
pos = ax1.get_position()
ax1.set_position(pos.translated(tx = -0.1,ty=0))

rawDescription: Python: Parallel coordinates subplots in subplot


code:
def makedictwithlists(f):
    keys = next(f).split()
    d = {}
    for k in keys: d[k] = []
    for line in f:
        for k, v in zip(keys, line.split()):
            d[k].append(v)
    return d

rawDescription: Handling file reading and multiple values to a key in dictionary


code:
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

for row_num in range(1, 10):
    cell = xl_rowcol_to_cell(row_num, 1)
    formula = '=IF(ISNUMBER(SEARCH("21",%s)),"x","")' % cell
    worksheet.write(row_num, 2, formula)

workbook.close()

rawDescription: How to Fill Down using xlsxwriter

description: Fill Down using xlsxwriter


code:
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(item['updated_parsed']))

rawDescription: Populating a Django DateTimeField with feedparser


code: print(''.join(filter(str.isupper, "This is my String")))

rawDescription: How to grab the upper case in Py3?

description: Grab the upper case in Py3


code:
def allocate_to_family(families, agents):
    for dummy_family in families:
        for dummy_agent in random.sample(agents, 4):
            dummy_family.add_agent(dummy_agent)

rawDescription: Setting items from a list to another list (both containing class instances) in random groups in python


code:
import numpy as np

def mean_if_no_missings(x, no_missings=3):
    if np.isnan(x).sum() < no_missings:
        return np.mean(x)
    else:
        return np.NaN

df['SCORE']=df.ix['Q1':'Q10'].apply(conditional_mean, axis=1)

rawDescription: Compute new pandas column (mean of other columns), only if NaN less than threshold?


code:
from io import StringIO
import csv
demo = StringIO('''\
foo,bar,baz
42,88,131
17,19,23
''')
reader = csv.DictReader(demo)
def only_answers(row):
    return '42' in row.values()

for row in filter(only_answers, reader):
    print(row)

rawDescription: Filter() on DictReader

description: Filter() on DictReader


code:
def reduce_wrapper(custom_param, function, iterable, *args):
    # do stuff
    reduce(function, iterable, *args)

rawDescription: How to define polymorphic python optional parameter?

description: Define polymorphic python optional parameter


code:
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    ...

rawDescription: Disable CSRF/XSRF validation in Django

description: Disable CSRF/XSRF validation in Django


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

# your data
data = 3. + 0.7 * np.random.randn(N)

# a small spreading of the data in x direction
x = 0.2 * np.random.randn(data.size)

# the plotting
fig,ax = mpl.subplots(1,figsize=(0.5,5))
ax.set_axis_bgcolor('#FFD7B1')
ax.scatter(x,data,alpha=0.2,c='k')
ax.plot([-1,1],[np.mean(data),np.mean(data)],'r',linewidth=2)
ax.set_xlim((-1,1))
ax.set_ylim((1,6))
ax.set_xticks([])
ax.grid(True,axis='y')
ax.set_ylabel('Note')

rawDescription: Python: Vertical 1D DotPlot

description: Python: Vertical 1D DotPlot


code:
for i in range(len(df.columns)):
    col = df.columns[i]
    df = df.merge(df_referential, left_on = col, right_on = 'id', how='left', suffixes = ['', '_%s'%i])

rawDescription: Merge on many variables on python

description: Merge on many variables on python


code:
import pydot
N = pydot.Dot()
N.set_node_defaults(shape='record')
p = pydot.Node('node0', label = "<f0> |<f1> G|<f2> ")
N.add_node(p)
N.write_dot('foo.dot')

rawDescription: How to use port names in record nodes in pydot

description: Use port names in record nodes in pydot


code:
import os
import subprocess
import time
path = r"C:\Users\Luke\Desktop\Tor_Browser\Browser\firefox.exe {0}"
url = "http://google.com"
views = 5
opened = 0
for i in range(views):
    proc = subprocess.Popen(path.format(url))   # Change here to bind pipe to a name
    time.sleep(15)
    opened = opened + 1
    print ("Times opened:", opened)
    proc.terminate()                            # send process term signal

rawDescription: How to hide output of subprocess in Python without preventing other subprocesses from running

description: Hide output of subprocess in Python without preventing other subprocesses from running


code:
from collections import namedtuple
names = namedtuple( 'names', ['a','b','c'] )
thing= names(3,2,1)
thing.a
thing.b
thing.c

rawDescription: Python higher-order sequence assignment?

description: Python higher-order sequence assignment


code:
def OnMessageStatus(msg, status):
    if status == Skype4Py.cmsReceived:
        msg.Chat.SendMessage("n/a")

rawDescription: Reply to Message Skype4Py

description: Reply to Message Skype4Py


code:
FILE_NAME = r"c:\\Python34\HospitalRecords.txt"

def main():

    choice = 0

    while choice != 2:
        print("1) Hospital_Records")
        print("2) Exit")

        choice = int(input("Enter your choice: "))

        if choice == 1:
            # create a bool variable to use as a flag
            found = False
            # Get the search value
            searchName = input("Enter your first and last name: ")
            file = open(FILE_NAME)
            # Read the first record's name field
            record_name = file.readline().rstrip('\n')

            # Read the rest of the file
            while record_name != '':
                days_in_hospital = int(file.readline())
                daily_rate = float(file.readline())
                service_charge = float(file.readline())
                medication_charges = float(file.readline())

                # determine if this record matches the search value
                if record_name == searchName:
                    print("Name: ", searchName)
                    print("Days in Hospital: ", days_in_hospital)
                    print("Daily Rate: ", daily_rate)
                    print("Service Charges: ", service_charge)
                    print("medication_Charges: ", medication_charges)

                    total_charges = ((days_in_hospital * daily_rate) + service_charge + medication_charges)

                    print("Total Charges: ", total_charges)
                    print()

                    # set the found flag to True
                    found = True

                    break

                record_separator = file.readline()

                # strip the newline character from the record
                record_name = file.readline().rstrip('\n')

            file.close()

            if not found:
                # If the search value was not found in the file
                # display a message
                print("That name was not found in the file.")
        elif choice == 2:
            print("You successfully exited the program.")
        else:
            print("Invalid entry!")

main()

rawDescription: Error parsing text file - Python

description: Error parsing text file - Python


code:
def my_uniform(a, b):
    while True:
        result = uniform(a, b)
        if a < result < b:
            return result

rawDescription: Python: Generate random floating point number in a range, excluding start-point


code:
def add(request):
    # Do something
    return redirect('/register/')

rawDescription: Django URL not changing even after redirection


code:
from django.utils.translation import ugettext as _

heading = (_('Service'), _('Price'), _('Note'))
table = Table([heading])

rawDescription: ugettext_lazy doesn't work with reportlab's Table

description: Ugettext_lazy doesn't work with reportlab's Table


code:
from urlparse import urljoin

def resource_url(page, resource):
  if not resource.startswith(page):
    # doesn't start with http://example.com
    resource = urljoin(page, resource)
  return resource

rawDescription: How to get a full URL from a resource URL in python

description: Get a full URL from a resource URL in python


code: result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

rawDescription: Flask SQLAlchemy query, specify column names


rawDescription: How to manage authentication across handler classes in google app engine /w python

description: Manage authentication across handler classes in google app engine /w python


code:
def do_POST(self):
    ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
    if ctype == 'multipart/form-data':
        postvars = cgi.parse_multipart(self.rfile, pdict)
    elif ctype == 'application/x-www-form-urlencoded':
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
    else:
        postvars = {}

    print(postvars.get("listName", "didn't find it"))

rawDescription: How do I access the data sent to my server using BaseHTTPRequestHandler?

description: Access the data sent to my server using BaseHTTPRequestHandler


code:
def format_value(v, indent):
    if isinstance(v, list):
         return ''.join([format_value(item, indent) for item in v])
    elif isinstance(v, dict):
         return format_dict(v, indent)
    elif isinstance(v, str):
         return ("   " * indent) + v + "\n"

def format_dict(d, indent=0):
    res = ""
    for key in d:
        res += ("   " * indent) + key + ":\n"
        res += format_value(d[key], indent + 1)
    return res

rawDescription: Python dictionary formating

description: Python dictionary formating


code:
import os
help(os.path.split)
os.path.split(r'c:\users\sony\desktop\f.html')
path,filename = os.path.split(r'c:\users\sony\desktop\f.html')
path
filename

rawDescription: How to extract a substring from a string in Python?

description: Extract a substring from a string in Python


code: text = db.TextProperty()

rawDescription: How to save non required properties to datastore?

description: Save non required properties to datastore


code:
from PIL import Image
def get_date_taken(path):
    return Image.open(path)._getexif()[36867]

rawDescription: Get date and time when photo was taken from EXIF data using PIL


code:
tx_rx = {TX1: RX1, TX2: RX2}
for tx in tx_rx:
    if tx in a:
        send.ser(tx_rx[tx])
        read_buf()

rawDescription: Best method for (HEX) string comparison

description: Best method for (HEX) string comparison


code:
from colormath import color_objects, color_conversions

lab_color = color_objects.LabColor(lab_l=70.0, lab_a=60.0, lab_b=0.0)
rgb_color = color_conversions.convert_color(lab_color, color_objects.sRGBColor)
print(repr(rgb_color))
# sRGBColor(rgb_r=1.045850317578614,rgb_g=0.47183611022803845,rgb_b=0.6825216680190419)
print((rgb_color.clamped_rgb_r, rgb_color.clamped_rgb_g, rgb_color.clamped_rgb_b))
# (1.0, 0.47183611022803845, 0.6825216680190419)

rawDescription: CIELAB is gain saturating when converting to float sRGB


code:
class YourView(generics.TypOfView):
    renderer_classes = (TemplateHTMLRenderer, JSONRenderer,)
    template_name = 'path_to_template.html'

rawDescription: How to handle web and mobile requests in django view

description: Handle web and mobile requests in django view


code:
urls = (
    '/(.*)', 'General'
)

class General:
    app_dir = 'www'

    def GET(self, path):
        root = os.path.abspath(os.path.join('.', os.pardir))
        dest = '%s/%s/index.html' % (root, self.app_dir)
        if path:
            dest = '%s/%s/%s' % (root, self.app_dir, path)
        with open(dest, 'r') as f:
            return f.read()
        return ''

rawDescription: Can web.py route static content with its builtin server?


code:
def compare_stocks(stock1, stock2, date):
    """ Compares stock data of two FinanceData objects at a certain time. """
    if isinstance(stock1, FinanceData) and isinstance(stock2, FinanceData):
        return 'comparison'

class FinanceData(object):
    def get_stock(self, date):
        """ Returns stock data in format XX, expects parameter date in format YY """
        raise NotImplementedError

class GoogleFinanceData(FinanceData):
    def get_stock(self, date):
        """ Implements FinanceData.get_stock() """
        return 'important data'

rawDescription: How to properly document hasattr() use

description: Properly document hasattr() use


code: sort(matches, key=lambda x: x.real_start, reverse=True)

rawDescription: Sort a list in Django

description: Sort a list in Django


code: line = i.strip().split(",", 1)

rawDescription: How to create a list in python when the elements contain commas

description: Create a list in python when the elements contain commas


code: sol = solvers.socp(c, Gq = G, hq = h)

rawDescription: cvxopt cone programming documentation

description: Cvxopt cone programming documentation


rawDescription: Write String of Hexadecimal Numbers to UTF-16 File


code:
cast((c_int*1)(1), POINTER(c_uint)).contents
cast((c_int*1)(-1), POINTER(c_uint)).contents

rawDescription: Casting between integer formats with Python ctypes


code:
# -*- coding: utf-8 -*-
do_it()

rawDescription: Python3.0: tokenize & BytesIO

description: Python3.0: tokenize & BytesIO


code:
num = 10
for i in range(num):
    setattr(self, "actionCOM%d" % i, QtGui.QAction(QtGui.QIcon(''), "COM%d" % i, self))
    action = getattr(self, "actionCOM%d" % i)
    action.setCheckable(True)
    self.COMPorts.append(action)

rawDescription: PyQT - creating a large list of actions

description: PyQT - creating a large list of actions