code: lines = ['this is a line', 'this is a second line', 'this one has beer']

rawDescription: Searching for substrings in file.readlines() in python


code: friend = models.ForeignKey("self", related_name="referral", null=True, blank=True)

rawDescription: implementing a counter that counts requests with django

description: Implementing a counter that counts requests with django


code:
types = ['Small', 'Medium','Large']
while True:
    print('Types: '+ types)
    choice = raw_input('Choose a type. ').capitalize()
    if choice in types:
        #choice = choice  this is superfluos
        break
     #else: no need for else since the loop will execute again and do exactly this
     #    choice = raw_input('Choose a type. ').capitalize()

rawDescription: Best way to select from a list

description: Select from a list


code: sorted(l1 + l2)

rawDescription: Combining two sorted lists in Python

description: Combining two sorted lists in Python


code:
from collections import defaultdict
def count(it):
    d = defaultdict(int)
    for j in it:
        d[j] += 1
    return d

rawDescription: Python: Convert this list into dictionary


code: dict([(x, func(y)) for x, y in l])

rawDescription: Is comprehension possible here?

description: Is comprehension possible here


code:
from itertools import chain
list(chain.from_iterable(zip(l1, l2)))
# [1,9,2,8,3,7,4,6]

rawDescription: python: Merge two 1D lists into one 1D list

description: Python: Merge two 1D lists into one 1D list


code:
value = yield x
if value:
    return

rawDescription: Sending values to zipped generators

description: Sending values to zipped generators


code: resolutions = models.CharField(RESOLUTIONS, max_length=1)

rawDescription: Help with validation in Models and Forms


code: A.flags.maskna = True

rawDescription: Improving performance of operations on a NumPy array


code:
def is_match(list_of_functions, user_a, user_b):
   return all([cur_fun(user_a, user_b) for cur_fun in list_of_functions])

rawDescription: What is a good pattern for validating multiple complex conditions?


code:
@login_required
def edit(request, id=None, template_name='article_edit_template.html'):
    if id:
        article = get_object_or_404(Article, pk=id)
        if article.author != request.user:
            return HttpResponseForbidden()
    else:
        article = Article(author=request.user)

    form = ArticleForm(request.POST or None, instance=article)
    if request.POST:
        if form.is_valid():
            form.save()

            # If the save was successful, redirect to another page
            redirect_url = reverse(article_save_success)
            return HttpResponseRedirect(redirect_url)

    return render_to_response(template_name, {
        'form': form,
    }, context_instance=RequestContext(request))

rawDescription: Django edit form based on add form?

description: Django edit form based on add form


rawDescription: Python pi calculation?

description: Python pi calculation


code: text = u"aren’t"

rawDescription: Handle Unicode characters with Python regexes


rawDescription: Python converting latin1 to UTF8

description: Python converting latin1 to UTF8


rawDescription: How to apply a modifier in Python, creating a new mesh?

description: Apply a modifier in Python, creating a new mesh


code:
cross = pd.crosstab(dd['Budget'], dd['Media'], values=dd['Budget'], aggfunc=sum)
cross

rawDescription: set modalities as new columns

description: Set modalities as new columns


code:
if all(toTest[i] == toTest[-i] for i in range(len(toTest)/2)):
    print("It's a palindrome!")

rawDescription: for loop nested inside the expression from an if statement

description: For loop nested inside the expression from an if statement


code:
file = request.FILES['csv_file']

# Updated to reflect OP's comments:
csv_file_data = [row for row in csv.reader(splitkeepsep(file.read(), '\n'), dialect=csv.excel_tab)]

rawDescription: Django - Keep line breaks when importing CSV file


code:
from __future__ import print_function
from random import choice, randrange, seed

def hash_function(s=''):   # 'Hello World!' -> 7b2ea1ba
    a, b, c, d = 0xa0, 0xb1, 0x11, 0x4d

    for byte in bytearray(s):
        a ^= byte
        b = b ^ a ^ 0x55
        c = b ^ 0x94
        d = c ^ byte ^ 0x74

    return format(d<<24 | c<<16 | a<<8 | b, '08x')

s = b'Hello World!'
print(s, hash_function(s))

#ASCII chars that print nicely
ascii = b''.join([chr(i) for i in range(33, 127)])

seed(37)

found = {}
for j in range(5000):
    #Build a random 4 byte random string
    s = b''.join([choice(ascii) for _ in range(4)])
    h = hash_function(s)
    if h in found:
        v = found[h]
        if v == s:
            #Same hash, but from the same source string
            continue
        print(h, found[h], s)
    found[h] = s

rawDescription: How can I find a collision for a toy hash function?

description: Find a collision for a toy hash function


rawDescription: List within a Dictionary as Value in <Key-Value> Pair


code: df = pd.read_csv('data.csv', names=['Id', 'Price'])

rawDescription: Merging two dataframes in pandas without column names (new to pandas)


rawDescription: Denormalize tab-delimited text file

description: Denormalize tab-delimited text file


code: 'C' in seto

rawDescription: How can I tell if a string pattern exists within any element of a set in Python?

description: Tell if a string pattern exists within any element of a set in Python


rawDescription: Merging lists of lists

description: Merging lists of lists


code:
var1 = "Arbaham"
var2 = "My name is: %s"
print(var2 % var1)
var1 = "Abraham"
print(var2 % var1)

rawDescription: "Updating" a string with a format operator


code: linux3, freebsd8, win32, dos, os2

rawDescription: Python 2.7, OS Detection return values

description: Python 2.7, OS Detection return values


code:
def get_form_list(request, form_list=None):
    if form_list is None:
        form_list = [ProviderForm, DummyForm, ConsummerForm, DummyForm, \
                     ServicesDescriptionForm]
    return UserServiceWizard.as_view(form_list=form_list)(request)

rawDescription: Dynamic FormWizard

description: Dynamic FormWizard


code:
self.c2_low.set("c2_low")
self.c2_high.set(23)   #gets converted to a str automatically

rawDescription: Automatic filling of Tkinter.entry boxes by a separate function


code: re.compile(r'[abë]|ɪ̈', re.DEBUG)

rawDescription: how regex in Python3 deal with diacritics?

description: How regex in Python3 deal with diacritics


rawDescription: Grouping Pandas DataFrame by date

description: Grouping Pandas DataFrame by date


code:
from collections import defaultdict
dic=defaultdict(list)
for x in lis:
    dic[x[0]].append(x)

[max(val,key=lambda x: x[2]) for val in dic.values()]

rawDescription: Sorting list of tuples based on multiple keys and returning top results


code: df.selectExpr('*', 'date_sub(date_col, day_col) as subtracted_dates')

rawDescription: How to subtract a column of days from a column of dates in Pyspark?

description: Subtract a column of days from a column of dates in Pyspark


code:
print(m + "... ", end='')
sys.stdout.flush()

rawDescription: python contextmanager newline issue

description: Python contextmanager newline issue


code: data=defaultdict(list)

rawDescription: python3 csv with duplicate keys + python defaultdict

description: Python3 csv with duplicate keys + python defaultdict


code:
import requests
import json

tracking_number = '570573906561'

data = requests.post('https://www.fedex.com/trackingCal/track', data={
    'data': json.dumps({
        'TrackPackagesRequest': {
            'appType': 'wtrk',
            'uniqueKey': '',
            'processingParameters': {
                'anonymousTransaction': True,
                'clientId': 'WTRK',
                'returnDetailedErrors': True,
                'returnLocalizedDateTime': False
            },
            'trackingInfoList': [{
                'trackNumberInfo': {
                    'trackingNumber': tracking_number,
                    'trackingQualifier': '',
                    'trackingCarrier': ''
                }
            }]
        }
    }),
    'action': 'trackpackages',
    'locale': 'en_US',
    'format': 'json',
    'version': 99
}).json()

rawDescription: Parsing HTML does not output desired data(tracking info for FedEx)


code:
from ..database import db

class User(db.Model):
    ...

rawDescription: Structure of a Flask app with more than one models.py


code: session.query(Child).join(Child, Child.parent_metadata_id == Parent.metadata_id)

rawDescription: Specify join condition in SQLalchemy ORM without foreign key


code:
Tuple = {(1,3),(3,5),(5,6)}
[list(item) for item in Tuple]

rawDescription: convert a 2d tuple into a list

description: Convert a 2d tuple into a list


code: bin(~a & ~b)

rawDescription: How to make a bitwise NOR gate

description: Make a bitwise NOR gate


code:
doc = SimpleDocTemplate(handler.response.out, pagesize=letter)
doc.build(story)

rawDescription: How to save generated PDF with Reportlab to Datastore in App Engine Python

description: Save generated PDF with Reportlab to Datastore in App Engine Python


rawDescription: Better / More pythonic way to process the results of a function with multiple return values


code:
zeniths = range(1,4)
azimuths = range(6,8)

product = list(itertools.product(zeniths, azimuths))
# [(1, 6), (1, 7), (2, 6), (2, 7), (3, 6), (3, 7)]

rawDescription: Parallelise nested for-loop in IPython

description: Parallelise nested for-loop in IPython


code:
mock=Mock()
mock.a()
assert not mock.b.called, 'b was called and should not have been'
assert not mock.a.called, 'a was called and should not have been'

rawDescription: Assert a function/method was not called using Mock


rawDescription: Execute a function randomly

description: Execute a function randomly


code: exl_set = set([a.node])

rawDescription: What is the best practice to add tuples to a set?


code:
def group_position(*args):
    """
    Get group position
    """
    from collections import defaultdict
    table = defaultdict(int)

    result = []
    for tup in zip(*args):
        result.append(table[tup])
        table[tup] += 1

    return np.array(result)

rawDescription: Multiindex from array in Pandas with non unique data


code:
it  = iter(myIntList)
out = [[next(it)]]
for ele in it:
    if ele != 0:
        out[-1].append(ele)
    else:
        out.append([ele])

print(out)

rawDescription: split list by certain repeated index value

description: Split list by certain repeated index value


rawDescription: Matplotlib: Specific color with imshow

description: Matplotlib: Specific color with imshow


code:
#!/usr/bin/env python

INDEX='value'
CROSS='value'
TRACE='value'

...

rawDescription: Confusion about environmental variables in python


code: [print(result) for result in generator_call(params) if result]

rawDescription: Alternatives for 3 lines of java-like code?


code:
all_ids = [1, 2, 4, 5]
# Note: using plot_id as integer now
for plot_id in all_ids:
    filename = 'plot_id_%i.file_extension' % plot_id
    spreadsheet = some_open_method(filename, option='write')
    for b in range(length_spread):
        data = read_spread[b].rstrip('\n')
        splitted = data.split(',')
        if plot_id == int(splitted[1]):
            spreadsheet.writelines('%s\n\n\n\n\n' % splitted)
    spreadsheet.close_method()

rawDescription: Iterate through a loop to change a conditional statement, python


code:
def __init__(self):
    self.outerLabels = {}
    self.upperLabels = {}
    # whatever else is currently in __init__()

rawDescription: Declaring callable variables in a for loop in python


code: function_that_uses_dict(AdditionalKeyValuePair(1001, "1001") + big_dict)

rawDescription: How to pass in a dictionary with additional elements in python?

description: Pass in a dictionary with additional elements in python


code:
db.session.add(
    BlogPost(title='My cool title', content='This is the first post.')
); db.session.commit()

rawDescription: Search Index for user articles

description: Search Index for user articles


code:
for ax, col in zip(axes.flat, df.columns):
    data = df[col]
    labels = [n if v > data.sum() * 0.2 else ''
              for n, v in zip(df.index, data)]

    ax.pie(data, autopct=my_autopct, colors=colors, labels=labels)

rawDescription: Conditional removal of labels in Matplotlib pie chart


