code:
def two_directional_slice(original, condition, q):
    condition = lambda l: (i for i,v in enumerate(l) if condition(v)).next()
    ending_condition = q + condition(mylist[q:])
    starting_condition = q - condition(mylist[:q:-1])
    return mylist[starting_condition:ending_condition]

rawDescription: Cutting list tails based on condition

description: Cutting list tails based on condition


code:
from datetime import datetime
dt = datetime.strptime(s, "%d/%m/%Y-%H:%M:%S")

rawDescription: Django - String to Date - Date to UNIX Timestamp


code:
class PyCompiler():
        def __init__(self, name_in, module, dep_list):
            self.file = name_in
            self.dep = dep_list
            self.module_name = module
            self.compiler_command = r"python setup.py  build_ext --inplace -c mingw32 "
            ''' Here it goes the creation of the setup.py file: '''
            self.set_setup()

rawDescription: Compiling C++ code using Python interpreter running under windows shell


code:
d = {'Name 1': ['link{}'.format(l) for l in list(range(10))], 'Name 2': ['link{}'.format(l) for l in list(range(10, 20))]}

{'Name 1': ['link0', 'link1', 'link2', 'link3', 'link4', 'link5', 'link6', 'link7', 'link8', 'link9'], 'Name 2': ['link10', 'link11', 'link12', 'link13', 'link14', 'link15', 'link16', 'link17', 'link18', 'link19']}

rawDescription: Reorder a dictionary to fit a data frame


code:
cmd = "/usr/local/bin/tesseract /Users/anthony/Downloads/rus.png outfile -l rus"
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)

rawDescription: How to add options to python subprocess

description: Add options to python subprocess


code:
text = """
//var NOC_Destinations  = new Array('BHX'); # Don't need any of this
var ABZ_Destinations    = new Array('DUB'); # Need this
//var RNS_Destinations  = new Array('ORK','DUB'); Don't need this
var BHX_Destinations    = new Array('ORK','DUB','SNN'); # Need this
"""

import re
import ast

from_to = {frm: ast.literal_eval(to) for frm, to in re.findall('^var ([A-Z]{3})_Destinations.*?\((.*?)\)', text, flags=re.M)}
# {'BHX': ('ORK', 'DUB', 'SNN'), 'ABZ': 'DUB'}

rawDescription: Regex to return 2 groups

description: Regex to return 2 groups


code:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^request/(?P<id>\d+)/$', 'appname.views.my_request_view'),
]

rawDescription: How to read parameters from request in django

description: Read parameters from request in django


code: length = log10(256) * len(var_text)     # or about (2.408 * x)

rawDescription: Python: Shorten ugly code?

description: Python: Shorten ugly code


rawDescription: How can I access the overridden properties of a .NET API object in IronPython?

description: Access the overridden properties of a .NET API object in IronPython


rawDescription: Create multi-level index pandas dataframe from delimited string column


code: vms = client.query("select * from Msvm_ComputerSystem where Caption=\"Virtual Machine\"")

rawDescription: Python WMI Hyper-v GetSummaryInformation result


code: stack.push(1 if stack.pop() > stack.pop() else 0)

rawDescription: Python operators returning ints

description: Python operators returning ints


code: np.where(df.even, 1, -1)

rawDescription: How to write a conditional array operation on a Pandas DataFrame

description: Write a conditional array operation on a Pandas DataFrame


code:
PythonProg = []
PythonProg.add(Popen(...))

rawDescription: Running a program in windows with a specific name, so that I can close it mid run later


code:
def parse(data, parent=''):
    if data is None or not len(data):
        yield parent
    else:
        for node in data:
            for result in parse(
                    node.get('files'), parent + '/' + node.get('name')):
                yield result

rawDescription: Python. How to get directory path from JSON?


code:
from collections import defaultdict
from itertools import product, combinations

def all_fill(source, num):
    output_len = (len(source) + num)
    for where in combinations(range(output_len), len(source)):
        poss = ([[0, 1]] * output_len)
        for (w, s) in zip(where, source):
            poss[w] = [s]
        for tup in product(*poss):
            (yield tup)

def variable_name(seq):
    return ('x' + ''.join((str(s) for s in seq)))
