code:
import matplotlib.patheffects as path_effects

e = ax.errorbar(x,y,yerr, fmt='o',color='r',capthick=2,elinewidth=2, label='path effects')

e[1][0].set_path_effects([path_effects.Stroke(linewidth=4, foreground='black'),
                          path_effects.Normal()])
e[1][1].set_path_effects([path_effects.Stroke(linewidth=4, foreground='black'),
                          path_effects.Normal()])
e[2][0].set_path_effects([path_effects.Stroke(linewidth=4, foreground='black'),
                          path_effects.Normal()])

ax.legend(loc=0)

rawDescription: Border on errorbars in matplotlib/python


code:
# order by user_id, and in decreasing order of timestamp
qs = SampleModel.objects.order_by('user_id', '-timestamp')

# get distinct rows using user_id, this will make sure that the first entry for
# each user is retained and since we further ordered in decreasing order of
# timestamp for each user the first entry will have last row added
# for the user in the database.
qs = qs.distinct('user_id')

rawDescription: Create model for MySQL view and join on it


code:
message = "whatever"*1000
msgList = [message[i:i+444] for i in range(0, len(message), 444)]

rawDescription: Splitting string in while loop and appending to list


code:
def roman_to_int_repl(match):
    exclude = set(["LLC"])   # add any other strings you don't want to replace
    if match.group(0) in exclude:
        return match.group(0)
    return str(roman_to_int(match.group(0)))

rawDescription: Convert a string containing a roman numeral to integer equivalent


code:
data = []
with open('weather.txt') as weather_file:
    for line in weather_file:
        if line.startswith('Heat Index'):
            words = line.rstrip().split()
            heat_index = int(words[-4])
            report_time = int(words[-2])
            data.append([heat_index, report_time])

rawDescription: Parsing simple weather data

description: Parsing simple weather data


code:
from py2docx.elements.text import Text

class PageBreak(Text):
    def __init__(self):
        self.xml = """<w:r><w:br w:type="page"/></w:r>"""

    def _get_xml(self):
        return self.xml

rawDescription: Create docx via python (page breaks, tables) - possible?


code:
import unittest

class MyTestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(MyTestCase, self).__init__(*args, **kwargs)
        self.addTypeEqualityFunc(str, self.assertMultiLineEqual)

    def test_a(self):
        a = """hi
there
ok"""
        b = """bye
there
ok
whatever"""
        self.assertEqual(a,b)  # Will actually call self.assertMultiLineEqual

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

rawDescription: assertEqual only shows differences

description: AssertEqual only shows differences


code:
from tkinter import *
from pprint import pprint

root = Tk()
pprint(root.config())

rawDescription: How to get a list of all config args?

description: Get a list of all config args


code:
import os, sys
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.mycustomsettingsfile")
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(SETTINGS_DIR, os.pardir))
sys.path.append(PROJECT_PATH)
application = get_wsgi_application()

rawDescription: BASE_DIR output within a subfolder, DJANGO


code:
from PyQt4 import QtGui
from PyQt4 import QtCore

class Main(QtGui.QTreeView):

  def __init__(self):

    QtGui.QTreeView.__init__(self)
    model = QtGui.QFileSystemModel()
    model.setRootPath( QtCore.QDir.currentPath() )
    self.setModel(model)
    QtCore.QObject.connect(self.selectionModel(), QtCore.SIGNAL('selectionChanged(QItemSelection, QItemSelection)'), self.test)

  @QtCore.pyqtSlot("QItemSelection, QItemSelection")
  def test(self, selected, deselected):
      print("hello!")
      print(selected)
      print(deselected)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = Main()
    w.show()
    sys.exit(app.exec_())

rawDescription: Python: PyQt QTreeview example - selection


code:
gb = new_df.groupby('model')
gb.hist()

rawDescription: Select multiple groups from pandas groupby object


code:
def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
# !!! another occurrence of a "method attribute," an attribute
# assigned to a function object.

class PersonAdmin(admin.ModelAdmin):
    list_display = (upper_case_name,)

rawDescription: What method attributes are used in Django?


code:
def dump(obj, file, protocol=None):
    ForkingPickler(file, protocol).dump(obj)

class Popen(object):
    '''
    Start a subprocess to run the code of a process object
    '''
    _tls = thread._local()

    def __init__(self, process_obj):
        ...
        # send information to child
        prep_data = get_preparation_data(process_obj._name)
        to_child = os.fdopen(wfd, 'wb')
        Popen._tls.process_handle = int(hp)
        try:
            dump(prep_data, to_child, HIGHEST_PROTOCOL)
            dump(process_obj, to_child, HIGHEST_PROTOCOL)
        finally:
            del Popen._tls.process_handle
            to_child.close()

    @staticmethod
    def thread_is_spawning():
        return getattr(Popen._tls, 'process_handle', None) is not None

rawDescription: Understanding Multiprocessing: Shared Memory Management, Locks and Queues in Python


code:
import os

def serve_file():
    filename = request.args(0)
    path = os.path.join(request.folder, 'private', 'file_subfolder', filename)
    return response.stream(path)

rawDescription: Display a set of Images from a folder on Web2py


code: [x for x in range(5) if x != 2 and x != 3]

rawDescription: Python LIST functions not returning new lists


code: value = d.get(key, "empty")

rawDescription: Return None if Dictionary key is not available


code:
a, b = None, None
#makes (None, None) before unpacking and giving to a and b

rawDescription: Unpack assignment vs chained assignment

description: Unpack assignment vs chained assignment


code:
a = np.column_stack(maximas)
a[np.unique(a[:,0], return_index=True)[1]]

rawDescription: Extracting required indices from the array of tuples


code:
p = slice(1, 29)
section = s[p, p]
section.shape

rawDescription: Slice numpy matrix using vectors as indices


code: feature3 = [d.get('Feature3') for d in a]

rawDescription: Extract dictionary value from column in data frame


code:
reader = csv.DictReader(StringIO.StringIO(r.text))
list_of_dicts = list(reader)

rawDescription: Why does the parsing of csv file not break things into their 'logical' order?


code:
B.add_weighted_edges_from(
    [(row['domain'], row['subdomain'], 1) for idx, row in df.iterrows()],
    weight='weight')

rawDescription: Construct bipartite graph from columns of python dataframe


code:
class Speaker(list):
    def __init__(self):
        list.__init__(self)
        self.activated = True

    def talk(self, string):
        if self.activated :
            talk = string.replace("\n", "")
            if talk :
                self.append(talk)
            else:
                self.activated = False

        return self.activated

class SpeakerIndex(dict):
    def __init__(self, filepath, separator):
        """ Creation of index """
        dict.__init__(self)
        self.separator = separator

        self.talk = 0

        self.toSpeak = []
        self.hadSpeak = []
        with open(filepath, 'r') as data:
            for line in data:
                ##print("line: ",line)
                ##print("toSpeak: ",self.toSpeak)
                self.speakersFeed(line)
                #save and remove person tha should have speak
                for speaker in self.toSpeak:
                    self.save_speaker(speaker)
                self.toSpeak = self.hadSpeak
                self.hadSpeak = []

    def speakersFeed(self, line):
        """ parse a line """
        if self.separator in line:
            for speaker_action in line.split(self.separator)[1:]:
                ##print("action :",speaker_action)
                speaker = None
                #Take the good speaker
                if self.toSpeak:
                    speaker = self.toSpeak.pop(0)
                else:
                    speaker = Speaker()
                #process the content
                result = speaker.talk(speaker_action)
                ##print("speaker : ",speaker)
                #put the speaker where is needed depending of its state
                if result :
                    self.hadSpeak.append(speaker)
                else:
                    self.save_speaker(speaker)
        else:
            #save speaker that may be not ended at this point
            for speaker in self.toSpeak:
                self.save_speaker(speaker)
            self.talk +=1

    def speaker_id(self, speaker):
        """ Return an unique Id for speakers """
        number = int(speaker[0].split(" ")[2])
        return "talk{0}-speaker{1}".format(self.talk, number)

    def save_speaker(self, speaker):
        self[self.speaker_id(speaker)]=speaker
        ##print("saved :",speaker)

    def __str__(self):
        """ override the str() comportment """
        keylist = list(self.keys())
        keylist.sort()
        result = "{\n"
        for key in keylist:
            result += "\t" + str(key) + " : " + str(self[key]) + "\n"
        result += "}"
        return result

if __name__ == "__main__":
    index = SpeakerIndex("foo.txt", ";")
    print(str(index))

rawDescription: extracting column data in multiple rows

description: Extracting column data in multiple rows


rawDescription: Wxpython browse for or drag and drop folder


code:
test = __import__('os',globals(),locals())
for k in dir(test):
    globals()[k] = test.__dict__[k]

rawDescription: Importing everything ( * ) dynamically from a module


rawDescription: Python regex not working in code

description: Python regex not working in code


code:
for k in li:
    d[k] = d.setdefault(k,0) + 2

rawDescription: python dict add and modify operation

description: Python dict add and modify operation


code:
for excluded in excludeList:
    kolaDataList = filter(lambda l: excluded not in l, kolaDataList)

rawDescription: not in as a function in filter-function

description: Not in as a function in filter-function


rawDescription: Entry box text clear when pressed Tkinter


rawDescription: Timeit module for qgis plugin

description: Timeit module for qgis plugin


code:
@app.route('/', methods=['HEAD'])
def head():
    response = Response()
    response.headers.add('content-length', LENGTH)
    return response

rawDescription: Why does Apache/WSGI map HEAD to GET? How to speed up HEAD in Flask?


code:
minutes = results[1]
texts = results[2]
minutes, texts

rawDescription: How to select specific content from table type structure in html

description: Select specific content from table type structure in html


code:
'//ch[@num="1"][@bk="Book1"]/ver[@num="1"]'
#  ^      ^        ^           ^      ^
# ch node |        |           |      |
#  + attributes num = 1        |      |
#  + AND Book attribute = 1    |      |
#                           ver node  |
#                           + num attribut = 1

rawDescription: Python XML Parsing with Tag Specific Info


code:
mi = pd.MultiIndex.from_product([['col1', 'col2', 'col3'], ['a', 'b']])
df = pd.DataFrame(1, index=[0], columns=mi)
df

rawDescription: Dropping a single (sub-) column from a MultiIndex


code:
s=[b'GATC',b'CTAG'] # A list of byte strings
s
s = [t.decode() for t in s] # decoding the list to Unicode
s
for t in s:    # iterating over the strings and characters
 for c in t:
  print(t,c)

rawDescription: Python 3.4 dictionary output different from python 2.7


code:
s = 'aaa bbb ccc ddd'
result = s.split()[2:]

rawDescription: Regex for matching the third,fourth,fifth... word


code:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

fig=plt.figure()
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212)
ax1.set_ylim(0,100)
ax2.set_ylim(40,70)