code:
def find_location(location_name):
    for region in regionList:
        if location_name in region:
            return [region[0], location_name]
    # if we get there the location name was found nowhere
    raise ValueError('Location {!r} unknown'.format(location_name))

rawDescription: Set player's main region depending on location - Python


code:
class Indexer(object):
    def __init__(self, *args, **kwargs):
        pass
    def __getitem__(self, item):
        if isinstance(item, tuple):
            # do special processing for tuples here
            print(item)
        # Everyone likes the number 3, so make sure to return an extra 3.
        return [item, 3]
i = Indexer()

# this will print (2, 3), and got_item will have the value [(2, 3), 3]
got_item = i[2,3]

# This will print [(2, 3), 3]
print(got_item)

rawDescription: How can I indexing nested lists?

description: Indexing nested lists


code:
def gammafied_func_1(gamma):
    def func_1(x):
        return x + gamma
    return func_1

def thing_1(alpha, beta):
    gamma = alpha+beta
    def func_2(x):
        return x*gamma
    return Funcs(gammafied_func_1(gamma), func_2)

rawDescription: Python: Equivalent of Inheritance with Closures


rawDescription: plotting orbital trajectories in python

description: Plotting orbital trajectories in python


code:
def memoize(fcn, cache = {}):
    def decorated(d, p):
        if p not in cache:
            cache[p] = fcn(d, p)
        return cache[p]
    return decorated

@memoize
def mc(d, p):
    if p in d:
        return (1, [p])

    cands = [n for n in d if n < p]

    if not cands:
        return (10**20, [])

    d_i, pair = min(
        [(d_i, mc(d, p-d_i)) for d_i in cands],
        key=lambda e: e[1][0]
    )

    return (1 + pair[0], pair[1] + [d_i])

rawDescription: Minimum coin change: reconstruct solution from this algorithm


rawDescription: Is it acceptable to subclass c_void_p in ctypes?


code: from ttk import Combobox

rawDescription: Implement a dynamic dropdown menu based on on the number of lines of text file


code:
s = '''C  DesignerTEE edBore 1 1/42006
Cylinder SingleVerticalB DesignerHHJ e 1 1/8Cooling 1
EngineBore 11/16 DesignerTDT 8Length 3Width 3
EngineCy DesignerHEE Inline2008Bore 1
Height 4TheChallen DesignerTET e 1Stroke 1P 305
Height 8C 606Wall15ccG DesignerQBG ccGasEngineJ 142
Height DesignerEQE C 60150ccGas2007'''
import re
exp = 'Designer[A-Z]{3}'
re.findall(exp, s)

rawDescription: replacing appointed characters in a string in txt file

description: Replacing appointed characters in a string in txt file


code:
def string(x):
    if x not in ('1', '2', '3', '4', '5', '6', '7'):
        return "Try again"

    d = {'1':'one', '2':'two', '3':'three', '4':'four',
    '5':'five', '6':'six', '7':'seven'}

    return d.get(x)

def main():
  print(string(input("Please enter a number between 1 and 7: ")))

main()

rawDescription: How to use IF or ELSE statements in Python? BTW, How is my username and profile picture?

description: Use IF or ELSE statements in Python? BTW, How is my username and profile picture


code:
class MyTableWidgetItem(QtGui.QTableWidgetItem):
    def __init__(self, text, sortKey):
            QtGui.QTableWidgetItem.__init__(self, text, QtGui.QTableWidgetItem.UserType)
            self.sortKey = sortKey

    #Qt uses a simple < check for sorting items, override this to use the sortKey
    def __lt__(self, other):
            return self.sortKey < other.sortKey

rawDescription: Python: numerical sorting in QTableWidget


code:
import logging
foo_logger = logging.getLogger('foo')
bar_logger = logging.getLogger('bar')
baz_logger = logging.getLogger('baz')

class Whitelist(logging.Filter):
    def __init__(self, *whitelist):
        self.whitelist = [logging.Filter(name) for name in whitelist]

    def filter(self, record):
        return any(f.filter(record) for f in self.whitelist)

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
    datefmt='%m-%d %H:%M')
for handler in logging.root.handlers:
    handler.addFilter(Whitelist('foo', 'bar'))

foo_logger.info('hello from foo')
# 06-24 09:41 foo                  INFO     hello from foo
bar_logger.info('hello from bar')
# 06-24 09:41 bar                  INFO     hello from bar
baz_logger.info('hello from baz')
# No output since Whitelist filters if record.name not begin with 'foo' or 'bar'

rawDescription: What is a correct way to filter different loggers using python logging?


code:
from operator import attrgetter
sorted([f, g], key=attrgetter('age'))

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code:
axMain = subplot(1,2,1)
axTable1 = subplot(2,2,2, frameon =False)
axTable2 = subplot(2,2,4, frameon =False)
setp(axTable1, xticks=[], yticks=[]) # another way of turning off ticks
setp(axTable2, xticks=[], yticks=[]) # another way of turning off ticks

axMain.plot([1,2,3])
axTable1.table(cellText=[[1,1],[2,2]], loc='upper center',
               rowLabels=['row1','row2'], colLabels=['col1','col2'])
axTable2.table(cellText=[[3,3],[4,4]], loc='upper center',
               rowLabels=['row1','row2'], colLabels=['col1','col2'])

rawDescription: two tables in matplotlib

description: Two tables in matplotlib


code: df2['grp'] = df2.index.values / 4

rawDescription: Python Pandas overlapping data with TimeGrouper


code:
employees = [repr(obj).split("'")[1] for obj in value]
positions = [repr(obj).split("'")[3][:-1] for obj in value]

rawDescription: how to split a list in to different strings in python

description: Split a list in to different strings in python


code: '{:<20} {}'.format('## execute', 'Execute an IRC command')

rawDescription: How to Left Justify part of a String in python?

description: Left Justify part of a String in python


code: output = re.sub(r'[ ]{2,}', input, '|')

rawDescription: In Python, how could I convert a whitespace-delimited log output to a Markdown-formatted table?


code:
def scores_to_dict(scores):
    d = {}
    team_1 = ('team_1', scores[:len(scores)/2])
    team_2 = ('team_2', scores[len(scores)/2:])
    teams = [team_1, team_2]
    for team, scores in teams:
        for idx, score in enumerate(reversed(scores)):
            if idx == 0:
                d['%s_total' % team] = score
            elif idx == 1:
                d['%s_overtime' % team] = score
            else:
                d['%s_round_%s' % (team, len(scores)-idx)] = score
    return d

rawDescription: Dynamically Build Dictionary From Different Lists


code:
for scaff in wanted_scaffs:
    with open(scaff + '.txt', 'r') as f:
        ... # summarize your data

rawDescription: Python large files, how to find specific lines with a particular string


code:
if my_dict:
    g.data_version = my_dict['dataVersion']

rawDescription: Python: Inline if statement else do nothing


rawDescription: Find position in a csv list

description: Find position in a csv list


code: test = sum(([x+1] for x in test), [])

rawDescription: Increase each list element in all possible ways


code:
import bs4
s = '<p itemprop="description"> DESCRIPTION HERE </p>'
soup = bs4.BeautifulSoup(s, "html.parser")
soup.find("p", {"itemprop": "description"}).text
u' DESCRIPTION HERE '

rawDescription: Using regex in Python to extract description of an app from Apple store html


code:
def connect(self):
    """Start connection to remote server."""
    if self.state != "disconnected":
        raise RuntimeError("can't connect in this state")

    self.state = "connecting"
    if not self.factoryStarted:
        self.factory.doStart()
        self.factoryStarted = 1
    ##################
    # ah here we are
    ##################
    self.transport = transport = self._makeTransport()
    if self.timeout is not None:
        self.timeoutID = self.reactor.callLater(self.timeout, transport.failIfNotConnected, error.TimeoutError())
    self.factory.startedConnecting(self)

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


code: current_level.set('Level 2')

rawDescription: Tkinter - Configuring a Label

description: Tkinter - Configuring a Label


code:
import operator

methods = {
    '+': operator.add
    # ...
}

rawDescription: Is there any idiomatic way to add methods to object in Python?


code: sequence_number = struct.unpack("!H", bytes_to_send)[0] >> 4

rawDescription: Spliting a 16 bits value to 12+4 python struct


code:
class B(Synchronized):
    @Synchronized.synchronized.im_func
    def foo(self):
        return 1

rawDescription: How does Python resolve decorator names

description: How does Python resolve decorator names


code:
import ruamel.yaml
from ruamel.yaml.comments import merge_attrib

with open('aaa.yaml') as f:
    result = ruamel.yaml.round_trip_load(f)

keys_to_delete = []
for k in result:
    v = result[k]
    if v.yaml_anchor():
        keys_to_delete.append(k)
    for merge_data in v.merge:  # update the dict with the merge data
        v.update(merge_data[1])
        delattr(v, merge_attrib)
for k in keys_to_delete:
    del result[k]

ruamel.yaml.round_trip_dump(result, sys.stdout)

rawDescription: yaml anchors definitions loading in PyYAML

description: Yaml anchors definitions loading in PyYAML


rawDescription: coordinates (str) to list

description: Coordinates (str) to list


code:
remainder = y % 100
if remainder:
    somevar = remainder

rawDescription: Slicing and if statements (Python)

description: Slicing and if statements (Python)


code:
import pandas as pd

data = {'johnny\nnewline': 2, 'alice': 3, 'bob': 3,
        'frank': 4, 'lisa': 1, 'tom': 8}
n = range(1, max(data.values()) + 1)

# Create DataFrame with columns = pos
output = pd.DataFrame(columns=n, index=[])

# Populate DataFrame with rows
for index, (bidder, pos) in enumerate(data.items()):
    output.loc[index, pos] = bidder

# Print the DataFrame and remove NaN to make it easier to read.
print(output.fillna(''))

# Fetch and print every element in column 2
for index in range(1, 5):
    print(output.loc[index, 2])

rawDescription: Pretty printing newlines inside a string in a Pandas DataFrame


code: dagger = Weapon('finesse', 'light', 'thrown', 0, 0)

rawDescription: Creating a variable inside of a for loop


code:
import re
a_number = re.compile(r'\d+')
only_a_number = re.compile(r'^\d+$')
a_number.search('This string is not a number, but does *contain* 1') is not None
only_a_number.search('This string is not a number, but does *contain* 1') is not None
a_number.search('1') is not None
only_a_number.search('1') is not None

rawDescription: Regex in Python: "\d+" and "[0-9]+ do NOT only recognize numbers&Digits but also Operators?


code:
for i in c:
   del i

rawDescription: Delete all objects in a list

description: Delete all objects in a list


code:
A[:,0][:,np.newaxis] # ->
A[:,0,np.newaxis] # or
A[:,np.newaxis,0]

rawDescription: Best way to iterate through a numpy array returning the columns as 2d arrays

description: Iterate through a numpy array returning the columns as 2d arrays


rawDescription: split command question

description: Split command question


code:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command help')

allon_parser = subparsers.add_parser('allon',
    help='Toggles all output pins to ON.')
allon_parser.set_defaults(func=do_allon)

alloff_parser = subparsers.add_parser('alloff',
    help="Toggles all output pins to OFF.")
alloff_parser.set_defaults(func=do_alloff)

cont_parser = subparsers.add_parser('cont',
    help="Toggles all output pins continously on and off.")
cont_parser.set_defaults(func=do_cont)

args = parser.parse_args()
# Call the associated `func` function
args.func()

rawDescription: Argparse not recognized and incorrectly handled


code:
for i, df in enumerate(chunked_data_iterator):
    df.index = range(i*chunksize, i*chunksize + len(df.index))
    df = df[dupemask]

rawDescription: Using Pandas how do I deduplicate a file being read in chunks?


code:
data = mydict.get('Bri')
if 'Diesel' in data and 'Hatchback' in data:
    ...

rawDescription: Make sure that there are two values in a Dictionaries Key Python


