code:
P2, fib, f1, f2 = 0, 0, 1, 0
while fib < 4000000:
    fib, f2 = f1 + f2, f1
    f1 = fib
    if fib % 2 == 0:
        P2 += fib
print(P2) # Its not fib

rawDescription: Why does this not work for project euler part 2? (Python) project euler instructions included


code:
{
    circles:[
        {
            "name": "Administrator",
            "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_gnSSWSO.pbm",
            "desc": "the group of administrators",
            "image": null,
            "created_date": "2015-07-31T03:24:21.116000Z"
        },
        {
            "name": "Developer",
            "avatar": "http://127.0.0.1:8000/media/circle_avatars/python_84E7KLC.ppm",
            "desc": "the group of developers",
            "image": null,
            "created_date": "2015-07-31T03:17:59.343000Z"
        }
    ]
}

rawDescription: django-rest-framwork how can i return the {[data1,data2]} instead of [data1,data2]

description: Django-rest-framwork how can i return the {[data1,data2]} instead of [data1,data2]


code: ssa_flat = [x[0] for x in subsetA_nodeID]

rawDescription: compare two lists and return not matching items

description: Compare two lists and return not matching items


code:
key = df["col5"].isnull()
df_NA = df.loc[key]
df_notNA = df.loc[~key]
df_NA
df_notNA

rawDescription: How to filter NA values and add it to a new DataFrame

description: Filter NA values and add it to a new DataFrame


code:
import pandas as pd
import numpy as np
import statsmodels.api as sm
from patsy import dmatrices

df = pd.read_csv('data.csv')
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
df = df.set_index('date')

rawDescription: Pandas - Split dataframe into multiple dataframes based on dates?


code:
mod = __import__('script2')
for name in [v for v in dir(mod) if not v.startswith('__')]:
    fvar = getattr(mod, name)
    print(fvar)

rawDescription: Passing values of unknown variables Python


code:
import email, email.utils, datetime, time

def dtFormat(s):
  dt = email.utils.parsedate_tz(s)
  dt = email.utils.mktime_tz(dt)
  dt = datetime.datetime.fromtimestamp(dt)
  dt = dt.timetuple()
  return dt

rawDescription: Parse date/time from a string

description: Parse date/time from a string


rawDescription: Dummy variables from levels of other data frame


code:
import re
s = "abc#def#ghi#jkl"
re.findall(r"(?<=#)[^#]+(?=#)", s)

rawDescription: python string parsing using regular expression

description: Python string parsing using regular expression


code:
import unittest

class MyTest(unittest.TestCase):

    currentResult = None # holds last result object passed to run method

    @classmethod
    def setResult(cls, amount, errors, failures, skipped):
        cls.amount, cls.errors, cls.failures, cls.skipped = \
            amount, errors, failures, skipped

    def tearDown(self):
        amount = self.currentResult.testsRun
        errors = self.currentResult.errors
        failures = self.currentResult.failures
        skipped = self.currentResult.skipped
        self.setResult(amount, errors, failures, skipped)

    @classmethod
    def tearDownClass(cls):
        print("\ntests run: " + str(cls.amount))
        print("errors: " + str(len(cls.errors)))
        print("failures: " + str(len(cls.failures)))
        print("success: " + str(cls.amount - len(cls.errors) - len(cls.failures)))
        print("skipped: " + str(len(cls.skipped)))

    def run(self, result=None):
        self.currentResult = result # remember result for use in tearDown
        unittest.TestCase.run(self, result) # call superclass run method

    def testA(self):
        self.assertTrue(True) # succeeds

    def testB(self):
        self.assertTrue(False) # fails

    def testC(self):
        self.assertTrue(1 + None is None) # raises TypeError

    @unittest.skip("skip it") # skipped
    def testD(self):
        self.assertTrue("whatever")

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

rawDescription: python unittest count tests

description: Python unittest count tests


code:
def runInParallel(*fns):
    proc = []
    for fn, arg in fns:
        p = Process(target=fn, args=(arg,))
        p.start()
        proc.append(p)
    for p in proc:
        p.join()

rawDescription: Run function with positional and optional arguments in parallel in python (follow up)


rawDescription: Sorting points on multiple lines

description: Sorting points on multiple lines


code:
print(mix("Hello", "abcde"))
print(mix("Guten Tag", "ihgfedcba"))
print(mix("Ni Hao", "Hello "))

rawDescription: How to use recursion to mix 2 strings and return both as 1 'interlaced' string?

description: Use recursion to mix 2 strings and return both as 1 'interlaced' string


code:
x = (
'a very long string - part 1'
'a very long string - part 2'
'a very long string - part 3' )
x

rawDescription: How to assign a value to a variable when writing the value takes multiple lines (python)

description: Assign a value to a variable when writing the value takes multiple lines (python)


code:
def parse_dir_contents(self, response):
    for sel in response.xpath('//h1[@itemprop="name"]'):
        item = thisItem()
        ...
        request = scrapy.Request("https://www.this-site.com.au/something?listing_id="+propID,callback=self.parse_other_content, meta={'item':item})
        yield request

rawDescription: Passing class between functions

description: Passing class between functions


rawDescription: How to implement this Depth-First-Search in a Sudoku Solver

description: Implement this Depth-First-Search in a Sudoku Solver


code:
timeit.timeit(stmt='[n ** 0.5 for n in range(1000000)]', setup='import math', number=1)
timeit.timeit(stmt='[math.sqrt(n) for n in range(1000000)]', setup='import math', number=1)
timeit.timeit(stmt='[sqrt(n) for n in range(1000000)]', setup='from math import sqrt', number=1)

rawDescription: Using exponentiation **0.5 less efficient than math.sqrt?


code:
x = [False, False, False, 10, False, False]
reduce(lambda i,j:i or j, x)

rawDescription: Find a unique element in a list

description: Find a unique element in a list


code: "\n\n".join([", ".join(row[1]) for row in orders_item.groupby("order_number")["item"]])

rawDescription: Converting pandas dataframe into basket type orange table


code:
N=G.order()
indegrees = G.in_degree().values()
max_in = max(indegrees)
centralization = float((N*max_in - sum(indegrees)))/(N-1)**2

rawDescription: calculate indegree centralization of graph with python networkx

description: Calculate indegree centralization of graph with python networkx


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.reader(f)
    scores = [int(row[-1]) for row in reader]

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code:
def linearfunc(x):
    return 3 * x

def getRandom(func, maxi, a, b):
    while True:
        x = random.uniform(a, b)
        y = random.uniform(0, maxi)
        if y < func(x):
            return (x, y)

points = [getRandom(linearFunc, 9, 0, 3) for i in range(10)]

rawDescription: random values from specific function python

description: Random values from specific function python


rawDescription: Python slice assignment in the reverse order doesn't work! Why?


rawDescription: How to sort keys only with same values?

description: Sort keys only with same values


code: "I went \n to the store\n".replace('\n', '')

rawDescription: Regex to remove newline character from string


code: [sum(ai) for ai in arra_mod]

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


code:
with open("new.txt") as file_2_read:
    text = file_2_read.read()

rawDescription: How to understand unicode and utf-8

description: Understand unicode and utf-8


code: tdic = dict((key, max(weeks) - min(weeks) + 1) for key, weeks in tdic.iteritems())

rawDescription: How can I create dictionary within dictionary

description: Create dictionary within dictionary


code: return None

rawDescription: What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check failes)?


rawDescription: How to split a matrix into 4 blocks using numpy?

description: Split a matrix into 4 blocks using numpy


code:
class Cls(object):
    def submthd(self):
        return 0
    def mthd(self):
        return self.submthd()
    def submthd2(self):
        return 0
    def mthd2(self):
        return self.submthd()

rawDescription: Can we pass a function and the mocker to another function for mocking?


code: Array[(byte_offset + ((bit_offset + Bit_Offset + i)/ 8))]

rawDescription: Understanding bit-manipulation function in Python


code:
subprocess.Popen('''export PATH=/usr/lib64/openmpi/bin/:$PATH;
export LD_LIBRARY_PATH=/usr/lib64/openmpi/lib/:$LD_LIBRARY_PATH;
source /opt/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc;
for i in *;
do surfaceConvert $i file_path/$i.stlb;
done''', shell=True)

rawDescription: Calling alias Command from python script


code:
existingFields = [] # empty list
for field in arcpy.ListFields(inputFC): # iterate over fields
    existingFields.append(field.name)   # add the attribute name to list for each field

rawDescription: How to use the List field function for a toolbox script?

description: Use the List field function for a toolbox script


code:
import re
s = """< a href="http://xxxx"><div> < image> < /image> < div> < /a>
< a href="http://xxxx">Some text< /a>"""
re.findall(r"< a\s*href=['\"]http.*?['\"][^<>]*>([^<>]*)<\s*/a>", s)

rawDescription: How to get href title from a element and delete all string?

description: Get href title from a element and delete all string


rawDescription: How to alter a part of an array

description: Alter a part of an array


code:
import pandas as pd
import pandas.rpy.common as com
import rpy2.robjects as ro

r = ro.r
statedata = r('''cbind(data.frame(state.x77), state.abb, state.area, state.center,
                 state.division, state.name, state.region)''')
df = com.convert_robj(statedata)
df.columns = df.columns.to_series().str.replace('state.', '')
subdf = df.loc[df['region']=='Northeast', 'Murder']
print(subdf)
# Connecticut       3.1
# Maine             2.7
# Massachusetts     3.3
# New Hampshire     3.3
# New Jersey        5.2
# New York         10.9
# Pennsylvania      6.1
# Rhode Island      2.4
# Vermont           5.5
# Name: Murder, dtype: float64
print(subdf.idxmax())

rawDescription: How do I get the maximum within a subset of my dataframe in Pandas?

description: Get the maximum within a subset of my dataframe in Pandas


rawDescription: Getting data from specific datetime range


code:
matrices.shape
points.shape
p = np.einsum('ijk,ik->ij', matrices, points)
p[0]
matrices[0].dot(points[0])
p[1]
matrices[1].dot(points[1])

rawDescription: Large point-matrix array multiplication in numpy


code:
halfwedge = np.pi/8
for i in range(8):
    ax.text(np.pi/2 - halfwedge*(2*i+1), 0.425, labels2[i])

for i in range(4):
    ax.text(np.pi/2 - halfwedge*2*(2*i+1), 0.15, labels[i])

rawDescription: insert text in the sections of circle in matplotlib

description: Insert text in the sections of circle in matplotlib


code:
max((cell[k], x, y)
    for (y, row) in enumerate(m)
    for (x, cell) in enumerate(row))[1:]

rawDescription: How to pick the largest number in a matrix of lists in python?

description: Pick the largest number in a matrix of lists in python


code:
from operator import attrgetter

search_result.sort(key=attrgetter('last_name', 'first_name'))

rawDescription: python sorting objects in a list using to criteria

description: Python sorting objects in a list using to criteria


code: (server_msg, body, octets) = self.conn_pop3.retr(number)

rawDescription: Get emails with Python and pop lib

description: Get emails with Python and pop lib


code:
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

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

prop = fm.FontProperties(fname='/usr/share/fonts/truetype/groovygh.ttf')
ax.set_title('This is some random font', fontproperties=prop, size=32)

plt.show()

rawDescription: How to use a (random) *.otf or *.ttf font in matplotlib?

description: Use a (random) *.otf or *.ttf font in matplotlib


code:
import random
import time
choices = list(range(0,11))
choices[3] = "3 was number 3!" #override the third indice
x = 1
ran = None #previous value before you start, needs to be defined for rule 1 to work
while True:
    last = ran
    while ran == last:
        ran = random.randrange(0,11)
    print ('Random :', choices[ran])
    x += 1
    time.sleep(1)