# set ticks every 10
tickspacing = 10
ax1.yaxis.set_major_locator(ticker.MultipleLocator(base=tickspacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(base=tickspacing))

plt.show()

rawDescription: same scale of Y axis on differents figures

description: Same scale of Y axis on differents figures


code:
coords = np.vstack([np.random.multivariate_normal(coordstest[i,:],
               [[10,0],[0,10]], 200) for i in range(10)])

rawDescription: Localized random points using numpy and pandas


code:
plt.plot(df['time'], fit_fn(x), 'k-')
plt.plot(df['time'], df['data'], 'go', ms=2)

rawDescription: Linear regression with panda time series


code:
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patches as mpatches
from matplotlib.path import Path
import numpy as np

# Create some lons/lats
lats = np.linspace(20,40,50)
lons = np.linspace(110,130,50)
lons,lats = np.meshgrid(lons,lats)

# Some data with 'cloud'.
thedata = np.zeros_like(lats)
thedata[5:8, 7:13] = 1

ax = plt.axes()

mycmap = mcolors.ListedColormap(['white', 'black'])
bounds=[0, 0.5, 1]
norm = mcolors.BoundaryNorm(bounds, mycmap.N)

im = ax.pcolormesh(lons, lats, thedata, cmap=mycmap,
                   norm=norm)

data_extent = np.array((lons[0,0], lons[-1,-1], lats[0,0], lats[-1,-1]))

# Make the extent larger to see a margin outside of the domain
ax.set_xlim(data_extent[:2] + [-1, 1])
ax.set_ylim(data_extent[2:] + [-1, 1])

# Create a path which has the exterior of the map, with an interior of the data we care about.
path_with_hole = Path([[-180, 90],
                       [180, 90],
                       [180, -90],
                       [-180, -90],
                       [-180, 90],
                       [data_extent[0], data_extent[2]],
                       [data_extent[1], data_extent[2]],
                       [data_extent[1], data_extent[3]],
                       [data_extent[0], data_extent[3]],
                       [data_extent[0], data_extent[2]]],
                      codes=[Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
                             Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])

geom = mpatches.PathPatch(path_with_hole, facecolor='lightgrey',
                          edgecolor='white',
                          hatch='xxxx', alpha=0.6)
ax.add_patch(geom, )

plt.show()

rawDescription: Cartopy background color (outside of data domain)


code:
def split(s):
    return s.split()

pickle.dumps(split)
tfidf_vectorizer = TfidfVectorizer(analyzer=split)
type(pickle.dumps(tfidf_vectorizer))

rawDescription: how to pickle customized vectorizer?

description: Pickle customized vectorizer


code:
@login_required
def show_info(request):
    url = get_base_url  + "/api/get-info/"  # http://localhost:8000/api/get-info/
    r = requests.get(url, cookies=request.COOKIES)
    return HttpResponse(r.json())

rawDescription: Alternative of Requests in django

description: Alternative of Requests in django


code:
for i in range(len(words)):
    words[i]=words[i].rstrip()

rawDescription: manipulating list items python

description: Manipulating list items python


code:
def count():
    # ... same
    print ("Database version : %s " % data)
    # return the database result from the 'count' function
    return data

rawDescription: connecting with database and showing result on localhost

description: Connecting with database and showing result on localhost


code:
dialog = driver.find_element_by_css_selector("div.review-dialog-list")
last_scroll_height = 0

while True:
    reviews = driver.find_elements_by_css_selector("div._ju")
    driver.execute_script("arguments[0].scrollIntoView();", reviews[-1])

    # adding artificial delay (don't tell anyone I'm using sleep here)
    time.sleep(1)

    # if scroll height has not changed - exit
    scroll_height = driver.execute_script("return arguments[0].scrollHeight;", dialog)
    if scroll_height == last_scroll_height:
        break
    else:
        last_scroll_height = scroll_height

print(len(reviews))

rawDescription: How to scroll a div when ajax is used to load data in python selenium

description: Scroll a div when ajax is used to load data in python selenium


code:
i = ["user_arr", 100, True]
locals()[i[0]] = prev_def_func(*i[1:])
print(user_arr)

rawDescription: Unpack a list so the first element is assigned the result of a function operated on the following elements


code: samples

rawDescription: randomly select multichoice options

description: Randomly select multichoice options


code:
import dis
def f():
  x = 'google.com'
  return x is 'google.com'

dis.dis(f)

rawDescription: Why does the "is" keyword have a different behavior when there is a dot in the string?


code:
# -*- coding: iso-8859-1 -*-
# from http://code.activestate.com/recipes/576694
from orderedset import OrderedSet

class AreaFisicoAmbiental(object):
    def __init__(self, persona, datos):
        self._members = OrderedSet()
        self.persona = persona
        self.tipoEdificacion = datos[0]
        self.tipoDeParedes = datos[1]

    def __setattr__(self, name, value):
        object.__setattr__(self, name, value)
        if name != '_members':
            self._members.add(name)

    def __delattr__(self, name):
        if name != '_members':
            object.__delattr__(self, name)
            self._members.discard(name)

    def methodA(self, value1, value2):  # add some members
        self.attribute1 = value1
        self.attribute2 = value2

    def methodB(self):
        del self.attribute1  # remove a member

if __name__ == '__main__':
    a = AreaFisicoAmbiental('Martineau', ['de albañilería', 'vinilo'])
    a.methodA('attribute1 will be deleted', 'but this one will be retained')
    a.methodB()  # deletes a.attribute1
    a.attribute3 = 42  # add an attribute outside the class

    print('current members of "a":')
    for name in a._members:
        print('  {}'.format(name))

rawDescription: Generate a list of class members that preserves their definition order


rawDescription: How to split a character in list and must still exist in python?

description: Split a character in list and must still exist in python


code: self.syn0norm = (self.syn0 / sqrt((self.syn0 ** 2).sum(-1))[..., newaxis]).astype(REAL)

rawDescription: Gensim Word2vec storing attribute syn0norm


code:
from collections import defaultdict, Counter
data = {'cat':'red', 'a':1, 'b':2}, {'cat':'red', 'a':3, 'b':3}, {'cat':'blue', 'a':1, 'b':3}
totals = defaultdict(Counter)
for item in data:
    cat = item.pop('cat')
    totals[cat] += Counter(item)

totals
totals['blue']
totals['red']

rawDescription: python dictionary with two running totals

description: Python dictionary with two running totals


code: expressionangle2 = sympy.log( n ).as_real_imag()[1]

rawDescription: Python Sympy angle of a complex number?

description: Python Sympy angle of a complex number


code:
False
True

rawDescription: How can I check if an ip is in a network in python

description: Check if an ip is in a network in python


code:
conn.execute("""INSERT INTO users (username, email)
                    VALUES ("Alice", "alice@wonderland.com");""")

rawDescription: SQLite / Python database retrieval and comparison


code: result

rawDescription: String searching library's outcome - bug or feature or my coding error?


code:
[{'moduletitle': 'Parent Module 1',
  'position': '1',
  'submodules': [{'content': [],
                  'moduletitle': 'sub module 11',
                  'position': '1'},
                 {'content': [],
                  'moduletitle': 'sub module 22',
                  'position': '2'}]},
 {'moduletitle': 'Parent Module 2',
  'position': '2',
  'submodules': [{'content': [{'content': 'Dj.docx',
                               'contenttitle': 'test content',
                               'contenttype': 'Pdf/Doc',
                               'coursemoduleid': 55341,
                               'position': '10'}],
                  'moduletitle': 'sub module 1',
                  'position': '1'},
                 {'content': [],
                  'moduletitle': 'sub module 2',
                  'position': '3'}]},
 {'moduletitle': 'Parent Module 3', 'position': '3', 'submodules': []}]

rawDescription: Python code not working similar in Jinja Template


code: os.system('SMILExtract -C config/demo/demo1_energy.conf -I {0}.wav -O csv/user.csv'.format(somevar))

rawDescription: variable inside a string used as an os command in python

description: Variable inside a string used as an os command in python


code:
from multiprocessing import Process, Queue
import time, tkinter, queue, random, sys

class Test:
    def __init__(self, root):
        self.root = root
        txt = tkinter.Text(root)
        txt.pack()

        self.q = Queue()

        p = Process(target=self.bg)
        p.start()

        self.checkqueue()
        print('__init__ done', end=' ')

    def bg(self):
        print('Starting bg loop', end=' ')
        n = 42
        while True:
            # Burn some CPU cycles
            (int(random.random() * 199999)) ** (int(random.random() * 1999999))
            n += 1
            self.q.put(n)
            print('bg task finished', end=' ')

    def checkqueue(self):
        try:
            print(self.q.get_nowait(), end=' ')
        except queue.Empty:
            print('Queue empty', end=' ')

        sys.stdout.flush()

        # Run myself again after 1 second
        self.root.after(1000, self.checkqueue)

root = tkinter.Tk()
Test(root)
root.mainloop()

rawDescription: Background Process Locking up GUI Python


code: [list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]

rawDescription: python sorting two lists

description: Python sorting two lists


code: [(i,j,k) for i in S for j in S for k in S if i+j+k == 0]

rawDescription: Finding all combinations of length 3 from a set of numbers such that sum(combination) is 0


code: molecules = relationship("Molecule", secondary=molecule2atom, backref="atoms")

rawDescription: Many to many relationship with a composite key on SQLAlchemy


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({
        'label' : ['a', 'b', 'c', 'b','a', 'c', 'b', 'a'],
        'x1' : np.random.choice(2, 8),
        'x2' : np.random.choice(2, 8),
        'x3' : np.random.choice(2, 8)})

pd.pivot_table(df, index='label').transpose().apply(np.count_nonzero)

rawDescription: Pandas histogram from count of columns

description: Pandas histogram from count of columns


rawDescription: how to specify the partition for mapPartition in spark

description: Specify the partition for mapPartition in spark


rawDescription: Converting String Date to Timestamp and back python


code:
from pyspark.sql.functions import collect_list, struct, col

df = sc.parallelize([
    (1, 100, "2012-01-01 00:00:00"),
    (1, 200, "2016-04-04 00:00:01")
]).toDF(["user_id","product_id","timestamp_gmt"])

pi = (collect_list(struct(col("product_id"), col("timestamp_gmt")))
    .alias("purchase_info"))

df.groupBy("user_id").agg(pi)

rawDescription: Pyspark: Rename a dictionary key which is within a DataFrame column


code:
class freezefunc:
    def __init__(self, func, **funcargs):
        self.func = func
        self.funcargs = {}

    def __call__(self, **kwargs):
        self.funcargs.update(kwargs)
        return self.func(**self.funcargs)

def func(a):
    print(a)

rawDescription: Freezing Function Arguments

description: Freezing Function Arguments


code:
myarray = np.zeros((64, 52))
myarray[3:-3,3:-3] = np.random.uniform(0, 5000, (64-6,52-6))
myarray
myarray[myarray==0] = np.nan
myarray

rawDescription: zero values to nan values in an array of Python

description: Zero values to nan values in an array of Python


code: first_list, second_list, third_list = [l[i::3]for i in range(3)]

rawDescription: split a list into three lists with a stepsize and a starting point

description: Split a list into three lists with a stepsize and a starting point


code:
ax.tripcolor(triang, z2**2, shading='gouraud', cmap='Greens')
ax.tripcolor(triang, z1**2, shading='gouraud', cmap='Reds')

rawDescription: Plot multiple sets of data with tripcolor - transparency in colormaps


code:
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
import numpy as np
x = np.linspace(0,5,100)
y = np.sin(x)

plt.plot(x,y)
ax = plt.gca()

polygon = Polygon([[.1,.1],[.3,.2],[.2,.3]], True, transform=ax.transAxes)
ax.add_patch(polygon)

plt.show()

rawDescription: Matplotlib artists to stay the same size when zoomed in?


code: if 0: foo = Bar()

rawDescription: Komodo 7 or 8 code completion for django


code:
def valid(name):
    return not name[0].isdigit() and all(c.isalnum() or c == '_' for c in name)

rawDescription: Python- checking for letters, numbers, and underscore character.


code:
from django.shortcuts import get_object_or_404, redirect, render

def choose_city(request):
    return redirect('deals_by_city', city_id=request.POST['city'])

def deals_by_city(request, city_id):
    city = get_object_or_404(City, pk=city_id)
    deals = Deal.objects.filter(city=city)
    return render(request, 'deals_by_city.html', {'city': city,
                                                  'deals': deals})

rawDescription: Django forms and passing data between views/pages


code:
for i in kinetic_parameters:
        d[i[1]]={}
for i in kinetic_parameters:
        d[i[1]][i[2]]=i[3]

rawDescription: How can I correct my code to produce a nested dictionary?

description: Correct my code to produce a nested dictionary


rawDescription: Splicing a list at different intervals based on a value of a list in python


code: all_the_inputs = [ process_value(x) for y in all_the_stuff for x in y ]

rawDescription: How much nesting of python list comprehensions is appropriate?


rawDescription: get previous row's value and calculate new column pandas python

description: Get previous row's value and calculate new column pandas python


code:
from dis import dis
code = "[i for i in xrange(100)]"
dis(compile(code, '', 'single'))

rawDescription: List comprehension optimization

description: List comprehension optimization


code:
reqset = {re.search('SRC=(\S+)',l).group(1) for l in content}
print('\n'.join(reqset))

rawDescription: How to get the nth parameter of a list with delimiter space in python

description: Get the nth parameter of a list with delimiter space in python


code:
import sys
import codecs

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
inData = codecs.getreader('utf-8')(sys.stdin)

(last_key, tot_cnt) = (None, 0)
for line in inData:
    (key, val) = line.strip().split("\t")
    if last_key != key:
        if(tot_cnt > 1):
            sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))
        (last_key, tot_cnt) = (key, int(val))
    else:
        (last_key, tot_cnt) = (key, tot_cnt + int(val))