n = 12
shortn = ((2 * n) // 3)
x = (n // 3)
all_seqs = list(product([0, 1], repeat=shortn))
hit_sets = defaultdict(set)
for seq in all_seqs:
    for fill in all_fill(seq, x):
        hit_sets[fill].add(seq)
print('Minimize')
print(' + '.join((variable_name(seq) for seq in all_seqs)))
print('Subject To')
for (fill, seqs) in hit_sets.items():
    print(' + '.join((variable_name(seq) for seq in seqs)), '>=', 1)
print('Binary')
for seq in all_seqs:
    print(variable_name(seq))
print('End')

rawDescription: Minimum set cover

description: Minimum set cover


code:
def run_sql_safe(sql, input_tuple=(), get_update_id=False, debug = False):
    from contextlib import closing
    conn = get_mysql_connection(cursorclass=MySQLdb.cursors.DictCursor)
    with closing(conn):
        with conn as cursor:
            cursor.execute(sql, input_tuple)
            if get_update_id:
                return cursor.lastrowid

rawDescription: Why the "cursor.lastrowid" return 3?

description: Why the "cursor.lastrowid" return 3


code: C = pd.merge(C, B, on=['Marca', 'Formato'])

rawDescription: Efficient calculation on a pandas dataframe


rawDescription: Compare 1st element in list of lists and write number of repeated values


rawDescription: How to replace different blocks of text in all combinations using awk?

description: Replace different blocks of text in all combinations using awk


code:
fix_tweet('AdeleOfficial')    # -> 'Adele Official'
fix_tweet('EPPGroup')         # -> 'EPP Group'

rawDescription: Finding and combining acronyms in Python


code:
import re
numbers = re.compile(r'\(\s*passengers:\s*(\d{1,3}|\?)\s+ crew:\s*(\d{1,3}|\?)\s*\)')
numbers.search('26   (passengers:22  crew:4)').groups()
numbers.search('32   (passengers:?  crew: ?)').groups()

rawDescription: splitting string in Python (2.7)

description: Splitting string in Python (2.7)


code: sameModel = LogisticRegressionModel.load(sc, "lrm_model.model")

rawDescription: How to save and load MLLib model in Apache Spark

description: Save and load MLLib model in Apache Spark


rawDescription: Python get start and end date of the week


code: print('@company.com '.join(x.split()) + '@company.com')

rawDescription: Python regex - extend string

description: Python regex - extend string


code:
lines = open("/proc/net/dev", "r").readlines()

columnLine = lines[1]
_, receiveCols , transmitCols = columnLine.split("|")
receiveCols = map(lambda a:"recv_"+a, receiveCols.split())
transmitCols = map(lambda a:"trans_"+a, transmitCols.split())

cols = receiveCols+transmitCols

faces = {}
for line in lines[2:]:
    if line.find(":") < 0: continue
    face, data = line.split(":")
    faceData = dict(zip(cols, data.split()))
    faces[face] = faceData

import pprint
pprint.pprint(faces)

rawDescription: How can I parse the output of /proc/net/dev into key:value pairs per interface using Python?

description: Parse the output of /proc/net/dev into key:value pairs per interface using Python


code: globals()[S](A, B)

rawDescription: Dropdown box representing a method call on a string


code: dict(zip(headers, sdata))

rawDescription: Storing the columns of a spreadsheet in a Python dictionary


code:
class Parent(object):
    @classmethod
    def new(cls,*args,**kwargs):
        return cls(*args,**kwargs)
class Child(Parent): pass

p=Parent()
p2=p.new()
assert isinstance(p2,Parent)
c=Child()
c2=c.new()
assert isinstance(c2,Child)

rawDescription: Python Inheritance : Return subclass

description: Python Inheritance : Return subclass


code:
for value in joedict.itervalues():
    value.sort()

rawDescription: How can I access and sort lists within lists in python?

description: Access and sort lists within lists in python


rawDescription: iterating through a list of dictionary names

description: Iterating through a list of dictionary names


code:
from pyspark.sql.functions import col

df = sc.parallelize([
    ('2015-07-02T11:22:21.050Z', ),
    ('2016-03-20T21:00:00.000Z', )
]).toDF(("d_str", ))

df_casted = df.select("*",
    col("d_str").cast("date").alias("dt"),
    col("d_str").cast("timestamp").alias("ts"))

rawDescription: PySpark: filtering a DataFrame by date field in range where date is string


code:
import maya.cmds as cmd
import maya.OpenMaya as api
import maya.OpenMayaUI as apiUI

def grabViewport(directory, imageName, ext="jpg"):
    viewport = apiUI.M3dView.active3dView()
    viewport.refresh()

    img = api.MImage()
    img.create(1280, 720)
    viewport.readColorBuffer(img, True)

    filePath = os.path.join(directory, imageName + "." + ext)
    img.writeToFile(filePath, ext)

cmd.viewSet(front=True)
cmd.viewFit()
filename = "image"
dir = "c:/snapshots"
ext = "jpg"
imageName = filename + "_front"
grabViewport(dir, imageName, ext)

rawDescription: maya/python modify modelPanel layout and behaviour

description: Maya/python modify modelPanel layout and behaviour


code:
d = {}
with open("output.txt") as inf:
    for line in inf:
        values = line.rstrip("\r\n").split("|")
        key = values.pop(0)
        d[key] = values

rawDescription: Writing dictionary to text file with python


code:
# emulate pre-1.2 find/findtext/findall behaviour
def find(self, element, tag, namespaces=None):
    for elem in element:
        if elem.tag == tag:
            return elem
    return None

rawDescription: ElementTree: What is the syntax for the 'match' argument to the 'find' method?


code:
def normalize(lists):
    items = set(x for y in lists for x in y)
    counter = itertools.count()
    sorter = lambda x: sorted(len(y) for y in lists if x in y)
    mapping = {k: next(counter) for k in sorted(items, key=sorter)}
    return tuple(sorted(tuple(sorted(mapping[x] for x in y)) for y in lists))

rawDescription: Check if two nested lists are equivalent upon substitution


code:
ClassType
CodeType
FunctionType, LambdaType
InstanceType
MethodType, UnboundMethodType
ModuleType

rawDescription: Where can I find documentation for calling the various types in Python's types module?


code: print('a\ta\t')

rawDescription: Python: select a line if specific characters spaced by tab at end of line


code:
my_list = ['[tag]', 'there', 'are', 'many', 'words', 'here', '[/tag]', '[tag]', 'some', 'more', 'here', '[/tag]', '[tag]', 'and', 'more', '[/tag]']

# string together your list
my_str = ','.join(mylist)

# split the giant string by tag, gives you a list of comma-separated strings
my_tags = my_str.split('[tag]')

# split for each word in each tag string
my_words = [w.split(',') for w in my_tags]

# count up each list to get a list of counts for each tag, adding one since the first split removed [tag]
my_cnt = [1+len(w) for w in my_words]

rawDescription: Python - Count elements of a list within a range of specified values


rawDescription: How to change a global variable value inside a task map or reduce in Apache Spark using Python

description: Change a global variable value inside a task map or reduce in Apache Spark using Python


code:
import pycurl
c = pycurl.Curl()
c.setopt(pycurl.URL, 'www.example.com/login.php')
pycurlConnect.setopt(pycurl.POSTFIELDS, POST_DATA)
c.setopt(pycurl.PROXY, 'yourproxy')
c.setopt(pycurl.PROXYPORT, 8080)
c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)
c.perform()

rawDescription: How to use Python with different SOCKS 5 Proxies?

description: Use Python with different SOCKS 5 Proxies


code:
while j < (N):
    j=j+1
    B=A[1+(10*j)+R][1:k] #Extraction expression.
    C=[float(i) for i in B] #Float conversion.
    D[0].append(C[0]),D[1].append(C[1]),D[2].append(C[2])
    if NC >= 4:
        D[3].append(C[3])
    if NC >= 5:
        D[4].append(C[4])
    if NC >= 6:
        D[5].append(C[5])
    if NC >= 7:
        D[6].append(C[6])
    if NC >= 8:
        D[7].append(C[7])
    if NC >= 9:
        D[8].append(C[8])
    if NC >= 10:
        D[9].append(C[9])
    if NC >= 11:
        D[10].append(C[10])
    if NC == 12:
        D[11].append(C[11])

rawDescription: Alternative to large "if-else" tree algorithm?


rawDescription: Comparing NumPy arrays so that NaNs compare equal


code:
from django.core import urlresolvers

class Location(models.Model):
    # ... [snip]
    def get_absolute_url(self):
        return urlresolvers.reverse('selected_holidays', args=(self.location_name,))

rawDescription: Django URL dispatcher example - pass url from view to another


code:
rules = {}
for id, rule in read_rules_file():
    rules[id] = rule
for id, isUsed in read_pairs_file():
    if isUsed:
       write_rule(id, rules[id])
    else:
       write_commented_rule(id, rules[id])

rawDescription: Random searching and modification of a file in python


rawDescription: Is there an efficient way to fill date gaps in python?


code:
import sqlalchemy.types as types

class LowerCaseText(types.TypeDecorator):
    '''Converts strings to lower case on the way in.'''

    impl = types.Text

    def process_bind_param(self, value, dialect):
        return value.lower()

class User(Base):
    __tablename__ = 'user'
    id = Column(LowerCaseText, primary_key=True)
    ...

rawDescription: What is the correct way to make SQLalchemy store strings as lowercase?


code:
i, j = np.mgrid[:10, :10]
cov = i*j - i

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
from collections import defaultdict
dic=defaultdict(int)
for i,j in d:
  dic[i]+=j

dic.items()

rawDescription: merging sorted list of list members if neighbors are equal

description: Merging sorted list of list members if neighbors are equal


rawDescription: Python: Running command line application to the script. Sending parameters in files


code: b = [i for i in a if type(i) == datetime.datetime]

rawDescription: Python pulling all datetime objects (dates) out


code:
import numpy as np

a = np.random.randint(5, size=(6, 192))
s1 = str(a)
np.set_printoptions(threshold = np.prod(a.shape))
s2 = str(a)

print('...' in s1)
print('...' in s2)

rawDescription: Ellipses when converting list of numpy arrays to string in python 3


code:
np.in1d(df1['ID'], df2['ID']).astype('int')
df1['Appears'] = np.in1d(df1['ID'], df2['ID']).astype('int')
df1

rawDescription: Check if ID in one DF exists in another DF (Python 3, Pandas)


code:
df
df.fillna(method='pad')

rawDescription: Pandas df.fillna(method = 'pad') not working on 28000 row df


code:
s = "At least, that's what {pronoun} told me.".format(pronoun="he" if gender == "male" else "she")
s

rawDescription: Python conditional string formatting

description: Python conditional string formatting


code:
sorted_columns = sorted(columns, key=operator.itemgetter(1))
formats = []
offset = 0
for name, start, length, vtype in sortedcolumns:
    # add padding bytes
    if start > offset:
        formats.append('{}x'.format(start-offset))
    formats.append('{}s'.format(length))
format = struct.Struct('=' + ''.join(formats))

rawDescription: Parsing a string with defined data dictionary into a list efficiently


rawDescription: Sorting data for plotting in mplot3d

description: Sorting data for plotting in mplot3d


rawDescription: Writing to a .txt file (UTF-8), python

description: Writing to a .txt file (UTF-8), python


code:
result = ''
for line in text.split('\n'):
    result += re.sub(r'([^,;.]{20,}.*)', r'\t\1', line) + '\n'

rawDescription: Grouping characters in Python

description: Grouping characters in Python


rawDescription: Cutting of unused frequencies in specgram matplotlib


code:
while True:
    new_punch_every_time = self.moveset[0]() #note: parentheses

rawDescription: Re-evaluating a function to get a new random value in python


code:
DIALECT = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
READER = csv.reader(csvfile, DIALECT)

for skip in range(4): # skip the first four rows
    READER.next()

# Find the header line
header = []
while 'Patient Name' not in header:
    header = READER.next()

# Now start parsing
for line in READER:
    if line == []:
        continue
    # `line` contains the data and `header` the headings so we can
    # do things like
    line_as_dict = dict(zip(header,line))
    # or build the column lists as before

rawDescription: Python Column Indexing out of order

description: Python Column Indexing out of order


code:
def view_post(request, question_id):
    tpost = get_object_or_404(Post, pk=question_id)
    comment = tpost.comments_set.filter(pk=request.POST['commentID'])[0]
    [...]

rawDescription: django: Referring to a specific comment in a voting system

description: Django: Referring to a specific comment in a voting system


code:
def other_function():
    variable = 0
    def function():
        if variable == 9:
            #do these things
            variable = 0
        elif variable > 9:
            variable += 1
            #do these things until its time to
            #do the other stuff

    # variable has not been modified
    function()
    # variable has been modified

rawDescription: in Python Is there ever a good time to use a global variable inside a class?

description: In Python Is there ever a good time to use a global variable inside a class


code:
a = {
   'Mylist' : [[1,2,3],[4,5,6],[7,8,9]]
    }
[sublist for sublist in a['Mylist'] if sublist[1] != 8]
{key: [sublist for sublist in value if sublist[1] != 8]
 for key, value in a.iteritems()}

rawDescription: eliminate entries in dictionary based on a certain value

description: Eliminate entries in dictionary based on a certain value


code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder

kv_string = '''
<MyWidget>:
    Widget:
        pos_hint: {'center_y': 0.5, 'center_x': 0.5}
        size_hint: 0.2, 0.2
        canvas:
            Color:
                rgb: 0.1, 0.6, 0.3
            Rectangle:
                size: self.size
                pos: self.pos
    Widget:
        pos_hint: {'center_y': 0.5, 'center_x': 0.2}
        size_hint: 0.2, 0.2
        canvas:
            Color:
                rgb: 0.1, 0.6, 0.3
            Rectangle:
                size: self.size
                pos: self.pos
    Widget:
        pos_hint: {'center_y': 0.5, 'center_x': 0.8}
        size_hint: 0.2, 0.2
        canvas:
            Color:
                rgb: 0.1, 0.6, 0.3
            Rectangle:
                size: self.size
                pos: self.pos
    Widget:
        pos_hint: {'center_y': 0.2, 'center_x': 0.5}
        size_hint: 0.2, 0.2
        canvas:
            Color:
                rgb: 0.1, 0.6, 0.3
            Rectangle:
                size: self.size
                pos: self.pos
    Widget:
        pos_hint: {'center_y': 0.8, 'center_x': 0.5}
        size_hint: 0.2, 0.2
        canvas:
            Color:
                rgb: 0.1, 0.6, 0.3
            Rectangle:
                size: self.size
                pos: self.pos
'''

Builder.load_string(kv_string)

class MyWidget(FloatLayout):
    pass

class TestApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    TestApp().run()

rawDescription: Basic Kivy Q, Positioning Canvas Child {kivy language}


code:
def build_multilevel(entries):
    result = []
    stack = [result]
    for i, entry in enumerate(entries):
        if entry == 'OPEN':
            # convert last element of the top-most list on the stack
            # to a new, nested list, and push that new list on top
            stack[-1][-1] = [stack[-1][-1]]
            stack.append(stack[-1][-1])
        elif entry == 'CLOSE':
            stack.pop()
        else:
            stack[-1].append(entry)
    return result

rawDescription: Python: flat delimited list to nested multilevel list


code:
lines = s.split("\n")
lines == ['Add: 3rd Floor Khemha House',
          'Drive in Road, Opp Drive in Cinema',
          ...]

rawDescription: Extract data from a site using python

description: Extract data from a site using python


code:
smallcustdict[custID1] = customerdict[custID1].copy()
smallcustdict[custID2] = customerdict[custID2].copy()

rawDescription: Python memory management with list comprehensions


rawDescription: How to read specific lines in a file and insert them to a dictionary in python?

description: Read specific lines in a file and insert them to a dictionary in python


rawDescription: Fill a Pandas dataframe using information from another Pandas dataframe


code: remove_times('hi my name is 4:30 bob')

rawDescription: Stripping time (in the format hh:mm) from a string in Python 2


rawDescription: Create a list of tuples from list of tuples


code:
a = StatsTrackerBorg()
b = StatsTrackerBorg()
a is b          # would be True for StatsTrackerSingleton
vars(a) is vars(b)
vars(a)
a.data['running_time'] = 10000
b.bar = 10
vars(a)
b.foo = 'y'
a.foo

rawDescription: Python Singleton design pattern tracking application stats


code:
dict1 = {}
dict2 = {}
for x in range(0, 10):
    dict1[x] = "initValue{}".format(x)
    y = x+3
    dict2[y] = "address{}".format(y)

rawDescription: Compare two dictionaries with one key in common and form a new dictionary combining the remaining keys associated with this common key


rawDescription: Plot rolling mean together with data

description: Plot rolling mean together with data


code:
i=0
while i<n:
    j=0
    while j<n:
        ok = True
        x=0
        while x<n:
            # Why 'x-1' here?
            if((arr[i][x]==1) or (arr[x][j]==1)):
                ok = False
                break
            x+=1
        if ok:
            arr[i][j]=1
        j+=1
    i+=1

rawDescription: filling a n*n matrix with n elements

description: Filling a n*n matrix with n elements


code:
from operator import itemgetter
sorted(D.items(), key=itemgetter(1), reverse=True)

rawDescription: How to display dictionary by their values, descending?

description: Display dictionary by their values, descending


code: {k: [(nk,) + tuple(nv) for nk, nv in v.iteritems()] for k, v in ff.iteritems()}

rawDescription: dictionary of lists to tuples

description: Dictionary of lists to tuples


code:
xyzv = np.random.randint(98,104,(7,4)).astype(float)
xyzv
search_nums = [100,102]
xyzv[np.in1d(xyzv[:,3].astype(int),search_nums)]

rawDescription: How to delete rows where specific column value is not within other array?

description: Delete rows where specific column value is not within other array


code:
import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output, delimiter = '\t')

    for row in csv.reader(f_input, delimiter = '\t'):
        if len(row[2]) and len(row[3]):
            csv_output.writerow(row)

rawDescription: delete line, of a .csv, when certain column has no value python

description: Delete line, of a .csv, when certain column has no value python


code: pCorp = map(rmRepeatedPatterns, pCorp)

rawDescription: Text mining and NLP: from R to Python

description: Text mining and NLP: from R to Python


rawDescription: python tkinter calender, placing the numbers

description: Python tkinter calender, placing the numbers