rawDescription: block repeat of random only for certain step through the random value

description: Block repeat of random only for certain step through the random value


code: #!/usr/bin/python

rawDescription: How do I execute a python script from the command line using custom commands?

description: Execute a python script from the command line using custom commands


code:
import myModule

myModule.main()

rawDescription: In Python, can I call the main() of an imported module?


code:
[
 ['Joakim Noah', 'Wilson Chandler', 'Michael Kidd-Gilchrist', 'Lance Stephenson', 'Joe Johnson', 'Blake Griffin', 'Darrell Arthur', 'Chris Paul', 'D.J. Augustin'],
 ['Joakim Noah', 'Wilson Chandler', 'Michael Kidd-Gilchrist', 'Lance Stephenson', 'Kyle Korver', 'Blake Griffin', 'Terrence Jones', 'Chris Paul', 'Shaun Livingston'],
 ['Joakim Noah', 'Wilson Chandler', 'Michael Kidd-Gilchrist', 'Lance Stephenson', 'Kyle Korver', 'Blake Griffin', 'Kris Humphries', 'Chris Paul', 'Jerryd Bayless'],
 ['Joakim Noah', 'Wilson Chandler', 'Michael Kidd-Gilchrist', 'Gordon Hayward', 'Joe Johnson', 'Blake Griffin', 'Andray Blatche', 'Chris Paul', 'Jerryd Bayless'],
 ['Joakim Noah', 'Wilson Chandler', 'Michael Kidd-Gilchrist', 'Gordon Hayward', 'Kyle Korver', 'Blake Griffin', 'Andray Blatche', 'Chris Paul', 'Avery Bradley']
]

rawDescription: Load lists from a text file

description: Load lists from a text file


code:
def numberToLetters(q):
    """
    Helper function to convert number of column to its index, like 10 -> 'A'
    """
    q = q - 1
    result = ''
    while q >= 0:
        remain = q % 26
        result = chr(remain+65) + result;
        q = q//26 - 1
    return result

def colrow_to_A1(col, row):
    return numberToLetters(col)+str(row)

def update_sheet(ws, rows, left=1, top=1):
    """
    updates the google spreadsheet with given table
    - ws is gspread.models.Worksheet object
    - rows is a table (list of lists)
    - left is the number of the first column in the target document (beginning with 1)
    - top is the number of first row in the target document (beginning with 1)
    """

    # number of rows and columns
    num_lines, num_columns = len(rows), len(rows[0])

    # selection of the range that will be updated
    cell_list = ws.range(
        colrow_to_A1(left,top)+':'+colrow_to_A1(left+num_columns-1, top+num_lines-1)
    )

    # modifying the values in the range

    for cell in cell_list:
        val = rows[cell.row-top][cell.col-left]
        cell.value = val

    # update in batch
    ws.update_cells(cell_list)

rawDescription: How to write a table (list of lists) to Google Spreadsheet using gspread

description: Write a table (list of lists) to Google Spreadsheet using gspread


code:
with open(input_file, 'r') as f_in:
    with open(output_file, 'w') as f_out:
       f_out.writelines(remove_duplicates(ifilter(is_line_ok, f_in)))

rawDescription: What's the fastest way to remove duplicate lines in a txt file(and also some lines which contain specific strings) using python?


code: [threed(x, y, z) for x in range(1, 3) for y in range(1,3) for z in range(1,3)]

rawDescription: Naming coordinates in python

description: Naming coordinates in python


code:
import re
exp = r'^set address "\w+" "(.*?)".*?$'
re.findall(exp, i, re.M)

rawDescription: get the content of what is in between the second set of quotes

description: Get the content of what is in between the second set of quotes


code:
[('Will Ferrell', 'Nick Halsey'), ('Rebecca Hall', 'Samantha'),
 ('Glenn Howerton', 'Gary'), ('Glenn Howerton', 'Brad'), ('Stephen Root', ''),
 ('Laura Dern', 'Delilah'), ('Laura Dern', 'Stacy')]

rawDescription: Using regex to extract information from a string


code: [[] for _ in range(3)]

rawDescription: Dereferencing lists inside list in Python


code:
lst = [{'very','beauty','place'},{'very','good','place'},{'another','trigram','item'}]
filterSimilar(lst)
lst

rawDescription: How to remove duplicates from a list in python

description: Remove duplicates from a list in python


rawDescription: For any rows with a NaN in a Pandas DataFrame, shift by 1


rawDescription: Printing to file works on Linux but not on Windows?


rawDescription: How to count rows in a data frame in Pandas conditionally against values in another column of the same data frame?

description: Count rows in a data frame in Pandas conditionally against values in another column of the same data frame


rawDescription: Retrieving values from 2 different tables with Django's QuerySet


code:
sizer.Add(description, (i*3, 0), (1, 3))
sizer.Add(question, (i*3+1, 0), flag=wx.EXPAND)
sizer.AddStretchSpacer((i*3+1,1))
sizer.Add(yes, (i*3+1, 2), flag=wx.ALIGN_RIGHT)
sizer.Add(no, (i*3+1, 3))

rawDescription: Filling available space with a column in GridBagSizer


code:
timeit.timeit('outcome = Result._member_map_["lose"]', 'from __main__ import Result')
timeit.timeit('outcome = map["lose"]', 'from __main__ import Result; map = Result._member_map_')

rawDescription: How to use Python 3.4's enums without significant slowdown?

description: Use Python 3.4's enums without significant slowdown


code:
if self.context.relocate:
            self.context.relocate = bool(self.context.relocate)

rawDescription: How to change values/types of Dictionary and put them back

description: Change values/types of Dictionary and put them back


code:
condition = Q(full_name__icontains=s[0])
for string in strings[1:]:
    condition &= Q(full_name__icontains=string)
queryset = Profile.objects.filter(condition)

rawDescription: Filter Django database for field containing any value in an array


code:
s = []
for i in new_list:
    s.append(i[:6])

rawDescription: Script Slicing in Python

description: Script Slicing in Python


rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


code: x = np.linalg.lstsq(A, B)[0]

rawDescription: Using Python to Find Integer Solutions to System of Linear Equations


code:
keys = ['Bob', 'Mary', 'Sue', 'George']
vals = [1, 2, 3, 4]
dict( zip(keys, vals) )
# {'Bob': 1, 'Mary': 2, 'Sue': 3, 'George': 4}

rawDescription: Python: Applying common keys from one Dictionary to another


code: request.add_header('User-Agent','None of your business.')

rawDescription: Can a server find out I am accessing it with a python script? If so, how to hide it?


code: [(function_a, function_b, function_c)[line.split('\t').index('?')]() for line in fileinput.readlines()]

rawDescription: Parsing through a file

description: Parsing through a file


code:
data_wins = as_strided(data, shape=(data.size - 2*winsize + 1, 2*winsize), strides=(8, 8))
inds = np.random.randint(low=0, high=data.size - 2*winsize, size=inds_size)
sliced = data_wins[inds]
sliced = sliced.transpose((2, 0, 1))    # to use the same index order as before

rawDescription: Efficiently slice windows from a 1D numpy array, around indices given by second 2D array


rawDescription: Python - How to launch a subprocess before exiting the program (which is running on a detached screen)?


code: cell_list = cell_list + [{'num':1, 'state':0}]

rawDescription: problem with a 2 dimensional array(list of list of dict)

description: Problem with a 2 dimensional array(list of list of dict)


code:
import pandas as pd
pd.read_clipboard()            # If you have selected the headers
pd.read_clipboard(header=None) # If you haven't selected the headers

rawDescription: Copying excel data into a python list in IPython using clipboard?


code:
user = User(name='MyName')
db.session.add(user)
db.session.commit()
manager = Manager(designation='Some designation', user=user)
db.session.add(manager)
db.session.commit()

rawDescription: Inheritance in Flask-SqlAlchemy

description: Inheritance in Flask-SqlAlchemy


rawDescription: How can I change the view of my list?

description: Change the view of my list


code:
my_list = [[1, 2], [3, 7], [4, 6]]
my_list.sort(key=lambda x: abs(x[0] - x[1]))
my_list

rawDescription: Sort list of lists by expression in Python


rawDescription: Partitioning multiline string in python

description: Partitioning multiline string in python


code:
import os
os.system("python userscript.py")

rawDescription: Open the terminal in python and run a python script


code:
string="aacctcaaaca"
find="aaa"
[m.group(0) for m in re.finditer(find, string+string) if m.start() < len(string)]

rawDescription: In python: How to perform regular expression search on "circular" string


code: [x for x in ilist if x]

rawDescription: filter lists of lists by taking out items less than a certain length - more pythonic way?

description: Filter lists of lists by taking out items less than a certain length - more pythonic way


code: ['#For5Rs', 'Javed Bashir', 'Milan Luthria', 'Vidya Balan']

rawDescription: How to get list of values of a single key from JSON using Python

description: Get list of values of a single key from JSON using Python


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

y, x = np.mgrid[-10:10:20j, -10:10:20j]
land = np.hypot(x, y) < 7

coast = scipy.ndimage.morphological_gradient(land,
                                            footprint=[[0, 1, 0],
                                                       [1, 1, 1],
                                                       [0, 1, 0]])

fig, ax = plt.subplots()
ax.pcolormesh(coast, cmap='gray', edgecolor='gray', antialiased=True)
plt.show()

rawDescription: Isolating coastal grids using convolving window (python)


code:
script = argv[0]
first = argv[1]
second = argv[2]
third = argv[3]

rawDescription: Printing individual script arguments repeatedly prints all of them


code:
import itertools
import random

probabilities = [0.3, 0.2, 0.5]
totals = list(itertools.accumulate(probabilities))

def sample():
    n = random.uniform(0, totals[-1])
    for i, total in enumerate(totals):
        if n <= total:
            return i

rawDescription: Generating weighted random numbers

description: Generating weighted random numbers


code:
inputListTrue = [[1,1,1],[2,2,2],[3,3,3]]
inputListFalse = [['a','a','a'],['b','b','b'],['c','c','c']]
pattern = [[True, False, True],[True, True, True],[False, False, True]]
choose(inputListTrue, inputListFalse, pattern)

rawDescription: pick and choose from two nested lists by a pattern using Python

description: Pick and choose from two nested lists by a pattern using Python


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

data = np.genfromtxt('file1.dat', delimiter=',', skip_header=1, names=['MAG', 'X0', 'Y0','X1','Y1'])
plt.scatter(data['X0'], data['Y0'], color='r', zorder=10)
plt.scatter(data['X1'], data['Y1'], color='r', zorder=10)

for d in data:
    if(d['MAG'] > 0):
        plt.arrow(d['X0'],d['Y0'],d['X1']-d['X0'], d['Y1']-d['Y0'],
         shape='full', color='b', lw=d['MAG']/2., length_includes_head=True,
         zorder=0, head_length=3., head_width=1.5)

plt.show()

rawDescription: Arrows on Scatter

description: Arrows on Scatter


rawDescription: Two Combination Lists from One List

description: Two Combination Lists from One List


rawDescription: adding two consecutive numbers in a list

description: Adding two consecutive numbers in a list


code:
for idx, row in df.iterrows():
    get_prices = Quandl.get(row['Codes'], returns='pandas')
    # Data to SQL
    get_prices.to_sql(name=row['Company Name'], con=engine)

rawDescription: How to structure a For loop with pandas dataframe

description: Structure a For loop with pandas dataframe


rawDescription: GAE - Issue with GET

description: GAE - Issue with GET


code:
def ShowGroupROIFunction(self):
    dialog = SGROIWidget_ui.Ui_ShowGroupWidget()
    if dialog.exec_():
        print(dialog.roiGroups)

rawDescription: PyQt QDialog - returning a value and closing from dialog