if last_key and tot_cnt > 1:
    sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))

rawDescription: How to get the Reducer to emit only duplicates

description: Get the Reducer to emit only duplicates


code: return Polynomial(*poly)

rawDescription: creating class instances from a text file in python

description: Creating class instances from a text file in python


code: (ctypes.c_int * len(x))(x)

rawDescription: What does (ctypes.c_int * len(x))(*x) do?


code:
# add some items with associated data
for identifier in (123, 456, 789):
    combo.addItem('text', identifier)

rawDescription: Inserting hidden data into a combobox pyqt


code:
a = float('nan')
print(a)
print(a + 2)
a == a
import math
math.isnan(a)
# Python 3.5+
math.isnan(math.nan)

rawDescription: Assigning a variable NaN in python without numpy


code:
def four():
    print ('this is four')

rawDescription: Directory setup for python modules

description: Directory setup for python modules


code:
from pyplot import hist
from matplotlib.dates import date2num
hist(date2num(list_of_dates), cumulative=True)

rawDescription: Plotting a cumulative graph of python datetimes


code: M = genfromtxt (file_iterator(filename, R1, R2), delimiter=delimiter, cols=range(C1,C2+1))

rawDescription: numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file

description: Numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file


code:
axes = fig.gca(projection='3d')

t_step = 8
for t_pos in range(0, len(t)-1, t_step):
    t_val_start = t[t_pos]
#     t_val_end = t[t_pos+1]

    vel_start = [rx(t_val_start), ry(t_val_start), t_val_start]
    vel_end = [rx(t_val_start)+vx(t_val_start), ry(t_val_start)+vy(t_val_start), t_val_start]
    vel_vecs = list(zip(vel_start, vel_end))
    vel_arrow = Arrow3D(vel_vecs[0],vel_vecs[1],vel_vecs[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="g")
    axes.add_artist(vel_arrow)

    acc_start = [rx(t_val_start), ry(t_val_start), t_val_start]
    acc_end = [rx(t_val_start)+ax(t_val_start), ry(t_val_start)+ay(t_val_start), t_val_start]
    acc_vecs = list(zip(acc_start, acc_end))
    acc_arrow = Arrow3D(acc_vecs[0],acc_vecs[1],acc_vecs[2], mutation_scale=20, lw=1, arrowstyle="-|>", color="m")
    axes.add_artist(acc_arrow)

axes.plot(rx(t), ry(t), t)
plt.xlim(-2*np.pi,2*np.pi)
plt.ylim(-6,6)

rawDescription: Python - Plotting velocity and acceleration vectors at certain points


code: [(el[0], el[1]) for el in grouper(2, elements)]

rawDescription: Logical task for Python programmers. Make tuple of lists from list


rawDescription: How do I generate 8 different random numbers in python?

description: Generate 8 different random numbers in python


rawDescription: How to limit decimal places when using complex numbers

description: Limit decimal places when using complex numbers


code: [ p for p in database if type(p.data) == Foo ]

rawDescription: Storing information on points in a 3d space


code:
bbox = dict(boxstyle='round,pad=0.5', fc='green', alpha=0.3)
ha = 'right'
va = 'bottom'
arrowprops = dict(arrowstyle='->', connectionstyle='arc3,rad=0')
xytext = (-20, 20)
textcoords = 'offset points'

data.Price.plot(marker='*')
annotate_plot(data, 'Price', 'Volume', bbox=bbox, ha=ha, va=va,
              xytext=xytext, textcoords=textcoords)

plt.show()

rawDescription: Include labels for each data point in pandas plotting


code:
t = np.array([[0, 1, 2], [1, 2, 3], [3, 2, 1]])
import matplotlib.pyplot as plt
plt.imshow(t)
plt.show()
plt.imshow(t, interpolation='nearest')
plt.show()

rawDescription: Plot 2D Numpy Array

description: Plot 2D Numpy Array


code:
data = data.replace('POLYGON ((', '').replace('))', '').strip()
res = []
for rec in data.split(', '):
    res.append(tuple(float(val) for val in rec.split()))

rawDescription: creating a list of tuples (x, y) from a string

description: Creating a list of tuples (x, y) from a string


code:
def is_low(n):
    if n <= 20:
        return True
    if n > 20:
        return False

rawDescription: How to limit the parallel python code for specific/ required value

description: Limit the parallel python code for specific/ required value


code:
info = [
    {
        "_id": {
            "$oid": "55c737029380f82fbf52eec3"
        },
        "created_at": {
            "$date": 1439129906376
        },
        "desc": "Description.....",
        "title": "This is title"
    },
    #etc...
]

def fix_array(info):
    ''' Change out dict items in the following case:
           - dict value is another dict
           - the sub-dictionary only has one entry
           - the key in the subdictionary starts with '$'
        In this specific case, one level of indirection
        is removed, and the dict value is replaced with
        the sub-dict value.
    '''
    for item in info:
        for key, value in item.items():
            if not isinstance(value, dict) or len(value) != 1:
                continue
            (subkey, subvalue), = value.items()
            if not subkey.startswith('$'):
                continue
            item[key] = subvalue

fix_array(info)
print(info)

rawDescription: Get rid of Mongo $ signs in JSON

description: Get rid of Mongo $ signs in JSON


code:
from itertools import groupby

unique_items = [key for key, group in groupby(a) if len(list(group)) == 1]

rawDescription: Find the occurrences of unique element in list in python


code: outlists = [[func(j*2) for j in y] for func in functions]

rawDescription: Loop through function in python generating separate list for each set of data


code:
sorted_values = sorted(the_values, key=lambda x: x[1])   #sort by second column
# ...
#use sorted_values, instead of the_values
sorted_values.sort(key=lambda x: x[1], reverse=True)
# ...

rawDescription: Python: Concatenating and formatting strings/floats while writing to a csv


code: from six import b

rawDescription: How to define a binary string in Python in a way that works with both py2 and py3?

description: Define a binary string in Python in a way that works with both py2 and py3


code:
y = df.iloc[:, -1].values
X = df.iloc[:, :-1].values

rawDescription: Correct and most efficient way to pull data in to a pandas data frame for machine learning


code:
import urllib
import urllib2

url = 'http://acme.com:8080/wm/core/controller/switches/json'
params = urllib.urlencode({
  'firstName': 'John',
  'lastName': 'Doe'
})
response = urllib2.urlopen(url, params).read() # a POST request

rawDescription: How do i use native rest api in Django frame work?

description: Use native rest api in Django frame work


code:
new_dict = {}
names = [] # used map 0, 1, 2 to `name`, `last`, `middle`
with open('/path/to/test.txt') as f:

    # Handle header (the first) line: `name, last, middle`
    for name in next(f).split(','): # split fields by `,`
        name = name.strip()  # remove surrounding spaces
        names.append(name)
        new_dict[name] = []  # initialize dictionary with empty list.

    # Handle body.
    for line in f:
        # enumerate(['bob', 'jones', 'm']) return an interator
        #    that generates (0, 'bob'), (1, 'jones'), (2, 'm')
        for i, value in enumerate(line.split(',')):
            new_dict[names[i]].append(value.strip())

print(new_dict)

rawDescription: File, strip each line and add to key in dictionary


code:
r = requests.get('http://github.com', allow_redirects=False)
r.status_code
r.history

rawDescription: python: how to tell if a link redirects to another?

description: Python: how to tell if a link redirects to another


code:
try:
    from pkg_resources import working_set
except ImportError:
    pass
else:
    for entry_point in working_set.iter_entry_points(GROUP_NAME,
                                                     method):
        func = entry_point.load(require=True)
        break

rawDescription: Examples of entry_point usage

description: Examples of entry_point usage


code:
class A:
    def __init__(self, callback):
        self.callback(1, 2)

    # now it won't get passed self
    callback = staticmethod(callback)

rawDescription: Preventing a class's function attributes from being passed self as the first arg


rawDescription: How to Print An Odd Number of Backslashes in Python


code:
cd('/')
cmo.createCluster('Cluster-0')
cd('/Clusters/Cluster-0')
cmo.setClusterMessagingMode('unicast')
...

rawDescription: Anyone tried Cluster automation with WLST?


code: np.where(df.applymap(lambda x: x == ''))

rawDescription: Find empty or NaN entry in Pandas Dataframe


rawDescription: Django-Tables column templates with django permissions


code:
import os
def convert(in_fname, out_fname = None):
    # start by sanitizing parameters
    if out_fname is None:
        basename, ext = os.path.splitext(in_fname)
        out_fname = basename + ".faa"

    # read data
    with open(in_fname) as inf:
        data = inf.read()   # or inf.readlines()

    # do conversion
    result = do_conversion(data)

    # write result
    with open(out_fname, "w") as outf:
        outf.write(result)  # or .write("\n".join(result))

rawDescription: Making default output file dependent on input file


code:
from flask import json
@app.route('/get_data', methods=['GET'])
def get_data():
    #get time and path
    time=...
    path=...
    return json.dumps({time:time,url:path}), 200, {'Content-Type':'application/json'}

rawDescription: Dynamically update image using Python Flask AJAX


rawDescription: Retrieving JSON objects from a text file (using Python)


rawDescription: How to read a file block-wise in python

description: Read a file block-wise in python


code: new_list = old_list

rawDescription: Sign seperating function overwrites passed in list instead of returning new one


code:
def test_n_props(self):
    for cur_prop in petersen_prop:
        func = getattr(myfuncs, cur_prop)
        self.assertTrue(func(self.adj,**self.args) ==
                        petersen_prop[cur_prop])

rawDescription: Unittest from a dictionary of functions and values


rawDescription: How to save Multi-layered dictionary to csv

description: Save Multi-layered dictionary to csv


code: set([np.array(range(10)), 22])

rawDescription: Python: Intersection of two lists of lists


code:
links = {'fox': [], 'dog': []}
text = "The quick brown fox jumps over the lazy dog. fox. Redfox."
reg_iter(text, links)

rawDescription: Positions of substrings in string

description: Positions of substrings in string


code:
from multiprocessing import Pool
from collections import defaultdict

def matches(wordset_100, row):
    return wordset_100.intersect(row.phrase.split(" ")), row

if __name__ == "__main__":
    accu = defaultdict(int)
    p = Pool()
    wordset_100 = set(worldlist_100)
    for m, r in p.map(matches, data_3k):
        for word in m:
            accu[word] += r.number

rawDescription: Searching values in a large matrix

description: Searching values in a large matrix


code:
from itertools import repeat
def simple_gen():
    for number in range(5):
        yield number ** 2
def recreate(callable, count=None):
    for c in repeat(callable, count):
        for val in c():
            yield val
list(recreate(simple_gen, 2))

rawDescription: Chain repetitions of same generator in python


code:
class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj)
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name != "car":
            kwargs.pop('obj', None)
        return super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        person = kwargs.pop('obj', None)
        if db_field.name == "car" and person:
            kwargs['queryset'] = Cars.objects.filter(owner=person)
        return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