code: urls('^foo/', include('fooapp.urls')),

rawDescription: reusable apps and access control

description: Reusable apps and access control


code:
import subprocess
file_ = open("ouput.txt", "w")
subprocess.Popen("ls", stdout=file_)

rawDescription: python Save the output of a shell command into a text file

description: Python Save the output of a shell command into a text file


code:
uncle_bob = Relative.from_input()
uncle_bob.first_name
uncle_bob.first_name = '123'

rawDescription: Class method to create new instance

description: Class method to create new instance


code:
def split_bits(value, n):
    ''' Split `value` into a list of `n`-bit integers '''
    mask, parts = (1 << n) - 1, []
    parts = []
    while value:
        parts.append(value & mask)
        value >>= n
    parts.reverse()
    return parts

rawDescription: Split each after 32 bits of 128 bit input in Python


code:
name = "bob"
age = 20

def changename():
    global name  # This tells that name is not local variable.
    name = "tim"

def getname():
    return name

rawDescription: Python: Import all variables

description: Python: Import all variables


code:
from calendar import day_abbr
from collections import defaultdict
from datetime import datetime, timedelta
from pprint import pprint

def solve(start, end, data):
    days = list(day_abbr)
    output = defaultdict(lambda: defaultdict(int))

    while start <= end:
        day = days[start.weekday()]
        if start.hour in data[day]:
            output[day][start.hour] += 1
        start = start + timedelta(minutes=60)
    return {k: dict(v) for k, v in output.items()}

data = {
 'Mon': [9, 23],
 'Thu': [12, 13, 14],
 'Tue': [11, 12, 14],
 'Wed': [11, 12, 13, 14],
 'Fri': [13],
 'Sat': [],
 'Sun': [],
}

start = datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime(2015, 8, 30, 10, 22, 36, 363912)

pprint(solve(start, end, data))
# output
{'Fri': {13: 6},
 'Mon': {9: 5, 23: 5},
 'Thu': {12: 6, 13: 6, 14: 6},
 'Tue': {11: 5, 12: 5, 14: 5},
 'Wed': {11: 5, 12: 5, 13: 5, 14: 5}}

rawDescription: Counting day-of-week-hour pairs between two dates


code:
theks = {}
for k in pi:
    pieces = k.split(' ')
    theks[k[0]] = k[1:]

rawDescription: append multiple results from one list to another

description: Append multiple results from one list to another


code:
s = 'steve && chris || joe && george'
s.split(' || ')  # returns ['steve && chris', 'joe && george']

rawDescription: capturing repeating groups with reg ex in python

description: Capturing repeating groups with reg ex in python


code:
from django.contrib.auth.models import AnonymousUser

class PatientForm(ModelForm):
    class Meta:
        model=Patient

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', AnonymousUser())
        super(PatientForm, self).__init__(*args, **kwargs)
        if user.is_staff():
            # hide field and set doctor to request.user
            self.fields['doctor'].widget = forms.HiddenInput()
            self.fields['doctor'].initial = user

rawDescription: Choosing which fields appear in a modelform according to user


code:
result = add.apply_async(queue="queuename1")
result = result.get() #This contain the return value of task

rawDescription: How to switch tasks between queues in Celery

description: Switch tasks between queues in Celery


code: a = [c.text for c in kontent.xpath('//table[@id="blk-ctnt-2308"][1]//tr/td[5]') ]

rawDescription: python lxml can't find table

description: Python lxml can't find table


code:
mystring = "Hello world, how how are you doing today"
words = mystring.split()

lastword = ""
for word in words:
    if lastword.lower() == word.lower():
        print("The word " + word + " is repeated")
        break
    lastword = word

rawDescription: I am relatively new to Python, I was wondering how to see if two words in a string are the same like this:


code:
from BufferMethods import *
Buff = Buffer(800,600)
dataList = Buff.getList()
dataList[2]
dataList[2][2]

rawDescription: From C++ buffer to python::boost::list

description: From C++ buffer to python::boost::list


code:
import tkinter as tk

def onChange(val):
    if val == "Square":
        r = 2
    elif val == "Sphere":
        r = 1
    else:
        r = 5

    # Destroys all existing widgets in the container frame
    for wid in container.winfo_children():
        wid.destroy() # Using destory instead of grid_forget

    # Dynamically create Entry widgets in container frame
    # Number is equal to r
    for x in range(r):
        e = tk.Entry(container)
        e.grid(row = 1 + x, column = 0)

root = tk.Tk()
root.minsize(200, 200)

options = ["Square", "Sphere", "Other"]
var = tk.StringVar()
var.set("Square")

op_menu = tk.OptionMenu(root, var, *options, command = onChange)
op_menu.grid(row = 0, column = 0)

# Container frame for the Entry widgets
container = tk.Frame(root)
container.grid()

rawDescription: Python grid_remove

description: Python grid_remove


code: print (result.dump())

rawDescription: Cannot parse correctly this file with pyparsing


code:
def str_replace(search, replace, subject):
    for s in search:
        subject = subject.replace(s, replace)
    return subject

rawDescription: Python - How to match and replace words from a given string?


code:
import multiprocessing
from functools import partial

def func(a, b, c, d):
   print("{} {} {} {}".format(a, b, c, d))

def func_star(a, b, c_d):
   func(a, b, *c_d)

if __name__ == "__main__":
    pool = multiprocessing.Pool()
    partfunc = partial(func_star, '1', '2') # '1' and '2' are the fixed args
    var_list1 = ['a', 'b', 'c']
    var_list2 = ['x', 'y', 'z']
    pool.map(partfunc, zip(var_list1, var_list2))

rawDescription: Building tuple arguments for function

description: Building tuple arguments for function


code:
import numpy as np
import warnings
# genfromtxt warns if it encounters an empty file. Let's silence this warnings since
# the code below handles it.
warnings.filterwarnings("ignore", message='genfromtxt', category=UserWarning)

# This reads 2 lines at a time
chunksize = 2
with open('data', 'rb') as fin, open('out.csv', 'w+b') as fout:
    while True:
        arr = np.genfromtxt(fin, max_rows=chunksize, usecols=(0,1,2),
                            delimiter='', dtype=float)
        if not arr.any(): break
        arr = np.atleast_2d(arr)
        mask = (arr[:, 0] >= 0.807375) & (arr[:, 0] <= 0.807982)
        arr = arr[mask]

        # uncomment this print statement to confirm the file is being read in chunks
        # print('{}\n{}'.format(arr, '-'*80))
        np.savetxt(fout, arr, fmt='%g')

rawDescription: How to read only some lines from a large file in python?

description: Read only some lines from a large file in python


code:
s = set()
sl = []
for elem in ls:
    if elem == 4 or elem not in s:
        sl.append(elem)
        s.add(elem)

rawDescription: How to remove all duplicates from list except one element in Python?

description: Remove all duplicates from list except one element in Python


code:
# acknowledgement:
# this is structurally the same as one of hughdbrown's benchmark functions
def currently_accepted_solution_augmented_without_extra_closure(targets, paragraph):
    def tester(x):
        return len(re.findall(r"\b" + x + r"\b", paragraph))
    return map(tester, targets)

rawDescription: Using map() to get number of times list elements exist in a string in Python


code:
import cStringIO
def my_cgi( environ, start_response ):
    page = cStringIO.StringIO()
    sys.stdout= page
    os.environ.update( environ )
    # you may have to do something like execfile( "my_cgi.py", globals=environ )
    execfile( "my_cgi.py" )
    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'text/html')] # HTTP Headers
    start_response(status, headers)
    return page.getvalue()

rawDescription: Python cgi performance

description: Python cgi performance


code:
if (let, ind_count) in c_dict:
    c_dict[let, ind_count].add(new_word)
else:
    c_dict[let, ind_count] = set([new_word])

rawDescription: Manipulating sets in dictionaries

description: Manipulating sets in dictionaries


rawDescription: using reg exp to check if test string is of a fixed format

description: Using reg exp to check if test string is of a fixed format


code:
def __hash__(self):
    return hash("foobar"*len(self))

rawDescription: What makes a user-defined class unhashable?


code: a = pd.DataFrame({'a':np.arange(20), 'b':np.random.random(20), 'Code':np.random.random_integers(0, 10, 20)})

rawDescription: how to group all the data as fast as possible?

description: Group all the data as fast as possible


code:
def template(pattern, flags=0):
    "Compile a template pattern, returning a pattern object"
    return _compile(pattern, flags|T)

rawDescription: What does the python re.template function do?


code:
lines = ""

with open('D:\File.txt') as file:
    for line in file:
        lines += line.strip() + ";\n"

file = open('D:\File.txt', "w+")
file.writelines(lines)

file.flush()

rawDescription: Changing format of output text file

description: Changing format of output text file


rawDescription: Is there any alternative ways other than loop to update the dictionary from any sequence data (Python)?


code:
class InitialValues(object):
    def process_request(self, request):
        from app.forms import AppForm
        AppForm.base_fields['fieldname'].initial="your default value"

rawDescription: Form interceptor, populate a form field without touching the original application


rawDescription: Confusing double usage of python asterisk notation (as a function argument, or as a function definition)


code:
class ThesaurusBase():
    def __init__(self, singleton=None):
        self.singleton = singleton

    def mymethod1(self):
        raise NotImplementedError

    def mymethod2(self):
        raise NotImplementedError

class ThesaurusSingleton(ThesaurusBase):
    def mymethod1(self):
        return "meaw!"

class Thesaurus(TheraususBase):
    def __init__(self, singleton=None):
        TheraususBase.__init__(self, singleton)

    def mymethod1(self):
        return "quack!"

    def mymethod2(self):
        return "\\_o<"

rawDescription: Python2.7: infinite loop when super __init__ creates an instance of it's own subclass


code: dialog = FileChooser()

rawDescription: How to make filename/path from Gtk+ (Python 3.4) FileChooserDialog accessible globally

description: Make filename/path from Gtk+ (Python 3.4) FileChooserDialog accessible globally


rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
js = select([profiles.c.id,
             profiles.c.keep,
             profilefields.c.keep,
             profiles.c.fieldid,
             profilefields.c.fieldid],
            use_labels=True,
            from_obj=j)
mapper(DBObj,alias(js),properties={'fieldid':[profiles.c.fieldid,profilefields.c.fieldid]})
q = Session().query(DBObj).all()
q

rawDescription: SQLAlchemy - Mapping subset of columns from inner join of autoloaded tables


rawDescription: Django if value is in list

description: Django if value is in list


code:
rank_list = []
for m in A:
    score = 0
    for n in A:
        if (n[3] > m[3]) and (n in rank_list):
            score += 1
    rank_list.append(m + [score])

rawDescription: Compare two nested lists and append a third list based on nested values - Python


rawDescription: Newick tree representation to scipy.cluster.hierarchy linkage matrix format


code:
import curses
import sys

clear_screen_seq = b''
if sys.stdout.isatty():
    curses.setupterm()
    clear_screen_seq = curses.tigetstr('clear')

rawDescription: Python - Clearing the terminal screen more elegantly


code:
from collections import Counter
count = Counter()
for name, amount, drink in tuples:
    key = name, drink
    count.update({key: int(amount)})  # increment the value

# represent the aggregated data
for (name, drink), amount in count.items():
    print('{}: {} {}'.format(name, amount, drink))

rawDescription: how to merge data in python

description: Merge data in python