code:
def mult_mat(x, nbr, y=None):
    if nbr == 1:
        # if y is None, it means we called `mult_mat(x, 1)`, so return `x`
        if y is not None:
            return y
        return x

    if y is None:
        y = x
    result = [[0, 0],
              [0, 0]]
    for i in range(len(x)):
        for j in range(len(result[0])):
            for k in range(len(result)):
                result[i][j] += x[i][k] * y[k][j]
    return mult_mat(x, nbr-1, result)

m = [[2, 4],
      [1, 3]]

# the number of times m1 will be multiplied
n = 3
res = mult_mat(m, n)
for r in res:
    print(r)

rawDescription: Recursive function to calculate matrix multiplication


code:
import csv

with open(filename, 'rb') as infh:
    reader = csv.reader(infh)
    next(reader)  # skip the header row
    result = {tuple(row[:3]): row[4] for row in reader}

rawDescription: Create a dictionary from CSV file, with multiple keys


code:
from itertools import takewhile
len([1 for _ in takewhile(lambda x:x==a[0], a)])

rawDescription: Find number of consecutive elements that are the same before they change


code:
import mimetypes
type, subtype = mimetypes.guess_type(filename_or_url)

rawDescription: How to know the filetype through python

description: Know the filetype through python


code:
difference = (cost_with - cost_without)/100

if b == 1:
    max_difference = difference
    currentRow = ['PV Size' + ' ' + str(size), difference]
else:
    currentRow.append(difference)

if max_difference > difference:
    max_difference = difference

if b==6:
   wb2s1.append(currentRow)

rawDescription: Openpyxl to write in a single cell

description: Openpyxl to write in a single cell


code:
session['my_list'] = some_list
return redirect(url_for('show_list'))

rawDescription: How can I "redirect" to another URL and pass a list object using Flask


code:
def filter_low(lst, maxk, threshold=3):
    for item in lst:
        c = sum(1 for k in maxx if item==k.f)
        if c >= threshold:
             yield item

new_seen = list(filter_low(seen, maxk, 3))

rawDescription: PYTHON - 'for' index changing because of list.pop() call


code: s.drop(s.index[1: 4])

rawDescription: Removing elements from pandas series in python


code:
list = [1, 2, 3]
# List is [1, 2, 3]

list += [4]
# Added an element at the end

list[0] = 42
# We changed the first element to 42
# List is [42, 2, 3, 4]

rawDescription: Explaining persistent data structures in simple terms


code:
def get_cells(size):
    return [(x_axis, y_axis) for x_axis in range(size) for y_axis in range(size)]

rawDescription: Python: returning the cell coordinates

description: Python: returning the cell coordinates


code: left = recursion(a,l,m)         # T(n/2)

rawDescription: Theta(n**2) and Theta(n*lgn) algorithm perform unproperly


code:
my_list = ["A", "B", "C", "X", "X", "X"]
list(mergefill(my_list, 'X', product('LE', repeat=3)))

rawDescription: Replacing List values sequentially with values from another list


code:
print("{:{width}} \t current ver: {} \t latest ver: {}".format(
    name, current_version, latest_version, width = maxLength)
)

rawDescription: How to make specific parts of a text line indented properly?

description: Make specific parts of a text line indented properly


code:
if x == THING_THAT_RESULTS_IN_NONE:
    result = DEFAULT_VALUE
else:
    result = could_return_none(x) # But it won't return None, because we've restricted the domain.

rawDescription: python how to convert Nonetype to int or string

description: Python how to convert Nonetype to int or string


code:
import psycopg2
import psycopg2.extras
pg_conn = psycopg2.connect("dbname=dbname host=localhost user=postgres")
pg_cur = pg_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
pg_cur.execute('whatever')
pg_conn.commit()

rawDescription: SQL : Insert and Update a new column from existing column


code:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
g = sns.clustermap(flights)

rawDescription: Add custom border to certain cells in a matplotlib / seaborn plot


code:
import music21
import pandas as pd
import numpy as np

s1 = pd.Series(['C4', 'E-4', 'G4', 'A-4'])
df = pd.DataFrame({0:s1, 1:s1.shift(1)})

def myfunc(x):
    if not any([pd.isnull(x[0]), pd.isnull(x[1])]):
        return music21.interval.Interval(music21.note.Note(x[0]),music21.note.Note(x[1])).name

df.apply(myfunc, axis = 1)

rawDescription: Make a pandas series by running a function on all adjacent values


code:
# Create the ball
ball = Ball()
allsprites.add(ball)
balls.add(ball)

rawDescription: Understand object orientated python - initialization of objects in pygame


code:
line_width = 10
for i in range(20):
    msg = 'BOOTING{0}'.format('.' * i)
    # Get only the last portion of the message
    # that is shorter than the line width
    msg = msg[-line_width:]
    # Pad with spaces if shorter than line width
    # Ensures old content is overwritten
    msg = msg.ljust(line_width)
    sys.stdout.write('\r{0}'.format(msg))

rawDescription: Stdout looping halt after certain amount of characters


code:
with logname("stuff"):
    logging.info("I'm doing stuff!")
    do_more_stuff()

rawDescription: How can you make logging module functions use a different logger?

description: Make logging module functions use a different logger


rawDescription: Python remove separating spaces

description: Python remove separating spaces


code:
def get_instances_by_purpose(access_key,secret_key,region,env,project):
    conn = ec2.connect_to_region(region,aws_access_key_id=access_key,aws_secret_access_key=secret_key)
    reservations = conn.get_all_instances(filters={"tag:env":env, "tag:project":project})
    instances = [i for r in reservations for i in r.instances]
    instances_by_purpose = {}
    [instances_by_purpose.setdefault(i.tags.get('purpose'), []).append(i.id) for i in instances]
    return instances_by_purpose

rawDescription: Getting only unique tags from a set of tagged ec2 instances


code:
def cycle(lst, val, stop=None):
    d = dict(lst)
    stop = stop if stop is not None else val
    while True:
        yield val
        val = d.get(val, stop)
        if val == stop: break

rawDescription: How to join links in Python to get a cycle?

description: Join links in Python to get a cycle


code: list(map(formatter, data))

rawDescription: add leading zeros to a list of numbers in Python

description: Add leading zeros to a list of numbers in Python


code:
from datetime import datetime, timedelta

original_time = datetime.now() # datetime.datetime(2015, 5, 11, 12, 32, 46, 246004)
print(original_time) # 2015-05-11 12:32:46.246004

offset = timedelta(hours=12) # datetime.timedelta(0, 43200)
shifted_time = original_time + offset # datetime.datetime(2015, 5, 12, 0, 32, 46, 246004)
print(shifted_time) # 2015-05-12 00:32:46.246004

rawDescription: getting the hour from current time

description: Getting the hour from current time


rawDescription: python read data build association rules

description: Python read data build association rules


rawDescription: Append a dict in a nested dict python

description: Append a dict in a nested dict python


code: [map(float, pair) for pair in zip(A, B) if all(pair)]

rawDescription: Plot two vectors for elements which exist - i.e. skip rows without entries


code:
from excel_response import ExcelResponse

def vw_export_to_Excel(request):
    data = list(_Custumer.objects.values_list())
    return ExcelResponse(data, 'customer')

rawDescription: Export RawQuerySet to excel with ExcelResponse. Error "ExcelResponse requires a sequence of sequences"


code:
a = C(1)
a.num = 2
b = C(1)
b.num
a is b

rawDescription: Unique representations of Python objects


code:
class Demo():
    good = 'Spice'
    price = 10
    location = 'Betazed'
    fromsys = 'Arrakis'
    tosys = 'Endor'

formats = {
    'Price': '{0.good} is worth {0.price} at {0.location}',
    'Wormhole': '{0.fromsys} has a wormhole to {0.tosys}',
}
formats['Price'].format(Demo())
formats['Wormhole'].format(Demo())

rawDescription: Evaluating a string-producing statement 'later' when stored in a dict


rawDescription: How to check if a dictionary is in another dictionary in python

description: Check if a dictionary is in another dictionary in python


code: return data['response']

rawDescription: Why can I call all these methods that aren't explicitly defined in a class?


rawDescription: Printing a list of list without brackets in python


rawDescription: Python: three different delimiters between columns, column to list, quickest way


code:
for item in mylist:
    value = get(item)
    if value is not None:
        return value

rawDescription: How to use return in for loop with function in python

description: Use return in for loop with function in python


code:
def files(a):
    entries =  [os.path.join(a,i) for i in os.listdir(a)]

    f =  [i for i in entries if os.path.isfile(i)]
    if len(os.listdir(a)) == 0:
            return
    if len(f) > 0:
            fi.extend(f)
    for j in [i for i in entries if os.path.isdir(i)]:
            files(j)

rawDescription: Recursively list all files in directory (Unix)


code:
route = boto.connect_route53()
hc = boto.route53.healthcheck.HealthCheck(...)
route = create_health_check(hc)

rawDescription: python boto - how to create health check for route 53

description: Python boto - how to create health check for route 53


rawDescription: Many numpy array manipulations in one array


code:
mod = win32com.client.gencache.GetModuleForProgID("MyProgram.Application")
IAnotherList = mod.IAnotherList
setattr(IAnotherList, '__getitem__', generic_getitem)
setattr(IAnotherList, '__iter__', com_generic_iter)

rawDescription: Add __getitem__ function to COM object in Python, OR: Overriding __slots__?


code:
import re
'%s%s' %(lambda m:d1[m.group()[0]], lambda m:d2[m.group()[1]])

rawDescription: Why my regex replaces match pattern with function object rather than the replacement value?


code:
curveSel = []
meshSel = []
for xform in curSel:
   shapes = cmds.listRelatives(xform, shapes=True) # it's possible to have more than one
   for s in shapes:
       if cmds.nodeType(s) == 'mesh':
          curveSel.append(xform)
       if cmds.nodeType(s) == 'nurbsCurve':
          meshSel.append(xform)

rawDescription: Maya + Python array collecting

description: Maya + Python array collecting


code:
from collections import OrderedDict

def group_ordered(list_in):
    result = OrderedDict()
    for value in list_in:
        result.setdefault(value, []).append(value)
    return [v for group in result.values() for v in group]

rawDescription: Group list-items by order of appearance in unsorted list


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

if __name__ == "__main__":
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

rawDescription: Continuously parse CSV files which are updated by another process