rawDescription: How to get the current model instance from inlineadmin in Django

description: Get the current model instance from inlineadmin in Django


code:
from datetime import datetime

start_date = "2011-01-01"
stop_date = "2013-05-01"

start = datetime.strptime(start_date, "%Y-%m-%d")
stop = datetime.strptime(stop_date, "%Y-%m-%d")

from datetime import timedelta
while start < stop:
    start = start + timedelta(days=1)  # increase day one by one

rawDescription: Iterating over date in python

description: Iterating over date in python


code: timeit.timeit('a = cplxarr.copy(); a.real *= factarr ',setup='from __main__ import factarr,cplxarr')

rawDescription: Scale the real part of complex numpy array


code:
from pyspark.mllib.evaluation import MulticlassMetrics
from operator import itemgetter

metrics = MulticlassMetrics(
    labels_and_preds.map(itemgetter("actual", "predicted")))

metrics.confusionMatrix().toArray()
## array([[ 2.,  0.],
##        [ 0.,  2.]])

rawDescription: How to use spark Naive Bayes classifier for text classification with IDF?

description: Use spark Naive Bayes classifier for text classification with IDF


code:
suma = array[::2]
return sum(suma)

rawDescription: In Python, loop for don't "save" items with same value in a list


code:
from Tkinter import *

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

rawDescription: How to set default text for a Tkinter Entry widget

description: Set default text for a Tkinter Entry widget


code: entropy = unpack('I', buf[8:12])

rawDescription: Can't reproduce working C bitwise encoding function in Python


code:
d
for i,j in d.items():
    print(i,j)

rawDescription: Searching lists and comparing with another not exact list


code: 'Hafst\xc3\xa4tter' == 'Hafstätter'

rawDescription: Python list items encoding

description: Python list items encoding


code: return (model-data)/data

rawDescription: Fitting two non-linear models to data

description: Fitting two non-linear models to data


code:
Example #1:
class MetaOne(metaclass=ABCMeta):
    pass

class Eggs(MetaOne):
    pass

class Spam(Eggs):
    pass

rawDescription: How to apply a metaclass to all my class without hardcoding it in the class declaration

description: Apply a metaclass to all my class without hardcoding it in the class declaration


code:
import sys
import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg
from PySide import QtGui, QtCore

def mathTex_to_QPixmap(mathTex, fs):

    #---- set up a mpl figure instance ----

    fig = mpl.figure.Figure()
    fig.patch.set_facecolor('none')
    fig.set_canvas(FigureCanvasAgg(fig))
    renderer = fig.canvas.get_renderer()

    #---- plot the mathTex expression ----

    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    ax.patch.set_facecolor('none')
    t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs)

    #---- fit figure size to text artist ----

    fwidth, fheight = fig.get_size_inches()
    fig_bbox = fig.get_window_extent(renderer)

    text_bbox = t.get_window_extent(renderer)

    tight_fwidth = text_bbox.width * fwidth / fig_bbox.width
    tight_fheight = text_bbox.height * fheight / fig_bbox.height

    fig.set_size_inches(tight_fwidth, tight_fheight)

    #---- convert mpl figure to QPixmap ----

    buf, size = fig.canvas.print_to_buffer()
    qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1],
                                                  QtGui.QImage.Format_ARGB32))
    qpixmap = QtGui.QPixmap(qimage)

    return qpixmap

rawDescription: Displaying LaTeX in pyQt/pySide QTableWidget


code:
WSGIScriptAlias /admin /path/to/django/my_app/wsgi.py
WSGIScriptAlias /api   /path/to/django/my_app/wsgi.py

rawDescription: Apache config for static site on root, and Django on sub-locations


rawDescription: Using matplotlib how could I plot a histogram with given data in python


code:
[['assign (resid 3 and name H ) (resid 18 and name H ) 2.5 2.5 2.5 ! note '
  'string 1'],
 ['assign (resid 44 and name H ) (resid 53 and name H ) 2.5 2.5 2.5 ! note '
  'string 4',
  'assign (resid 53 and name H ) (resid 44 and name H ) 2.5 2.5 2.5 ! note '
  'string 5 DUPLICATE ! note string 5',
  'assign (resid 53 and name H ) (resid 44 and name H ) 2.5 2.5 2.5 ! note '
  'string 6 DUPLICATE ! note string 6'],
 ['assign (resid 42 and name H ) (resid 55 and name H ) 2.5 2.5 2.5 ! note '
  'string 3'],
 ['assign (resid 16 and name H ) (resid 5 and name H ) 2.5 2.5 2.5 ! note '
  'string 2']]

rawDescription: Python Find Duplicate with Note String Preservation


code:
playerdata = responser.json()
playerdata[0]
playerdata[1]

rawDescription: Type error with json item

description: Type error with json item


code: parser.add_argument('--library', nargs=3, type=NargsTypeChecker((int, float, str)))

rawDescription: Argparser and complex types

description: Argparser and complex types


code: [ int(x) for y in List1 for x in y.split() ]

rawDescription: Turn a List of Str into a List of Int (Python)


Dan

city: San Francisco

fav_food: Mac and Cheese

rawDescription: Google cloud endpoint RequestMessage with multiple fields resolution


code:
import numpy as np
data1d = np.arange(10)
data1d
data2d = np.arange(20).reshape(2,10)
data2d
np.atleast_2d(data2d) # <-- No change!
np.atleast_2d(data1d) # <-- Makes it a "row vector"
np.column_stack([data2d]) # <-- No change (note the []!)
np.column_stack([data1d]) # <-- Makes it a column vector

rawDescription: determine number of rows of an (M,N) array and (M,) array with same function

description: Determine number of rows of an (M,N) array and (M,) array with same function


code: triple1pwm = [x / 255.0 * 100 for x in triple1]

rawDescription: Python: How to convert a rgb or hex value to single color values


rawDescription: Python pandas column merging

description: Python pandas column merging


code:
import time

def timed(f):
    def dec(*args, **kwargs):
        verbose = kwargs.pop('verbose', False)
        t = time.clock()

        ret = f(*args, **kwargs)

        if verbose:
            print("%s executed in %ds" % (f.__name__, time.clock() - t))

        return ret

    return dec

@timed
def add(a, b):
    return a + b

print(add(2, 2, verbose=True))

rawDescription: Function Decorators

description: Function Decorators


code:
from uuid import uuid4
from google.appengine.ext import db
from google.appengine.api import memcache

cache = memcache.Client()

class InstanceStamp(db.Model):
    code = db.StringProperty()

    INSTANCE_STAMP_KEY = "instance_stamp"

    @classmethod
    def get_stamp(cls):
        cache_key = cls.INSTANCE_STAMP_KEY
        stamp_code = cache.get(cache_key)
        if stamp_code is None:
            code = uuid4().hex
            stamp = cls.get_or_insert('instance_stamp', code=code)
            if stamp is not None:
                cache.set(cache_key, stamp.code, 300)
                stamp_code = stamp.code
        return stamp_code

rawDescription: In Python App Engine How Do I Uniquely Identify An Instance Of My App Running On The Dev SDK?


code:
class Test:
    pass

rawDescription: Cython: share pure python module

description: Cython: share pure python module


code: adict = {"Adap1": Adap1, "Adap2": Adap2, "Adap3": Adap3, "Adap4": Adap4}

rawDescription: How to change a global variable in python?

description: Change a global variable in python


code:
for r in rangesets:
    ra = compose(r, algo_001)
    ra(lsrc)

rawDescription: python, functions combination via names and chain them to invoke in-a-go?

description: Python, functions combination via names and chain them to invoke in-a-go


code:
import asyncio
from test import Test

async def main():
    print("entering with")
    async with Test() as t:
        print("in here")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

rawDescription: Coroutine in python between 3.4 and 3.5, How can I keep backwords compatibility?


code:
a = {'foo': 'bar'}
b = a
b
a.clear()
b

rawDescription: Python The appended element in the list changes as its original variable changes


code:
import Tkinter

coordinates = [[25, 40], [410, 40], [650, 40],
               [35, 180], [200, 180], [410, 180], [655, 180]]
message = "Hello, do you wanna push to master?".split(' ')

labels = []
interval = 0

root = Tkinter.Tk()
root.geometry("750x210")

for (x,y), msg in zip(coordinates, message):
    lab = Tkinter.Label(root, text=msg)
    labels.append(lab)
    root.after(interval, lambda a=x,b=y,l=lab:l.place(x=a, y=b))
    interval += 500

root.mainloop()

rawDescription: Tkinter place widgets from a list using a loop


code:
desc = {'names':('name','Color'),'formats':('a3','3f')}
colorlist = np.array([('ABC', (1, 2, 3)), ('CBA', (3, 2, 1))], desc)
colorlist[colorlist['name']=='ABC']['Color'][0]

rawDescription: Tuple Numpy Data Type

description: Tuple Numpy Data Type


rawDescription: Python permutations

description: Python permutations


code:
def func_you( lambdafunc1, lambdafunc2, lambdafunc3, lambdafunc4):
    return lambda x: lambdafunc1(x) * lambdafunc2(x) * lambdafunc3(x) * lambdafunc4(x)

rawDescription: A function that returns a function (in python)


code:
x = numpy.empty([1], dtype=object)
x[:] = [Foo()]

rawDescription: Numpy arrays containing iterable objects


code: ax3.plot_surface(ti, xi, u_int, cmap=cm.coolwarm)

rawDescription: Why is my 2D interpolant generating a matrix with swapped axes in SciPy?


code:
import string
import random
...
N = 20  # Length of the string we want, adjust as appropriate
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

rawDescription: How to limit one session from any browser for a username in flask?

description: Limit one session from any browser for a username in flask


code:
from System.Reflection import BindingFlags

# you can omit the flags if you want all public .NET members
flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly

members = instance.GetType().GetMembers(flags)
dir_members = [ mi.Name for mi in members ]
print(dir_members)

rawDescription: ironpython: any way to distinguish my methods from inherited methods in c# defined class?

description: Ironpython: any way to distinguish my methods from inherited methods in c# defined class


code:
if settings.DATABASE_NAME != 'my_test_db':
    sys.exit("You cannot run tests using the %s database. Please switch DATABASE_NAME to my_test_db in settings.py" % settings.DATABASE_NAME)

rawDescription: How do I test a django database schema?

description: Test a django database schema


code:
lst = [3 * [None] for i in range(3)]
lst[0][0] = 2
lst

rawDescription: python operator "*" with List， any others like it?

description: Python operator "*" with List， any others like it


code:
import os
import subprocess
import sys
import time

scripts = sys.argv[1:]
mtimes = {script: os.stat(script).st_mtime for script in scripts}
while True:
    for script in scripts:
        mtime = os.stat(script).st_mtime
        if mtime != mtimes[script]:
            subprocess.call([script], shell=True)
            mtimes[script] = mtime
    time.sleep(250)