code:
def update(self):
    self.calcPos()  # This moves the position - 5 in the x direction
    self.rect.center = self.x, self.y
    self.rotate()  # This calls the bit to change the angle
    if self.count > self.lifespan:
        self.kill()
    oldCenter = self.rect.center
    self.image = pygame.transform.rotate(self.imagePuff, self.angle) # This rotates
    self.rect = self.image.get_rect()
    self.rect.center = oldCenter

def calcPos(self):
    self.x -= 5

def rotate(self):
    self.angle = (self.angle + 45) % 360

rawDescription: How to animate scale and rotate in pygame using rotozoom

description: Animate scale and rotate in pygame using rotozoom


code:
ic = lambda x: pd.Int64Index(np.arange(x))
df1.iloc[:,~ic(len(df1.columns)).isin([2,4])]

rawDescription: Slicing pandas dataframe by column numbers I don't want


code:
from collections import Counter
a = 'One,One,Two,Two,Three,Four,Five,Five'.split(',')
count = Counter(a)
for key, c in count.most_common():
    print("{}: {}".format(key, c))

for key, c in sorted(count.items(), key=lambda i: a.index(i[0])):
    print("{}: {}".format(key, c))

numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
for key, c in sorted(count.items(), key=lambda i: numbers[i[0].lower()]):
    print("{}: {}".format(key, c))

rawDescription: Display 'Counter' results on seperate line (Python)


code:
bestPlayer = max(self.players, key = lambda p: p.best)
bestPlayer.wins += 1
print ("Winner: ", bestPlayer.name, "\nResult: ", bestPlayer.best)

rawDescription: Using a for loop instead of if,elif?

description: Using a for loop instead of if,elif


code:
def end_int(self, data):
    self.append(int(data))
    self._value = 0
dispatch['i8'] = end_int

rawDescription: How can you adjust xmlrpclib to interpret custom types?

description: Adjust xmlrpclib to interpret custom types


code:
x = [2, 4, 7, 12, 3]
sum_of_all_numbers= reduce(lambda q,p: p+q, x)

rawDescription: How do I add together integers in a list in python?

description: Add together integers in a list in python


code:
fruits = {"apple":12, "banana":4}
with open("test.txt", 'w') as out:
    for fruit,number in fruits.iteritems():
        line = fruit + '=' + str(number) + '\n'
        out.write(line)

rawDescription: Python program to store values in an external file


rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


code:
def cycles(a):
    return [ a[i:] + a[:i] for i in range(len(a)) ]

description: Clean way to accomplish -- if x in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]:


code:
import re
re.findall("[A-Z]+(?: [A-Z]+)*", "ABCD AAA lkjl JJJJJJ")

rawDescription: Continuous capital run strings in sentence in one line preferably using reduce or map function in python


code:
from itertools import product

def compose(lst_of_tuples, iter=True):
    iters = get_iters() if iter else get_lists()
    return [t + i for i in product(*get_iters()) for t in lst_of_tuples]

rawDescription: Python: compose list from nested iterators


code: df1.resample('H', how='count')

rawDescription: Python pandas multiindex getting info from series


code:
edge = np.array(EDGE)
edge[edge > 0].min()
np.where(edge == edge[edge > 0].min())

rawDescription: Identify offset of a value in numpy

description: Identify offset of a value in numpy


code: re.search(r"\b%s\b" % re.escape(word), string)

rawDescription: Determining if a query is in a string

description: Determining if a query is in a string


code:
parser.add_argument('--words', '-w', action='store_true')
parser.add_argument('--characters', '-c', action='store_true')
parser.add_argument('--lines', '-l', action='store_true')

rawDescription: How to implement command line switches to my script?

description: Implement command line switches to my script


rawDescription: Convert a string key to int in a Dictionary


code: oldpuzzle = puzzle

rawDescription: python sudoku puzzle? checking puzzle before and after

description: Python sudoku puzzle? checking puzzle before and after


code: df['Block'] = df.groupby(['SID', 'Trial']).cumcount()

rawDescription: do i want rolling_apply?

description: Do i want rolling_apply


code: [dict(duple_list).get(e, 0) for e in element_list]

rawDescription: matching a string to a list of tuples

description: Matching a string to a list of tuples


code:
def show_word(self):
    """ Shows the word behind the cell """
    self.hidden = not self.hidden
    self.button["text"] = str(self)

    if mem.choice1 is None:
        mem.choice1 = self
    else:
        mem.choice2 = self
        self.check(mem.choice1, mem.choice2)

def check(self, choice1, choice2):
    """ Checks if the chosen words are a pair """
    mem.choice1, mem.choice2 = None, None
    if choice1.word != choice2.word:
        for cell in (choice1, choice2):
            cell.hidden = True
            cell.button['text'] = str(cell)

rawDescription: Something wrong without any error - Includes Tkinter


code:
from itertools import izip
def get_all_records(users, dt):
    return [[record for record in user.records if dt <= record.datetime < dt + timedelta(days=7)] for user in users]

for dt in ...:

    records = get_all_records(users, dt)
    userInfo   = [(user, record) for user, record in izip(users, records) if len(record)]

rawDescription: Extracting two sets (class + class property) using list comprehension


code:
def bbox_rotate_3d(bbox_in, angle_x, angle_y, angle_z, centre):

    rmin, rmax, cmin, cmax, zmin, zmax = bbox_in

    # bounding box corners in homogeneous coordinates
    xyzu_in = np.array(([[cmin, cmin, cmin, cmin, cmax, cmax, cmax, cmax],
                         [rmin, rmin, rmax, rmax, rmin, rmin, rmax, rmax],
                         [zmin, zmax, zmin, zmax, zmin, zmax, zmin, zmax],
                         [   1,    1,    1,    1,    1,    1,    1,    1]]))

    # translate centre to origin
    cr, cc, cz = centre
    cent2ori = np.eye(4)
    cent2ori[:3, 3] = -cr, -cc -cz

    # rotation about the x-axis
    theta = np.deg2rad(angle_x)
    rmat_x = np.eye(4)
    rmat_x[1:3, 1:3] = np.array([[ np.cos(theta),-np.sin(theta)],
                                 [ np.sin(theta), np.cos(theta)]])

    # rotation about the y-axis
    theta = np.deg2rad(angle_y)
    rmat_y = np.eye(4)
    rmat_y[[0, 0, 2, 2], [0, 2, 0, 2]] = (
        np.cos(theta), np.sin(theta), -np.sin(theta), np.cos(theta))

    # rotation about the z-axis
    theta = np.deg2rad(angle_z)
    rmat_z = np.eye(4)
    rmat_z[:2, :2] = np.array([[ np.cos(theta),-np.sin(theta)],
                               [ np.sin(theta), np.cos(theta)]])

    # translate from origin back to centre
    ori2cent = np.eye(4)
    ori2cent[:3, 3] = cr, cc, cz

    # combine transformations (rightmost matrix is applied first)
    tform = ori2cent.dot(rmat_z).dot(rmat_y).dot(rmat_x).dot(cent2ori)
    xyzu_out = tform.dot(xyzu_in)

    r, c, z = xyzu_out[:3]

    rmin = int(r.min())
    rmax = int(r.max())
    cmin = int(c.min())
    cmax = int(c.max())
    zmin = int(z.min())
    zmax = int(z.max())

    return rmin, rmax, cmin, cmax, zmin, zmax

rawDescription: bounding box of numpy array

description: Bounding box of numpy array


code:
#! python
f = open("ip.txt", "w")
for line in open('/var/log/apache2/access.log'):
        ip = line.split(' ')[0]
        f.write(ip + '\n')
f.close()

rawDescription: Trying to parse source IP's from apache access log and write the output to a file but only 1 ip is written


code:
from itertools import dropwhile
try:
    item = next(dropwhile("the one I'm looking for".__ne__, items))
    found = True
except:
    found = False

rawDescription: For loops and multiple conditions

description: For loops and multiple conditions


code:
df_quad
df_quad.columns = pd.MultiIndex.from_tuples(combs)
df_quad
combs

rawDescription: generate all quadratic combinations of any 2 columns

description: Generate all quadratic combinations of any 2 columns


code:
from netifaces import AF_INET, AF_INET6, AF_LINK, AF_PACKET, AF_BRIDGE
import netifaces as ni

rawDescription: How to get the physical interface IP address from an interface

description: Get the physical interface IP address from an interface


rawDescription: Finding largest indices of non-zero elements along each axis


code:
myservice = build('my-service', 'v1', http=http, discoveryServiceUrl=discoveryServiceUrl)
data = myservice.my-path().endpoint-name()
results = data.execute()

rawDescription: Failing to authorize connection to own GAE endpoints API with service account


code:
# A "ColumnDataSource" is like a dict, it maps names to columns of data.
# These names are not special we can call the columns whatever we like.
source = ColumnDataSource(
    data=dict(
        x = [row['name'] for row in joined],
        y = [row['name'] for row in joined],
        color = list_of_colors_one_for_each_row,
    )
)

# We need a list of the categorical coordinates
names = list(set(row['name'] for row in joined))

# rect takes center coords (x,y) and width and height. We will draw
# one rectangle for each row.
rect('x', 'y',        # use the 'x' and 'y' fields from the data source
     0.9, 0.9,        # use 0.9 for both width and height of each rectangle
     color = 'color', # use the 'color' field to set the color
     source = source, # use the data source we created above
     x_range = names, # sequence of categorical coords for x-axis
     y_range = names, # sequence of categorical coords for y-axis
)

rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code:
import os

for parent, dirnames, filenames in os.walk('/path/to/the/directory'):
    for fn in filenames:
        if fn.lower().endswith('.pdf'):
            os.remove(os.path.join(parent, fn))

rawDescription: Delete pdf files in folders and subfolders with python?


code:
from collections import defaultdict
def invert(oldDict):
    invertedDict = defaultdict(list)
    i=0
    while oldDict:
        key, valuelist = oldDict.popitem()
        for value in valuelist:
            invertedDict[value].append(key)
        i+=1
        if i%1000==0: # allow the dict to release memory from time to time
            oldDict[None]=None
            del oldDict[None]
    return invertedDict

rawDescription: In-place dictionary inversion in Python

description: In-place dictionary inversion in Python


code: thread.setDaemon = True

rawDescription: How to end a program properly with threads?

description: End a program properly with threads


code:
def answers(self, other):
    if not isinstance(other, TCP):
        return 0
    if conf.checkIPsrc:
        if not ((self.sport == other.dport) and
                (self.dport == other.sport)):
            return 0
    if (abs(other.seq-self.ack) > 2+len(other.payload)):
        return 0
    return 1

rawDescription: Scapy sr() with custom layers

description: Scapy sr() with custom layers


code:
from itertools import groupby
from operator import itemgetter
{v: ids for v, ids in groupby(enumerate(sorted(A)), itemgetter(1))}

rawDescription: Dictionary Comprehension for list values


rawDescription: PySide Drop down menu

description: PySide Drop down menu


code:
import itertools as IT
patterns = [pattern1, pattern2, pattern3, pattern4, pattern5]
empty = (df.TAG == '')
for pattern, grp in IT.izip(patterns, group):
    mask = df.IDnumber.str.contains('|'.join(pattern)) & empty
    df.loc[mask, 'TAG'] = grp

rawDescription: Python pandas tagging entries in dataframe shortening code


code:
@task
def add(x,x):
    return x+y

rawDescription: Celery and custom consumers

description: Celery and custom consumers


code:
import datetime
current_dt = datetime.datetime.now()
current_dt
['AM','PM'][current_dt.hour>=12]

rawDescription: Various Python datetime issues

description: Various Python datetime issues