code:
import subprocess
def runCmd(exe):
    p = subprocess.Popen(exe,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while True:
        retcode = p.poll()
        line = p.stdout.readline()
        yield line
        if retcode is not None:
            break
def hasRQJob():
    jobs = runCmd('qstat')
    for line in jobs:
        columns = line.split()
        if columns[-2] in ('Q','R'): return True
    return False

rawDescription: Script to Check if Torque Jobs are Running/Queued


code:
import aenum
class EnumWithAttrs(aenum.AutoNumberEnum):
    _init_ = 'a b'
    GREEN = 'a', 'b'
    BLUE = 'c', 'd'

rawDescription: python enums with attributes

description: Python enums with attributes


code:
pool = mp.Pool()
foo = MyClass()
foo.my_parallelized_function()

rawDescription: Python: Efficient workaround for multiprocessing a function that is a data member of a class, from within that class


rawDescription: selecting rows in numpy ndarray based on the value of two columns

description: Selecting rows in numpy ndarray based on the value of two columns


code: df.index = p2['DT_COMPUTE_FORCAST']

rawDescription: Pandas / SQLITE DataFrame plot

description: Pandas / SQLITE DataFrame plot


rawDescription: Attach callback to Counter() value

description: Attach callback to Counter() value


rawDescription: Pandas - finding the row with least value of one of the levels of a multiindex


code:
row = cur.fetchone()
config_params = dict(
    hostname=row[0], syslocation=row[1],
    ipaddress=socket.inet_ntoa(struct.pack('!L', row[2])),
    netmask=socket.inet_ntoa(struct.pack('!L', row[3])),
    username=row[4], password=row[5], bri1=row[6], bri2=row[7],
    bri3=row[8], bri4=row[9])

rawDescription: Get value from dict

description: Get value from dict


rawDescription: Apply a weighted average function to a dataframe without grouping it, as if it was a single group


code: np.allclose(func1(xy, 2), func3(xy, 2))

rawDescription: Can numpy einsum() perform a cross-product between segments of a trajectory


code:
import time
a="Some Random text of undetermined length Jan 28, 1986"
datetuple = a.rsplit(" ",3)[-3:]
datetuple
time.strptime(' '.join(datetuple),"%b %d, %Y")

rawDescription: How do I strptime from a pattern like this?

description: Strptime from a pattern like this


code: data.sort(key = lambda row: (row[0], int(row[1])))

rawDescription: Sort a list of lists with two index

description: Sort a list of lists with two index


code: [f(*par) for par in  zip(a, b)]

rawDescription: Vectorize a 2-dimensional function in python


rawDescription: Python: Effective reading from a file using csv module


code:
def format_f(f):
    if isinstance(f, int) or '+' not in f:
        return "{0}".format(f)
    return "({0})".format(f)

def fib(n, first=True):
    if first:
        yield "fib({0})".format(n)
    if n < 2:
        yield n
    else:
        yield "fib({0}) + fib({1})".format(n-1, n-2)
        for f1 in fib(n-1, False):
            yield "{0} + fib({1})".format(format_f(f1), n-2)
        for f2 in fib(n-2, False):
            yield "{0} + {1}".format(f1, format_f(f2))
        yield f1 + f2

rawDescription: How to print recursive evaluation process?

description: Print recursive evaluation process


code:
from Pyside.QtGui import QMessageBox

def add_helpWindow(self):
    help_dialog = QMessageBox.information(self, 'Help', 'Some Help Text Here')
    help_dialog.setModal(True)
    return help_dialog.exec_()

rawDescription: Query regarding Pyside

description: Query regarding Pyside


code:
input_text= "I have a dog and a cat"
re.sub(".*?(cat|dog|rat)", "\\1", input_text, 1)
re.sub("(?s).*?(cat|dog|rat)", "\\1", input_text, 1)
input_text= "This is irrational"
re.sub("(?s).*?(cat|dog|rat)", "\\1", input_text, 1)

rawDescription: Delete all characters in a multline string up to a given pattern


code:
eq = eq[:,~np.isnan(eq).all(0)]
eq = eq[~np.isnan(eq).all(1)]
eq

rawDescription: Removing nan elements from matrix

description: Removing nan elements from matrix


code:
import cStringIO
fp = cStringIO.StringIO()
MyImage.save(fp,'GIF')
MyPhotoImage = PhotoImage(data=fp.getvalue())

rawDescription: Tkinter using a non-saved picture as an image


code: rows=zip(powery,powerx)

rawDescription: Python - Outputting two data sets (lists?) to data file as two columns


code:
def starttls(self, keyfile=None, certfile=None, context=None):
    """Puts the connection to the SMTP server into TLS mode.

    If there has been no previous EHLO or HELO command this session, this
    method tries ESMTP EHLO first.

    If the server supports TLS, this will encrypt the rest of the SMTP
    session. If you provide the keyfile and certfile parameters,
    the identity of the SMTP server and client can be checked. This,
    however, depends on whether the socket module really checks the
    certificates.

    This method may raise the following exceptions:

     SMTPHeloError            The server didn't reply properly to
                              the helo greeting.
    """
    self.ehlo_or_helo_if_needed()
    if not self.has_extn("starttls"):
        raise SMTPNotSupportedError(
            "STARTTLS extension not supported by server.")
    (resp, reply) = self.docmd("STARTTLS")
    if resp == 220:
        if not _have_ssl:
            raise RuntimeError("No SSL support included in this Python")
        if context is not None and keyfile is not None:
            raise ValueError("context and keyfile arguments are mutually "
                             "exclusive")
        if context is not None and certfile is not None:
            raise ValueError("context and certfile arguments are mutually "
                             "exclusive")
        if context is None:
            context = ssl._create_stdlib_context(certfile=certfile,
                                                 keyfile=keyfile)
        self.sock = context.wrap_socket(self.sock,
                                        server_hostname=self._host)
        self.file = None
        # RFC 3207:
        # The client MUST discard any knowledge obtained from
        # the server, such as the list of SMTP service extensions,
        # which was not obtained from the TLS negotiation itself.
        self.helo_resp = None
        self.ehlo_resp = None
        self.esmtp_features = {}
        self.does_esmtp = 0
    return (resp, reply)

rawDescription: Sending email from Python using STARTTLS


code: from folder1.folder2 import *

rawDescription: Python project architecture

description: Python project architecture


code: [k for k,v in b.iteritems() if k.startswith('id123')]

rawDescription: python get all ids startingwith a pattern

description: Python get all ids startingwith a pattern


code:
def func(content):
    f.write()

rawDescription: Downloading .pdf file from FTP using a Python Script


code:
for name in name_company:
    ford = name.find('h2').string
    f.writerow([ford, all_data[2].getText()])

rawDescription: Python: BeautifulSoup Findall Skip to the Next Tag


code:
with open("/path/to/file.xml") as source:
    xml = "".join(itertools.chain(["<something>"], source, ["</something>"]))
# etc...

rawDescription: Modifying a Python file object without writing a new file


rawDescription: how to create local dynamic variables

description: Create local dynamic variables


rawDescription: Pandas: decompress date range to individual dates


code:
M = L[0:len(L):2]
newL = reversed(M)

rawDescription: why reversed() list iteration with step doesn't work properly?

description: Why reversed() list iteration with step doesn't work properly


code:
def finite_generator(source=[3, 2, 1]):
    while source:
        yield source.pop()

rawDescription: Why does Python's itertools.cycle need to create a copy of the iterable?


code:
uniqueVals = ['foo', 'bar', 'ter']

# Create your own list of markers here (needs to be the same size as `uniqueVals`)
markers = ['o', '^', 's']
colors = ['r', 'g', 'b']

for color, marker, val in zip(colors, markers, uniqueVals):
    toUse = coordLabels == val
    ax.scatter(coordData[toUse,0], coordData[toUse,1], c=color, marker=marker)

rawDescription: How to change marker and color in matplotlib for a specific column value?

description: Change marker and color in matplotlib for a specific column value


code:
player_input = raw_input("Enter a character: ")
while player_input not in ('n', 'r', 'e'):
    player_input = raw_input("Enter a character: ")

rawDescription: Multiple 'or' on while loop

description: Multiple 'or' on while loop


code:
def myview(request):
  rows = MyModel.objects.using('mysql').all()
  return render_to_response("mytemplate.html", {"rows" : rows })

rawDescription: Pulling data to the template from an external database with django


code:
from functools import wraps
import inspect

def initializer(func):
    """
    Automatically assigns the parameters.

    >>> class process:
    ...     @initializer
    ...     def __init__(self, cmd, reachable=False, user='root'):
    ...         pass
    >>> p = process('halt', True)
    >>> p.cmd, p.reachable, p.user
    ('halt', True, 'root')
    """
    names, varargs, keywords, defaults = inspect.getargspec(func)

    @wraps(func)
    def wrapper(self, *args, **kargs):
        for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
            setattr(self, name, arg)

        for name, default in zip(reversed(names), reversed(defaults)):
            if not hasattr(self, name):
                setattr(self, name, default)

        func(self, *args, **kargs)

    return wrapper

rawDescription: Python: Automatically initialize instance variables?


code:
x is False
x if x is False else y     # x and y

rawDescription: Custom chained comparisons

description: Custom chained comparisons


code:
h4 = soup.select_one("div.article-contents > h4")
print(h4.find_next_sibling(text=True))

rawDescription: Python: parsing texts between keywords

description: Python: parsing texts between keywords


code:
sentence = 'AASFG BBBSDC FEKGG SDFGF KETGG'

def neighborhood(iterable):
    iterator = iter(iterable)
    prev = None
    item = iterator.next()  # throws StopIteration if empty.
    for next in iterator:
        yield (prev,item,next)
        prev = item
        item = next
    yield (prev,item,None)

matches = [word for word in sentence.split() if word.endswith("GG")]
results = []

for prev, item, next in neighborhood(sentence.split()):
    for match in matches:
        if match == item:
            results.append((prev, item, next))

rawDescription: Find word infront and behind of a Python list


code: isPNGBlock(0, 0, 0, sys.stdout.write)

rawDescription: Python builtin function as keyword argument default?


code:
for reps in range(replications):

    current_run = initialize.Run(input_data[run])
    '''some other code here'''

    env.run(until=end)

    reps += 1

rawDescription: Method to automate simulation runs

description: Method to automate simulation runs


code:
if request.method == 'POST':
    form = ProjectForm(request.POST)
    if form.is_valid():
        # get cleaned data from form
        prj_name = form.cleaned_data['name']
        prj_manager = form.cleaned_data['manager']  # this is a User-object

        # generate project and store it to db
        prj = Project(name=prj_name)
        prj.save()

        # handling now m2m relation for manager
        prj.manager.add(prj_manager)

        return HttpResponseRedirect("/project/list")

else:
    form = ProjectForm()

rawDescription: Replacing ManyToMany-Relation with ModelChoiceField


code:
tf_train_dataset = tf.placeholder(tf.float32,shape=(batch_size, image_size * image_size))
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))

rawDescription: Printing an object in TensorFlow

description: Printing an object in TensorFlow


code:
from xlutils.copy import copy as copy_workbook

output_wb = copy_workbook(input_wb)

rawDescription: Conditionally formatting text strings from Excel using python


code:
json.dumps(
    [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
)

rawDescription: two Lists to Json Format in python

description: Two Lists to Json Format in python


code:
if msg.is_multipart():
    for part in msg.walk():
        if part.get_content_type() and part.get_content_type()=='text/plain': # ignore text/html
            charset = part.get_content_charset()
            body = part.get_payload(decode=True).decode(charset)
else:
    body = msg.get_payload(decode=True)
    body = body.decode('utf-8')

rawDescription: How to log e-mail details in AppEngine Admin console?

description: Log e-mail details in AppEngine Admin console


rawDescription: MongoEngine: Limiting number of responses from DBRef


rawDescription: Replace values of a numpy array by values from another numpy array


code:
rows = list(Entry(*l.split()) for l in open('t.tsv', 'r'))
import random
random.sample(rows, 1)
random.sample(rows, 1)
random.sample(rows, 1)
random.sample(rows, 1)
random.sample(rows, 1)
random.sample(rows, 1)
random.sample(rows, 3)
random.sample(rows, 3)
random.sample(rows, 3)

rawDescription: How to read a specific row of a csv file in python?

description: Read a specific row of a csv file in python


code:
data = {
   "comment": "this is a comment",
   "post_id": 1234
}

rawDescription: Alternative to using mechanize to fetch data?


code: do_n(print_greeting, 3)

rawDescription: Python: Passing a function and calling it recursively


rawDescription: trouble setting index values to date.time pandas

description: Trouble setting index values to date.time pandas


code:
import re
source = "blahblah'url=:'http://link.com/=tag/blahblah'url=:'http://link2.com/=tag'"
re.findall(r"(url=:'http://.+?=tag)", source)

rawDescription: python regular expression on first occurance

description: Python regular expression on first occurance


code:
if condition:
    import fileA as file
else:
    import fileB as file
file.foo()

rawDescription: run another .py file when condition is true

description: Run another .py file when condition is true


code:
# Find out the unique elements and their starting positions
unq_data, idx = np.unique(data,return_index=True)

# Find out the positions for each unique element, their duplicate positions
dup_idx = np.setdiff1d(np.arange(data.size),idx)

# Set those duplicate positioned elemnents to 0s
data[dup_idx] = 0

rawDescription: Set duplicate elements as zeros

description: Set duplicate elements as zeros


code:
game.state = initState
self.initialState = initState.deepCopy()

rawDescription: "self" as method attribute

description: "self" as method attribute


code:
def create_mask(self):
    self.mask = Image.new('L', (200,200), 0)
    draw = ImageDraw.Draw(self.mask)
    draw.ellipse((0, 0) + self.mask.size, fill=255)

rawDescription: Create circular image PIL Tkinter

description: Create circular image PIL Tkinter


rawDescription: Reshape wide to long in PANDAS

description: Reshape wide to long in PANDAS


code: 'g' and 'd'

rawDescription: Using python to search a text file for the occurence of specific characters


code:
import PIL.ExifTags
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS
}