rawDescription: Automatically run python code on save

description: Automatically run python code on save


rawDescription: Decimal to hex in python

description: Decimal to hex in python


code:
Z_square = linkage((DF_dissm.values),method="average")
Z_triu = linkage(np.triu(DF_dissm.values),method="average")
Z_tril = linkage(np.tril(DF_dissm.values),method="average")

rawDescription: Triangle vs. Square distance matrix for Hierarchical Clustering Python?


code: with open(from_file) as f: indata = f.read()

rawDescription: Explicitly closing files in python

description: Explicitly closing files in python


code:
import boto.rds
regions = boto.rds.regions()

rawDescription: Difficulty in finding the Region names in AWS rds


code:
def __unicode__(self):
    """
    Return a string representation for a particular DataFrame

    Invoked by unicode(df) in py2 only. Yields a Unicode String in both
    py2/py3.
    """
    buf = StringIO(u(""))
    if self._info_repr():
        self.info(buf=buf)
        return buf.getvalue()

    max_rows = get_option("display.max_rows")
    max_cols = get_option("display.max_columns")
    if get_option("display.expand_frame_repr"):
        width, _ = fmt.get_console_size()
    else:
        width = None
    self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,
                   line_width=width, show_dimensions=True)

    return buf.getvalue()

rawDescription: Disabling DataFrame dimensions printing

description: Disabling DataFrame dimensions printing


code: first = word.split()

rawDescription: Looping over a text file list with python


rawDescription: How to deal with indeterminate form in Python

description: Deal with indeterminate form in Python


rawDescription: split numbers and symbols from normal text

description: Split numbers and symbols from normal text


code:
y.nonzero()
z.nonzero()

rawDescription: Python numpy array replacing

description: Python numpy array replacing


code:
sports_questions = ["What sport did michael jordan play?", "blablalba?", "and so on"]
computer_questions = ["Who founded microsoft?", "blabla", "many questions"]

rawDescription: Having large lists in main scripts, is there anyway to get it out of the main-script and into another module?


rawDescription: check that a script is actually using a proxy from a ip list

description: Check that a script is actually using a proxy from a ip list


code:
star1 = next(x for x in starlist if x.id==starid1)
star2 = next(x for x in starlist if x.id==starid2)

rawDescription: value assignment in python

description: Value assignment in python


rawDescription: Select random element from "non uniform" python dictionary


code: self.TAB_OPTION(tab, self.tabsvar, *self.list_of_tabs, command=self.read_columns)

rawDescription: Tkinter how to make a dynamic optionmenu without using a dictionary


rawDescription: Sorting a dictionary in python

description: Sorting a dictionary in python


code:
def shift_cipher_noloop(plain, i):

    if(plain == ""):
        return ""

    else:
        # Iterate with your string, moving first character to last on each iteration
        if len(plain) > 3 and i > 0:
            return shift_cipher_noloop(plain[1:] + plain[0], i - 1)

        else:
            # else Will be executed when either len <= 3, or `i <= 0`.
            # when (i <= 0) is true, you have created a new string,
            # with each character shifted by `original i` indices.
            # So, just return it.

            return plain

x = "ABCDEF"
index_to_shift = 3
y = shift_cipher_noloop(x, len(x) - index_to_shift)

print(y)

rawDescription: Recursion on strings - back to beginning of string?


code: result = z[z_idx, np.arange(z_idx.size)]

rawDescription: Selecting multiple elements from an 2d array using a 1d array in numpy


code:
import random

def random_group(d, size=10):
    keys = list(d.keys())
    random.shuffle(keys)
    for i in range(0, len(keys), size):
         yield [(key, d[key]) for key in keys[i:i + size]]

rawDescription: Random groups of elements of a dictionary


code:
def insertSources(self, srctype, link):
    """ Insert rss sources so we can parse them """
    new = {'srctype': srctype, 'link': link}
    self.__sources.insert(new)

rawDescription: MongoDB and PyMongo - SQL like columns

description: MongoDB and PyMongo - SQL like columns


code:
counter = 0

divTag = soup.find_all("div", {"class":"classname"})
for tag in divTag:
  ulTags = tag.find_all("ul", {"class":"classname"})
  for tag in ulTags:
    aTags = tag.find_all("a",{"class":"classname"})
    for tag in aTags:
     name = tag.find('img')['alt']
     print(name)
     #update counter:
     counter += 1

print(counter)

rawDescription: How to count the number of lines of code retrieved using beautiful soup?

description: Count the number of lines of code retrieved using beautiful soup


code:
from bitarray import bitarray

def index_to_number(i): return 2*i+3
def number_to_index(n): return (n-3)//2

LIMIT_NUMBER = 50
LIMIT_INDEX = number_to_index(LIMIT_NUMBER)+1

odd_primes = bitarray(LIMIT_INDEX)
# index  0 1 2 3
# number 3 5 7 9

odd_primes.setall(True)

for i in range(LIMIT_INDEX):
    if odd_primes[i] is False:
        continue
    n = index_to_number(i)
    for m in range(n**2, LIMIT_NUMBER, 2*n):
        odd_primes[number_to_index(m)] = False

primes = [index_to_number(i) for i in range(LIMIT_INDEX)
          if odd_primes[i] is True]
primes.insert(0,2)

print('primes: ', primes)

rawDescription: Optimize Sieve of Eratosthenes Further

description: Optimize Sieve of Eratosthenes Further


code:
x = shutdown(5)
threading.Thread(target = x).start()

rawDescription: Python thread holds up the rest of the script


code:
my_list = range(10)
bounds = (2, 5)
my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])
my_list

rawDescription: Python - set list range to a specific value


code:
A = np.array([[5,20],[8,10]])      # Indices and values
X = np.zeros(10,dtype=A.dtype)     # Array to store additions
np.add.at(X,A[:,0],A[:,1])         # Perform np.add.at
X                                  # Show output

rawDescription: How do I add elements from one numpy array to another at certain indices?

description: Add elements from one numpy array to another at certain indices


code:
('Working Dir', '/serves/test_servers')
('Java Data Model', '64-bit')

rawDescription: Simple example regarding how to parse data from html output using lxml


rawDescription: Pandas: add dataframes to dataframe - match on index and column value


code: from models.mymodels import Model1, Model2, Model3

rawDescription: How to structure a python project with three applications that use common module

description: Structure a python project with three applications that use common module


rawDescription: Built-in function in numpy to interpret an integer to an array of boolean values in a bitwise manner?


code:
#!/usr/bin/env python
import tarfile, StringIO
reles = StringIO.StringIO()
with tarfile.open("6genomes.tgz", "r:gz") as tar:
    for m in tar.members():
        if m.isreg():
            reles.write(tar.extractfile(m).read())
# do what you want with "reles".

rawDescription: How to pipe tar.extractall from python

description: Pipe tar.extractall from python


code:
class BlogPost(Displayable, Ownable, Content):
    def __init__(self, *args, **kwargs):
        super(BlogPost, self).__init__(*args, **kwargs)
        def formfield_new(self, *args, **kwargs):
            # do here what you would like to do
            return formfield
        instancemethod = type(self._meta.get_field('content').formfield)
        self._meta.get_field('content').formfield = instancemethod(formfield_new,
                                                                   self, BlogPost)

rawDescription: How do I override this method on a Django Model Field

description: Override this method on a Django Model Field


code:
for line in some_file:
    if ":" in line and all(x not in line for x in black_list):
        pass

rawDescription: How to check if elements of a list are in a string

description: Check if elements of a list are in a string


rawDescription: Why does PyMongo encode uuid.uuid1() as a BSON::Binary?


code: {'DestURL': 'some_URL', 'URLNAME': 'https://', 'CustDetails': 'NOthing', 'DirName': 'TEST', 'General': 'C:\\Work\\July\\abc'}

rawDescription: Parse the file section wise in python

description: Parse the file section wise in python


rawDescription: Timer or stopwatch in python

description: Timer or stopwatch in python


code:
a = Author()
a.publications.add(AuthorPublication(content_object=Book()))
a.publications.add(AuthorPublication(content_object=Article()))

rawDescription: Django Many-to-Many with a Model Inheritance


code:
class StudentSerializer(serializers.ModelSerializer):
    test_set = TestSerializer(many=True, required=False)

    class Meta:
        model = Student
        fields = ('id','title', 'name', 'address', 'city', 'test_set')

rawDescription: Consuming api from django rest framework


rawDescription: Regular expression in python 2.7 to identify any non numeric symbol in a column in dataframe


rawDescription: Finding columns which contain dates in Pandas


code:
def create_modeladmin(modeladmin, model, name = None):
    class  Meta:
        proxy = True
        app_label = model._meta.app_label

    attrs = {'__module__': '', 'Meta': Meta}

    newmodel = type(name, (model,), attrs)

    admin.site.register(newmodel, modeladmin)
    return modeladmin

rawDescription: Multiple ModelAdmins/views for same model in Django admin


rawDescription: Structuring Plain Text to JSON

description: Structuring Plain Text to JSON


code:
def some_func(format_byte, format_word):
    format_byte(...)
    #
    format_word(...)

rawDescription: Strategy pattern in Python when a "strategy" consists of more than one function


code:
getattr(object, attrname)
setattr(object, attrname, value)

rawDescription: How to access object attribute given string corresponding to name of that attribute

description: Access object attribute given string corresponding to name of that attribute


code:
class myModel(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True)

    class Meta:
        ordering = ['owner__username']

rawDescription: Unable to sort a user ForeignKey in Django


code: qvalues = [value for offset,length in offsets for value in qvalues[offset:offset+length]]

rawDescription: Generating a new order for a list of lists in python


code:
import time

class TimedSet(set):
    def __init__(self):
        self.__table = {}
    def add(self, item, timeout=1):
        self.__table[item] = time.time() + timeout
        set.add(self, item)
    def __contains__(self, item):
        return time.time() < self.__table.get(item)
    def __iter__(self):
        for item in set.__iter__(self):
            if time.time() < self.__table.get(item):
                yield item

rawDescription: Set class with timed auto remove of elements


code:
def expantree():
    lines = txtfile.readlines()
    library = create_library(lines)
    ET.ElementTree(lib).write(xmlfile)

rawDescription: creating a xml file with For Loop in python

description: Creating a xml file with For Loop in python


code:
if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    w = MyQTableWidget()
    w.verticalHeader().hide()

    headerLabels = [
        '$C_{soil}=(1 - n) C_m + \\theta_w C_w$',
        '$k_{soil}=\\frac{\\sum f_j k_j \\theta_j}{\\sum f_j \\theta_j}$',
        '$\\lambda_{soil}=k_{soil} / C_{soil}$']

    w.setColumnCount(len(headerLabels))
    w.setHorizontalHeaderLabels(headerLabels, 25)
    w.setRowCount(3)
    w.setAlternatingRowColors(True)

    k = 1
    for j in range(3):
        for i in range(3):
            w.setItem(i, j, QtGui.QTableWidgetItem('Value %i' % (k)))
            k += 1

    w.show()
    w.resize(700, 200)

    sys.exit(app.exec_())

rawDescription: Displaying LaTeX in pyQt/pySide QTableWidget


code: input('Press Enter to continue')

rawDescription: Python: Execute a line by user input?

description: Python: Execute a line by user input


rawDescription: Align numeric indexes to temporal period in pandas


code: rnaStart = rnaSequence.index(begin)

rawDescription: Extract a part of a string in python

description: Extract a part of a string in python


code:
import ConfigParser