rawDescription: Django Get multiple fields from database


code:
period = datetime.timedelta(days=28)  # 4 weeks
delta = today - start
remainder = delta.days % period.days
end = today + datetime.timedelta(days=remainder)

rawDescription: Divide two timespans by eachother in Python/dateutil


code:
class StaticUtilities:

    @staticmethod
    def methodA():
        return 1

    @classmethod
    def methodB(cls):
        return cls.methodA() + 1

rawDescription: Alias a fully static class's reference within itself


code:
def remote_read(self, params=[], fields=[]):
    ...
    params['fields'] = fields
    ...

rawDescription: Filtering statistics from facebook ads api using the python sdk


code:
class GroupProfile(models.Model):
    group = models.OneToOneField('auth.Group', unique=True)
    url = models.CharField(max_length=100)

rawDescription: How to extend Django Group and still use in Django User

description: Extend Django Group and still use in Django User


code:
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
numpy.savetext(filename, (a,b), fmt="%d")

# gives:
# 1 2 3
# 4 5 6

rawDescription: Saving numpy array to txt file row wise

description: Saving numpy array to txt file row wise


code:
import numpy as np

A = np.zeros((7, 6, 2))
B = np.zeros((6,2))
C = np.concatenate((A,B[np.newaxis,:,:]),axis=0)
print(A.shape,B.shape,C.shape)

rawDescription: concatenating two multidimensional arrays in numpy

description: Concatenating two multidimensional arrays in numpy


rawDescription: Is there way to use dictionary in python to print 2 outputs: one as string of whole token and one as number


code:
def upload_file(request):
    if request.method == 'POST':
        form = YourForm(request.POST, request.FILES)
        if form.is_valid():
            data = loginForm.cleaned_data
            username = data['username']
            first_name = data['first_name']
            #you can retrieve the filename here
            filename = request.FILES['file'].name
            handle_uploaded_file(request.FILES['file'])
            #...
            return HttpResponseRedirect('/success/url/')
    else:
        form = YourForm()

    return render_to_response('your.html', {'form': form})

def handle_uploaded_file(f):
    #or here
    filename = f.name
    #...
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

rawDescription: uploading a file but did not get a file name

description: Uploading a file but did not get a file name


code: string = string or "defaultValue"

rawDescription: How to set default value for variable?

description: Set default value for variable


code:
def update_text(text):
    char = text[0]
    remainder = text[1:]
    current_string = canvas.itemcget(variable, "text")
    new_string = current_string + char
    canvas.itemconfigure(variable, text=new_string)
    if len(remainder) > 0:
        canvas.after(delay, update_text, remainder)

rawDescription: How to make a text button which speeds up text animation

description: Make a text button which speeds up text animation


code:
a = np.arange(5)
b = np.arange(8)[::-1]
a
b
a[:, None] - b

rawDescription: Use outer function with FUN="-" in Python


code:
import multiprocessing
import copy_reg
import types

def _reduce_method(m):
    if m.im_self is None:
        return getattr, (m.im_class, m.im_func.func_name)
    else:
        return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _reduce_method)

def test1():
    print("Hello, world 1")

def increment(x):
    return x + 1

class testClass():
    def process(self):
        process1 = multiprocessing.Process(target=test1)
        process1.start()
        process1.join()
        process2 = multiprocessing.Process(target=self.test2)
        process2.start()
        process2.join()

    def pool(self):
        pool = multiprocessing.Pool(1)
        for answer in pool.imap(increment, range(10)):
            print(answer)
        print
        for answer in pool.imap(self.square, range(10)):
            print(answer)

    def test2(self):
        print("Hello, world 2")

    def square(self, x):
        return x * x

def main():
    c = testClass()
    c.process()
    c.pool()

if __name__ == "__main__":
    main()

rawDescription: Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?


code: --force-reinstall

rawDescription: Can I force pip to reinstall the current version?

description: Force pip to reinstall the current version


code:
lis = [1,2,3]
lis.extend('foo')      #string is an iterable in python
lis
lis.extend([7,8,9])    #same thing happend here
lis
lis.extend(4)          #an integer is an not iterable so you'll get an error

rawDescription: Nested float arrays in Python

description: Nested float arrays in Python


code:
for index, value in enumerate(list1):
    list1[index] = list2[index]

rawDescription: Python CSV: write rows according to dict mapping


rawDescription: from list of strings into list of floats

description: From list of strings into list of floats


code:
from operator import add,sub,mul,div,pow
ops = {'+':add,'-':sub,'/':div, '*':mul,'**':pow}
B = ['+','-','/','*','**']
A = 1
[ops[item](A,100) for item in B]

rawDescription: Python: Altering code between iterations


code:
c
[{'name': name, 'count': count} for name, count in c.items()]

rawDescription: Python list grouping and sum

description: Python list grouping and sum


code:
def addimg(request, pk):
    ...

rawDescription: Passing variable to html page using Python Django


code:
import random
help(random)

rawDescription: Fortune cookie game in Python

description: Fortune cookie game in Python


code:
datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M').strftime('%c')
import locale
locale.getlocale()
locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M').strftime('%c')

rawDescription: Django - Change default locale

description: Django - Change default locale


code:
import spotipy

sp = spotipy.Spotify()
sp.trace = False

# find album by name
album = "Pestbringer"
results = sp.search(q = "album:" + album, type = "album")

# get the first album uri
album_id = results['albums']['items'][0]['uri']

# get album tracks
tracks = sp.album_tracks(album_id)
for track in tracks['items']:
    print(track['name'])

rawDescription: Get Spotipy album ID from album

description: Get Spotipy album ID from album


code:
df.registerTempTable("df")

sqlContext.sql("""
    SELECT MONTH(timestamp) AS month, SUM(value) AS values_sum
    FROM df
    GROUP BY MONTH(timestamp)""")

rawDescription: Group spark dataframe by date

description: Group spark dataframe by date


code:
filename = ctypes.c_char_p('something')
filename = ctypes.c_wchar_p('something') # for unicode

rawDescription: python ctypes how to map PTSTR

description: Python ctypes how to map PTSTR


code:
import itertools

biglist = [['x','y','z'],['a','b'],['d','f','g'],['r','e','w','q','t','u','i']]

print(list(list(i[1]) for i in itertools.groupby(sorted(biglist, key=len), len)))

rawDescription: Python : compare lists of a list by length and create new lists of equal sizes


code:
import pygame, sys
pygame.init()
window=pygame.display.set_mode((1500, 800))
background=pygame.Surface((window.get_rect().width, window.get_rect().height))
background.fill((0, 0, 0))
image=pygame.image.load('InsertImageHere.png')
image=image.convert()
image2=pygame.image.load('InsertImage2Here.png')
image2=image2.convert_alpha()
rect=image.get_rect()
rect2=image2.get_rect()
rect2.left=rect.width+1
i=1
while True:
    for event in pygame.event.get():
        if event.type==12:
            pygame.quit()
            sys.exit()
    image.set_alpha(i)
    image2.set_alpha(i)
    window.fill((255, 255, 255))
    window.blit(background, background.get_rect())
    window.blit(image, rect)
    window.blit(image2, rect2)
    pygame.time.delay(20)
    i+=1
    if i==255:
        i=1
    pygame.display.update()

rawDescription: how to use pygame set_alpha() on a picture

description: Use pygame set_alpha() on a picture


rawDescription: Multiple copies of array returned by numpy.arange?


code:
lst2 = [0.12, -0.23, 0.52, 0.2, 0.6, -0.3, 0.4] # the list
minmax = [min(v) if k else max(v) for k,v in groupby(lst2, lambda a: a < 0)]
[abs(j-i) for i,j in zip(minmax[:-1], minmax[1:])]

rawDescription: Calculate difference each time the sign changes in a list of values


code:
def heat(number):
    m = { "r" : 12,
          "b" : 24 }

    return m[number] if number in m else 0.0

rawDescription: Improving readability and functionality of a function


code:
True
True
False

rawDescription: Create python functions from expression trees


code:
subqry = session.query(func.max(Data.counter)).filter(Data.user_id == user_id)
qry = session.query(Data).filter(Data.user_id == user_id, Data.counter == subqry)

rawDescription: SQLAlchemy: Return a record filtered by max value of a column


rawDescription: Pandas slicing along multiindex and separate indices


code:
weighted_counts = pivoted.mul(age_weights, axis=0).mul(gender_weights, axis=0)
weighted_counts

rawDescription: Weighting values based on variables

description: Weighting values based on variables


code:
def traverse(tree):
    if not isinstance(tree, dict):
        return tree.isalpha() # if leafs can't be alphabetic, simply return 0
    return sum(k.isalpha() + traverse(v) for k, v in tree.items())

rawDescription: Parse dictionaries within a dictionary in python


code:
friends = db.Table('friends',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('friend_id', db.Integer, db.ForeignKey('user.id'))
)

rawDescription: Make only one BestFriend with flask-sqlalchemy


rawDescription: A* Search - least number of hops?

description: A* Search - least number of hops


code:
l = [1, 1, 2, 3]
inds = []
seen = set()
for i, ele in enumerate(l):
    if ele not in seen:
        inds.append(i)
    seen.add(ele)

rawDescription: Remove duplicates in python list but remember the index


code:
from django.core.files.base import ContentFile

obj = Article()
data = base64.b64decode(encoded)
# You might want to sanitise `data` here...
# Maybe check if PIL can read the `data`?
obj.image.save('some_file_name.ext', ContentFile(data))
obj.save()

rawDescription: Upload photo from Android device to Django backend and save it to database


code: '{0} is less than {1}'.format(a, b)

rawDescription: Returning different types in Python

description: Returning different types in Python


rawDescription: Suppressing scientific notation when applying operators to very long decimal numbers using the standard library Decimal


rawDescription: Converting php loop to python

description: Converting php loop to python


rawDescription: Search neighboring points using k-d trees


rawDescription: Remove tuples in a 2D numpy array that satisfy 2 conditions


code:
with open("output.txt", "wb+") as f:
  for line in lines:
    # Stuff...
    for name in names:
      f.writelines(name)

rawDescription: Writing a results to a .txt file using csv


code: Product.name = lambda self: "stubbed_name"

rawDescription: Mocking out methods on any instance of a python class


code:
import Tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()

canvas_text = canvas.create_text(10, 10, text='', anchor=tk.NW)

test_string = "This is a test"
#Time delay between chars, in milliseconds
delta = 500
delay = 0
for i in range(len(test_string) + 1):
    s = test_string[:i]
    update_text = lambda s=s: canvas.itemconfigure(canvas_text, text=s)
    canvas.after(delay, update_text)
    delay += delta

root.mainloop()

rawDescription: How can i animate text by character in Tkinter?

description: Animate text by character in Tkinter


code:
dict_input = [{"name":"kishore", "age":23},{"name":"xyz", "age":21}]
next((d for d in dict_input if d['name'] == 'kishore'), None)
next((d for d in dict_input if d['name'] == 'no-such-name'), None)
next((d for d in dict_input if d['name'] == 'no-such-name'), None) == None

rawDescription: Find a dictionary based on a key in list of dictionaries in python


code:
df['change'] = ~ (df == df.shift())
def func(row, state):
    t = row['type']
    if row['change']:
        state[t] = state.get(t, -1) + 1
    return t + str(state[t])
df.apply(func, args=({},), axis=1)