rawDescription: In Python, how do I read the exif data for an image?


code:
def is_consecutive(n):
    x = n | (n - 1)
    return x & (x + 1) == 0

rawDescription: How to check if there is only consecutive ones and zeros in bytestream

description: Check if there is only consecutive ones and zeros in bytestream


code:
last_mouse_pos = None

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit

        if event.type == MOUSEBUTTONDOWN:
            last_mouse_pos = pygame.mouse.get_pos()

        elif event.type == KEYDOWN and event.unicode == 'c':
            # clear the circle when pressing the 'c' key
            last_mouse_pos = None

    screen.blit(background,(0,0))
    x,y = pygame.mouse.get_pos()
    x -= mousec.get_width()/2
    y -= mousec.get_height()/2

    screen.blit(mousec, (x,y))

    if last_mouse_pos:
        color = (100,100,100)
        posx,posy = last_mouse_pos
        pygame.draw.circle(screen, color, (posx,posy), 50)

    pygame.display.update()

rawDescription: Why won't pygame draw a circle?

description: Why won't pygame draw a circle


code:
app_phone = 5555555555
query_string="""SELECT biz_name, biz_addr, biz_owner
                 FROM business_t
                 WHERE regexp_replace(biz_phone_1, E'\\\\D|^1', '', 'g') = '%(phone)s'
                     OR regexp_replace(biz_phone_2, E'\\\\D|^1', '', 'g') = '%(phone)s'
                     OR regexp_replace(biz_cell_1, E'\\\\D|^1', '', 'g') = '%(phone)s'
                     OR regexp_replace(biz_cell_2, E'\\\\D|^1', '', 'g') = '%(phone)s';
             """
result = run_query(query_string, {'phone': app_phone})

rawDescription: Database query grammar in python

description: Database query grammar in python


code:
self.window.focus_group(0)
self.window.open_file(htmlFile)

self.window.focus_group(1)
self.window.open_file(jsFile)

self.window.focus_group(2)
self.window.open_file(sassFile)

rawDescription: How to use the sublime plugin api to create a new layout and open a file in each cell

description: Use the sublime plugin api to create a new layout and open a file in each cell


code:
def my_dec_factory(param1, param2):
   ...
   ...
   def real_decorator(func):
       ...
       def wraper_func(*args, **kwargs):
           ...
           #use param1
           result = func(*args, **kwargs)
           #use param2
           return result
       return wraper_func
   return real_decorator

rawDescription: Python decorator best practice, using a class vs a function


rawDescription: Updating elements in nested list using 'for' won't work in python list


code:
import sys
a=list()
type(a)
sys.getsizeof(a)
b=1
type(b)
sys.getsizeof(b)

rawDescription: Python: How much space does each element of a list take?


code: ax = plt.gca()

rawDescription: Hierarchy in matplotlib

description: Hierarchy in matplotlib


code:
import sys
sys.modules["renderer"] = OpenGLRenderer()
import renderer   # gives current module access to the "module"

rawDescription: Intercepting module calls, python

description: Intercepting module calls, python


code:
import json
a = '[[a b] [c d]]'
a = ''.join(map(lambda x: '"{}"'.format(x) if x.isalpha() else x, a))
a
json.loads(a.replace(' ', ','))

rawDescription: how to turn a string of letters embedded in squared brackets into embedded lists

description: Turn a string of letters embedded in squared brackets into embedded lists


code:
def __str__(self):
    return "Connector between {} and {}".format(self.fgate.name, self.tgate.name)

rawDescription: Python class inheritance/Logic gate & circuit example


code:
def format_epilog(self, formatter):
    return formatter.format_epilog(self.epilog)

def format_help(self, formatter=None):
    if formatter is None:
        formatter = self.formatter
    result = []
    if self.usage:
        result.append(self.get_usage() + "\n")
    if self.description:
        result.append(self.format_description(formatter) + "\n")
    result.append(self.format_option_help(formatter))
    result.append(self.format_epilog(formatter))
    return "".join(result)

rawDescription: python optparse, how to include additional info in usage output?

description: Python optparse, how to include additional info in usage output


code:
lens = np.array([len(i) for i in x])
cut_idx = np.append(0,lens[:-1]).cumsum()
out = np.add.reduceat(np.vstack(x),cut_idx,axis=0)/lens[:,None]

rawDescription: numpy - apply aggregation on each row of array

description: Numpy - apply aggregation on each row of array


code:
elevation_change = np.zeros_like(sediment_transport)
nrows, ncols = flow_direction.shape
lookup = {32: (-1, -1),
          16:  (0, -1),
          8:   (1, -1),
          4:   (1,  0),
          64: (-1,  0),
          128:(-1,  1),
          1:   (0,  1),
          2:   (1,  1)}

for [i, j], flow in np.ndenumerate(flow_direction):
    dr, dc = lookup.get(flow, (0,0))
    r, c = i + dr, j + dc
    if not ((0 <= r < nrows) & (0 <= c < ncols)):
        elevation_change[i,j] = 0
    else:
        elevation_change[i,j] = sediment_transport[r, c]

rawDescription: Iterating through a numpy array and then indexing a value in another array


code:
np.arange(4) + t
t + np.arange(4)

rawDescription: Argument types differ in normal and reflected operator overload (__sub__ / __rsub__)


code:
df = pd.concat([df1, df3], axis=1)
df.plot()

rawDescription: How to equalise two different Dataframe column into same size

description: Equalise two different Dataframe column into same size


rawDescription: Concatenating Columns Pandas

description: Concatenating Columns Pandas


code:
l=[('A', '<function __main__.percentile_50>'),
 ('B', '<function numpy.core.fromnumeric.sum>'),
 ('C', '<function numpy.core.fromnumeric.sum>'),
 ('D', '<function numpy.core.fromnumeric.mean>')]

[(i,j.strip('>').split('.')[-1]) for i,j in l]

rawDescription: Extract characters from string after last period


code:
a = np.arange(27)
indices = [0, -1]
b = a[indices] # array([0, 26])

rawDescription: Pythonic way to get the first AND the last element of the sequence


code:
d = {'1': 'stack', '2': 'over', '3': 'flow'}
from itertools import chain
tuple(chain.from_iterable(d.items()))

rawDescription: How can I convert a dictionary to a tuple in python?

description: Convert a dictionary to a tuple in python


code:
A = [np.random.random((5, 5)) for i in xrange(4)]
product1 = A[0].dot(A[1]).dot(A[2]).dot(A[3])
product2 = reduce(numpy.dot, A)
numpy.all(product1 == product2)

rawDescription: Multiply several matrices in numpy

description: Multiply several matrices in numpy


rawDescription: Regular expression in python: removing square brackets and parts of the phrase inside of the brackets


code: res.columns = range(1, 25)

rawDescription: Ho to convert a pd data frame to matrix structure in python


code: not all(str(s).isdigit() for s in a)

rawDescription: How to detect non-number of the list?

description: Detect non-number of the list


code:
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include('contact.urls')),
]

urlpatterns += staticfiles_urlpatterns()

urlpatterns += [
    url(r'', TemplateView.as_view(template_name='index.html')),
]

rawDescription: decoupled frontend and backend with Django, webpack, reactjs, react-router

description: Decoupled frontend and backend with Django, webpack, reactjs, react-router


code:
[map(first, row) for row in data]
[map(second, row) for row in data]

rawDescription: How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?

description: Achieve two separate list of lists from a single list of lists of tuple with list comprehension


code: pprint(result)

rawDescription: find duplicates in a column, return the unique item and list its corresponding values from another column in python

description: Find duplicates in a column, return the unique item and list its corresponding values from another column in python


rawDescription: Issue with merging time series variables to create new DataFrame with arbitrary index


code:
import os
[os.remove(os.path.join("E:\\test",f)) for f in os.listdir("E:\\test") if f.endswith(".txt")]

rawDescription: Delete files with python through OS shell


code: df

rawDescription: Pandas: convert upper triangular dataframe by shifting rows to the left


code:
import itertools

symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",       "K"]

combinations = itertools.product(symbols, numbers)

cards = ["{}:{}".format(suit, rank) for suit,rank in combinations]

rawDescription: Python list and for loop

description: Python list and for loop


code:
def foo(a, b, c):
    arguments = locals()
    return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None)

foo(None, 'Antioch', 3)

rawDescription: How to iterate over function arguments

description: Iterate over function arguments


rawDescription: Scrapy Calling another Url

description: Scrapy Calling another Url


code:
from dateutil import tz
from datetime import datetime
NEW_YORK = tz.gettz('America/New_York')
dt = datetime(2008, 1, 1, 16, 0, tzinfo=NEW_YORK)
dt_naive = dt.replace(tzinfo=None)   # datetime(2008, 1, 1, 16)

rawDescription: How to store time without date in Python so it's convenient to compare?

description: Store time without date in Python so it's convenient to compare


code:
import re
match = re.match("PHOTO(.+)\n", string)
match.groups()

rawDescription: Python regex remove string

description: Python regex remove string


code:
def get_row():
    response = input('Enter your name and score, separated by a space: ').split()
    return response[0], int(response[1])

rawDescription: Is there a real-life advantage of mixed lists


code:
import cherrypy
import os.path
import struct
from jinja2 import Template

class Server(object):
    led_switch=1
    def index(self,  switch=''):
        myText = ''
        if switch:
            self.led_switch = int(switch)
            myText = "Please Wait"
        html = Template("""

{{ htmlText }}

                """)

        return html.render(htmlText=myText)
    index.exposed = True

    conf = {
        'global' : {
            'server.socket_host': '0.0.0.0', #0.0.0.0 or specific IP
            'server.socket_port': 8080 #server port
        },

        '/images': { #images served as static files
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('images')
        },

        '/favicon.ico': {  #favorite icon
            'tools.staticfile.on': True,
            'tools.staticfile.filename': os.path.abspath("images/bulb.ico")
        }
    }
cherrypy.quickstart(Server(), config=conf)

rawDescription: How to display text on the web page using python and HTML

description: Display text on the web page using python and HTML


code:
customer = {
    'first_name': first_name,
    'last_name': last_name,
    'addresses': [{
        'street' : item[0],
        'city' :   item[1],
        'state' :  item[2],
        'zip' :    item[3]
     } for item in addresses]}

rawDescription: Dynamically add lists as embedded document in Python pymongo mongodb


code: vars()[MOD_BUFFER + str(assigned_layers)] = modules_dict[c_buff]  #modules_dict is a dict and not a callable object

rawDescription: Matching Binary operators in Tuples to Dictionary Items


code:
class IntMeta(type):
    def __init__(cls, *args):
        setattr(cls, "__add__", lambda self, other: self.value + other)

class Int(object):
    __metaclass__ = IntMeta
    def __init__(self, value):
        self.value = value