class GrumpyConfigParser(ConfigParser.ConfigParser):
  """Virtually identical to the original method, but delimit keys and values with '=' instead of ' = '"""
  def write(self, fp):
    if self._defaults:
      fp.write("[%s]\n" % DEFAULTSECT)
      for (key, value) in self._defaults.items():
        fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
      fp.write("\n")
    for section in self._sections:
      fp.write("[%s]\n" % section)
      for (key, value) in self._sections[section].items():
        if key == "__name__":
          continue
        if (value is not None) or (self._optcre == self.OPTCRE):

          # This is the important departure from ConfigParser for what you are looking for
          key = "=".join((key, str(value).replace('\n', '\n\t')))

        fp.write("%s\n" % (key))
      fp.write("\n")

if __name__ == '__main__':
  config = GrumpyConfigParser()
  config.optionxform = str
  with open('config.ini', 'w') as config_file:
    config.add_section('config')
    config.set('config', 'NumberOfEntries', 10)
    config.write(config_file)

rawDescription: configparser without whitespace surrounding operator

description: Configparser without whitespace surrounding operator


code:
regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})')
m = regex.search('may 2013')
print(m.group('month'), m.group('year'))

rawDescription: regular expression in python for 'month year'

description: Regular expression in python for 'month year'


rawDescription: Average time a substring occurs

description: Average time a substring occurs


code: sortedlist = sorted(list, lambda x: x.rsplit('-', 1)[-1])

rawDescription: Python help sorting after hyphen

description: Python help sorting after hyphen


code:
def list_list(x,y):
    for a,b in zip(x,y):
        # decide pass or fail
        if a >= 60 or b >= 60:
            word = 'pass'
        else:
            word = 'fail'

        # yield intermediary result
        yield [a, b, word]

print(list(list_list([28, 59, 22, 5], [59, 85, 55, 60]))) # [[28, 59, 'fail'], [59, 85, 'pass'], [22, 55, 'fail'], [5, 60, 'pass']]

rawDescription: Iterating List of lists- Return only one list out of four lists


code:
import numpy, scipy.io
scipy.io.savemat('/home/myfiles/mydata.mat', mdict={'whatever_data': whatever_data})

rawDescription: In matlab, how to read python pickle file?


code:
t = test()
t.__dict__["foo"] = "bla"
t.foo

rawDescription: Object class override or modify

description: Object class override or modify


code:
def add(a,b):
    return a+b
def subtract(a,b):
    return a-b
def multiply(a,b):
    return a*b
def divide(a,b):
    return a/b

print('Please select an operation:')
print('1.Add')
print('2.Subtract')
print('3.Multiply')
print('4.Divide')
choice = input("Enter a choice: '1/2/3/4'")
a = int(input('Enter first number'))
b = int(input('Enter second number'))

if choice == '1':
    result = add(a, b)
elif choice == '2':
    result = subtract(a, b)
elif choice == '3':
    result = multiply(a, b)
elif choice == '4':
    result = divide(a, b)
print(result)

rawDescription: How do you print a function's result in python?

description: Print a function's result in python


code:
with open(myfile) as f:
    for i in xrange(number_of_wanted_lines):
        line = next(f)
        # do stuff with line

rawDescription: python 2.7: reading a file only up to a known line

description: Python 2.7: reading a file only up to a known line


rawDescription: Recursive expressions with pyparsing

description: Recursive expressions with pyparsing


code:
{'microsoft': {'green widget': {'Cost': '5', 'Price': '7'},
               'purple widget': {'Cost': '6', 'Price': '7'}},
 'sony': {'blue widget': {'Cost': '4', 'Price': '5'},
          'red widget': {'Cost': '5', 'Price': '6'}}}

rawDescription: Using Python CSV DictReader to create multi-level nested dictionary


rawDescription: Type error with json item

description: Type error with json item


code: [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj,a))]

rawDescription: Iterate over object attributes in python


code:
def common_elements( static_counter, dynamic_sorted_list ):
    last = None # previous element in the dynamic list
    count = 0 # count seen so far for this element in the dynamic list

    total_count = 0 # total common elements seen, eventually the return value

    for x in dynamic_sorted_list:
        # since the list is sorted, if there's more than one element they
        # will be consecutive.
        if x == last:
            # one more of the same as the previous  element

            # all we need to do is increase the count
            count += 1
        else:
            # this is a new element that we haven't seen before.

            # first "flush out" the current count we've been keeping.
            #   - count is the number of times it occurred in the dynamic list
            #   - static_counter[ last ] is the number of times it occurred in
            #       the static list (the Counter class counted this for us)
            # thus the number of occurrences the two have in common is the
            # smaller of these numbers. (Note that unlike a normal dictionary,
            # which would raise KeyError, a Counter will return zero if we try
            # to look up a key that isn't there at all.)
            total_count += min( static_counter[ last ], count )

            # now set count and last to the new element, starting a new run
            count = 1
            last = x

    if count > 0:
        # since we only "flushed" above once we'd iterated _past_ an element,
        # the last unique value hasn't been counted. count it now.
        total_count += min( static_counter[ last ], count )

    return total_count

rawDescription: Fastest way to compare ordered lists and count common elements *including* duplicates


rawDescription: Wrong path results the python program runs using crontab


rawDescription: The number of intersections between columns


code: [file for file in os.listdir("directoryone") if os.path.isfile(os.path.join("directoryone", f))]

rawDescription: Python - Copying only new files into another directory


code:
from heapq import nlargest

calculations = [('ABC', 18), ('CDE', 85), ('BAC', 36), ('CDE', 57),
                ('ECD',  2), ('BAD', 45), ('EFG', 55), ('DCE',  1)]

highest_per_name_combi = dict()

for name_combi, value in calculations:
    normal_name_combi = ''.join(sorted(name_combi)) # Slow solution
    current = highest_per_name_combi.get(normal_name_combi, float('-inf'))
    highest_per_name_combi[normal_name_combi] = max(value, current)

top3 = nlargest(3, highest_per_name_combi.iteritems(), key=lambda x: x[1])

rawDescription: Pythonic way to store top 10 results

description: Pythonic way to store top 10 results


rawDescription: How to get 1-100, 110-130 between numbers in python

description: Get 1-100, 110-130 between numbers in python


code:
def generate(ast):
    if ast[0] == '+':
        return generate(ast[1]) + " + " + generate(ast[2])
    elif ast[0] == 'for':
        return "for %s in %s:\n" % (ast[1], generate(ast[2])) + generate(ast[3])
    ...

rawDescription: Using a grammar parser for Python and constructing files from the tree


code:
import mechanize
browser = mechanize.Browser()
response = browser.open('http://example.com/your/url')
info = response.info()
header = info.getheader('Content-Disposition')
header

rawDescription: How to get filename from Content-Disposition in headers

description: Get filename from Content-Disposition in headers


rawDescription: Numpy does treat float('nan') and float differently - convert to None


code:
data, cols, rows = [np.array(j) for j in [[1,4,2,4,1],[0,1,1,1,2],[0,1,2,1,1]]]
x=np.zeros(cols.shape,dtype=object)
x[:]=list(zip(rows,cols))
x
i=np.unique(x,return_index=True)[1]
i
c1=sparse.csc_matrix((data[i],(cols[i],rows[i])),shape=(3,3))
c1.A

rawDescription: Ignoring duplicate entries in sparse matrix


code: np.append( my_list, var1 * harmonic )

rawDescription: Preventing nested list output from a for-loop / list comprehension when appending new values to an Array


code:
np.random.seed(12345)
x = np.random.randint(0, 10, size=(10, 3))
x
i, j = argrelmax(x, axis=0)
i
j

rawDescription: Scipy: Argrelmax Find Maxmima along Dimension in 3d Array


code:
class CompanyMiddleware(object):
    def process_request(self, request):
        if settings.DEBUG:
            request.company = CompanyClass.objects.get(id=1)
            return None

        short_url = request.META.get("HTTP_X_CUSTOMURL")

        try:
            company = CompanyClass.objects.get(short_url=short_url)
        except Model.DoesNotExist:
            return HttpResponseBadRequest('Company not found')

        request.company = company

        return None

rawDescription: Django multi tenancy

description: Django multi tenancy


code:
A
B
join(A, B)
group_by(AB, 0)

rawDescription: Moving large SQL query to NumPy

description: Moving large SQL query to NumPy


code:
g('plot "' + plot_cmd + datFile + '" using 1:3' + ' title "' + "Line 1" +'" with lines')
g('plot "' + plot_cmd + datFile + '" using 1:5' + ' title "' + "Line 2" +'" with lines')

rawDescription: Gnuplot.py plotting multiple lines on the one graph


code:
def start_something():
    do_starting_actions()

def stop_something():
    do_terminal_actions()

def parse_args():
    parser = ArgumentParser()
    subparsers = parser.add_subparsers()
    start = subparsers.add_parser("start")
    start.set_defaults(func=start_something)
    stop = subparsers.add_parser("stop")
    stop.set_defaults(func=stop_something)
    # ...
    return parser.parse_args()

def main():
    args = parse_args()
    args.func()

rawDescription: Using argparse to create custom command line formats


code: HexFile = open(FileNameIn, 'r')

rawDescription: Saving data into a text file

description: Saving data into a text file


rawDescription: Get rect tag from this XML file

description: Get rect tag from this XML file


code: max( cur2, key=lambda x:int(x[2]))

rawDescription: Python - 2d list max based on certain part of inner list


code:
def remove_between_anchors(text, start, end):
    return re.sub(r'{0}.+?{1}'.format(start, end), '', text)

remove_between_anchors('123<abc>456', '<', '>') # returns '123456'

rawDescription: Remove character starting with x and ending with x and everything between it in a string


code:
[b[index][0] for index in np.ndindex(b.shape)]
# [0, 2, 4, 6, 8, 10]

rawDescription: Convert a numpy array to an array of numpy arrays


code:
col.aggregate([
    { "$project": { "impressions": {"$setDifference": [{ "$map": { "input": "$impressions", "as": "imp", "in": { "$cond": { "if": { "$eq": [ "$$imp.service", "furniture" ] }, "then": "$$imp.id", "else": 0 }}}}, [0]]}}},
    { "$unwind": "$impressions" },
    { "$group": { "_id": "$impressions", "impressions_count": { "$sum": 1 }}}
])

rawDescription: MapReduce in PyMongo

description: MapReduce in PyMongo


rawDescription: Concatenate generators in python 3 with +-operator


rawDescription: Loop through list and changing indexes

description: Loop through list and changing indexes


code:
x=np.zeros((2,3),int)
x[[0,1,0],[0,1,2]]=1
x
x.nonzero()
np.where(x)   # same as nonzero()
np.argwhere(x)
np.argwhere(x).T

rawDescription: From argwhere to where?

description: From argwhere to where


code:
import ast
#hexadecimal
ast.literal_eval("0x3f")
#binary
ast.literal_eval("0b01010")
#octal
ast.literal_eval("0712")
#decimal
ast.literal_eval("42")

rawDescription: Python String to hex

description: Python String to hex


code: df['col_c'] = g.cumcount()

rawDescription: Enumerate each row for each group in a DataFrame


code:
# check to see if sprite collides with any sprite in the car group
collided = pygame.sprite.Sprite.spritecollide(sprite, cars, False)

rawDescription: What are PyGame sprites, and what do they do?


code: p_value = sess.run(value)

rawDescription: How to convert tensorflow variable to a python variable?

description: Convert tensorflow variable to a python variable


code:
import pandas as pd
try:
    # for Python2
    from cStringIO import StringIO
except ImportError:
    # for Python3
    from io import StringIO

content = '''\
1.0    2    A
3.0    4    B
5      X    C
M      Y    D
'''
header = ['foo', 'bar', 'baz']