code:
def sigma_num(n):
    fields = ['ra','dec','zcosmo','r200','m200','is_central','r']
    hdulist = pyfits.open(
                  ('/home/ssridhar/mock_test_files/Roncarelli_test'
                  '/roncarelli_dist_halo{0}.fits').format(n)
              )
    var = dict((f, hdulist[1].data.field(f)) for f in fields)
    N, r_hist = np.histogram(var['r'], bins=20, range=None, normed=False, weights=None)
    area = [math.pi*(R**2-r**2) for R, r in zip(r_hist[1:], r_hist)]
    return N/area

rawDescription: Shortening a Python program

description: Shortening a Python program


rawDescription: Elegant access to edge attributes in networkx


rawDescription: Python how to plot (x,y) data on a netcdf image


rawDescription: Count number of non-NaN entries in each column of Spark dataframe with Pyspark


code:
# to xyz export *
exports = [(k, v) for (k, v) in globals().iteritems() if not k.startswith("_")]
import xyz
for k, v in exports: setattr(xyz, k, v)

rawDescription: Is there anything like Python export?

description: Is there anything like Python export


code:
def thread1():
    update_or_create(SomeModel, {'some_unique_field':1}, {'some_field': 1})

def thread2():
    update_or_create(SomeModel, {'some_unique_field':1}, {'some_field': 2})

rawDescription: Django. Thread safe update or create.

description: Django. Thread safe update or create.


rawDescription: How to properly report an exit status in batch?

description: Properly report an exit status in batch


code:
mask = np.arange(4) != np.vstack(B)
mask

rawDescription: Python: Optimize deletion of elements not aligned in a numpy array


code: links = driver.find_elements_by_css_selector("#GridView1 tbody tr td:nth-child(2) a")

rawDescription: Selenium pull HREF out of TD in table

description: Selenium pull HREF out of TD in table


rawDescription: Python script not putting entire line in excel spreadsheet


code:
import os.path
def ignorePath(path):
  def ignoref(directory, contents):
    return (f for f in contents if os.abspath(os.path.join(directory, f)) == path)
  return ignoref

shutil.copytree('Path', 'target', ignore=ignorePath('/Full/Path/To/aDir/Common'))

rawDescription: Filter directory when using shutil.copytree?


code: tmplt = tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))

rawDescription: Replacing or substituting in a python string does not work


code:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a':range(1,6,1), 'b':range(10,60,10)})
np.convolve(df["a"].values, df["b"].values[::-1])[:5]

rawDescription: Pandas Dataframe: How to perform operation on 2 columns from different direction


code:
class RentalPhoto(BaseModel):
    def is_owned_by(self, user):
        return self.rental.is_owned_by(user)

rawDescription: Adding per-object permissions to django admin


code:
class FoodFilter(filters.FilterSet):
   component_food_pair = FoodComponentFilter(name='dummy_field')
   [...]
   class Meta:
        model = Food
        fields = ('component_food_pair',[...])

rawDescription: Django FilterSet AND(?) condition

description: Django FilterSet AND(?) condition


code:
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
{key:value*number for key,value in dictionary.items()}

rawDescription: Changing all the values of a dictionary

description: Changing all the values of a dictionary


code: stretch = Linear.linear_stretch

rawDescription: multiprocessing.Process - Variable as function

description: Multiprocessing.Process - Variable as function


code:
with open(r'\\network\loc\build_ver.txt','r+') as f:
    value = int(f.read(), 16)
    f.seek(0)
    f.write(hex(value + 1))

rawDescription: how to do a hexadecimal increment?

description: Do a hexadecimal increment


code:
def at(self, t):
    def get_arr(t):
        try: # Iterate over me
            return [get_arr(t1)[0] for t1 in t]
        except TypeError:
            #Opps am not Iterable
            pass
        try: # you can subtract datetime object
            return [(t-self.t0).total_seconds()]
        except TypeError:
            #Opps am not a datetime object
            pass
        # I am just a float
        return [t]
    self.initial*numpy.exp(self.growth*np.array(get_arr(t)))

rawDescription: Pythonic way of writing a library function which accepts multiple types?


code:
res = df1['items'].str.split("|", return_type='frame')
res
res.index = df1['view']
res

rawDescription: Python Pandas merge two data frames based on multiple values field


code:
subprocess.Popen(["date"], env={'TZ': 'America/New_York'}).wait()
subprocess.Popen(["date"], env={'TZ': 'Asia/Taipei'}).wait()

rawDescription: Python: Exporting environment variables in subprocess.Popen(..)


code: seta==setb

rawDescription: Compare lines in 2 text files with different number of columns


code:
all([c.isdigit() or c == '/' for c in match])
all([c.isdigit() or c == '/' for c in no_match])

rawDescription: How to I check that a string contains only digits and / in python?


code:
from itertools import islice
print(sorted(([ele[0],mean(islice(ele,1,None))] for ele in l),key=itemgetter(1),reverse=True))

rawDescription: Sort tuple by averages

description: Sort tuple by averages


rawDescription: List as value in dictionary, get key of longest list


code: simple_page = Blueprint('simple_page', url_prefix='/pages')

rawDescription: Flask Blueprint Initialization - Initializing some global variables


code:
admin.add_view(UserView(model=User, session=db.session, category='Account', name='Users', roles_accepted=['admin']))
admin.add_view(RoleView(model=Role, session=db.session, category='Account', name='Roles', roles_accepted=['admin']))
admin.add_view(PostView(model=Post, session=db.session, category='Blog', name='Posts (Editor Only)', roles_accepted=['editor']))
admin.add_view(PostView(model=Post, session=db.session, category='Blog', name='Posts (Admins & Editors)', endpoint="post_special", roles_accepted=['editor', 'admin']))

rawDescription: flask-admin is_accessible usage

description: Flask-admin is_accessible usage


code:
def products(n, min_divisor=2):
    """Generate expressions of n as a product of ints >= min_divisor."""
    if n == 1:
        yield []
    for divisor in range(min_divisor, n+1):
        if n % divisor == 0:
            for product in products(n // divisor, divisor):
                yield product + [divisor]

rawDescription: How can I generate all possible divisor products for a number?

description: Generate all possible divisor products for a number


code:
from bisect import bisect

l = ['a', 'c', 'e']

print(bisect(l,"d"))
2

rawDescription: Python - efficiently find where something would land in a sorted list?


code: data = "0xb1ca2a3e4fac"[2:]

rawDescription: Best way to regroup a string into a list of 2-character string

description: Regroup a string into a list of 2-character string


code:
file_bytes = open('/tmp/gsutil.tar.gz', 'rb').read()
import crcmod
crc32c = crcmod.predefined.Crc('crc-32c')
crc32c.update(file_bytes)
crc32c.crcValue

rawDescription: Difficulty comparing generated and google cloud storage provided CRC32c checksums


code:
class Word(Base):
    __tablename__ = "words"

    id = Column(Integer, primary_key=True)
    eng = Column(String(32), unique=True)
    chinese = relationship("Chinese", backref="eng")

    def __init__(self, eng, chinese):
        self.eng = eng
        self.chinese = map(Chinese, chinese)

class Chinese(Base):
    __tablename__ = "chinese_words"

    word = Column(String(128), primary_key=True)
    eng_id = Column(Integer, ForeignKey('words.id'), primary_key=True)

    def __init__(self, word):
        self.word = word

rawDescription: python using sqlalchemy store a list into sql database

description: Python using sqlalchemy store a list into sql database


code: dlist = [{'name': x.name, 'age': x.age, 'gender': y.gender} for x, y in zip(list1, list2)]

rawDescription: Same output for a list in django

description: Same output for a list in django


code: print_range(20, 105, ncolumns=10)

rawDescription: Can I format n numbers in Python

description: Format n numbers in Python


code:
class JsonRpcEncoder(json.JSONEncoder):
    def decimalize(self, val):
        if isinstance(val, dict):
            return {k:self.decimalize(v) for k,v in val.items()}

        if isinstance(val, (list, tuple)):
            return type(val)(self.decimalize(v) for v in val)

        if isinstance(val, float):
            return FancyFloat(val)

        return val

    def encode(self, val):
        return super().encode(self.decimalize(val))

JsonRpcEncoder().encode(evil)
#>>> '{"x": 0.00000000000999999999999999939496969281939810930172340963650867706746794283390045166015625}'

rawDescription: Disable scientific notation in python json.dumps output


code: "<ParentRedirec\r\ntSequenceID>"

rawDescription: Dealing with Windows line-endings in Python


code:
a = pd.read_csv("52w_h.csv")
b = a.groupby('Date')
df_h= b['52wh'].sum()

rawDescription: Python: for loop to find how many stocks hits 52 weeks high and low


rawDescription: Efficiently Removing Very-Near-Duplicates From Python List


code: f = open(file, "r")

rawDescription: Python. File open procedure

description: Python. File open procedure


code:
hours = input[0:2]
minutes = input[2:4]

rawDescription: 24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python


rawDescription: How to plot beautifully the segmentation of time series (pandas dataframe)

description: Plot beautifully the segmentation of time series (pandas dataframe)


rawDescription: Django quering objects with timestamp delta


code: filt_df = pd.concat([df.loc[:,'User_id'], filt_df], axis=1)

rawDescription: Remove Outliers in Pandas DataFrame using Percentiles


code:
args = {};

def add(argument, command):
    args[argument] = command;

def run():
    for arg in args:
        args[arg]()     # <<<<<<<<<<

def prnt():
    print("test");

add("-v", prnt);
run();

rawDescription: Storing code inside a dictionary

description: Storing code inside a dictionary


code:
import datetime

def same_week(dateString):
    '''returns true if a dateString in %Y%m%d format is part of the current week'''
    d1 = datetime.datetime.strptime(dateString,'%Y%m%d')
    d2 = datetime.datetime.today()
    return d1.isocalendar()[1] == d2.isocalendar()[1] \
              and d1.year == d2.year

rawDescription: what would be the pythonic way to find out if a given date belongs to the current week?

description: What would be the pythonic way to find out if a given date belongs to the current week


code:
class Bunch(object):
  def __init__(self, adict):
    self.__dict__.update(adict)

rawDescription: Accesing dictionary with class attribute


code: ax.twinx().plot(x, df.another)

rawDescription: Pandas Dataframe Multicolor Line plot

description: Pandas Dataframe Multicolor Line plot


code: list(zip(*[iter(my_list)] * counter))

rawDescription: Getting every X word from list

description: Getting every X word from list


code:
r = reprlib.Repr()
r.maxlist = 4       # max elements displayed for lists
r.maxstring = 10    # max characters displayed for strings

obj = [[1, 2, 3], list(range(10000)), 'looooooong string', 'a', 'b', 'c']

print(r.repr(obj))

rawDescription: Limiting print output

description: Limiting print output


rawDescription: If path is symlink to another path

description: If path is symlink to another path


code: result = [train_dict.get(test[sample], predictions[sample]) for sample in xrange(len(listed_predictions))]

rawDescription: Tips for speeding up my python code

description: Tips for speeding up my python code


code:
plt.figure()
ax=plt.gca()
DF.plot(kind='bar', ax=ax)
plt.grid(True, 'both')
minor_XT=ax.get_xaxis().get_majorticklocs()
DF['XT_V']=minor_XT
major_XT=DF.groupby(by=DF.index.get_level_values(0)).first()['XT_V'].tolist()
DF.__delitem__('XT_V')
ax.set_xticks(minor_XT, minor=True)
ax.set_xticklabels(DF.index.get_level_values(1), minor=True)
ax.tick_params(which='major', pad=15)
_=plt.xticks(major_XT, (DF.index.get_level_values(0)).unique(), rotation=0)

rawDescription: Group labels in matplotlib barchart using Pandas MultiIndex


rawDescription: Removing empty dictionary elements in Python


code: [x.strip() for x in "2.MATCHES $$TEXT$$ STRING".split("$$TEXT$$")]

rawDescription: Split a string by a delimiter in python

description: Split a string by a delimiter in python


code:
#!/usr/bin/env python3
import sys
from urllib.request import urlretrieve

def reporthook(blocknum, blocksize, totalsize):
    readsofar = blocknum * blocksize
    if totalsize > 0:
        percent = readsofar * 1e2 / totalsize
        s = "\r%5.1f%% %*d / %d" % (
            percent, len(str(totalsize)), readsofar, totalsize)
        sys.stderr.write(s)
        if readsofar >= totalsize: # near the end
            sys.stderr.write("\n")
    else: # total size is unknown
        sys.stderr.write("read %d\n" % (readsofar,))

urlretrieve(url, 'downloaded_file.py', reporthook)

rawDescription: Download progressbar for Python 3

description: Download progressbar for Python 3


code:
mode = lambda x: x.mode() if len(x) > 2 else np.array(x)
df.groupby('tag')['category'].agg(mode)

rawDescription: Python: select most frequent using group by


code:
def next_configuration(y):
    """Take a configuration of heaps and remove one card from each
    heap to create a new heap.
    """
    new_y = [x - 1 for x in y if x > 1]
    new_y.append(len(y))
    new_y.sort(reverse=True)
    return new_y

rawDescription: Simple solitaire

description: Simple solitaire


code:
class MyListView(ListView):
    def dispatch(self, request, *args, **kwargs):
        self.queryset = Resources.objects.filter(user = request.user.username)
        return super(MyListView, self).dispatch(request, *args, **kwargs)

rawDescription: How to access HttpRequest from urls.py in Django

description: Access HttpRequest from urls.py in Django


code:
first_index = -1
match = re.search(r'[^f]', line)
if match:
    first_index = match.start()

rawDescription: Python: Find first non-matching character


code: return sum(line.strip().startswith("for ") for line in lines)

rawDescription: Combining for and if loops

description: Combining for and if loops


code: extra_context['importe_iva_incluida'] = fact.importe_sin_iva * 1.21

rawDescription: How to make equations in views.py with a model field (beginner)

description: Make equations in views.py with a model field (beginner)


code:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)