rawDescription: Why aren't my Python custom math-overload class methods working?


code:
for event, elem in ET.iterparse("books.xml", events=("end",)):
    for book_with_desc in elem.iterfind(".//Subject[Revision_History]"):
        for child in book_with_desc:
            if child.tag == "Revision_History":
                remove(child)

rawDescription: Python removing elements from large xml file with xml iterparse


code:
from fabric.api import *
import ssh
ssh.util.log_to_file("paramiko.log", 10)

rawDescription: paramiko, isn't talking to ssh-agent. same behavior in fabric

description: Paramiko, isn't talking to ssh-agent. same behavior in fabric


code:
input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
from natsort import natsorted
natsorted(input)

rawDescription: Sort results non-lexicographically?

description: Sort results non-lexicographically


code:
import csv
ccy_fields = ['Ccy1', 'Ccy2']

with open('real_sample.csv') as f:
    reader = csv.reader(f)
    headers = next(reader)
    indices = [i for i,field in enumerate(headers) if field in ccy_fields]
    data = [[row[i] for i in indices] for row in reader]

rawDescription: Items not being removed from list when list is larger


code:
import struct

lastInt = struct.unpack('<I', mybigvalue[-4:])[0]
lastInt += 1
mybigvalue = mybigvalue[:-4] + struct.pack('<I', lastInt & ((1 << 32) - 1))

rawDescription: How do I convert raw ascii values in string to integer?

description: Convert raw ascii values in string to integer


code: req, filename, content_type = download_file('http://some.url')

rawDescription: How to download file from ftp?

description: Download file from ftp


code:
def some_fun(another_fun, value):
    another_fun(value)

def foo(v):
    return v + v

def bar(v):
    return v * v

some_fun(foo, 5)
some_fun(bar, 5)

rawDescription: Why can't I change attribute of a class in Python


code:
line = '1.2.3.4 17622  5.6.7.8 15932 0xEE531C47 ITU-T G.711 PCMU 60962     2 (0.0%)          106.78            8.55            0.34 X'

parts = line.split()
# Make it readable
maxtokens = 15
numcols = 12
col6 = 5

# Get number of tokens for column 6
idx = col6 + len(parts) - maxtokens + 3

# Build the list
a = [p for p in parts[:col6]]           # Cols 1-5
a.append(' '.join(parts[col6:idx]))     # Col 6
a.extend(parts[idx:idx+1])              # Col 7
a.append(' '.join(parts[idx+1:idx+3]))  # Col 8
a.extend([p for p in parts[idx+3:]])    # Cols 9-12
print(a)

rawDescription: Converting text to columns

description: Converting text to columns


code:
response = urllib2.urlopen('http://api.icndb.com/jokes/random')
response.headers.type

rawDescription: How to get urllib2 response in json

description: Get urllib2 response in json


rawDescription: counterdict unique values Python

description: Counterdict unique values Python


code:
p = Panel(data)
p
p = p.swapaxes(0, 2)
p
p['A']

rawDescription: indexing several csv files with pandas from records?

description: Indexing several csv files with pandas from records


code:
from calendar import TimeEncoding, day_name, day_abbr

def get_day_name(day_no, locale, short=False):
    with TimeEncoding(locale) as encoding:
        if short:
            s = day_abbr[day_no]
        else:
            s = day_name[day_no]
        if encoding is not None:
            s = s.decode(encoding)
        return s

rawDescription: Python calendar: day/month names in specific locale


code:
def f():
    g.db = connect_db()

f = app.before_request(f)

rawDescription: '@' python decorator used to do something similar to method overriding in java?


rawDescription: RethinkDB: multiple comparisons filtering


code:
# Read the file as a list of strings, each string is a line.
with open('urls.txt', 'r') as f:
    lines = f.readlines()

# Delete the first line.
del lines[0]

# Write the rest back to the file.
with open('urls.txt' , 'w') as f:
    f.writelines(lines)

rawDescription: Pull a line from a file and then delete it


code:
from bs4 import BeautifulSoup, SoupStrainer # pip install beautifulsoup4

player_links = SoupStrainer('a', 'playerLink', subtab=False)
soup = BeautifulSoup(html, parse_only=player_links)
names = [a.get_text().strip() for a in soup]
print(names)

rawDescription: Parse 'a' tags based on attribute using Python and BeautifulSoup


code:
user_details = {
    'username': entry[1]['sAMAccountName'][0].lower(),
    'displayName': entry[1]['displayName'][0].replace(",", " "),
    'phoneNumber': entry[1]['telephoneNumber'][0].replace("-", ""),
    'emailAddress': entry[1]['mail'][0].lower(),
    'employeeNumber': entry[1]['employeeID'][0].lower(),
    'firstName': entry[1]['givenName'][0],
    'lastName': entry[1]['sn'][0],
}
SystemUser.objects.create(**user_details)

rawDescription: Django How to iterate over list returned from ldap to save new object


code:
lst = [-1, 3, -8]
results = [cmath.sqrt(x) for x in lst]

rawDescription: Square root of a negative array Python

description: Square root of a negative array Python


code:
import copy

class Foo:
    def __init__(self, a, b):
        self.a = a
        self.b = b

def main():
    classTwo = Foo(3,4)
    classOne = copy.deepcopy(classTwo)

rawDescription: Python: How to set class vars to another class of the same type


rawDescription: How to do element-wise multiplication of a matrix of scalars with a matrix of vectors?

description: Do element-wise multiplication of a matrix of scalars with a matrix of vectors


code:
import functools

class Person(object):
    def __init__(self):
        self.pet = Pet()
        self.residence = Residence()

class Pet(object):
    def __init__(self,name='Fido',species='Dog'):
        self.name = name
        self.species = species

class Residence(object):
    def __init__(self,type='House',sqft=None):
        self.type = type
        self.sqft=sqft

def rsetattr(obj, attr, val):
    pre, _, post = attr.rpartition('.')
    return setattr(rgetattr(obj, pre) if pre else obj, post, val)

sentinel = object()
def rgetattr(obj, attr, default=sentinel):
    if default is sentinel:
        _getattr = getattr
    else:
        def _getattr(obj, name):
            return getattr(obj, name, default)
    return functools.reduce(_getattr, [obj]+attr.split('.'))

rawDescription: getattr and setattr on nested objects?

description: Getattr and setattr on nested objects


code: "%x" % h_int

rawDescription: Python string manipulation. Adding a character to the fifth place


code:
s = SomeSpriteClass()
s.rect.move_ip(100, 0)

rawDescription: Pygame in-place methodes

description: Pygame in-place methodes


code:
buffer = numpy.core.multiarray.int_asbuffer(
    ctypes.addressof(y.contents), 8*array_length)

rawDescription: Getting data from ctypes array into numpy


code:
from collections import defaultdict
values = defaultdict(int)
for o in my_object:
    values[o.day] += o.seconds

rawDescription: Appending to a list of lists in Python, with conditions


code:
import collections

class PrivateList(collections.MutableSequence):
    def __init__(self, initial=None):
        self._list = initial or []

    def __repr__(self):
        return repr(self._list)

    def __getitem__(self, item):
        print("Accessed element {}".format(item))
        return self._list[item]

    def __setitem__(self, key, value):
        print("Set element {} to {}".format(key, value))
        self._list[key] = value

    def __delitem__(self, key):
        print("Deleting element {}".format(key))
        del self._list[key]

    def __len__(self):
        print("Getting length")
        return len(self._list)

    def insert(self, index, item):
        print("Inserting item {} at {}".format(item, index))
        self._list.insert(index, item)

class Foo(object):
    def __init__(self, a_list):
        self.list = PrivateList(a_list)

rawDescription: Create a list property in Python

description: Create a list property in Python


code:
# The function call will wait for command to complete, then return the returncode attribute.
rcode = subprocess.call(['python', 'gui_input.py'])

rawDescription: Python gui - passing input to script

description: Python gui - passing input to script


code:
def next_in_line(supobj):
    print('The instance class: {}'.format(supobj.__self_class__))
    print('in this class\'s method: {}'.format(supobj.__thisclass__))
    mro = inspect.getmro(supobj.__self_class__)
    nextindex = mro.index(supobj.__thisclass__) + 1
    print('super will go to {} next'.format(mro[nextindex]))

rawDescription: How do I get the instance method's next-in-line parent class from `super()` in Python

description: Get the instance method's next-in-line parent class from `super()` in Python


code:
import string
allowed = set(string.lowercase + string.digits)
''.join(filter(allowed.__contains__, a.lower()))

rawDescription: How to remove all symbols and spaces from the String?

description: Remove all symbols and spaces from the String


code:
for x in a:
    for y in b:
        print(x + " " + y)

rawDescription: is there a way to get the index for multiple lists python?

description: Is there a way to get the index for multiple lists python


code:
def binaryToAscii(string_of_binary):
    '''
    binaryToAscii takes in a string of binary and returns an ASCII character
    '''
    charVal = int(string_of_binary,2)
    char    = chr(charVal)
    return char

rawDescription: Read binary file in Python using IDL function as reference


code:
self.cursor1 = db.cursor(dictionary=True)
# ...
self.cursor1.execute(
     '''SELECT title, availed_title, episode_number,
               platform_id_series, platform_id_season,
               platform_id_episode, season_number, url,
               provider_id, country, currency_code, est_hd_offer,
               est_sd_offer, vod_hd_offer, vod_sd_offer
     FROM main_googlecatalogtmp WHERE asset_type="episode"'''
)
item = cursor.fetchone()
print('My title is {title} and my url is {url}'.format(**item))

rawDescription: Suggested formatting for SQL SELECT return


code: 0 if indexTag else 1

rawDescription: What would be a compact way to return 1 if a variable is 0 and to return 0 if it is 1?


code:
df = pd.DataFrame([[1,2,3],[2,4,5]], columns=['a','b','c'])
process_df(df, print_to_screen)
process_df(df, save_to_file, 'temp.csv')

rawDescription: How to use a functional in this case?

description: Use a functional in this case


code:
arrays = {}
for file in os.listdir(directoryPath):
    if file.endswith(".csv"):
       arrays[file] = numpy.genfromtxt(file, delimiter=',')[:,2]

rawDescription: On using a string as an integer counter (aka index) in a for loop


code: mpl_is_inline = 'inline' in matplotlib.get_backend()

rawDescription: How to check that pylab backend of matplotlib runs inline?

description: Check that pylab backend of matplotlib runs inline


rawDescription: How to set first column to a constant value of an empty np.zeros numPy matrix?

description: Set first column to a constant value of an empty np.zeros numPy matrix


code:
wally -= .8*wally * ~mask[:,:,None]
imshow(wally)

rawDescription: How do I find Wally with Python?

description: Find Wally with Python


code:
from collections import deque

# The number 5 indicates for how many iterations the actors should be rendered.
rendered_actors = deque([None] * 5, maxlen=5)

for point_and_mag in pm.points_mag:
    if rendered_actors[-1] is not None:
        renderer.removeActor(rendered_actors[-1])
        renderer.ResetCamera()
        renderWindow.Render()

    time.sleep(0.5)
    mag = point_and_mag[1]
    point = point_and_mag[0]
    if mag > 2:
        pointCloud = VtkPointCloud(pm)
        pointCloud.addPoint(point, math.log(mag)*10)
        rendered_actors.appendleft(pointcloud.vtkActor)
        renderer.AddActor(pointCloud.vtkActor)
        renderer.ResetCamera()
        renderWindow.Render()
    else:
        rendered_actors.appendleft(None)

rawDescription: Python - How to track (add/remove) lots of class instances over mulitple iterations?


code:
result = my_function(big, long, list,
                      of, args)
a,b,c,d = result

rawDescription: Python coding style on function call with multiple parameters