for df in pd.read_fwf(StringIO(content), header=None, chunksize=2, names=header,
                      converters={h:str for h in header}):
    print(df)
df.info()

rawDescription: Pandas read_fwf: specify dtype

description: Pandas read_fwf: specify dtype


rawDescription: Add two arrays without using for. Python


code:
from cv2 import cv
import numpy as np

def subimage(image, centre, theta, width, height):
   output_image = cv.CreateImage((width, height), image.depth, image.nChannels)
   mapping = np.array([[np.cos(theta), -np.sin(theta), centre[0]],
                       [np.sin(theta), np.cos(theta), centre[1]]])
   map_matrix_cv = cv.fromarray(mapping)
   cv.GetQuadrangleSubPix(image, output_image, map_matrix_cv)
   return output_image

rawDescription: How to straighten a rotated rectangle area of an image using opencv in python?

description: Straighten a rotated rectangle area of an image using opencv in python


code:
import pyexcel as pe
sheet = pe.load("comments.csv", name_columns_by_row=0)
sheet

rawDescription: Python flask writing to a csv file and reading it


code:
import pandas as pd
import numpy.random as rd

df = pd.DataFrame(rd.randn(1e6).reshape(1e5,10),columns=list('abcdefghij'))
store = pd.HDFStore('newstore.h5')

# only data columns can serve as indices to select for on-disk, but there's a
# speed penalty involved, so it's a conscious decision what becomes data_column!
store.append('df',df,data_columns=['a','b'])

rawDescription: Can pandas and file system be used as a replacement for databases?


code:
addresses = [
    ['Bruno', 44444, 'bruno@hotmail.com'],
    ['Mariah', 333, 'mariah@hotmail.com'],
    ['Oliver', 3333, 'oliver@yahoo.co.uk']
]

# prints: [['Bruno', 44444, 'bruno@hotmail.com'], ['Mariah', 333, 'mariah@hotmail.com'], ['Oliver', 3333, 'oliver@yahoo.co.uk']]
print(addresses)

# Remove "Bruno" from your addresses
# prints: [['Mariah', 333, 'mariah@hotmail.com'], ['Oliver', 3333, 'oliver@yahoo.co.uk']]
print([address for address in addresses if address[0] != "Bruno"])

# Sort your addresses descending by name
# prints: [['Oliver', 3333, 'oliver@yahoo.co.uk'], ['Mariah', 333, 'mariah@hotmail.com'], ['Bruno', 44444, 'bruno@hotmail.com']]
print(sorted(addresses, key=lambda address: address[0], reverse=True))

rawDescription: Why isn´t it updating?

description: Why isn´t it updating


code: a * b

rawDescription: working with negative numbers in python

description: Working with negative numbers in python


code:
from collections import defaultdict
v = {1: 1, 2: 8, 3: 0}
M = {(1, 2): 2, (3, 1): 1, (3, 3): 7, (2, 1): -1}
newDict = defaultdict(int)
for x, y in M:
    newDict[x] += M[x, y] * v.get(x, 0)

newDict

rawDescription: Python: dict multiplication

description: Python: dict multiplication


code: {value : secondDictionary[key] for key, value in firstDictionary.items()}

rawDescription: new dictionary from existing dictionary values

description: New dictionary from existing dictionary values


rawDescription: applying a function on an object in python

description: Applying a function on an object in python


code: Query(kind='UserSetting', filters=OR(AND(FilterNode('name', '<', 'cookieAck'), FilterNode('name', '<', 'newkey'), FilterNode('name', '<', 'tempCelsius')), AND(FilterNode('name', '<', 'cookieAck'), FilterNode('name', '<', 'newkey'), FilterNode('name', '>', 'tempCelsius')), AND(FilterNode('name', '<', 'cookieAck'), FilterNode('name', '>', 'newkey'), FilterNode('name', '<', 'tempCelsius')), AND(FilterNode('name', '<', 'cookieAck'), FilterNode('name', '>', 'newkey'), FilterNode('name', '>', 'tempCelsius')), AND(FilterNode('name', '>', 'cookieAck'), FilterNode('name', '<', 'newkey'), FilterNode('name', '<', 'tempCelsius')), AND(FilterNode('name', '>', 'cookieAck'), FilterNode('name', '<', 'newkey'), FilterNode('name', '>', 'tempCelsius')), AND(FilterNode('name', '>', 'cookieAck'), FilterNode('name', '>', 'newkey'), FilterNode('name', '<', 'tempCelsius')), AND(FilterNode('name', '>', 'cookieAck'), FilterNode('name', '>', 'newkey'), FilterNode('name', '>', 'tempCelsius'))))

rawDescription: Google App Engine - NDB - best way of inversing the IN(list)


code:
rank_cards_map = {c: i for i, c in enumerate(rank_cards)}
max(hand, key=lambda c: rank_cards_map[c[0]])

rawDescription: Getting highest value card in list

description: Getting highest value card in list


code:
def chunk(fname):
    with open(fname, 'rb') as fin:
        return list(iter(lambda: fin.read(4096), ''))

rawDescription: Break a text file into smaller chunks in python


code: "i,split,on commas".split(',') # = ['i', 'split', 'on commas']

rawDescription: How to split a string by using [] in Python

description: Split a string by using [] in Python


code:
extent = [0,2,0,2]
plt.imshow(H, extent=extent, interpolation='nearest')
plt.colorbar()
plt.show()

rawDescription: 2D Histogram from a 3x3 array in PYTHON

description: 2D Histogram from a 3x3 array in PYTHON


code:
from collections import Counter

counter = None
bases = 'ATCG'

def print_counter():
    print(' '.join('%s=%s' % (k, counter[k]) for k in bases))

with open("a.txt", "r") as f:  # Always open files like this
    for line in f:  # no need for readlines
        line = line.strip("\n")
        if line.startswith(">"):
            if counter is not None:
                print_counter()
            print(line)
            counter = Counter()
        elif line and line[0] in bases:
            counter.update(line[2::3])
print_counter()

rawDescription: Reading ATCG DNA sequences, and calculates the numbers of ATCG in third place


rawDescription: Python Selenium get current window handle


code:
def compose(*funcs):
    if len(funcs) == 1:
        return funcs[0]
    else:
        def composition(*args, **kwargs):
            return funcs[0](compose(*funcs[1:])(*args, **kwargs))
        return composition

rawDescription: Call several functions and return the collective result


code:
import A.B.C1
C1 = A.B.C1

rawDescription: importing modules with submodules from deep in a library

description: Importing modules with submodules from deep in a library


rawDescription: How do I get the first timestamp (index) of a group when applying groupby to a python pandas dataframe?

description: Get the first timestamp (index) of a group when applying groupby to a python pandas dataframe


rawDescription: Change column values to column headers in pandas


code: connection.query('SELECT * FROM your_table WHERE id=?', ('yourid',))

rawDescription: How to directly query a relational/SQL database from a ZOPE product?

description: Directly query a relational/SQL database from a ZOPE product


rawDescription: Calculator that excludes primes up to 10th prime


code:
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

rawDescription: adding header to python request module

description: Adding header to python request module


code:
class Example(db.Model):
    #other fields
    status = db.StringProperty()

rawDescription: Add a column to an existing table using GQL?


code: zip(*data)

rawDescription: Parsing a text file with Python and split()


code:
import re

def getstring(string):
    testforstring = re.search("\((.*)\)",string)
    if testforstring:
        return testforstring.group(1)
    testforstring = re.search("@(.*?)\s+.*",string)
    if testforstring:
        return testforstring.group(1)
    return None

rawDescription: Extract value from string in Python?

description: Extract value from string in Python


code:
def decorator(cls):
    slots = set(cls.__slots__)
    slots.add('y')
    dct = cls.__dict__.copy()
    for name in cls.__slots__:
        dct.pop(name)
    dct['__slots__'] = tuple(slots)
    return type(cls)(cls.__name__, cls.__bases__, dct)

@decorator
class A:
    __slots__ = ('x',)
    def __init__(self):
        self.x = self.y = 42

print(A().x, A().y)

rawDescription: Is it possible to add __slots__ in decorator of class that already defines __slots__?


code: map(get_country, df['season'])

rawDescription: Find key from value for Pandas Series

description: Find key from value for Pandas Series


code: json.dumps(record, ensure_ascii=False)

rawDescription: UnicodeDecodeError while using json.dumps()


code: df[(df.index==i)].start_sec = 25

rawDescription: Updating values in a DataFrame

description: Updating values in a DataFrame


code:
clientEndpoint = clientFromString(reactor, options["client-endpoint"])
serverEndpoint = serverFromString(reactor, options["server-endpoint"])

rawDescription: Can Perspective Broker be used over stdio instead of TCP?


code:
def lines(xcoord, ycoord):
    penup()
    goto(xcoord, ycoord)
    startPoint = pos()
    pensize(3)
    pendown()
    color("blue")
    forward(10)
    right(randint(0,360))
    endPoint = pos()
    penup()
    return (startPoint, endPoint)

rawDescription: How can I check if 2 drawn lines overlap?

description: Check if 2 drawn lines overlap


rawDescription: Complex Python List Comprehension

description: Complex Python List Comprehension


code: f = max_execs(5)(f)

rawDescription: How are these type of python decorators written?


code: a - b[:,None]

rawDescription: Subracting all elements of array A from all elements of B?


code:
content = html.xpath('//span[@id="target_text"]')[0].text_content()
import re
re.sub('\s+', ' ', content).strip()

rawDescription: how to extract text from html tags which contain other tags ? regular expression

description: Extract text from html tags which contain other tags ? regular expression


code:
class ResourcePopen(subprocess.Popen):
    def _try_wait(self, wait_flags):
        """All callers to this function MUST hold self._waitpid_lock."""
        try:
            (pid, sts, res) = _eintr_retry_call(os.wait4, self.pid, wait_flags)
        except OSError as e:
            if e.errno != errno.ECHILD:
                raise
            # This happens if SIGCLD is set to be ignored or waiting
            # for child processes has otherwise been disabled for our
            # process.  This child is dead, we can't get the status.
            pid = self.pid
            sts = 0
        else:
            self.rusage = res
        return (pid, sts)