rawDescription: How do I construct a variable query with pymongo

description: Construct a variable query with pymongo


rawDescription: Decimal(str(my_float)) seems to be better than Decimal(my_float), what's going on?


code:
from functools import partial

def operation(args, operator):
    return operator(*args)
final_op = partial(operation, [1,2])

rawDescription: Asynchronously apply list of python functions to single argument


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(index=pd.date_range('2009-1-1', periods=4))
df['Datetime'] = df.index
df.reset_index(inplace=True, drop=True)
df['id'] = df.index
df.index = df['Datetime']
df.drop('Datetime', axis=1, inplace=True)

rawDescription: Is there a better way to index dataframes?


code:
def some_view(request):
    # ...
    if request.method == 'POST':
        form = TestModelForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            ref = get_ref_according_to_url()
            instance.ref1 = ref
            instance.save()
            # ...

rawDescription: How to hide a field in django modelform?

description: Hide a field in django modelform


code:
from ftplib import FTP
ftp = FTP('ftp.debian.org')
login_response = f.login()

rawDescription: ftplib capture and process ftp server response code

description: Ftplib capture and process ftp server response code


rawDescription: How to add attribute to python *class* that is _not_ inherited?

description: Add attribute to python *class* that is _not_ inherited


code:
import csv

with open('file1') as file1, open('file2') as file2, open('output', 'w') as output:
    next(file1), next(file2) # skip the header lines
    c1, c2 = csv.reader(file1, delimiter=' '), csv.reader(file2, delimiter=' ')
    c3 = csv.writer(output, delimiter=' ')
    c3.writerow(['listname', 'a', 'b', 'diff(b-a)'])
    for (row1, row2) in zip(c1, c2):
        c3.writerow(('full', row1[1], row2[1], int(row2[1])-int(row1[1])))
        c3.writerow(('part', row1[2], row2[2], int(row2[2])-int(row1[2])))

rawDescription: do column operation between two csv files

description: Do column operation between two csv files


code:
import html
html_string = "ampersand lt;div ampersand gt;\n ampersand lt;div ampersand gt; ampersand lt;span ampersand gt;Customer..".replace("ampersand ", "&")
html.unescape(html_string)

rawDescription: Python convert html tags in ampersand format


code:
def f2():
    return (lambda *args: args)(1, *f1())

rawDescription: Python: easiest way to flatten a tupple containing another tupple from a function


code:
df = pd.DataFrame(data=np.linspace(50, 100, 200), index=pd.date_range(end='2014-06-18', periods=200), columns=['value'])
df.head()
month_offset = MonthAnchor(day_anchor = df.index[-1].day + 1)
df.resample(month_offset, how='ohlc')

rawDescription: pandas timeseries resampling ending a given day

description: Pandas timeseries resampling ending a given day


rawDescription: Importing modules to a package

description: Importing modules to a package


code: new_user = User(name='Johnny', country_id=session.query(Country).filter_by(name='Spain').one().id)

rawDescription: SQLAlchemy ORM Insertion based on related object


code:
import scrapy

class BookmyshowSpider(scrapy.Spider):
    name = "bookmyshow"
    start_urls = ['https://in.bookmyshow.com/movies']
    allowed_domains = ['bookmyshow.com']

    def parse(self, response):
        links = response.xpath('//a/@href').re('movies/[^\/]+\/.*$')
        for url in set(links):
            url = response.urljoin(url)
            yield scrapy.Request(url, callback=self.parse_movie)

    def parse_movie(self, response):
        for sel in response.xpath('//div[contains(@class, "movie-card")]'):
            item = {}
            item['Moviename'] = sel.xpath('.//a[@class="__movie-name"]/text()').extract()
            item['Language'] = sel.xpath('/html/body/div[1]/div[2]/div/div[1]/div[2]/section[1]/div/div[2]/div[1]/div[1]/div/div/div[2]/div[2]/ul/li/text()').extract()
            item['Info'] = sel.xpath('.//div[@class="__rounded-box __genre"]/text()').extract()
            item['Synopsis'] = sel.xpath('/html/body/div[1]/div[2]/div[1]/div[2]/div[4]/div[2]/div[2]/blockquote/text()').extract()
            item['Release'] = sel.xpath('.//span[@class="__release-date"]/text()').extract()
            yield item

rawDescription: Getting data from multiple links using scrapy


code:
mode = lambda x: x.mode() if len(x) > 2 else np.array(x)
df.groupby('tag')['category'].agg(mode)

rawDescription: Python: select most frequent using group by


code:
content=browser.response().read()
doc=lh.fromstring(content)
params=dict((elt.attrib['name'],elt.attrib['value']) for elt in doc.xpath('//input'))
params['king_format']=2
url='http://www.cbs.gov.il/ts/databank/data_ts_format_e.xml'
params=urllib.urlencode(dict((p,params[p]) for p in [
    'king_format',
    'tod',
    'time_unit_list',
    'mend',
    'yend',
    'co_code_list',
    'name_tatser_list',
    'ybegin',
    'mbegin',
    'code_list',
    'co_name_tatser_list',
    'level_1',
    'level_2',
    'level_3']))

browser.open(url+'?'+params)
content=browser.response().read()

rawDescription: How can I scrape data from the Israeli Bureau of Statistics web query tool?

description: Scrape data from the Israeli Bureau of Statistics web query tool


code: node = p.find('div', text="Content I Want")

rawDescription: Select specific child elements with BeautifulSoup


code:
with open(filename, 'w'), fd:
    for row in rows:
        fd.write(','.join(map(quote, row)) + '\r\n')

rawDescription: csv writer in Python with custom quoting

description: Csv writer in Python with custom quoting


code: from captcha.models import CaptchaStore

rawDescription: How to unit test a form with a captcha field in django?

description: Unit test a form with a captcha field in django


code: #!/usr/bin/env python

rawDescription: Run python script without the "python" keyword


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

df1 = pd.read_table(StringIO('''
    Name    Username    Alias1
    Tom     Tomfoolery   TJZ
    Meryl   MsMeryl      Mer
    Timmy   Midsize      Yoda'''), sep='\s+')

df2 = pd.read_table(StringIO('''
    Name    Username   Alias1   Alias2
    Bob     Firedbob   Fire      Gingy
    Tom     Tomfoolery  TJZ      Awww'''), sep='\s{2,}')

result = pd.concat([df1, df2], axis=0)
print(result)

rawDescription: Merging Data with Varying Column Lengths in Pandas / Python


code: headers = [u'Index', u'Current', u'% Change', u'Open', u'High', u'Low', u'Prev. Close', u'Today', u'52w High', u'52w Low']

rawDescription: How to write a list of tuple in python with header mapping

description: Write a list of tuple in python with header mapping


rawDescription: Find 2 or more Newlines

description: Find 2 or more Newlines


code:
import types
isinstance(len, types.FunctionType)
def mylen(): pass

isinstance(mylen, types.FunctionType)

rawDescription: Determine whether a Python function is already implemented in C extension


rawDescription: Generating a probability from a pdf?

description: Generating a probability from a pdf


code:
d = {'bar': 1, 'foo': 1, 'iitem': 1, 'item': 1, 'itemm': 1}
sum([d[i] for i in d.keys() if re.search(r'item', i)])

rawDescription: regex match item in python Counter

description: Regex match item in python Counter


code:
def sortkey(tup):
    return tup[1]

sorted(list_of_tuples, key=sortkey)

rawDescription: Explaination of this lambda function please?


rawDescription: Not able to view all columns in Pandas Data frame


code:
_sentinel = object()

def perms(elements, setLength=_sentinel):
    if setLength is _sentinel:
        setLength = elements

rawDescription: Is there a way to set a default parameter equal to another parameter value?


rawDescription: XML file edit with Python script

description: XML file edit with Python script


code:
with open('foo', 'a') as f:
    do_stuff(f)
    do_more_stuff(f)
    # ...

rawDescription: How can I have my program read updates that it has just made to a text file?

description: Have my program read updates that it has just made to a text file


rawDescription: iterating through a Django model field produces unwanted format

description: Iterating through a Django model field produces unwanted format


code:
def change_file(in_file,cols):
    with open(in_file) as f, NamedTemporaryFile("w", dir=".", delete=False) as tmp:
        r = csv.reader(f)
        wr =  csv.writer(tmp)
        for row in r:
            new = [datetime.strptime(dt, "%m/%d/%Y %H:%M:%S %p").isoformat() for dt in itemgetter(*cols)(row)]
            wr.writerow(new)
        move(tmp.name, in_file)

rawDescription: Edit a csv to show 5 columns in a specific order while applying a format to the datetime field


code:
text = 'ab\\fx*abcdfansab\\fasdafdab\\f664s'
for m in re.finditer( 'ab\\\\f', text ):
    print( 'll found', m.start(), m.end() )

rawDescription: Recognize \ literally in Python strings

description: Recognize \ literally in Python strings


rawDescription: I want to cut variable on another variables using Python


code: [var for var in nc.variables.itervalues() if var.ndim > 1]

rawDescription: How can I find all the variables 2D or higher in a netcdf file using python?

description: Find all the variables 2D or higher in a netcdf file using python


rawDescription: Python Regular Expression to Edit First Comment


code:
mydbconnobj = DBConnection('localhost',3306,'foouser','foopass','foodbname')
mydbconn = mydbconnobj.get_conn()

rawDescription: Writing an object-oriented MySQLdb connection


code:
while True:  # Your main processing loop
    msg = inqueue.dequeue()  # A blocking wait
    if msg is None:
        break
    do_something()
outqueue.flush()
outqueue.close()

rawDescription: Handling child process shutdown gracefully


rawDescription: Adding digits in list in python

description: Adding digits in list in python


rawDescription: BeautifulSoup: How to replace value in an element with an element tag?