code:
def countSeq(src):
  last = src[0]
  count = 0
  current = 1
  while current < len(src):
    if src[current] != last:
      count += 1
      last = src[current]
    current += 1
  return count + 1 # last

rawDescription: Operation with Arrays in Python

description: Operation with Arrays in Python


code:
import pandas.tseries.converter as converter
c = converter.DatetimeConverter()
type(c.convert(df['Date'].values, None, None))
type(c.convert(df['Date'], None, None))

rawDescription: Pandas and Matplotlib - fill_between() vs datetime64


code:
counter = Counter('abcdef')
most_common = sorted(counter.items(), key=lambda pair: (-pair[1], pair[0]))

rawDescription: How to sort the results of Counter.mostCommon(n) lexicographically (by counter, then by value)?

description: Sort the results of Counter.mostCommon(n) lexicographically (by counter, then by value)


code:
import numpy as np
n = np.array([0, 1, 3, 0, 1])
max_n = max(n)
np.vstack(n > i for i in range(max_n)).T.astype(int) # xrange(max_n) for python 2.x

rawDescription: Transform an array of count data into a matrix of ones and zeroes


code: df

rawDescription: Pandas: How to convert column of string objects representing categories to integers?


code:
output = ''
for i in range(len(MyArray)):
    C = chr(int(MyArray[i],2))
    output = output + C

print(output)

rawDescription: Convert a while loop into a for loop in Python 3.3


code:
nlist = []
if x < n:
    nlist.append((x+1,y))
if y < n:
    nlist.append((x,y+1))
if x > 0:
    nlist.append((x-1,y))
if y > 0:
    nlist.append((x,y-1))

rawDescription: how to manipulate a list in python

description: Manipulate a list in python


rawDescription: How do i append a list with new data?

description: Append a list with new data


code: return (p and p.group(1), d and d.group(1))

rawDescription: Better way to return any match in a python regex search?


code:
for obj in self.things:
    self.choiceCar.Append(obj.name, obj)

rawDescription: python: Using the choice box to get data besides getString()

description: Python: Using the choice box to get data besides getString()


code:
A.item()
type(A.item())
type(A[0])

rawDescription: Array operations on heterogeneous numpy arrays


code:
import collections
import sys

ps = [int(s) for s in list(sys.stdin)[1].strip().split()]
ps_prev = []
days = 0
while collections.Counter(ps_prev) != collections.Counter(ps):
    ps_prev = ps[:]
    i = len(ps) - 1
    while i > 0:
        if ps[i] > ps[i-1]:
            ps.pop(i)
        i -= 1
    days += 1

print(days - 1)

rawDescription: Why is Poisonous plants stack solution giving TLE?


code:
import numpy as np

a = np.random.random((1000000, 10))
b = np.random.randint(0,10,1000000)
c = a[np.arange(len(b)), b]

rawDescription: Is there a faster method to do this sort of indexing in numpy?


code:
def myfunc(x):
    ''' a normal python function that acts on individual numbers'''
    return x + 3

myfunc_v = np.vectorize(myfunc)

rawDescription: Numpy time based vector operations where state of preceding elements matters - are for loops appropriate?


rawDescription: Segment a korean word into individual syllables - C++/Python


code:
element = 9
container = set(range(1, 10))

print("Match Found." if element in container else "Match Not Found.")

rawDescription: For loops and else statements in Python

description: For loops and else statements in Python


code:
my_dict = {}

for obj in objects:
    my_dict.setdefault(obj.date, []).append(obj) # Don't forget to call the `date` if it's callable

rawDescription: Turn list into list of lists using an object attribute


code:
parser.add_argument(
    "date"
    , type=lambda x: DT.datetime.strptime(x, '%Y-%m-%d')
    , help="date to check dependencies")

rawDescription: adding and subtracting from a date

description: Adding and subtracting from a date


rawDescription: Decode High Level Python to easier code

description: Decode High Level Python to easier code


code:
myList = [1,2,3,4,5]

if 3 in myList:
    print("3 is present")

rawDescription: How to check if a specific integer is in a list

description: Check if a specific integer is in a list


code:
from operator import attrgetter

max(self.allPartners, key=attrgetter('attrOne'))

rawDescription: Get the object with the max attribute's value in a list of objects


code: igpay("An apple a day keeps the doctor away")

rawDescription: Converting a sentence into piglatin

description: Converting a sentence into piglatin


code:
def frontend(data):
  product = 1
  for elem in data[:-1]:
    product = product * elem
  return [product, data[-1]]

rawDescription: Get a 3D or 4D array as input and reshape it to 2D array in a function from external script


code:
stream = StringIO()
new_commit._serialize(stream)
streamlen = stream.tell()
stream.seek(0)

istream = repo.odb.store(IStream(Commit.type, streamlen, stream))
new_commit.binsha = istream.binsha

rawDescription: How can I specify the committed_date of a Commit using GitPython?

description: Specify the committed_date of a Commit using GitPython


code:
merged = pd.merge(A,B,on="key")
answer = merged['val_x']/merged['val_y']

rawDescription: How to divide two DataFrames by key

description: Divide two DataFrames by key


code:
w0 = datetime.datetime(2014,12,28,6)
d7 = datetime.timedelta(7)

rawDescription: Get a date based on week number (python)


code:
ra_list = [5,5,6,7,7]
e_list = [(7, 'A'), (7, 'B'), (6, 'C'), (5,'D')]
cate_dict = {}
#Creating dictionary of categories
for key,val in e_list:
    cate_dict.setdefault(key,[]).append(val)
import random
for i in ra_list:
    cate = random.choice(cate_dict.get(i,[0]))
    if cate != 0:
            print(i,cate)

rawDescription: Python list within list

description: Python list within list


code:
SOCIAL_AUTH_FACEBOOK_CUSTOM_KEY = '...'
SOCIAL_AUTH_FACEBOOK_CUSTOM_SECRET = '...'
SOCIAL_AUTH_FACEBOOK_CUSTOM_SCOPE = [...]

rawDescription: How can I ask for different permissions from facebook at different times?

description: Ask for different permissions from facebook at different times


rawDescription: I want to use Python to list a directory, then sort the filenames by size


rawDescription: How to parse the header files of the pcap file?

description: Parse the header files of the pcap file


code:
concerts = Concert.objects.filter(...)

concerts.order_by('venue__attribute') # ordering beyond PK.
concerts.filter(venue__name='foo') # filter by a value across the relationship
concerts.values_list('venue__name') # get just venue names
concerts.values('venue__city').annotate() # get unique values across the venue

concerts.filter(venue__more__relationships='foo')

Venue.objects.filter(concert__name='Coachella') # reverse lookups work too

# with an integer field for Concert.venue, you'd have to do something like...
Venue.objects.filter(id__in=Concert.objects.filter(name='Coachella'))

rawDescription: why is models.ForeignKey advantageous?

description: Why is models.ForeignKey advantageous


code: configfilePath = os.path.join(myPath, 'config.txt')

rawDescription: Where should I place a config.txt in my python project


code: days = dates.days_in_month

rawDescription: Applying cell wise function in a dataframe


code:
class A:
    def __private(self):
       pass

rawDescription: private method in python

description: Private method in python


code: float('inf') < Ellipsis

rawDescription: How can I represent an infinite number in Python?

description: Represent an infinite number in Python


rawDescription: clicking on a link via selenium in python

description: Clicking on a link via selenium in python


code:
for i,d in enumerate(data):
    # Directly use pre-computed covariances for each triangle
    vals, vecs = np.linalg.eig(cov3D[i])

rawDescription: Quickly compute eigenvectors for each element of an array in python


rawDescription: Key Value For Loop Template - Django Inquiry


code:
for i in range(1, 21):
    "python code.py in_file{} in_file2 outfile{}".format(i, i)

rawDescription: how to direct a sh script to run a python script?

description: Direct a sh script to run a python script


code:
class Foo(object):
    __metaclass__ = FooMeta
    FOO = 123
    def a(self):
        pass

rawDescription: Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?


code:
pf3 = pd.DataFrame(pf2.pivot(index='idx2', columns='State', values='OpTime'))
pf3.index=asarray(pf3.index.values, 'int')

rawDescription: pandas - determine the duration of an event

description: Pandas - determine the duration of an event


code: printSelected (n, 0)

rawDescription: More on dynamic programming

description: More on dynamic programming


code:
positions = np.concatenate((a['position'], b['position'], c['position']))
uinqPos, count = count_positions(positions)
uinqPos = uinqPos[count == 3]

rawDescription: create intersection from two or more 2d numpy arrays based on common value in one column

description: Create intersection from two or more 2d numpy arrays based on common value in one column


code: file.write("Multiple of 1000!\r\n" * sum(filter(lambda i: i % 1000 == 0, a2)))

rawDescription: How do I maximize efficiency with numpy arrays?

description: Maximize efficiency with numpy arrays


code:
re.split(r'\b', 'foo-BAR_baz')
re.split(r'\W+', 'foo-BAR_baz')
re.split(r'[\W_]+', 'foo-BAR_baz')

rawDescription: python check if utf-8 string is uppercase

description: Python check if utf-8 string is uppercase


code:
df1['Name'] = df1.Surname + ',' + df1.Knownas
merge = pd.merge(df1, df2, on=['Name'])

rawDescription: How to join two tables while merging column names

description: Join two tables while merging column names


code: x2 > y

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


rawDescription: Tuple with nested list into dictionary

description: Tuple with nested list into dictionary


code:
from functools import reduce # python 3+ only
list(reduce(lambda x, y: x + (y,)*N, [42,19,73], ()))

rawDescription: Pythonic list spreading (element repetition)


code:
class SomeType (object):
    def __init__ (self, x, y):
        self.x = x
        self.y = y

    def __eq__ (self, other):
        return self.x == other.x and self.y == other.y

    def __hash__ (self):
        return hash((self.x, self.y))

rawDescription: `object in list` behaves different from `object in dict`?


code:
World
Hello

rawDescription: How does Python interpret its code?

description: How does Python interpret its code


rawDescription: python3 interpret ascii string as unicode string

description: Python3 interpret ascii string as unicode string


code:
import re
text = '   hello'
re.sub('\s+', '', text)
text

rawDescription: How to perform re substitutions on <p> tags within a specific class?

description: Perform re substitutions on <p> tags within a specific class


code:
Enrolment:"Boys; 123 Girls: 102   (2012/13)"
Ethos:"Catholic  &nbsp "
Fees:" No "

rawDescription: Parsing an html page using beautifulsoup/python


code:
width *= fig.dpi
height *= fig.dpi

rawDescription: determine matplotlib axis size in pixels

description: Determine matplotlib axis size in pixels


code:
import pandas as pd

df = pd.DataFrame({'actual_label' : [0,0,1,1],
                  'pred_label' : [-1,-1, [1, 0.34496911461303364], -1]})

def split_label(v):
  if isinstance(v, list):
    return pd.Series(v, index = ['pred_label', 'pred_score'])
  return pd.Series(v, index = ['pred_label'])

new_pred = df.pred_label.apply(split_label)
df_new = pd.concat([df.actual_label, new_pred], axis=1)

rawDescription: Pandas split a column value to new column if list


code: last_max_index3 = lambda s: max((x, i) for i, x in enumerate(s))[1]

rawDescription: Get the last index with same max values in a list


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

fig, axes = plt.subplots(nrows=2, ncols=2)
for i, ax in enumerate(axes.flat, start=1):
    ax.set(adjustable='datalim', aspect=1)
    ax.plot(np.arange(0, i * 4, i))

plt.show()

rawDescription: matplotlib: aspect ratio in subplots with various y-axes

description: Matplotlib: aspect ratio in subplots with various y-axes