rawDescription: pandas: identify "portions" along a DataFrame

description: Pandas: identify "portions" along a DataFrame


code:
import itertools
with open('/etc/passwd') as f:
    print (next(itertools.islice(f, i, i+1)))

rawDescription: Randomly generate a line from a .txt file


code:
a  = multiprocessing_np_arr_base_class(a=2,b=3)

shr_var
Out[15]: {'a': 2, 'b': 3}

rawDescription: Define a function that repeat commands for each input given in python


code:
import numpy as np
import scipy.ndimage

a= np.zeros((5, 5))
a[1:4, 1:4] = np.arange(3*3).reshape((3, 3))

default_out = scipy.ndimage.median_filter(a, size=(3, 3))
shift_pos_x = scipy.ndimage.median_filter(a, size=(3, 3), origin=(0, 1))
shift_neg_x = scipy.ndimage.median_filter(a, size=(3, 3), origin=(0, -1))

print(a)
print(default_out)
print(shift_pos_x)
print(shift_neg_x)

rawDescription: Scipy ndimage median_filter origin

description: Scipy ndimage median_filter origin


code:
import datetime as DT
import pytz

tzone = pytz.timezone('Europe/Budapest')
date1 = tzone.localize(DT.datetime(2014, 3, 29, 0, 0), is_dst=None)
# datetime.datetime(2014, 3, 29, 0, 0, tzinfo=<DstTzInfo 'Europe/Budapest' CET+1:00:00 STD>)

rawDescription: Difference of two timedelta objects, with timezones


code:
class CustomerEventsServiceEvent(Model):
    __table_name__ = "customer_events_service.events"

    acceptFirstContactDuration = columns.Decimal()
    allSeenPageCount = columns.Decimal()
    callAcceptedCount = columns.Decimal()

rawDescription: Insert a dict in cassandra DB

description: Insert a dict in cassandra DB


code:
import md5
md5.new("1387797294" + "9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1").hexdigest()

rawDescription: Convert Python Code to C# Code (generate HMAC)


code: {{ url_for('download_file', filename='dogs.jpg') }}

rawDescription: How do i link to images not in Static folder in flask

description: Link to images not in Static folder in flask


code:
self.seats[('screen1', 'day4')]['show4'] = 90

self.seats[('screen1', 'day4')]['show4']
90

rawDescription: how to access values of nested dictionary keys in python?

description: Access values of nested dictionary keys in python


code:
from scipy import integrate as integrate
def f(x,a):  #a is a parameter, x is the variable I want to integrate over
    return a*x

result = integrate.quad(f,0,1,args=(1,))

rawDescription: How to evaluate single integrals of multivariate functions with Python's scipy.integrate.quad?

description: Evaluate single integrals of multivariate functions with Python's scipy.integrate.quad


code:
names = ['Ben', 'Thor', 'Zoe', 'Katie']
player_name = input('What player are you looking for?')

if player_name in names:
    print('Yes, they have a top score')
else:
    print('No, they do not have a top score')

rawDescription: Python Program, while loop not executing?


code: return "side1: {} side2: {} side3: {}".format(self.__side1, self.__side2, self.__side3)

rawDescription: How to make the input into a parameter in a class for Python

description: Make the input into a parameter in a class for Python


code: form = self.form_class(request.POST)

rawDescription: Django login form not working for custom user model


rawDescription: split string with timestamps

description: Split string with timestamps


code: pairs = collections.Counter(zip(listX, listY))

rawDescription: extract repeated elements in a list in python

description: Extract repeated elements in a list in python


code:
with open(file, 'w') as handle:
    handle.write(result)

rawDescription: How to concatenate several Javascript files into one file using Python

description: Concatenate several Javascript files into one file using Python


code:
u.Member_list.all()
# output: [<Group: Group object>]

rawDescription: Queryset for ManyToMany relation in Django


code:
class Finalize(object):
    '''
    Class which supports object finalization using weakrefs
    '''
    def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None):
        assert exitpriority is None or type(exitpriority) is int

        if obj is not None:
            self._weakref = weakref.ref(obj, self)
        else:
            assert exitpriority is not None

        self._callback = callback
        self._args = args
        self._kwargs = kwargs or {}
        self._key = (exitpriority, _finalizer_counter.next())
        self._pid = os.getpid()

        _finalizer_registry[self._key] = self  # That's what we're looking for!

rawDescription: Context managers and multiprocessing pools


code:
import win32com.client
excel = win32com.client.gencache.EnsureDispatch ("Excel.Application")
excel.Visible = True
workbook = excel.Workbooks.Open(filepath)
if isinstance(worksheetName, str):
    worksheet = workbook.Worksheets(worksheetName)
else: #assume that worksheetName is number
    sheet = workbook.Worksheets[worksheetName]

def getRange(worksheet, address):
    return worksheet.Range(address)

def getValue(range_):
    """Returns values from specified range, as tuple of tuples (even if range
    is single row) or single value if range is one cell"""
    return range_.Value2

def setValue(range_, values):
    range_.Value2 = values

rawDescription: Python: How to open a multisheet .xslx file (with formatting) and edit a few cells and save it as another .xlsx file


code:
from lxml import etree

tree = etree.parse('xmlfile')
root = tree.getroot()

for elem in root.iter('*'):
    if elem.text is not None:
        elem.text = elem.text.strip()
    if elem.tail is not None:
        elem.tail = elem.tail.strip()

print(etree.tostring(root, encoding="utf-8", xml_declaration=True))

rawDescription: Python how to strip white-spaces from xml text nodes


code: errorcheck = PyModule_AddStringConstant(embmodule, "str", cStr);

rawDescription: How to create and assign a Python variable in C?

description: Create and assign a Python variable in C


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

def main():
    fig, ax = plt.subplots()
    x1 = np.linspace(-1,1,100)

    line1, = ax.plot(x1, np.sin(x1))
    line2, = ax.plot(x1, 3 * np.sin(x1))
    line3, = ax.plot(x1, np.sin(x1 / 2.0))
    autoscale_based_on(ax, [line1, line3])

    plt.show()

def autoscale_based_on(ax, lines):
    ax.dataLim = mtransforms.Bbox.unit()
    for line in lines:
        xy = np.vstack(line.get_data()).T
        ax.dataLim.update_from_data_xy(xy, ignore=False)
    ax.autoscale_view()

if __name__ == '__main__':
    main()

rawDescription: Make matplotlib autoscaling ignore some of the plots


code:
del thing1
del thing2

rawDescription: Python list anomalous memory usage

description: Python list anomalous memory usage


code:
from django.utils.safestring import mark_safe

class RegistrationForm(ModelForm):
    username = forms.CharField(error_messages={'required': mark_safe('Please enter a <b>username</b>.')})

rawDescription: Autoescape Django Form Errors

description: Autoescape Django Form Errors


code: {{ my_dict|get:"_my_key" }}

rawDescription: Accessing dict elements with leading underscores in Django Templates


rawDescription: How do i compute with (numpy) -arrays eloquently in python

description: Compute with (numpy) -arrays eloquently in python


avg

value:
import android
droid = android.Android()
droid.makeToast('Hello, Android!')

type: PythonScript

rawDescription: JSON: Concatenate 2 string values in value


code:
with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

rawDescription: Python 2.7 - Write and read a list from file


rawDescription: How to remove a node inside an iterator in python xml.etree.ElemenTree

description: Remove a node inside an iterator in python xml.etree.ElemenTree


code: self.connect(self.checkbox_color, QtCore.SIGNAL('stateChanged(int)'), partial(self.lock_choice, self.combo_color))

rawDescription: Lock a choice in PyQt4 QComboBox using a QCheckBox


code:
with open("karolo.txt","w") as file1, open("karolo.txt","r") as file3:
    file1.write("abcd\n")
    file1.flush()
    file34 = file3.read()

assert file1.closed and file3.closed

rawDescription: How to print strings from a txt file in python3.x

description: Print strings from a txt file in python3.x


code: df - v

rawDescription: minimizing a given vector of components with a dataframe

description: Minimizing a given vector of components with a dataframe


code:
class Hello:
    def __getattr__(self, name):
        def f(msg=""):
            print("{} {}".format(msg, name))
        return f

if __name__ == "__main__":
    h = Hello()
    h.aaa("hello")
    h.bbb("hello")

rawDescription: Is there a "wildcard method" in Python?

description: Is there a "wildcard method" in Python


rawDescription: How do Twisted python Factory and Protocol interfaces work?


code:
d = {}
for sheet in e.sheet_names:
    d[sheet] = pd.read_excel("PTE_Kinetics_04-30-2015.xlsx", sheet, index_col='Time').head(3)

rawDescription: python- pandas read_excel getting wrong numbers for index_col

description: Python- pandas read_excel getting wrong numbers for index_col


code:
result = {}
def count():
    fruit = input("What fruit are you getting at the store? ")
    if fruit not in result:
        result[fruit] = 0 # Create a new entry in the dictionary. 0 == int()
    result[fruit] += 1

rawDescription: Counting with python dictionaries and adding functionality


code:
def do_FOLD(self):
    game.bet(self, 'fold')

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


code:
from fileinput import input
for line in input("testDTC.txt",inplace=True):
    if line.strip() and not line.startswith(":"):
        spl = line.split(None,2)
        print("{} ;{}".format(" ".join(spl[:2]),spl[2]),end="")
    else:
        print(line,end="")

rawDescription: python, search .txt file and inject character

description: Python, search .txt file and inject character


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('outfile', type=argparse.FileType('w'))
parser.add_argument('infile', type=argparse.FileType('r'))

args = parser.parse_args()

for line in args.infile:
    print(line.strip())
args.infile.seek(0)
for line in args.infile:
    args.outfile.write(line)

rawDescription: Pass arguments from a class to another class that inherits from threading.Thread


code:
from Tkinter import *

root = Tk()
T = Text(root, height=2, width=30, bg='lightgrey', relief='flat')
T.insert(END, "Just a text Widget\nin two lines\n")
T.config(state=DISABLED) # forbid text edition
T.pack()
mainloop()

rawDescription: python tkinter popup window with selectable text

description: Python tkinter popup window with selectable text


code: np.linspace(1, 10, 6)

rawDescription: Assigning histogram bin to each data point


code:
import sys
import code

def reset():
    raise SystemExit(123)

sys.modules['__builtin__'].reset = reset

banner = None

while 1:
    try:
        code.interact(banner=banner, local={})
        break
    except SystemExit as e:
        if e.code == 123:
            banner = 'Resetting...'
            continue
        raise

rawDescription: Clear the environment of the evalutor

description: Clear the environment of the evalutor


rawDescription: filtering numpy matrix on a column

description: Filtering numpy matrix on a column


code:
@memoized
def fun(x1, y1, x2, y2, n, r=[]):
    ...

rawDescription: How can I rewite this Python code using iteration?

description: Rewite this Python code using iteration


code:
class Field_node(object):
    def __init__(self):
        self.field_phenotype_id = -1
        self.field_name = ''
        self.field_parent_id = -1
        self.child_nodes = []

rawDescription: My recursive function (populates a tree structure) is adding to the root node during every loop/call


code: result['nU'] = result.sum(axis=1)

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


rawDescription: How do I count occurences of a unique label?

description: Count occurences of a unique label


code:
subprocess.check_call(['/usr/bin/env', 'python2.6', '/path/to/your_script'] +
                      sys.argv[1:])