code:
def test(value):
    if value == 5:
        return False
    return True
    # these 3 lines can be shortened to: return value == 5

def go(number):
    if test(number): # test(value) returned True
        print('Test succeeded')
        return
    print('Test failed')

go(5) # will print 'Test failed'

rawDescription: How to prevent a function from continuing after a return statement in Python

description: Prevent a function from continuing after a return statement in Python


code:
f = inspect.currentframe()
print(f.f_locals)
print(inspect.getframeinfo(f))

rawDescription: repr the call resulting in a stack frame?

description: Repr the call resulting in a stack frame


code:
def double(n):
    return n * 2

def halve(n):
    return n // 2

def mult(m, n, a = 0):
    if n % 2 != 0:
        a = a + m
        m = double(m)
        n = halve(n)
    if n % 2 == 0:
        m = double(m)
        n = halve(n)
    if n != 0:
        return mult(m, n, a)
    return a

print(mult(57, 86))

rawDescription: Russian Peasant Multiplication Python using recursive-tail


code:
list(chained_zip('ABC', '123'))
list(chained_zip('AB', '1234'))

rawDescription: Breadth-first version of itertools.chain()


code:
from functools import wraps

def wrap(f):
    @wraps(f)
    def wrapped_f(*args, **kwargs):
        pass
    return wrapped_f

@wrap
def A(params):
    pass

print(A.__name__)

rawDescription: Function name of wrapped function?

description: Function name of wrapped function


code:
data = dict()
for covar_type in covs:
    for num in num_comp:
        data[(covar_type, num)] = GMM(...)

rawDescription: Python: list iteration only returns last value


code:
points = np.vstack((x, y, z)).reshape(3, -1).T
points

rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code:
url(
    r'^users/(?P<pk>\d+)/$',
    DetailView.as_view(
        model = User,
        template_name = 'doors/users/detail.html',
        context_object_name = 'user_object'
    ),
    name = 'users_detail'
)

rawDescription: How to do a DetailView of Users in Django?

description: Do a DetailView of Users in Django


rawDescription: How to flash tkinter label limited number of times, and only if conditions are met

description: Flash tkinter label limited number of times, and only if conditions are met


code: db.Key.from_path('Edge', vertex1.name + ' > ' + vertex2.name)

rawDescription: Storing a directed, weighted, complete graph in the GAE datastore


code: new_dict = {k: my_dict[k] for k in my_list if k in my_dict}

rawDescription: Dictionary keys match on list; get key/value pair


code: SendEMAPIMail(SendSubject, SendMessage, SendTo, MAPIProfile=None)

rawDescription: Python - Sending Outlook email from different address using pywin32


code:
from flask import Flask

class MyFlaskApp:

    def __init__(self):
        self.app = Flask(__name__)
        self.app.add_url_rule('/', 'index', self.index)

    def index(self):
        pass

rawDescription: Encapsulate flask api in class for testing purposes


code:
def reformat_authors(authors):
    names = [name.strip() for name in authors.split(r'\and')]
    if len(names) >= 4:
        return '{} et al.'.format(names[0])
    if len(names) > 1:
        return '{} and {}'.format(', '.join(names[:-1]), names[-1])
    return names[0]

rawDescription: Join author names with python: first ones by comma and last one by and


code:
def update(self, newdict):
    if len(newdict) <= 10: raise Exception
    super().update(newdict)

rawDescription: Overriding methods without falling into infinite recursion


code: message = 'hello Bob!'

rawDescription: Decripting RSA in python

description: Decripting RSA in python


code:
def overwriteKeys(data, type=2):
    t2 = dict([
        ('user1', 'user11'),
        ('user2', 'user21'),
        ('user3', 'user31'),
        ('user4', 'user1'),
        ('user5', 'user51'),
    ])

    t1 = {v: k for k, v in t2.items()}
    t = t1 if type == 1 else t2
    return {t.get(k, k): v for k, v in data.items()}

rawDescription: How can i overwrite the dictionary key names in python

description: Overwrite the dictionary key names in python


code:
import Image

def estimate_color(c, bit, c_error):
    c_new= c -  c_error
    if c_new > 127:
        c_bit= bit
        c_error= 255 - c_new
    else:
        c_bit= 0
        c_error= -c_new
    return c_bit, c_error

def image2cga(im):
    "Produce a sequence of CGA pixels from image im"
    im_width= im.size[0]
    for index, (r, g, b) in enumerate(im.getdata()):
        if index % im_width == 0: # start of a line
            r_error= g_error= 0
        r_bit, r_error= estimate_color(r, 1, r_error)
        g_bit, g_error= estimate_color(g, 2, g_error)
        yield r_bit|g_bit

def cvt2cga(imgfn):
    "Convert an RGB image to (K, R, G, Y) CGA image"
    inp_im= Image.open(imgfn) # assume it's RGB
    out_im= Image.new("P", inp_im.size, None)
    out_im.putpalette( (
        0, 0, 0,
        255, 0, 0,
        0, 255, 0,
        255, 255, 0,
    ) )
    out_im.putdata(list(image2cga(inp_im)))
    return out_im

if __name__ == "__main__":
    import sys, os

    for imgfn in sys.argv[1:]:
        im= cvt2cga(imgfn)
        dirname, filename= os.path.split(imgfn)
        name, ext= os.path.splitext(filename)
        newpathname= os.path.join(dirname, "cga-%s.png" % name)
        im.save(newpathname)

rawDescription: How do I convert any image to a 4-color paletted image using the Python Imaging Library?

description: Convert any image to a 4-color paletted image using the Python Imaging Library


code:
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

valuelist = [0,10,30,60,100,150,210,270]

def valuecheck(value):
    newvalue = min(valuelist, key=lambda x:abs(x-float(value)))
    slider.set(newvalue)

root = tk.Tk()

slider = tk.Scale(root, from_=min(valuelist), to=max(valuelist), command=valuecheck, orient="horizontal")

slider.pack()

root.mainloop()

rawDescription: tkinter: slider ("scale") with discrete steps?

description: Tkinter: slider ("scale") with discrete steps


code:
from rest_framework.decorators import api_view
from rest_framework import status