code:
ax.text(0.05, 0.5, "My y-axis", transform=f.transFigure, rotation='vertical',
        verticalalignment='center')

rawDescription: Share Y axis label

description: Share Y axis label


rawDescription: creating subclass form class returning pandas dataFrame

description: Creating subclass form class returning pandas dataFrame


code:
from bisect import bisect_left, bisect_right
filtered = sortedDates[bisect_right(sortedDates, minD):bisect_left(sortedDates, maxD)]

rawDescription: Splice list of date objects in Python

description: Splice list of date objects in Python


code:
f = {'A':['sum','mean'], 'B':['prod'], 'D': lambda g: df.ix[g.index].E.sum()}
df.groupby('GRP').agg(f)

rawDescription: Apply multiple functions to multiple groupby columns


code: '|'.join([re.escape(word) for word in B])

rawDescription: Delete item from list if it contains a substring from a "blacklist"


code:
s = ' '.join(line)
wholelookup[line[-2]].append(s)

rawDescription: How to read line in python using defaultdict?

description: Read line in python using defaultdict


rawDescription: Slug and generic views

description: Slug and generic views


code:
from numbers import Number

a = [[[1,2],[3,4]],[[5,6],[7,8]]]

def trav(root, s=""):
    if isinstance(root, Number):
        print("%s -> %s" % (root, s))
    else:
        trav(root[0], s + "0")
        trav(root[1], s + "1")

trav(a)

rawDescription: how to use iterator in recursive function in python?

description: Use iterator in recursive function in python


rawDescription: Merging hierarchy of dictionaries in Python


code:
import re
s = "ABCDXYv"
re.findall(r'.{1,2}',s,re.DOTALL)

rawDescription: Splitting a string into 2-letter segments


rawDescription: How to write a tuple of floats to the file space separated with only one call to write in python?

description: Write a tuple of floats to the file space separated with only one call to write in python


code:
import socket
address = ('127.0.0.1', 10000)
sock.connect(address)

rawDescription: getting remote ip from local ip

description: Getting remote ip from local ip


code: data['v_sum'] = data[v1] + data[v2] + data[v3]

rawDescription: python pandas : split a data frame based on a column value

description: Python pandas : split a data frame based on a column value


rawDescription: Strip double quotes from list

description: Strip double quotes from list


code:
"""
    Creates a filter which matches suitable right siblings for ``node``,
    where insertion should maintain ordering according to the list of
    fields in ``order_insertion_by``.

    For example, given an ``order_insertion_by`` of
    ``['field1', 'field2', 'field3']``, the resulting filter should
    correspond to the following SQL::

       field1 > %s
       OR (field1 = %s AND field2 > %s)
       OR (field1 = %s AND field2 = %s AND field3 > %s)

"""

rawDescription: Dynamic order in django-mptt

description: Dynamic order in django-mptt


code:
D_values = {}
for path in glob("F:\Thermal Motion\*.txt"):
    t, x, y = np.loadtxt(path, unpack=True)

    D_values[path] = [((x[i] - x[0])**2 + (y[i] - y[0])**2)**0.5
                      for i in range(len(x))]

rawDescription: Making subarray from function on multiple arrays


code:
import re
filter(lambda x:re.search(r'aet', x), names)

rawDescription: Grep on elements of a list

description: Grep on elements of a list


code:
import datetime

print(datetime(1, 2, 3))
print(datetime.timedelta(days=1))
print(datetime.now())

rawDescription: How to make statement `import datetime` bind the datetime type instead of the datetime module?

description: Make statement `import datetime` bind the datetime type instead of the datetime module


code: indices = zip(*np.where(myarray == 0))

rawDescription: Iterate over the output of `np.where`

description: Iterate over the output of `np.where`


code:
from bs4 import BeautifulSoup
from urllib import request

page = request.urlopen('http://www.federalreserve.gov/econresdata/researchdata/feds200628_1.html').read()
soup = BeautifulSoup(page)

desired_table = soup.findAll('table')[2]

# Find the columns you want data from
headers = desired_table.findAll('th')
desired_columns = []
for th in headers:
    if 'SVENY' in th.string:
        desired_columns.append(headers.index(th))

# Iterate through each row grabbing the data from the desired columns
rows = desired_table.findAll('tr')

for row in rows[1:]:
    cells= row.findAll('td')
    for column in desired_columns:
        print(cells[column].text)

rawDescription: Trouble parsing HTML page with Python

description: Trouble parsing HTML page with Python


code:
url = 'urlyouwanttoarchive.com'
archive = 'http://web.archive.org/save/'
requests.get(archive + url)

rawDescription: Send data and get the response

description: Send data and get the response


code: [h.get_height() for h in sns.distplot(x).patches]

rawDescription: Get data points from Seaborn distplot

description: Get data points from Seaborn distplot


rawDescription: Splitting on last delimiter in Python string?


code:
data = [['value1', 'value 2', 'value3'],
        ['value1', 'value 2', 'value3'],
        ['value1', 'value 2', 'value3']]

rawDescription: Write multiple lists into csv. file in Python


code:
#pickle collected data for later comparisons.
persistent=yes

rawDescription: How does pylint remember scores from previous runs?


code:
price_people = 30000
print( df[ ( df['inc'] >= price_people - 10000 ) & ( df['inc'] <= price_people + 10000 ) ] )

rawDescription: Work with intervals using pandas

description: Work with intervals using pandas


code:
for child in parent.findChildren(QtGui.QLineEdit):
    child.clear()

rawDescription: PyQt Collection of QLineEdit objects

description: PyQt Collection of QLineEdit objects


code:
from collections import namedtuple
TRX = namedtuple('TRX', ('file_name', 'bank', 'trans_type', 'account'))
TRX('foo.txt', 'Bar PLC', 'withdrawal', '1234xyz')

rawDescription: Output object attributes and values in alphabetical order


code:
def myself (*args, **kw):
    caller_frame = currentframe(1)
    code = caller_frame.f_code
    return  FunctionType(code, caller_frame.f_globals)(*args,**kw)

print (lambda l:len(l) if not isinstance(l,(tuple,list)) else sum(map(myself,l)))(some_list)

rawDescription: Lambda recursion over list in Python

description: Lambda recursion over list in Python


code: table = pd.pivot_table(df, values='Forecast Qty', rows='Part', cols='YYYY-MM', aggfunc=np.sum, fill_value=0)

rawDescription: Pivot DataFrame

description: Pivot DataFrame


code:
import time
from threading import Thread

from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None

def background_thread():
    """Here is where you'll perform your installation"""
    count = 0
    # Call Install function 1 using time.sleep(10) to simulate installation
    time.sleep(10)
    count += 1
    socketio.emit('my response',
                      {'data': '1 installed', 'count': count},
                      namespace='/test')

    # Call Install function 2 using time.sleep(10) to simulate installation
    time.sleep(10)
    count += 1
    socketio.emit('my response',
                      {'data': '2 installed', 'count': count},
                      namespace='/test')

    # Call Install function 3 using time.sleep(10) to simulate installation
    time.sleep(10)
    count += 1
    socketio.emit('my response',
                      {'data': '3 installed', 'count': count},
                      namespace='/test')

@app.route('/')
def index():
    thread = Thread(target=background_thread)
    thread.start()
    return render_template('index.html')

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app)

rawDescription: Python Flask Set Text in Website without reloading


code:
#!/usr/bin/env python

from PyQt5.QtGui import (
        QOpenGLBuffer,
        QOpenGLShader,
        QOpenGLShaderProgram,
        QOpenGLVersionProfile,
        QOpenGLVertexArrayObject,
        QSurfaceFormat,
    )
from PyQt5.QtWidgets import QApplication, QMainWindow, QOpenGLWidget

class QTWithGLTest(QMainWindow):
    """Main window."""

    def __init__(self, versionprofile=None, *args, **kwargs):
        """Initialize with an OpenGL Widget."""
        super(QTWithGLTest, self).__init__(*args, **kwargs)

        self.widget = QOpenGLControllerWidget(versionprofile=versionprofile)
        self.setCentralWidget(self.widget)
        self.show()

class QOpenGLControllerWidget(QOpenGLWidget):
    """Widget that sets up specific OpenGL version profile."""

    def __init__(self, versionprofile=None, *args, **kwargs):
        """Initialize OpenGL version profile."""
        super(QOpenGLControllerWidget, self).__init__(*args, **kwargs)

        self.versionprofile = versionprofile

    def initializeGL(self):
        """Apply OpenGL version profile and initialize OpenGL functions."""
        self.gl = self.context().versionFunctions(self.versionprofile)
        if not self.gl:
            raise RuntimeError("unable to apply OpenGL version profile")

        self.gl.initializeOpenGLFunctions()

        self.createShaders()
        self.createVBO()
        self.gl.glClearColor(0.0, 0.0, 0.0, 0.0)

    def paintGL(self):
        """Painting callback that uses the initialized OpenGL functions."""
        if not self.gl:
            return

        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT | self.gl.GL_DEPTH_BUFFER_BIT)
        self.gl.glDrawArrays(self.gl.GL_TRIANGLES, 0, 3)

    def resizeGL(self, w, h):
        """Resize viewport to match widget dimensions."""
        self.gl.glViewport(0, 0, w, h)

    def createShaders(self):
        ...

    def createVBO(self):
        ...

if __name__ == '__main__':
    import sys

    fmt = QSurfaceFormat()
    fmt.setVersion(4, 1)
    fmt.setProfile(QSurfaceFormat.CoreProfile)
    fmt.setSamples(4)
    QSurfaceFormat.setDefaultFormat(fmt)

    vp = QOpenGLVersionProfile()
    vp.setVersion(4, 1)
    vp.setProfile(QSurfaceFormat.CoreProfile)

    app = QApplication(sys.argv)
    window = QTWithGLTest(versionprofile=vp)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQT5 OpenGL 4.1 Core profile - invalid frame buffer operation - Mac OS


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, parent=None, title=None):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title)
        self.panel = wx.Panel(self, size=(350, 450))
        # this sets up the painting canvas
        self.panel.Bind(wx.EVT_PAINT, self.on_paint)
        # set frame size to fit panel
        self.Fit()

    def on_paint(self, event):
        # establish the painting canvas
        dc = wx.PaintDC(self.panel)
        x = 0
        y = 0
        w, h = self.GetSize()
        dc.GradientFillLinear((x, y, w, h), 'blue', 'black')

app = wx.App(0)
MyFrame(title='Gradient Test').Show()
app.MainLoop()

rawDescription: How to do a dregradê on wx.Panel Background?

description: Do a dregradê on wx.Panel Background


code:
df.set_index([df.index, 'etime'], inplace=True)
df
df0.join(df.loc[0])
df1 = DF.copy()
df1.join(df.loc[1])

rawDescription: Pandas. Selection by label. One-row output


code:
from __future__ import print_function
import re

tests = (
    '(c) 2012 DC Comics',
    'DC Comics. 2012',
    'DC Comics, (c) 2012.',
    'DC Comics, Copyright 2012',
    '(c) 2012 10 DC Comics',
    '10 DC Comics. 2012',
    '10 DC Comics , (c) 2012.',
    '10 DC Comics, Copyright 2012',
    'Warner Bros, 2011',
    'Stanford and Sons, Ltd. Inc. (C) 2011. All Rights Reserved.',
)

for input in tests:
    print("<", input)
    output = re.sub(r'''
            (?P<lead> (?: \S .*? \S )?? )
            [\s.,]*
            (?: (?: \( c \) | copyright ) \s+ )?
            (?P<year> (?:19|20)\d\d )
            [\s.,]?
        ''', r"\g<year>. \g<lead>", input, 1, re.I + re.X)
    print(">", output, "\n")

rawDescription: Re-order copyright with regex

description: Re-order copyright with regex