rawDescription: Python subprocess: How to run a python script using a different intepreter than the main thread


code:
from collections import defaultdict

alignments = defauldict(list)

for k in range(1, number_of_sent+1):

    sentences = bitext[k-1]
    chinese_sent = sentences[0]
    english_sent = sentences[1]

    for cs in chinese_sent:
        argmax = 0
        for es in english_sent:
            if probabilities[cs,es] >= argmax:
                argmax = probabilities[cs,es]
                alignments[k, cs].append(es)

rawDescription: writing maximum values to a dictionary without overwriting

description: Writing maximum values to a dictionary without overwriting


code:
from django import template

register = template.Library()

@register.inclusion_tag('individual_message.html')
def render_message(message):
    context_for_rendering_inclusion_tag = {'message': message}
    return context_for_rendering_inclusion_tag

rawDescription: DJANGO : Update div with AJAX

description: DJANGO : Update div with AJAX


rawDescription: How do I fill an unknown size gap in an series

description: Fill an unknown size gap in an series


code:
user_type = ContentType.objects.get(app_label="auth", model="user")
user_type = ContentType.objects.get(model="user")
# but this can throw an error if you have 2 models with the same name.

rawDescription: Django - Get ContentType model by model name (Generic Relations)


code: imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent)

rawDescription: Variable alpha blending in pylab

description: Variable alpha blending in pylab


code:
from pylab import *
x = linspace(0,1,10)
y = rand(10,2)
y[5:8,1] = nan
boolind = ~isnan(y)
plot(x[boolind[:,0]],y[boolind[:,0], 0],'.-')
plot(x[boolind[:,1]],y[boolind[:,1], 1],'.-')
show()

rawDescription: How to interpolate lines over nans in pylab?

description: Interpolate lines over nans in pylab


code: t.transpose(1, 2, 0).reshape(4, 3)

rawDescription: Stab a 3d array

description: Stab a 3d array


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://www.drugs.com/drug-class/laxatives.html?condition_id=&generic=0&sort=rating&order=desc")

# wait for the table list to load
table = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "table.data-list")))

for b in table.find_elements_by_css_selector("tr td > a[href] > b"):
    print(b.text)

rawDescription: How to select all tags with selenium and python

description: Select all tags with selenium and python


code: df['index'] = df.groupby(['cols'])['cols'].transform(lambda x: range(len(x)))

rawDescription: reshaping data frame in pandas

description: Reshaping data frame in pandas


rawDescription: Count number of occurences of specific words in Excel sheet using python & xlrd


rawDescription: Is there a way to autogenerate valid arithmetic expressions?


code: input_arr = raw_input('input here :').split(' ')

rawDescription: raw_input() with With White Spaces in Between the Inputs in Python 2

description: Raw_input() with With White Spaces in Between the Inputs in Python 2