@api_view()
def error_page(request):
    return Response({'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND)

rawDescription: Django Rest Framework how to return detail not found on all invalid urls?


rawDescription: Removing every other element in NumPy

description: Removing every other element in NumPy


code:
def multi(*args):
    p1, p2, p3 = args

def noargs(*args):
    pass

multi(1,2,3)
noargs()

rawDescription: Variable scope problems with dictionaries


code:
#!/usr/bin/env python3
import sys
from pathlib import Path

src_dir = sys.argv[1] if len(sys.argv) > 1 else Path.home() / 'Music'
for path in Path(src_dir).glob('*.mp3'): # list all mp3 files in source directory
    dst_dir, sep, name = path.name.partition('-')
    if sep: # move the mp3 file if the hyphen is present in the name
        dst_dir = path.parent / dst_dir.rstrip()
        dst_dir.mkdir(exist_ok=True) # create the leaf directory if necessary
        path.replace(dst_dir / name.lstrip()) # move file

rawDescription: Automatically move files with python

description: Automatically move files with python


rawDescription: Placing a histogram over scatter plot

description: Placing a histogram over scatter plot


code:
Resp1=Radiobutton(app, text=Guide_list[Current].R1, value=Guide_list[Current].V1,variable=R)
Resp2=Radiobutton(app, text=Guide_list[Current].R2, value=Guide_list[Current].V2,variable=R)
Resp3=Radiobutton(app, text=Guide_list[Current].R3, value=Guide_list[Current].V3,variable=R)
Resp4=Radiobutton(app, text=Guide_list[Current].R4, value=Guide_list[Current].V4,variable=R)
Resp5=Radiobutton(app, text=Guide_list[Current].R5, value=Guide_list[Current].V5,variable=R)
Resp6=Radiobutton(app, text="N/A", value="N/A",variable=R)

Resp1.pack(anchor=W)
Resp2.pack(anchor=W)
Resp3.pack(anchor=W)
Resp4.pack(anchor=W)
Resp5.pack(anchor=W)
Resp6.pack(anchor=W)

rawDescription: Can you update the text and value of a radio button in tkinter?

description: Update the text and value of a radio button in tkinter


code:
arr_invalid = ['aks', 'rabbbit', 'dog']

strings = [ "aks", "akss","foo", "saks"]

filt = list(filter(lambda x: not any(s in x.lower() for s in arr_invalid),strings))

rawDescription: Filter using lambda function python

description: Filter using lambda function python


code:
f=open('/path_to_file/list_2_array.dat', 'r')
l = [int(line.strip().split()[-1]) for line in f.readlines()]
array=np.array(l)

rawDescription: Assigning list to an array in python

description: Assigning list to an array in python


rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


code:
import os
from collections import defaultdict

fileExtensions  = ('.mobi', '.epub', '.pdf', '.djvu')

foundFiles = defaultdict(list)
for dirpath, dirs, files in os.walk(workDirectory):
    for file in files:
        if file.endswith(fileExtensions):
           basename = os.path.splitext(file)[0]
           foundFiles[basename].append(os.path.join(dirpath, file))

rawDescription: Iterating over an unknown number of lists referenced by dictionary key to allow comparison of values within each list


rawDescription: Find right URLs using Python and regex

description: Find right URLs using Python and regex


rawDescription: Pandas: Grouping DataFrame by hundreds

description: Pandas: Grouping DataFrame by hundreds


rawDescription: Converting a list to a nested dictionary?


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

description: Access values of nested dictionary keys in python


code:
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)

rawDescription: Multilayer-perceptron, visualizing decision boundaries (2D) in Python


code: repr(obj)

rawDescription: When __repr__() is called?

description: When __repr__() is called


code:
try:
    import contextlib
    contextlib.ExitStack
except AttributeError:
    import contextlib2 as contextlib

partnames = ['foo', 'bar', 'baz']
with contextlib.ExitStack() as stack:
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception
    files = [stack.enter_context(open(name, "w+")) for name in partnames]
    print(files)

rawDescription: Python close an array of files in a safe manner


code: outfile = input("Please name your output file")

rawDescription: Writing Array to txt file with requested name


code:
def process_response(self, request, response):
        if getattr(request, 'do_stuff', None):
            return do_some_other_stuff()
        return response

rawDescription: Django Middleware, single action after login


code:
import heapq
list_of_t = [('a', 100), ('b', 5), ('c', 50)]
heapq.nlargest(2, list_of_t, key=lambda x:x[1])

rawDescription: extracting tuples based on values in python

description: Extracting tuples based on values in python


code:
def run_func_on_args(input_arg_sets, func):
    for argset in input_arg_sets:
        yield lambda: func(argset)

rawDescription: Python: How to do break up array processing (using multiple queued functions) in timed chunks (600ms)


code:
#    # Selecting nodes using XPath, faster because the context
#    # is allocated just once per xmlDoc.
#    #
#    # Removed: DV memleaks c.f. #126735

rawDescription: Python libxml2: xpathEval vs xpathEval2?

description: Python libxml2: xpathEval vs xpathEval2


code:
# taken and modified from django online tutorial
class CustomValueInline(admin.StackedInline):
    model = CustomValue
    extra = 3

class BookAdmin(admin.ModelAdmin):
    fieldsets = [
       # your fields in here
    ]
    inlines = [CustomValueInline]

admin.site.register(Book, BookAdmin)

rawDescription: User-defined text fields in django admin


rawDescription: Quick comparison of numpy array elements, greater or less than each other


code:
def sub(u, v):
  return [ u[i]-v[i] for i in range(len(u)) ]

rawDescription: Check if a point collides with a surface (pixel perfect) in pygame


code:
def header(delimiter,fields):
    return '#h -F{d} {f}\n'.format(d = delimiter, f=' '.join(fields))

with open('data.csv', 'rb') as f:
    with open('output.csv', 'wb') as g:
        firstline = next(f).split()
        delimiter = firstline[1][-1]
        fields = firstline[2:]
        writer = csv.DictWriter(g, delimiter = delimiter, fieldnames = fields)
        g.write(header(delimiter,fields))
        for row in csv.DictReader(skip_comments(f),
                                   delimiter = delimiter, fieldnames = fields):
            writer.writerow(row)
            g.write('# comment\n')

rawDescription: Reading formatted text using python

description: Reading formatted text using python


code: stri = ''.join(map(lambda c: str(ord(c)),text))

rawDescription: I have string of characters that i need to turn to string of ASCII numbers, how to convert it?


code:
for i in index:
    binary_seq[i] = '0'

rawDescription: Determining all sub-vector combinations of a binary vector for a certain hamming weight


code:
meetings = [
    Meeting(0, 1),
    Meeting(1, 2),
    Meeting(2, 3),
    Meeting(3, 5),
    Meeting(4, 5)
]

print(max_meetings(meetings))   # => 4

rawDescription: Schedule Maximum Number Tasks That have Fixed Start and End times


rawDescription: Why list comprehension is much faster than numpy for multiplying arrays?


code: arr

rawDescription: python - choose top k elements of column 2 for each value of column 1 in sorted numpy matrix

description: Python - choose top k elements of column 2 for each value of column 1 in sorted numpy matrix


code:
MEDIA_ROOT = 'C:/Server/Projects/project_name/static/'
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/media/'

rawDescription: Django: how do you serve media / stylesheets and link to them within templates


code:
from locale import atof
import re

class WeirdSort:
    def __init__(self, in_list, rev=False, which=None, other=None):
        # holds all strings that don't match the pattern we want.
        self.temp = []
        self.in_list = in_list
        self.wrong_type = object()
        # what lambda to pass as the sort key.
        self.which = which
        # split data and sort in_list.
        self.in_list[:] = sorted(self.separate_types(), key=self.atof_pre, reverse=rev)
        # sort odd strings.
        self.temp.sort(key=other, reverse=rev)
        # merge both lists.
        if rev:
            self.temp.extend(self.in_list)
            self.in_list[:] = self.temp
        else:
            self.in_list.extend(self.temp)
        del self.temp

    def atof_try(self, x):
        """Try to cast using specified locale,
           return wrong_type on failure."""
        try:
            return atof(self.which(x))
        except ValueError:
            return self.wrong_type

    def atof_pre(self, x, patt=re.compile("^\d+")):
        """Try to cast using atof initially,
           on failure,  try to pull digits from
           front of string and cast to int.
           On failure, returns wrong_type object
           which will mean "x" will be sorted using a regular sort.
        """
        try:
            _atof = self.atof_try(x)
            if _atof is not self.wrong_type:
                return _atof
            temp = patt.search(x)
            return int(temp.group())
        except (ValueError, IndexError, AttributeError):
            return self.wrong_type

    def separate_types(self):
        """Separate elements that can be cast to a float
           using atof/int/re logic and those that cannot,
           anything that cannot be sorted will be
           added to temp_list and sorted separately.
        """
        for ele in self.in_list:
            if self.atof_pre(ele) is not self.wrong_type:
                yield ele
            else:
                self.temp.append(ele)

rawDescription: Sort numeric lines with thousand separators


code:
large_int = bytes2int(mystring)
large_int <<= 1
mystring = int2bytes(large_int)

rawDescription: Python: convert a byte to binary and shift its bits?


code:
codecs.BOM_UTF32_LE
codecs.BOM_UTF32_BE

rawDescription: Python 3: Demystifying encode and decode methods


code: keys = dct.values()[0].keys()

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code:
...

# Assign a date for a given task to each student,
# preferring a date that they like and is still free.
def fill(task, lowest_acceptable, spread_weight=0.1, tasks_to_spread="ABC"):
        random_order = range(nStudents) # randomize student order, so everyone
        random.shuffle(random_order)    # has an equal chance to get their first pick
        for i in random_order:
            student = students[i]
            if student.dates[task]: # student is already assigned for this task?
                continue

            # get available dates ordered by preference and how fully booked they are
            preferred = get_favorite_day(student, lowest_acceptable,
                                         spread_weight, tasks_to_spread)
            for date_nr in preferred:
                date = dates[date_nr]
                if date.is_available(task, student.count, lowest_acceptable == 1):
                    date.set_student(task, student.count)
                    student.dates[task] = date
                    break

# attempt to "fill()" the schedule while gradually lowering expectations
start_at = 5
while start_at > 1:
    lowest_acceptable = start_at
    while lowest_acceptable > 0:
        fill("A", lowest_acceptable, spread_weight, "AAB")
        fill("B", lowest_acceptable, spread_weight, "ABB")
        if lowest_acceptable == 1:
            fill("C", lowest_acceptable, spread_weight_C, "C")
        lowest_acceptable -= 1

rawDescription: Maximizing a combination of a series of values


code:
if mazeList[x][y] == 'E':
        mazeList[x][y] = 'o'
        return True

rawDescription: Python Maze solving program: how to mark correct path


code:
idx=np.zeros((80,),int)
M[idx,]

rawDescription: Is there a faster way of extracting row/column submatrices from scipy.sparse.dok_matrix?


code:
pi = 3.141
[int(i) for i in str(pi) if i.isdigit()]

rawDescription: Separate float into digits

description: Separate float into digits


rawDescription: python script speed improvements

description: Python script speed improvements


code:
import datetime
days = 10
endDate = datetime.date.today()
queryset = [datetime.date(2015,12,15), datetime.date(2015,12,11), datetime.date(2015,12,10), datetime.date(2015,12,9), datetime.date(2015,12,8)]
date_ranges = set([endDate - datetime.timedelta(x) for x in xrange(days)])
output = sorted(list(date_ranges - set(queryset)))
print([x.strftime('%Y-%m-%d') for x in output])

rawDescription: Return a list of missing values?

description: Return a list of missing values


code: self.redirect('login/%s' % wiki_topic) #wiki_topic = something like 'topic'

rawDescription: css working on all but two pages

description: Css working on all but two pages


code:
three_counter = 0
for i, v in enumerate(list_a):
    if v == "three":
        three_counter += 1
    # Add 20 for each "three" instead of 30 because the "three"s are also
    # counted in `i`, which adds an additional 10.
    a = X + (i + 1) * 10 + three_counter * 20
    print(a)

rawDescription: Irregular cumulative sum in python

description: Irregular cumulative sum in python


code: new_list = [None]*nbr

rawDescription: Generate a list of a given length with fake elements. Django


rawDescription: Using variables from a returned function as arguments in another function


code: ['eqw', 'qew', 'qwe', 'ewq', 'weq', 'wqe', 'etest', 'teest', 'teest', 'teset', 'teste']

rawDescription: Create new set of subsets out of set of subsets (python)


code:
import numpy as np
for i in range(len(fliers)):
    data = fliers[i].get_data()
    # Get the index of the maximum y in data if
    # i is 0 or even, else get index of minimum y.
    if i%2 == 0:
        id = np.where(data[1] == data[1].max())[0][0]
    else:
        id = np.where(data[1] == data[1].min())[0][0]
    fliers[i].set_data([data[0][id], data[1][id]])

rawDescription: Matplotlib boxplot show only max and min fliers


code:
def num_points(arr, axis):
    return nparray[:,...,np.newaxis].shape[1]

rawDescription: Check number of columns numpy array that returns 1 if is a 1-dimensional array


code: tabv = {key: value for key, value in zip(idv,v)}

rawDescription: Two string list into dictionary: key order changing


code:
if is_iterable(test):
    for x in test:
        do_stuff(x)
else:
    do_stuff(test)

rawDescription: Pythonic way of looping over variable that is either an element or a list


code:
for name in names:
    df['mean'+name] = pd.expanding_mean(df.ptsA*(df.plA==name) + df.ptsB*(df.plB==name))

rawDescription: Calculating expanding mean on 2 columns simultaneously


code:
import datetime

def enteredMonth():
    month = int(input("Enter a month in terms of a number: "))
    return month

def enteredYear():
    year = int(input("Enter a year: "))
    return year

def numberOfDays(year, month):
    first_of_entered_month = datetime.date(year, month, 1)
    someday_next_month = first_of_entered_month + datetime.timedelta(days=31)
    first_of_next_month = someday_next_month.replace(day=1)
    last_of_entered_month = first_of_next_month - datetime.timedelta(days=1)
    return last_of_entered_month.day

def main():
    month = enteredMonth()
    year = enteredYear()
    number_of_days = numberOfDays(year, month)
    pretty_month_year = datetime.date(year, month, 1).strftime('%B %Y')
    print(pretty_month_year, "has", number_of_days, "days")

rawDescription: Converting the number of days in a month in Python?


code:
class Bunch:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

def foo():
    my_local = 42
    ...
    myobj = Bunch(my_local=my_local) # create the dummy instance
    show_prop(myobj, "my_local")     # call the original code
    my_local = myobj.my_local        # get modified value back
    ...

rawDescription: An object that describes the current scope


code: auth_response = hmac.digest() #Binary format

rawDescription: python M2Crypto HMAC SHA1

description: Python M2Crypto HMAC SHA1


code:
class A(models.Model):
    name = models.CharField(max_length=200)

class B(models.Model):
    a = models.ManyToManyField(A, through='C')
    ...

class C(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)

rawDescription: adding the same object twice to a ManyToManyField

description: Adding the same object twice to a ManyToManyField


code:
# insertion:
cursor.execute('INSERT INTO dates VALUES(?, ?)', utciso8601, dt.tzname())

# querying
for row in query:
    timezone = iso8601.iso8601.parse_timezone(row[1])
    utcdt = iso8601.parse_date(row[0])
    dt = utcdt.astimezone(timezone)

rawDescription: Android Python MySQL Datetime Parsing

description: Android Python MySQL Datetime Parsing


rawDescription: Python logging won't set a logging level using basicConfig


rawDescription: list of dicts to/from dict of lists

description: List of dicts to/from dict of lists


rawDescription: Plotting and GroupBy methods

description: Plotting and GroupBy methods


code: a ^ b

rawDescription: Opposite of set.intersection in python?

description: Opposite of set.intersection in python


rawDescription: for information retrieval course using python, accessing given tf-idf weight

description: For information retrieval course using python, accessing given tf-idf weight


code:
import pandas as pd

df = pd.read_csv('data.csv')#a csv file with data just how you presented it above.
dataDict = pd.DataFrame.to_dict(df, orient='list')#turns the dataframe into a dictionary, with the values presented as a list for each column.

print (dataDict)

rawDescription: How to add columns and rows of a dataframe as keys and values of a dictionary in python

description: Add columns and rows of a dataframe as keys and values of a dictionary in python


rawDescription: How to effectively merge Spark output files on EMR?

description: Effectively merge Spark output files on EMR


code: [{'color': value} for value in colors]

rawDescription: bulk insert list values with SQLAlchemy Core

description: Bulk insert list values with SQLAlchemy Core


code: [w for w in words if 'I=' in w][0]

rawDescription: Searching a string and returning only things I specify


rawDescription: Python: How do I find the complement of a list?


code:
class VideoNotifier(pyglet.event.EventDispatcher):

    def updateIndex(self, value):
        self.dispatch_events('on_update_index', value)

VideoNotifier.register_event('on_update_index')

videoNotifier = VideoNotifier()

@videoNotifier.event
def on_update_index(newIndex):
    # thread has notified of an update
    # Change the video here
    pass

rawDescription: Play Different Video Files Depending On Value of a Variable At Runtime


code:
for n in itertools.count(0):
    if x0 <= xmin:
        break
    xy.createSomeCube(x0,y0,z0,x1,y1,z1)
    xy.someCube(n).setSomeParameters(dx,dy,dz)

    ...

    x0 -= someDecrement(someArgument)

rawDescription: Python: get the index in a while loop

description: Python: get the index in a while loop


code:
from Xlib import X, XK, protocol, display, Xcursorfont
from Xlib.ext import xtest
from Xlib.protocol import request

disp = display.Display()

root = disp.screen().root
pointer_info = request.QueryPointer(display = disp.display,
                                    window = root)
root_xpos, root_ypos = (pointer_info._data['root_x'], pointer_info._data['root_y'])
targetwindow = disp.get_input_focus().focus

rawDescription: Python - How do I get the process name of the focused window on Ubuntu?(not the window title)


code:
from itertools import defaultdict
SNPs = defaultdict(list)

rawDescription: How do I clear this list at the end of every loop?

description: Clear this list at the end of every loop


code: results = {}

rawDescription: Python parsing log file for IP address and Protocol


code:
for j in xrange(min(limit2, limit1*2)):
    l.append('First index: %d, Second index: %d' % (j//2, j))

rawDescription: Iterate with 2 Indexes Variable in Python


code:
class Filter(models.Model):
    Filter_Query = models.CharField(max_length=30)

rawDescription: Customize Django Admin Advice

description: Customize Django Admin Advice


code: from __future__ import print_function

rawDescription: Unexpected Python print behavior

description: Unexpected Python print behavior


code:
n = numpy.random.randint(0, 3, size=(3,3))
n
n == 1
(n == 1).sum()

rawDescription: python count number of ones in a binary image

description: Python count number of ones in a binary image


code:
lis = ["link1", "link2",...]

def update():
  global lis
  #do something
  return lis

rawDescription: how to update global variable in python

description: Update global variable in python


rawDescription: Index into dataframe by column value

description: Index into dataframe by column value


rawDescription: Replacing values in two dimensional list


code:
from itertools import product
res = res.reindex(columns=list(product(df['String1'], df['String2'])))
res.columns.names = ['String1', 'String2']
res

rawDescription: Efficient matricization of a pandas dataframe


rawDescription: Using pandas to find daily averages

description: Using pandas to find daily averages


code: import SimpleCV

rawDescription: Python No module named, even though the module does appear


code: line2 = "Build Date: " + time.strftime("%d%m%Y", time.localtime())

rawDescription: create a input and create a file python script

description: Create a input and create a file python script


code:
from itertools import product
[dict(zip(d.keys(), combo)) for combo in product(*d.values())]

rawDescription: Get list of all possible dict configs in Python


code:
import pkg_resources
import os
pythonhome = os.environ["PYTHONHOME"]
pkgs = pkg_resources.find_distributions(pythonhome + "/Lib/site-packages")
for pkg in pkgs:
    pkg_resources.working_set.add(pkg)
# import the modules
# Note: that this does not import the dependencies of the packages imported
# You could get the dependencies by following the guide here:

rawDescription: Python: Sharing python site-packages libraries between two python installations


code:
def h():
    for el in range(4):
        yield el

rawDescription: Difference between generator expression and generator function


code:
import pandas as pd
pd.read_csv('data.txt', delim_whitespace=True)

rawDescription: Creating lists from a text file by splitting it vertically


code:
qs = FooModel.objects.all()
for model in qs:
    model.attr = 'foo'

rawDescription: Django Query Result Is NoneType?

description: Django Query Result Is NoneType


code:
client = Client(url='file://path/to/.wsdl')
xml_request = open('/path/to/obj.xml', 'rb').read()
xml_request = xml_request.replace('REPLACE_ME', value)
result = client.service.TheService(__inject={'msg': xml_request})

rawDescription: soap wrong xml serialization

description: Soap wrong xml serialization


code:
class Plugin(object):
    """A plugin which must provide a register_signals() method"""
    __metaclass__ = PluginMount

rawDescription: Plugin architecture - Plugin Manager vs inspecting from plugins import *


code:
s = "%2 is a %1 %0"
args = ("Ram", "Good")
def f(x):
    g = x.group()
    return "{"+g[1:]+"}" if int(x.group()[1:]) < len(args) else g

sub = re.sub(r"%\d+\b",f,  s).format(*args)

rawDescription: String formatting : Replace "%0 %1 %2" with tuple with 0,1,2 indexes


code:
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("yourdoc.xml")
roottree = tree.getroot()

rawDescription: Get part of XML document in Python

description: Get part of XML document in Python


code: user_countries_count = select(count(u.country) for u in User).get()

rawDescription: how to make a rowcount in ponyorm? Python

description: Make a rowcount in ponyorm? Python


code:
import argparse

example = argparse.ArgumentParser(description='main parser')
example.add_argument('Kill')

subexample = example.add_subparsers()
person = subexample.add_parser('who')
person.add_argument('name')
person.add_argument('address')
person.set_defaults(kind = 'person')

animal = subexample.add_parser('what')
animal.add_argument('name')
animal.set_defaults(kind = 'animal')
args = example.parse_args()
print(args)

rawDescription: Distinguishing subparser arguments

description: Distinguishing subparser arguments


rawDescription: How can i query for objects in current year , current month in django

description: Query for objects in current year , current month in django


code:
# the self param passed to installEventFilter indicates the object which
# defines eventFilter(), see below:
self.list.installEventFilter(self)

rawDescription: PyQt4 - Enter key pressed on item in QListView


code:
{'Product Composition': '93% Polyamide 7% Elastane Lining: 100% Polyester',
 'Product Attributes;': ': Boat Neck, Long Sleeve, Midi, Zip, Concealed, Laced, Side Lining Type: Full Lining'}

rawDescription: how to make a selection for the dictionary?

description: Make a selection for the dictionary


code: plt.figure(0, figsize=(6,2))

rawDescription: PyPlot: Trying to generate shared legend in a subplot, but legends don't appear properly when embedded in a loop. (PDF backend)


code:
f = open("outfile.txt", "w")
f.write("User input: ")
user_input = raw_input("Your input? ")
f.write(user_input)
f.write("\n")
f.close()

rawDescription: python script to automatically write a text file

description: Python script to automatically write a text file


code:
def probability(n, s, t):
    all_rolls = itertools.product(range(1,s+1), repeat=n) #no list, leave it a generator
    target_rolls=sum(1 for l in all_rolls if sum(l)==t) #just total them up
    return round(target_rolls/s**n, 4)

rawDescription: probability of T total eyes when throwing N dice with S sides

description: Probability of T total eyes when throwing N dice with S sides


code:
text = '''
void
shapex_msg (struct shaper *s)
{
  msg (M_INFO, "Output Traffic Shaping initialized at %d bytes per second",
       s->bytes_per_second);
}

void shapex_msg (struct shaper *s)
{
  msg (M_INFO, "Output Traffic Shaping initialized at %d bytes per second",
       s->bytes_per_second);
}

void shapex_msg (struct shaper *s) {
  msg (M_INFO, "Output Traffic Shaping initialized at %d bytes per second",
       s->bytes_per_second);
}'''
shapex_msg = make_regex_for_function('shapex_msg')
shapex_msg.findall(text)

rawDescription: Python - Regexp - Find function names but not function calls


code:
import pandas as pd
from matplotlib.pyplot import pie, axis, show

df = pd.DataFrame({
    'Sex': ['female', 'male', 'female'],
    'Smoke': [1, 1, 1]})

rawDescription: How do I plot a pie chart using Pandas with this data

description: Plot a pie chart using Pandas with this data


rawDescription: Accessing the first returned object in python


code:
schema_props = lambda: schema[exp][node]['properties']
schema_props()['date'] = ...

node = node + 1

# this now uses the next node
schema_props()['date'] = ...

rawDescription: short name for a string/dict/list index

description: Short name for a string/dict/list index


code: [fullList.index(i) for i in fullList if i[0]=='c']

rawDescription: Python find the index of a multi value List?


rawDescription: Is it possible to assign two different returned values from a python function to two separate variables?


rawDescription: Convert row-column-value data to an array - numpy


code:
from pylab import *
spread= rand(50) * 100
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)
r = boxplot(data)

rawDescription: Finding the outlier points from matplotlib : boxplot


code:
if var == 'stringone' or var == 'stringtwo':
    dosomething()

rawDescription: Python: How to check if a variable is equal to one string or another string


code:
def use_sparse_extra_axis(A,ind,f):
    B=scipy.sparse.coo_matrix((A, (range(len(A)), ind))).toarray()
    return f(B)

def use_sparse(A,ind,f):
    return [f(v) for v in scipy.sparse.coo_matrix((A, (ind, range(len(A))))).tolil().data]

rawDescription: Functional assignment in numpy

description: Functional assignment in numpy


code:
if n < k:
        raise Exception("Degree of Ngrams (n) needs to be bigger than skip (k)")

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
import tkinter as tk

root = tk.Tk()
fontfamily = tk.font.families()

def selectcolor(col=None):
    fontlist.config(bg='white') ##unnecessary
    option_selected = fontlist.curselection()
    fontlist.itemconfig(option_selected[0], selectbackground='yellow')

fontlist = tk.Listbox (root, bg='white')
fontlist.grid()

for eachfont in fontfamily:
    fontlist.insert(tk.END, eachfont)

fontlist.bind('<<ListboxSelect>>', selectcolor)
##<<ListboxSelect>> is magic, this option is not shown in_
##ebook John Shipman tkinter 8.5 reference
##.curselection() doesn't work as expected

tk.mainloop()

rawDescription: How to refresh the tkinter Listbox

description: Refresh the tkinter Listbox


code: def rshift(val, n): return (val % 0x100000000) >> n

rawDescription: How to get the logical right binary shift in python

description: Get the logical right binary shift in python


code:
from celery.decorators import task

@task
def publish_post(post_id):
    ''' Sets the status of a post to Published '''
    from blog.models import Post
    from datetime import datetime

    Post.objects.filter(
        pk=post_id,
        date_published__lte=datetime.now(),
        status=Post.STATUS_SCHEDULED
    ).update(status=Post.STATUS_PUBLISHED)

rawDescription: Trouble scheduling and rescheduling posts with Celery


code:
import UserScore
UserScore.user = user

rawDescription: Carry a variable across two files in different classes


code:
class DynamicForm(Form):
  def __init__(self, *args, **kwargs):
    my_arg = kwargs.pop('my_arg')
    super(DynamicForm, self).__init__(*args, **kwargs)
    for item in range(5):
        self.fields['test_field_%d' % item] = CharField(max_length=255)

rawDescription: passing arguments to a dynamic form in django

description: Passing arguments to a dynamic form in django


rawDescription: Arduino - python read serial layout

description: Arduino - python read serial layout


code:
import copy

c = copy.copy(a)

rawDescription: Copying mutable lists in python

description: Copying mutable lists in python


code:
with open("file.txt","w") as f:
    while(operator):
        f.write("string")
        f.flush()

rawDescription: Python: File empty while script is running with sequential write operations


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", help="Enter a number", type=int)

rawDescription: Python - Optional Command Line Argument

description: Python - Optional Command Line Argument


rawDescription: Python - Remove accents from all files in folder


code:
for old, new, indices in changes:
    print("Replaced '{0}' with '{1}'".format(old, new))
    undo = "Would you like to undo that change (y/n)? ".lower()
    if undo == "y":
        for i in indices:
            encoded[i] = old

rawDescription: Deleting from a python array and restoring to previous state


code:
class GetAverageContext(object):
    def __init__(self, average=pkg1.average, get_lengths=pkg2.get_lengths):
        self.average = average
        self.get_lengths = get_lengths

DefaultGetAverageContext = GetAverageContext()

def get_average(lists, context=DefaultGetAverageContext):
    return context.average(*context.get_lengths(*lists))

rawDescription: Injecting "global imports" into Python functions


rawDescription: Indexing from an ndimensional array - numpy/ python