def resource_call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute and resource usage.

    The arguments are the same as for the Popen constructor.  Example:

    retcode, rusage = call(["ls", "-l"])
    """
    with ResourcePopen(*popenargs, **kwargs) as p:
        try:
            retcode = p.wait(timeout=timeout)
            return retcode, p.rusage
        except:
            p.kill()
            p.wait()
            raise

rawDescription: measure elapsed time, amount of memory and cpu used by the extern program

description: Measure elapsed time, amount of memory and cpu used by the extern program


code:
class Monster(object):

  def __init__(self):
     self.name = "Snake"
     self.health = 100

  def decreaseHealth(self):
     if self.health <= 0:
        print('Dead')
     else:
        self.health -= 4

m = Monster()
m.decreaseHealth()

rawDescription: Class method: 'self' not being read

description: Class method: 'self' not being read


code:
A = ord('A')
for c in tempWord:
    if 'A' <= c <= 'Z':
        tempSum += ord(c) - A + 1

rawDescription: Faster way to assign numerical value to letters?


code:
try:
   assert something == something_else
except AssertionError:
   take_screenshot()

rawDescription: triggering a function on failed assertion

description: Triggering a function on failed assertion


code:
def foo(x):
    y = 1
    z = 2
    def bar(a):
        return (x, y, a)
    return bar

rawDescription: Does lexical scope have a dynamic aspect?


code: left.div(right.loc[::-1, 'Counts'], axis=0)  # permute the indices

rawDescription: Normalizing data in data frame with data from different data frame


code: playerletter = input("What letter would you like to be? X or O? \n").upper

rawDescription: Variable won't be assigned to input in Python


code: df.loc[(slice(None),'y'),0] = np.nan

rawDescription: Assign to MultiIndex slice

description: Assign to MultiIndex slice


code: repr(A)

rawDescription: Can I define a __repr__ for a class rather than an instance?

description: Define a __repr__ for a class rather than an instance


code: filter(lambda x: x[0].startswith('img'), l)

rawDescription: Finding in elements in a tuple and filtering them


code: list = [x for x in wx.all_synsets('n')]

rawDescription: Searching through an entire series of synsets (from NLTK) in Python NLP


rawDescription: Fastest way of comparing lists of strings


code:
from celery.execute import send_task

send_task('my_task', [], kwargs)

rawDescription: Call Django celery task by name

description: Call Django celery task by name


code:
@property
def area(self):
    try:
        return self._area
    except AttributeError:
        self.recalc_area()
        return self._area

def recalc_area(self):
    self._area = pi*self.r**2

rawDescription: When and how often are properties calculated in python?


code:
D = {}
for something in yourthings:
    if something.key in D:
        D[something.key] = something.auxfield
    else:
        D[something.key] = merge(D[something.key], something.auxfield)

rawDescription: Retrieving a specific set element in Python


code:
pattern = re.compile("[\uD800-\uDFFF].", re.UNICODE)
pattern = re.compile("[^\u0000-\uFFFF]", re.UNICODE)

rawDescription: How to filter (or replace) unicode characters that would take more than 3 bytes in UTF-8?

description: Filter (or replace) unicode characters that would take more than 3 bytes in UTF-8


code:
data = a['data']
data

rawDescription: improve speed when reading a binary file

description: Improve speed when reading a binary file


code:
SAA = SA.reshape(8,2,2,2)
SAA[0]
SAA[1]

rawDescription: split ndarray into chunks - whilst maintaining order

description: Split ndarray into chunks - whilst maintaining order


code:
from PyQt4 import QtCore, QtGui
from mainwindow_ui import Ui_MainWindow

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        header = self.tableWidget.horizontalHeader()
        header.setResizeMode(QtGui.QHeaderView.ResizeToContents)
        ...

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

rawDescription: Horizontal Header to Large in QtDesigner


rawDescription: Cumulative numbers in python dictionaries


code:
class values:

    class struct1:
         def __init__(self):
             self.a = 1
             self.b = 2

    class struct2:
         def __init__(self):
             self.c = 3
             self.d = 4

    def __init__(self):
         self.struct1 = self.struct1()
         self.struct2 = self.struct2()

    def setValue(self, **kwargs):
        for key, value in kwargs.items():
            try:
                getattr(self.struct1, key)
            except AttributeError:
                # self.struct1 don't have any attribute which name is the value of 'key'.
                pass
            else:
                setattr(self.struct1, key, value)

            try:
                getattr(self.struct2, key)
            except AttributeError:
                # self.struct2 don't have any attribute which name is the value of 'key'.
                pass
            else:
                setattr(self.struct2, key, value)

rawDescription: How to handle data in python similar to IDL structures?

description: Handle data in python similar to IDL structures


rawDescription: First common element from different lists of numbers


code:
nan_row = numpy.repeat(numpy.nan, d1.shape[1])
d1_nan = numpy.vstack((nan_row, d1))
d2 = d1_nan[numpy.searchsorted(t1, t2, side="right")]

rawDescription: "as of" in numpy

description: "as of" in numpy


code:
from functools import reduce  # Python 3 only

dfs = [df1, df2, df3, df3, df5]

def my_merge(df1, df2):
    return pd.merge(df1, df2, how='outer')

merged_dfs = reduce(my_merge, dfs)

rawDescription: pandas: merge several dataframes

description: Pandas: merge several dataframes


code:
print(mom("THAT"))       # prints ThAt
print(mom("that"))       # prints ThAt
print(mom("Hello dear")) # prints HeLlO DeAr
print(mom("HELLO DEAR")) # prints HeLlO DeAr
print(mom("hello dead")) # prints HeLlO DeAd

rawDescription: Use upper and lower cases on a same word


code:
mkimap = lambda: imap(str,xrange(1,4))
list(mkimap())
list(mkimap())

rawDescription: Itertools for containers

description: Itertools for containers


code:
if not has_item or \
        space.is_true(compare(w_compare_with, w_max_val)):
    has_item = True
    w_max_item = w_item
    w_max_val = w_compare_with

rawDescription: Does min with lambda always return the first value in python?


code:
cust_ids = set()
for element in collection.find({'city': 'Pittsburg'}):
    cust_ids.add(element['cust_id'])

cust_ids

rawDescription: Passing variables onto a MongoDB Query

description: Passing variables onto a MongoDB Query


code:
def image_request(url, file):
    response = urllib.request.urlopen(url)
    fh = open(file, "wb") #open the file for writing
    fh.write(response.read()) #

rawDescription: Download and SAVE MANY Images from google Image search to a LOCAL FOLDER (Python)


code:
from selenium import webdriver

cookie_file_path = 'cookie.txt'

args = ['--cookies-file={}'.format(cookie_file_path)]
driver = webdriver.PhantomJS(service_args=args)
driver.get('http://google.com')
driver.get('http://facebook.com')
with open(cookie_file_path) as f:
    print(f.read())

rawDescription: How to get 3rd party cookies?

description: Get 3rd party cookies


code:
x = float(input("Enter a real number for x: "))
t = int(input("Enter a non negative integer for t: "))
counter = 1
series = 1
num = 1
denom = 1
while counter <= t :
    num = num * x
    denom = denom * counter
    series = series + num / denom
    counter = counter + 1
print(series)

rawDescription: How do I return a value within a while loop

description: Return a value within a while loop


code:
def latex_float(f):
    float_str = "{0:.2g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
    else:
        return float_str

rawDescription: Format number using LaTeX notation in Python


code:
it = iter(seq)
first = it.next()
rest = list(it)

rawDescription: How to unpack tuple of length n to m<n variables

description: Unpack tuple of length n to m<n variables


code:
# your imports and data above
fig = plt.figure()
ax0a = fig.add_axes([0.1, 0.1, 0.8, 0.25])
ax0b = fig.add_axes([0.1, 0.39, 0.8, 0.25], sharex=ax0a)
ax0c = fig.add_axes([0.1, 0.68, 0.8, 0.25], sharex=ax0a)
ax0a.set_xticklabels([])
ax0b.set_xticklabels([])
ax0a.plot(x,y)
nbins = len(ax0a.get_xticklabels())
ax0a.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper'))
ax0b.plot(x,y)
ax0b.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper'))
ax0c.plot(x,y)
ax0c.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper'))
plt.show()

rawDescription: Matplotlib subplot y-axis scale overlaps with plot above


code:
for elem in soup.select("div.product *"):
    y.append(elem.string.strip().encode('utf8'))

rawDescription: Parsing HTML tags using python

description: Parsing HTML tags using python


code:
for var in request.GET:
    value = request.GET[var]
    # do something with the value ...

rawDescription: Django: Handling several page parameters


code: result = matrix.sum()

rawDescription: Sum ndarray values

description: Sum ndarray values


code:
roll_dice("5d6")
roll_dice("5d6")
roll_dice("3d100")
roll_dice("1d20")

rawDescription: VicBot Dice Roller (Python 2.7)

description: VicBot Dice Roller (Python 2.7)


code:
def create_myDict(mylists):
    myDict = {}
    for sublist in mylists:
        for i in range(len(sublist)):
            if sublist[i] in myDict:
               myDict[sublist[i]].append(i)
            else:
               myDict[sublist[i]] = [i]

    return myDict

rawDescription: Create dictionary from multiple lists

description: Create dictionary from multiple lists


code:
#Caculate logarithimic slope and intercept in HMDrr Dataset
def calc_linear(z):
    y = HMDrr.loc[z,binLabels].dropna()
    number = y.count()+1
    y = y.values.astype(float)
    x = np.log(range(1,number,1))
    slope, intercept, r, p, stderr = linregress(x, y)
    return slope, intercept

rawDescription: How do I use row index to create a function based calculated column

description: Use row index to create a function based calculated column


rawDescription: Parse JSON and store data in Python Class


code:
with open('Stockinventory.txt', 'w') as f:
    for row in items:
        f.write(', '.join(row) + '\n')

rawDescription: Rewriting array to text file, need to put each part on new line


code: data_unique = dict((d[0], d) for d in data)

rawDescription: Uniquifying a list of lists in python

description: Uniquifying a list of lists in python


code:
def enumerate(collection, start=0):  # could add stop=None
    i = start
    it = iter(collection)
    while 1:                         # could modify to `while i != stop:`
        yield (i, next(it))
        i += 1

rawDescription: How can I limit iterations of a loop in Python?

description: Limit iterations of a loop in Python


code:
any([True, True, False])
any([False, False, False])
any([False, False, True])

rawDescription: How do you apply 'or' to all values of a list in Python?

description: Apply 'or' to all values of a list in Python


code:
df1
df2

rawDescription: Pandas / Numpy: How to Turn Column Data Into Sparse Matrix


code:
import wx

class Screen(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(900,500))

        self.SetBackgroundColour("#E4F1FE")
        self.Show(True)

        self.InitUI()

    def InitUI(self):

        pnlMain = wx.Panel(self, size=(900,500))

        # Setup Font
        font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)

        # Setup horizontal box sizer
        self.bsMain = wx.BoxSizer(wx.HORIZONTAL)
        self.bsMain.SetDimension(0,0,900,500)

        # Setup LEFT box sizer
        self.bsLeft = wx.BoxSizer(wx.VERTICAL)
        self.bsLeft.SetMinSize((3*(self.GetSize()[0]/4),self.GetSize()[1]))

        # Make add button
        btnAdd = wx.Button(pnlMain, label="+", size=(50,50))

        # Add all the components to the LEFT sizer
        self.bsLeft.Add(btnAdd, flag = wx.ALIGN_BOTTOM | wx.ALIGN_LEFT )

        # Setup RIGHT bsMain sizer
        self.bsRight = wx.BoxSizer(wx.VERTICAL)
        self.bsRight.SetMinSize((self.GetSize()[0]/4,self.GetSize()[1]))

        # Make users headline
        stUsers = wx.StaticText(pnlMain, label="USERS")
        stUsers.SetFont(font)

        # Make users list control
        lcUsers = wx.ListCtrl(pnlMain,style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        lcUsers.Show(True)
        lcUsers.InsertColumn(0,"user")
        lcUsers.InsertColumn(1,"status")

        # Add all the components to the RIGHT sizer
        self.bsRight.Add((-1,10))
        self.bsRight.Add(stUsers, flag=wx.LEFT | wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_CENTRE, border=5)
        self.bsRight.Add((-1,10))
        self.bsRight.Add(lcUsers, flag=wx.EXPAND)

        # Add the vertical sizers to the horizontal sizer
        self.bsMain.Add(self.bsLeft)
        self.bsMain.Add(self.bsRight)

        # Add the vertical sizer to the panel
        pnlMain.SetSizer(self.bsMain)
        self.bsMain.Layout()

if __name__ == '__main__':
    app = wx.App(False)
    frame = Screen(None, 'Layout')
    app.MainLoop()

rawDescription: wxPython widgets are one on top of the other

description: WxPython widgets are one on top of the other


code:
it = scan('foo(); i++')
it.next()
it.next()
it.next()
it.next()
it.next()
it.next()

rawDescription: Where do you use generators feature in your python code?