code:
def discrete_cmap(N=8):
    """create a colormap with N (N<15) discrete colors and register it"""
    # define individual colors as hex values
    cpool = [ '#bd2309', '#bbb12d', '#1480fa', '#14fa2f', '#000000',
              '#faf214', '#2edfea', '#ea2ec4', '#ea2e40', '#cdcdcd',
              '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ]
    cmap3 = col.ListedColormap(cpool[0:N], 'indexed')
    cm.register_cmap(cmap=cmap3)

rawDescription: Customize colorbar in matplotlib

description: Customize colorbar in matplotlib


code:
import os
import stat
import shutil

INCOMING = '/some/path/with/new/files/'
PROCESSED = '/some/path/for/processed/files/'
TIME_WITH_NO_WRITES = 600  # 10 minutes

def check_for_new_file(directory=INCOMING, files={}):
    for file in os.listdir(directory):
        if file in files:
            break
        size = os.stat(file)[stat.ST_SIZE]
        files[file] = (datetime.time.now(), size)
    now = datetime.time.now()
    for file, last_time, last_size in files.items():
        current_size = os.stat(file)[stat.ST_SIZE]
        if current_size != last_size:
            files[file] = (now, current_size)
            continue
        if now - last_time <= TIME_WITH_NO_WRITES:
            return file
    raise NoneReady()

def process_new_file():
    try:
        filename = check_for_new_file()   # raises ValueError if no file ready
    except NoneReady:
        return
    in_file = open(filename, 'rb')
    csv_file_in = csv.reader(in_file)
    out_file = open(MASTER_CSV, 'rb+')
    csv_file_out = csv.writer(out_file)
    for row in csv_file_in:
        csv_file_out.write(row)
    csv_file_out.close()
    csv_file_in.close()
    shutil.move(filename, PROCESSED)

if __name__ == '__main__':
    while True:
        process_new_file()     # does nothing if no new file
        time.sleep(60)

rawDescription: Updating CSV files automatically

description: Updating CSV files automatically


rawDescription: how to variate a parameter in an equation python

description: Variate a parameter in an equation python


code:
def splice(seq, exons):
    newseq = ""
    next = 0
    for x, y in exons:
        newseq += seq[next:x]
        next = y
    newseq += seq[next:]
    return newseq

rawDescription: Splicing mRNA using for a while loops

description: Splicing mRNA using for a while loops


rawDescription: aligning, spacing in python 3

description: Aligning, spacing in python 3


code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime

stacked_dates = []
for date in dates:
    stacked_dates.append( date.replace(year=2000)  )

stacked_dates = mpl.dates.date2num(stacked_dates)

fig = plt.figure()
ax = plt.subplot(111)
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
format = mpl.dates.DateFormatter('%m/%d')
ax.xaxis.set_major_formatter(format)

ax.hist(stacked_dates)

plt.xticks(rotation='vertical')
plt.show()

rawDescription: How to make a histogram from this nc file?

description: Make a histogram from this nc file


code: setattr(instance, self.name + '_is_set', True)

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


code:
list_of_things = [a,b,c]
map("".join, product(*list_of_things))

rawDescription: How can I simplify "for x in a for y in b for z in c ..." with the unordered?

description: Simplify "for x in a for y in b for z in c ..." with the unordered


rawDescription: Url decode UTF-8 in Python

description: Url decode UTF-8 in Python


code:
input_array = np.array([1, 2, 3, 4])
(input_array[:,None] * extend_array).ravel()

rawDescription: Vectorize numpy array expansion

description: Vectorize numpy array expansion


code:
a
b
c
c

rawDescription: How create a hash table for large data in python?


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

e = np.e
X, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
F = X ** Y
G = Y ** X

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
circ = plt.Circle((e, e), radius=0.07, color='g')
plt.contour(X, Y, (F - G), [0])
ax.add_patch(circ)
plt.show()

rawDescription: matplotlib: add circle to plot

description: Matplotlib: add circle to plot


rawDescription: Add 30 minutes to a time read from a text file and compare against current time


code:
with open("enc.txt","r") as f:
    content = f.read()

import re

def unicodize(seg):
    if re.match(r'\\u[0-9a-f]{4}', seg):
        return seg.decode('unicode-escape')

    return seg.decode('utf-8')

replaced = (unicodize(seg) for seg in re.split(r'(\\u[0-9a-f]{4})',content))

print(''.join(replaced))

rawDescription: Python 2.7 reading and writing "éèàçê" from utf-8 file


code: header = in_df[:5]  #only first rows

rawDescription: Pandas - read_table read selected lines

description: Pandas - read_table read selected lines


code:
AUTHENTICATION_BACKENDS = (
    'ai60.weixin.auth_backends.WeiXinAuthBackend',
    'ai60.accounts.auth_backends.AI60AccountBackend',
    'mezzanine.core.auth_backends.MezzanineBackend',
    'django.contrib.auth.backends.ModelBackend',
)

rawDescription: How to make custom authentication not based on User model

description: Make custom authentication not based on User model


rawDescription: Creating 2 x-axes on matplotlib not working


rawDescription: Accessing data in a Pandas dataframe with one row


code:
if __name__ == '__main__':
    import os
    import os.path
    import sys
    os.chdir(os.path.dirname(sys.argv[1]))

rawDescription: Bash run command with cd to each directory


code: np.array([1, 2, 3]).shape

rawDescription: numpy array that is (n,1) and (n,)

description: Numpy array that is (n,1) and (n,)


code: df.replace([np.inf, -np.inf], np.nan)

rawDescription: dropping infinite values from dataframes in pandas?

description: Dropping infinite values from dataframes in pandas


code:
Solution
isY = lambda x:int(x=='Y')
countRiskFactors = lambda row: isY(row['Smoker']) + isY(row['Diabetes']) + int(row["Age"]>45)

df['Risk_Factors'] = df.apply(countRiskFactors,axis=1)

rawDescription: COUNTIF in pandas python over multiple columns with multiple conditions


code: document: 7   # < the 8th document

rawDescription: Load specific PyYAML documents from file


code:
orders = {name.split('[')[1].split(']')[0]: request.POST[name]
          for name in request.POST if name.startswith('order[')}
# `orders` is not a dictionary maps `id`s to `order`s.
# Do something with `orders`.

rawDescription: Saving the order of items

description: Saving the order of items


rawDescription: Sparksql filtering (selecting with where clause) with multiple conditions


code:
[
 'Full Time Match ends, Everton 3, Swansea City 1.',
 '90:00 +4:09 Full time Full Time Second Half ends, Everton 3, Swansea City 1.',
 '90:00 +2:47 Attempt blocked. Nathan Dyer (Swansea City) right footed shot from the centre of the box is blocked. Assisted by Pablo Hern\xc3\x83\xc2\xa1ndez.',
 '90:00 +0:18 Offside, Swansea City. Leroy Lita tries a through ball, but Ashley Williams is caught offside.',
 '89:31 Corner, Swansea City. Conceded by Leighton Baines.',
 '88:42 Foul by James McCarthy (Everton). '
]

rawDescription: split string with timestamps

description: Split string with timestamps


rawDescription: Hexagonal Self-Organizing map in Python

description: Hexagonal Self-Organizing map in Python


code:
import string
def cleanup(s, remove=('\n', '\t')):
    newString = ''
    for c in s:
        # Remove special characters defined above.
        # Then we remove anything that is not printable (for instance \xe2)
        # Finally we remove duplicates within the string matching certain characters.
        if c in remove: continue
        elif not c in string.printable: continue
        elif len(newString) > 0 and c == newString[-1] and c in ('\n', ' ', ',', '.'): continue
        newString += c
    return newString

rawDescription: python strip function not working properly

description: Python strip function not working properly


code:
import bisect
tickets = [60, 80]
bisect.bisect_left(tickets, 60)
bisect.bisect_left(tickets, 61)
bisect.bisect_left(tickets, 80)
bisect.bisect_left(tickets, 81)

rawDescription: How to get rid of bunch of ifs

description: Get rid of bunch of ifs


code:
arr = np.ones((10,4,4)) # 10 all-white frames
arr[:,:2,:] = 0         # black out the top half of every frame
a

rawDescription: How can i iterate over image pixels in a faster manner in python?

description: Iterate over image pixels in a faster manner in python


code:
reductions = [0.25, 0.50, 0.75, 1.0]
filename = "foo"

for fraction in reductions:
    with open(filename, "r") as f, open('%s-%s' % (fraction, filename), 'w') as outfile:
        for key, group in groupby(f, key=getkey):
            outfile.writelines(choose_random(group, fraction=fraction))

rawDescription: Python File Reduction - part 2

description: Python File Reduction - part 2


code:
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import logging

class HomePage(db.Model):
    thumbnail = db.BlobProperty()
    firm_name = db.StringProperty()

class ImageUpload(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
        <form action="/imagesave" enctype="multipart/form-data" method="post">

firm name: <input type="text" name="firm_name" size=40>

<input type="file" name="img" />

<input type="submit" value="Upload image">

        </form>
        """)

class ImageSave(webapp.RequestHandler):
    def post(self):
        homepage = HomePage()
        thumbnail = self.request.get("img")
        firm_name = self.request.get("firm_name")
        homepage.thumbnail = db.Blob(thumbnail)
        homepage.firm_name = firm_name
        homepage.put()
        self.redirect("/imageupload")

class ImageResize(webapp.RequestHandler):
    def post(self):
        q = HomepageImage.all()
        q.filter("firm_name", "mta")
        qTable = q.get()
        if qTable:
            qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32))
            db.put(qTable)
        else:
            self.response.out.write("""firm not found""")
        self.redirect("/imageupload")

class DisplayImage(webapp.RequestHandler):
    def get(self):
        query = HomePage.all()
        query.filter("firm_name", "mta")
        result = query.get()
        self.response.out.write("""firm name: %s""" % result.firm_name)
        self.response.out.write("""""" %
        result.key())

class Image(webapp.RequestHandler):
    def get(self):
        img_id = self.request.get("img_id")
        logging.info("""**************************img_id: %s**************************""" % img_id)
        homepage = db.get(self.request.get("img_id"))
        if homepage.thumbnail:
                self.response.headers['Content-Type'] = "image/jpg"
                self.response.out.write(homepage.thumbnail)
        else:
                self.response.out.write("no image")

application = webapp.WSGIApplication(
[
("/imageresize",ImageResize),
("/imageupload", ImageUpload),
("/displayimage", DisplayImage),
("/imagesave", ImageSave),
("/image", Image),
],
debug=True
)

def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()

rawDescription: How to display an image in GAE datastore?

description: Display an image in GAE datastore


rawDescription: Splitting up a list into different length parts under special condition


code:
new_entry = form_data.save(commit=False)
new_entry.category = cat_get
new_entry.put()

rawDescription: GAE: How to use ReferenceProperty in django forms?


code:
x,y,r = np.broadcast_arrays( xbins[np.newaxis,...,np.newaxis], \
                             ybins[np.newaxis,np.newaxis,...], \
                             rbins[...,np.newaxis,np.newaxis])

rawDescription: Displaying a slice from a 3d ndarray

description: Displaying a slice from a 3d ndarray


code: var1, var2, var3, var4 = l

rawDescription: What's the simplest way to assign list members to different variables?


code:
import itertools
for first, second in itertools.combinations(l, 2):
    print(first, second)

rawDescription: Why is my for loop skipping an element in my list?


code:
from itertools import cycle
c=cycle(('1','0'))
n=3
[next(c) for _ in xrange(n*2)]

rawDescription: python function sorting alternating disks

description: Python function sorting alternating disks


code: result = zip(*[iter(a)] * 5)

rawDescription: How to return every 5 items from a list in python?

description: Return every 5 items from a list in python


code:
Output
{u'subType': [u'Athlete', u'AwardWinner'], u'type': u'Person'}

rawDescription: SimpleJson handling of same named entities


code:
from twisted.internet.protocol import Factory

factory = Factory.forProtocol(YourProtocol, reactor)

rawDescription: What is the preferred way to pass the reactor to a protocol in Twisted?


code:
from tkinter import *

def on_click(*args):
    print("frob called with {} arguments".format(len(args)))

root = Tk()
root.bind("<Return>", on_click)
b = Button(root, text="Click Me", command=on_click)
b.pack()
root.mainloop()

rawDescription: Call the same function when clicking the Button and pressing enter


code:
patients_s=patients.set_index('id').stack().reset_index()
patients_s.columns=['id', 'patient', 's2']

rawDescription: Set DataFrame row index to a different column


code:
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'w')
count = 0
for lines in file1.readlines():
    #print lines
    if (lines[-1:] == '\n') and (len(lines) == 1):
        if count >= 1:
            pass
        else:
            file2.write(lines)
        count += 1
    else:
        file2.write(lines)
        count = 0

file1.close()
file2.close()

rawDescription: Stripping empty lines from the print statement in python2.7


code: hello_lbl = Label(root, text="").grid(row=4, columnspan=2) # => None

rawDescription: Tkinter: Instatiate Object with Button

description: Tkinter: Instatiate Object with Button


rawDescription: how to change [1,2,3,4] to '1234' using python

description: Change [1,2,3,4] to '1234' using python


code:
text="   asd dfk dfjk\n   jdfk dfkj dkfj\n\n  dfjk dfjk dfjk\n"
print(text)
print("\n".join(line.strip() for line in text.split("\n")))

rawDescription: Most Pythonic way to concatenate indented, wrapped paragraphs?


code:
three
two
one

rawDescription: Python: how to determine if a list of words exist in a string


code:
np.savez("tmp.npz", *(np.arange(i) for i in xrange(2, 100)))
np.load("tmp.npz")['arr_60']

rawDescription: Python: How to pass a generator to a function?


code:
item['title'] = question.xpath('./text()').extract()
item['url'] = question.xpath('./@href]').extract()

rawDescription: scrapy return empty json file

description: Scrapy return empty json file


code:
myDoc = """link: '/Hidden/SidebySideGreen/dei1=1204970159862'};
link: '/Hidden/SidebySideYellow/dei1=1204970159862'};"""

print( re.findall( "'([^']+)'", myDoc ) )

rawDescription: Regular expression for string between two strings?


code:
from collections import Counter # Requires Python > 2.7

# Test abscissa values
x = [3.0, 4.0, 5.0, 5.0, 6.0, 7.0, 9.0, 9.0, 9.0, 11.0]

# Count of the number of occurances of each unique `x` value
xcount = Counter(x)

# Generate a list of unique x values in the range [0..len(set(x))]

nonRepetitive_x = list(set(x)) #making a set eliminates duplicates
nonRepetitive_x.sort()         #sets aren't ordered, so a sort must be made
x_normalised = [_ for i, xx in enumerate(set(nonRepetitive_x)) for _ in xcount[xx]*[i]]

rawDescription: How to assign equal scaling on the x-axis in Matplotlib?

description: Assign equal scaling on the x-axis in Matplotlib


rawDescription: Write a loop that sums the number of times that the words in wordList occur in the list


code:
p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE, stdin=PIPE)
p.stdin.write('yes')

rawDescription: Popen a command that contains need to say yes for all outputs


code:
class MySQLConstants():
  DECIMAL = 0
  TINY = 1
  SHORT = 2
  LONG = 3
  FLOAT = 4
  DOUBLE = 5

  def create_dict( dicForReversing ):
    fieldTypeDic = {}
    for key, value in dicForReversing.items():
      if isinstance(value, int):
        fieldTypeDic[ value ] = key
    return fieldTypeDic
  fieldTypeDic = create_dict( vars() )

rawDescription: is there a way to get a (static) method to be called when a class (not an instance) is created?

description: Is there a way to get a (static) method to be called when a class (not an instance) is created


rawDescription: Scrapping and string-formatting issue : one time scrap with '' another time with ""


code:
def new_dict(S):
            """ input of rle(S) i.e., tuples of bit and repeating counts
                output dict as bit as key and value as counts with binary conversion.
            """

            dict=rle(S)
            new_dict = []
            temp = []
            for k,v in dict:
                temp = k + "%07d" % int(bin(v)[2:])
                new_dict.append(temp)
            return new_dict

rawDescription: Image compression by def compress(S) function using run-length codig


code:
import sys
if "N:/ProjectX/Scripts" not in sys.path:
    sys.path.append("N:/ProjectX/Scripts")

rawDescription: PYTHONPATH set when loading Idle in virtual environment


code:
my_list = [[u'polySurface5.e[4]', u'polySurface5.e[1]', .5], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9], [u'polySurface5.e[1]', u'polySurface5.e[4]', .5], [u'polySurface5.e[2]', u'polySurface5.e[9]', 1.2], [u'polySurface5.e[2]', u'polySurface5.e[2]', 0] ]

new_list = []
my_set = set()
for sublist in my_list:
    if sublist[2] != 0:
        frozen_sub = frozenset(sublist)
        if not frozen_sub in my_set:
            new_list.append(sublist)
            my_set.add(frozen_sub)

rawDescription: compare similar items nested in a list, and removing them

description: Compare similar items nested in a list, and removing them


rawDescription: Selenium Webdriver Python page object MainPageLocators class why does it use an asterisk infront of the class name


code:
fruits['orange'].remove('0.34')
print( fruits['orange'] )

rawDescription: How do I generate a list for each list item

description: Generate a list for each list item


code: divisibleBySeven = filter(meetsCondition, inputList)

rawDescription: Return Subset of List that Matches Condition


code: bool(array)

rawDescription: python, numpy boolean array: negation in where statement

description: Python, numpy boolean array: negation in where statement


code: metaList[x] = tempList

rawDescription: Issue filling a list with other lists containing random numbers.


code:
import Queue
data_queue = Queue.Queue()

def data_stream():
    while True:
        data = data_queue.get()
        yield 'data: {}\n\n'.format(json.dumps(data))

rawDescription: Using SSE to pass on data from other APIs in real time


code:
import math

def fAlmostEqual(a, b, rtol=1.0000000000000001e-05, atol=1e-08):
    """Checks if the given floats are almost equal. Uses the algorithm
    from numpy.allclose."""
    return math.fabs(a - b) <= (atol + rtol * math.fabs(b))

rawDescription: Unexpected value of floor() function in python


code: tuple(set(dir(Foo)) - set(dir(Bar)))

rawDescription: Get the list of a class's variables & methods in Python


code:
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
model.fit(X, y)

rawDescription: How do I use use the tfidf-calculating functions in scikit-learn?

description: Use use the tfidf-calculating functions in scikit-learn


rawDescription: Plotting for conference posters (increase textsize, linewidth, ... at once)


code: 'P' in s

rawDescription: Python: converting string to flags

description: Python: converting string to flags


code:
def f():
    if __debug__: return 3
    else: return 4

def g():
    if True: return 3
    else: return 4

rawDescription: How do you implement "#ifdef" in python?

description: Implement "#ifdef" in python


code:
s = "[[ hello] [there]]"
s = s.replace("[", "")
s = s.replace("]", "")

rawDescription: Remove double and single square brackets from text file generated from python


code: A[A.index(1)] = None

rawDescription: Delete elements in a list and retaining the size of a list in Python?


code:
rules = [ rule1, rule2, rule3, rule4, ... ]
rules_generator = ( r( solution ) for f in rules )
return all( rules_generator )

rawDescription: Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting?


rawDescription: python create dictionary from list of strings and list of integers

description: Python create dictionary from list of strings and list of integers


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

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


code:
the_name = "jfall"
if t != None:
    final = [x[0] + " " + title + " " + x[1] for x in t.groups() if x[0] == the_name]

rawDescription: parse text using bash/python

description: Parse text using bash/python


code:
#!/usr/bin/env python
import sys
import urllib
arg = sys.argv[1]
handler, fullPath = arg.split(":", 1)
path, fullArgs = fullPath.split("?", 1)
action = path.strip("/")
args = fullArgs.split("&")
params = {}
for arg in args:
    key, value = map(urllib.unquote, arg.split("=", 1))
    params[key] = value

rawDescription: OSX : Defining a new URL handler that points straight at a Python script


code:
def co_counter():
    i = 0
    new_i = None
    while i < 20:
        if new_i is not None:
            i = new_i - 1
        new_i = yield i
        i += 1

counter = co_counter()
for i in counter:
    if i == 15:
        counter.send(5)
    print(i)

rawDescription: Make index go back in for loop

description: Make index go back in for loop


code:
# Count of rows where s3=1 or s2=1.
row_count = ((df['s3'] == 1) | (df['s2'] == 1)).sum()

rawDescription: Creating and manipulating dataframes with only binary values


rawDescription: How to parse a utf-8 encoded query parameter with Python 2.6

description: Parse a utf-8 encoded query parameter with Python 2.6


code:
def _import_package_files():
    """ Dynamically import all the public attributes of the python modules
        in this file's directory (the package directory) and return a list
        of their names.
    """
    import os

    exports = []
    globals_ = globals()
    package_path = os.path.dirname(__file__)
    package_name = os.path.basename(package_path)

    for filename in os.listdir(package_path):
        modulename, ext = os.path.splitext(filename)
        if modulename[0] != '_' and ext in ('.py', '.pyw'):
            # create a package relative subpackage name
            subpackage = '{}.{}'.format(package_name, modulename)
            module = __import__(subpackage, globals_, locals_, [modulename])
            modict = module.__dict__
            names = (modict['__all__'] if '__all__' in modict else
                     [name for name in modict if name[0] != '_'])  # public names
            exports.extend(names)
            globals_.update((name, modict[name]) for name in names)

    return exports

if __name__ != '__main__':
    __all__ = ['__all__'] + _import_package_files()  # '__all__' in __all__

rawDescription: Importing Python classes from different files in a subdirectory


code:
import sys
from PyQt4 import QtGui, QtCore

lista = ['r1c1', 'r1c2', 'r1c3']
listb = ['r2c1', 'r2c2', 'r1c3']
listc = ['r3c1', 'r3c2', 'r3c3']
mystruct = {'row1':lista, 'row2':listb, 'row3':listc}

class MyTable(QtGui.QTableWidget):
    def __init__(self, thestruct, *args):
        QtGui.QTableWidget.__init__(self, *args)
        self.data = thestruct
        n = 0
        for key in self.data:
            m = 0
            for item in self.data[key]:
                newitem = QtGui.QTableWidgetItem(item)
                self.setItem(m, n, newitem)
                m += 1
            n += 1
        self.itemSelectionChanged.connect(self.print_row)

    def print_row(self):
        items = self.selectedItems()
        print(str(items[0].text()))

def main(args):
    app = QtGui.QApplication(args)
    table = MyTable(mystruct, 3, 3)
    table.show()

    sys.exit(app.exec_())

if __name__=="__main__":
    main(sys.argv)

rawDescription: QTableWidget Current Selection Change Signal


code: key = name +'-'+id

rawDescription: How can I create dictionary within dictionary

description: Create dictionary within dictionary


code:
root = Tk()
root.title("Lazy Button 2")
root.geometry("500x500")
app = Application(root).create_widgets()  #creates and invokes
root.mainloop()

rawDescription: Creating buttons with Python GUI

description: Creating buttons with Python GUI


rawDescription: How does python sort a list of dictionaries?


code:
import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads", end='')
    else:
        print("Tails", end='')
    print("\r", end='')
    time.sleep(0.1)

rawDescription: Overwrite printed line in python 3.x on mac


code:
from itertools import islice

with open(fileDocStandard) as f,open(newfile) as out:
  for line in f:
       if 'BN30CWS' in f:
            f=islice(f,5,None)
       out.write(line)

rawDescription: Delete a chunk of text from a text file (Python)


code:
speed['created_delta'] = speed['created_time'].values - dates
speed['diff'] = speed['created_delta'] - speed['reached_time']

rawDescription: pandas date column subtraction

description: Pandas date column subtraction


code:
import  numpy as np

arr = np.loadtxt("in.csv",delimiter=",",dtype=object)

print(arr)

rawDescription: uploading mixed data from csv into a numpy array in python

description: Uploading mixed data from csv into a numpy array in python


rawDescription: Read selected columns from text file into a list in python


code:
label1 = gtk.Label("Label 1")
label2 = gtk.Label("Label 2")
label3 = gtk.Label("Label 3")

box.pack_start(label1)
box.pack_start(label2)
box.pack_start(label3)

rawDescription: In-place substitution of PyGTK widgets

description: In-place substitution of PyGTK widgets


code: nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9])

rawDescription: Generate random array of 0 and 1 with specific ratio (python , numpy)


code:
from collections import Counter
liste = [1,2,3,5,10]
liste2 = [[1,2,3,5,10], [1,2], [1,5,10], [3,5,10], [1,2,5,10]]
def get_syncounts(liste, liste2):
    c = Counter()
    for elt in liste2:
        nTuple = len(elt)   # number of elements in the syn
        for i in liste:
            if elt.count(i):
                   myTuple = (i, nTuple)
                   c[myTuple] += 1
    for item in c.items():
        print(item)
get_syncounts(liste, liste2)
get_syncounts(liste, liste2)

rawDescription: Count how many times a tuple appears in ouput results


code:
def first_n(iterable, n):
    it = iter(iterable)
    for _ in xrange(n):
        yield next(it)

rawDescription: Truncating a python generator

description: Truncating a python generator


code:
a,b,n = split_after(p,2)
a
b
n
l = list(split_after(p,3))
l

rawDescription: Python: Convert n-tuple to x-tuple where x < n


code:
for i in new_list:
    if not i:
        new_list.remove(i)

rawDescription: Delete all occurrences of specific values from list of lists python


rawDescription: how to replace an entire column on Pandas.DataFrame

description: Replace an entire column on Pandas.DataFrame


rawDescription: Visual module in python assign objects

description: Visual module in python assign objects


code: [inst.last_result for inst in instances]

rawDescription: Python dynamically generate dependencies between class instances


code:
threading.Thread(target=some_callable_function,
        args=(tuple, of, args),
        kwargs={'dict': 'of', 'keyword': 'args'},
    ).start()

rawDescription: What happened to thread.start_new_thread in python 3


rawDescription: How do I remove a character once from a string [python]?

description: Remove a character once from a string [python]


code:
url = 'https://' + username + ':' + api_key +'@api.service.softlayer.com/rest/v3/SoftLayer_Account/setVlanSpan.json'
data = '{"parameters":["True"]}'

rawDescription: Enable VLAN Spanning with Python API

description: Enable VLAN Spanning with Python API


code: percent_true = table[['percent_true']]

rawDescription: Pandas Column Calculations in PivotTable


code:
def start(list_of_entries):
    return [func(x.name, x.age) for x in list_of_entries]

rawDescription: Map/Iterating through List of Python Object


code: return some_list[:target_len] + [0 for _ in range(target_len - len(some_list))]

rawDescription: Most pythonic way to extend a list to exactly a certain length?


code:
class UserProfile(AbstractBaseUser, MyPermissionsMixin):
    id = models.CharField(primary_key=True, max_length=32, default=str(uuid.uuid4()).replace('-', ''))
    Telephone = models.CharField('Telephone', max_length=100, blank=True, null=True)
    Mobile = models.CharField('Mobile', max_length=100, blank=True, null=True)
    username = models.CharField(_('username'), max_length=30, unique=True,
                                help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                                            '@/./+/-/_ characters'),
                                validators=[
                                    validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'),
                                                              'invalid')
                                ])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
                                   help_text=_('Designates whether the user can log into this admin '
                                               'site.'))
    is_active = models.BooleanField(_('active'), default=True,
                                    help_text=_('Designates whether this user should be treated as '
                                                'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.username)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name

    def email_user(self, subject, message, from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email])

    def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        warnings.warn("The use of AUTH_PROFILE_MODULE to define user profiles has been deprecated.",
                      PendingDeprecationWarning)
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings

            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable(
                    'You need to set AUTH_PROFILE_MODULE in your project '
                    'settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise SiteProfileNotAvailable(
                    'app_label and model_name should be separated by a dot in '
                    'the AUTH_PROFILE_MODULE setting')
            try:
                model = models.get_model(app_label, model_name)
                if model is None:
                    raise SiteProfileNotAvailable(
                        'Unable to load the profile model, check '
                        'AUTH_PROFILE_MODULE in your project settings')
                self._profile_cache = model._default_manager.using(
                    self._state.db).get(user__id__exact=self.id)
                self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache

rawDescription: Error while logging in when primary key of Django `User` is a `CharField`


code:
import operator
transactions.sort(key=operator.itemgetter(0))

def transaction_fortnight(transaction):
    date,data=transaction
    return fortnight(date)

for key,grp in itertools.groupby(transactions,key=transaction_fortnight):
    print(key,list(grp))

rawDescription: Group together arbitrary date objects that are within a time range of each other


code:
def matchPat(str1, str2):
    index1 = 0
    index2 = 0
    while index1 < len(str1):
        c = str1[index1]
        #Check if the str2 has run it's course.
        if index2 >= len(str2):
            #This needs to be checked,assuming matchPatch("*", "") to be true
            if(len(str2) == 0 and str1 == "*"):
                return True
            return False
        #If c is not "*", then it's normal comparision.
        if c != "*":
            if c != str2[index2]:
                 return False
            index2 += 1
        #If c is "*", then you need to increment str1,
        #search for the next value in str2,
        #and update index2
        else:
            index1 += 1
            if(index1 == len(str1)):
                return True
            c = str1[index1]
            #Search the character in str2
            i = str2.find(c, index2)
            #If search fails, return False
            if(i == -1):
                return False
            index2 = i + 1
        index1 += 1
    return True

rawDescription: Search for a pattern in a string in python


code:
from nltk.corpus import swadesh
de2en = [(i.lower(),j.lower()) for i,j in swadesh.entries(['de','en'])]
translate = dict(de2en)
translate['hund']
translate['Hund']

rawDescription: How to translate words in NTLK swadesh corpus regardless of case - python

description: Translate words in NTLK swadesh corpus regardless of case - python


code: original[0::2], original[1::2] = original[1::2], original[0::2]

rawDescription: Efficient way to swap bytes in python

description: Efficient way to swap bytes in python


rawDescription: How can I detect when a Django server is started without a settings module?

description: Detect when a Django server is started without a settings module


code: role : mysiteid1

rawDescription: How do I manage minion roles with salt-stack pillars?

description: Manage minion roles with salt-stack pillars


code:
for (text, f) in zip(my_strings, file_list):
    f.write(text)

rawDescription: How to paste texts into a list of files in python

description: Paste texts into a list of files in python


code:
('Green Lantern', '21', None, None)
('Green Lantern', '21', None, '(Variant Cover Edition)')
('Dejah Thoris & Green Men Of Mars', '4', '8', None)
('Dejah Thoris & Green Men Of Mars', '4', '8', '(Variant Cover Edition)')
('Macabre One Shot', None, None, None)
('Detective Comics', '21', None, 'Combo Pack')

rawDescription: Optional regex groups for comic book titles (python)