code:
g.add(6)
s
t

rawDescription: Why use Inbuilt copy() function for sets in python when we can simply assign it?


code:
def AddShowings(self, showing_times, cinema, film):
    for showing_time in showing_times:
        self.session.merge(
            Showing(time=showing_time[0], link=showing_time[1],
                    film=film, cinema=cinema)
        )

rawDescription: Fastest way to insert object if it doesn't exist with SQLAlchemy


code:
@view_config(route_name='view_document', renderer='child.pt')
def document_view(request):
    foo = Document(title="bar", content="silly example")
    return {'document': foo}

rawDescription: Using parent template in pyramid framework


code:
a = numpy.zeros([4, 4])
a
indices = ([0, 3], [2, 1])
numpy.add.at(a, indices, 2)
a

rawDescription: Using ufunc.at on matrix

description: Using ufunc.at on matrix


code:
f = Foo ()
b = Bar ()

f_msg = f.get_message ()
b_msg = b.get_message ()

print ("f_msg:", f_msg)
print ("b_msg:", b_msg)

rawDescription: How can I wrap an empty function to be implemented by a child class in a try-except block?

description: Wrap an empty function to be implemented by a child class in a try-except block


rawDescription: How to construct regex for this text

description: Construct regex for this text


code:
while cur_data != "":
    seek_start = 0
    chunk_size = len(target_seq)

    input_file.seek(offset = seek_start, whence = 1) #whence=1 means seek from start of file (0 + offset)
    cur_data = input_file.read(chunk_size) # reads 123
    if target_seq == cur_data:
        # Found it!
        out_file.write("replacement_string")
    else:
        # not it, shove it in the new file
        out_file.write(cur_data)
    seek_start += 1

rawDescription: Removing a sequence of characters from a large binary file using python


code:
handle1=open('file.txt','r+')
handle1.write("I AM NEW FILE")
handle1.close()

rawDescription: How to read and write a file using python?

description: Read and write a file using python


rawDescription: How to modify a the level 0 of a pandas data frame multi index?

description: Modify a the level 0 of a pandas data frame multi index


code: o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 })

rawDescription: Create an anonymous class instance in python


code:
def permutations_with_repetition(s):
    base = len(s)
    for n in range(base**base):
        yield "".join(s[n // base**(base-d-1) % base] for d in range(base))

rawDescription: Generate all permutations of a string in Python without using itertools


code:
from collections import deque

def load_all_levels(root, p):
    """Load all levels reachable from `root`.
    Return a dictionary mapping level id to level.
    """
    # Queue of levels that have been loaded but whose neighbours have not.
    q = deque([root])
    # Map from level id to level for all levels loaded so far.
    loaded = {root.id: root}
    while q:
        for level_id in q.popleft().warps.values():
            if level_id not in loaded:
                level = LevelBuilder.loadLevel(level_id, p.screen)
                loaded[level_id] = level
                q.append(level)
    return loaded

rawDescription: How am I to get all the connections?

description: How am I to get all the connections


code:
# could not get a simple import to work from hosted
# works fine from "not hosted"
#import os

def GetIPData():
    #os.listdir(r'C:\\')
    return range(0,100)

rawDescription: SSIS: Execute Ironpython or Ironruby scripts through SSIS


code:
fruits = ['apple#1', 'apple#2', 'apple#3', 'apple#4']
[(f1, f2) for f1 in fruits for f2 in fruits if f1 < f2]

rawDescription: String loops in Python

description: String loops in Python


code:
def area_of_triangle(points):
    (x1, y1), (x2, y2), (x3, y3) = points
    return abs(x1 * y2 + x2 * y3 + x3 * y1 - y1 * x2 - y2 * x3 - y3 * x1) / 2

rawDescription: Area of a polygon (Recursively using Python)


code: df[['id']].merge(mdf[['id', 'index']], on='id', how='left')

rawDescription: Python Pandas isin return index

description: Python Pandas isin return index


code:
input = np.array(['2014-02-21','2014-02-28'])
for i in input:
    index = np.where(dt['Date']==i)[0][0]
    dt.iloc[index]

rawDescription: Pandas converting dtype object to string


code:
foo = 'a_b_c'
foo.rsplit('_', 1)
foo.rpartition('_')

rawDescription: Splitting string with multiple delimiters in python


code:
import requests

url = 'https://prodpci.etimspayments.com/pbw/inputAction.doh'
payload = {
    'plateNumber': 'notshown',
    'statePlate': 'CA',
    'requestType': 'submit',
    'clientcode': 19,
    'requestCount': 1,
    'clientAccount': 5,
}

s = requests.Session()
response = s.post(url, data=payload)
print(response.text)

rawDescription: POST to .jsp website with Python requests library


code:
n = n / i
if n==1:
    break
continue

rawDescription: Prime factorization: doesn't work with large numbers?


rawDescription: Find amount of times that the chosen letters appear


code:
input_list = [4.0, 4.1, 4.2, 4.0, 9.0, 9.4, 8.9, 4.3]

results = {input_list[0]: [input_list[0]]}    # Start with first value
for value in input_list[1:]:         # loop through our entire list after first value
    hi = value * 1.1
    low = value * 0.9
    print("Value: {0}\tHi: {1}\tLow:{2}".format(value, hi, low))
    for existing in results:     # search through our result set
        found_similar = False
        if low < existing < hi:  # if we find a match
            results[existing].append(value)    # we add our value to the list for that set
            found_similar = True
            break
    if not found_similar:        # if we looped through our entire results without a match
        results[value] = [value] # Create a new entry in our results dictionary

for entry in results:
    print(results[entry])

rawDescription: In Python, how can I check if 2 numbers in a list are within a certain percentage of each other?


code:
@contextfilter
def render(context, value, **kwargs):
    """
    Renders the filtered value as a string template, using the context
    and environment of the caller template.
    """
    if kwargs:
        kwargs.update(context)
        ctx = kwargs
    else:
        ctx = context

    #we render the string as its own template
    mini_template = _environment.from_string(value)
    return mini_template.render(ctx)

rawDescription: How to access a For variable from a Jinja2 contextfilter

description: Access a For variable from a Jinja2 contextfilter


code: mystring = re.sub(r'(?<=\d) ', r',',mystring)

rawDescription: Replacing spaces after any digit using re.sub


code:
def diff_fwd(x, y):
    return np.diff(y)/np.diff(x)

rawDescription: Numpy or SciPy Derivative function for non-uniform spacing?


code:
COMPRESS_JS_FILTERS = [
    'compressor.filters.template.TemplateFilter',
]

rawDescription: Passing STATIC_URL to file javascript with django


code:
a = A(1)
b = A(2)
A.instances
id(A.instances)
id(a.instances)
id(b.instances)

rawDescription: Keep track of instances in python

description: Keep track of instances in python


code:
count = 0
while count < 100:
    count += 1
    test.append(getMouseEvent())
    time.sleep(1)  # <--  optional

drawnow(makeFig)

rawDescription: How to stop data measuring without stopping the whole script

description: Stop data measuring without stopping the whole script


code:
def on_increasebutton_clicked(self):
    print ("Amplitude increased")
    self.amplitude += 1
    self.updateplot()

rawDescription: How to update a realtime plot and use buttons to interact in pyqtgraph?

description: Update a realtime plot and use buttons to interact in pyqtgraph


rawDescription: set the value of a django HiddenInput widget to another object's id rendered in the template

description: Set the value of a django HiddenInput widget to another object's id rendered in the template


rawDescription: How to convert time object into total minutes python

description: Convert time object into total minutes python


code:
def abspath(path):
    """Return the absolute version of a path."""
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)

rawDescription: How does abspath determine if a path is relative?


rawDescription: SVD - Matrix transformation Python

description: SVD - Matrix transformation Python


rawDescription: How can I add dynamic field in the model in django?

description: Add dynamic field in the model in django


code:
def get_nums(lst):
    return [ord(lett) - 96 for lett in lst]

rawDescription: swapping inside the list in python

description: Swapping inside the list in python


code: cnt = Counter(keywords)

rawDescription: Group counted words in python

description: Group counted words in python


code:
mask.dtype
mask.shape

rawDescription: Restricting a sparse matrix to a subspace in scipy


rawDescription: an elegant way to concatenate a list of chars in a string in Python

description: An elegant way to concatenate a list of chars in a string in Python


code:
class Migration(migrations.Migration):

    dependencies = [
        ('characters', '0005_auto_20150129_1035'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='dicepool',
            name='attribute',
        ),
        migrations.RemoveField(
            model_name='dicepool',
            name='contested_dicepool',
        ),
        migrations.RemoveField(
            model_name='dicepool',
            name='resisted_by_attribute',
        ),
        migrations.RemoveField(
            model_name='dicepool',
            name='second_attribute',
        ),
        migrations.RemoveField(
            model_name='dicepool',
            name='skill',
        ),
        migrations.DeleteModel(
            name='DicePool',
        ),
    ]

rawDescription: So, I have a Django migrate error when removing classes and their subclasses at the same time, which appears as an sql syntax error, with sqlite3


code:
from itertools import groupby
from operator import itemgetter

def exportplayers(request):
    d = [
        {"players": [{"id": 179, "name": "Santosh"}, {"id": 180, "name": "Hari"}], "coach": "Xavi Alonso"},
        {"players": [{"id": 175, "name": "Hitman"}], "coach": "Anna Puyol"}
    ]
    my_list = []
    for g, data in groupby(sorted(d, key=itemgetter('coach')),  key=itemgetter('coach')):
        my_list.append({"coach": g, "players": [player for item in data for player in item["players"]]})
    return HttpResponse(json.dumps(my_list))

rawDescription: Merge duplicates list of dictionaries item value


rawDescription: Python List of tuples positionally

description: Python List of tuples positionally


code: values = request.POST.getlist('n')

rawDescription: Getting all request input values

description: Getting all request input values


code:
cols
[i.encode('ascii', 'ignore') for i in cols]

rawDescription: pandas column names to list

description: Pandas column names to list


code:
from collections import Counter

# count how many times each sublists first element appears in all sublists
keys = Counter((ele[0] for sub in (a,b,c) for ele in sub))
for l in (a, b, c):
    for sub in reversed(l):
        # if the count is not 1 then it is not unique so remove it
        if keys[sub[0]] != 1:
            l.remove(sub)

print (a)
print(b)
print(c)

rawDescription: Remove all lists of multiple sets where the specific index is same


code: players = models.ManyToManyField(User, through='Participants')

rawDescription: How do I do multiple joins and aggregation with django ORM?

description: Do multiple joins and aggregation with django ORM


code: out = image1 * (1.0 - alpha) + image2 * alpha

rawDescription: Overlay polygon on top of image in Python


code:
with open('data.json', 'r') as fp:
    data = json.load(fp)

rawDescription: Storing Python dictionaries

description: Storing Python dictionaries


rawDescription: How does argparse store all of the added argument? Is there a way to access their names, and help strings?


code:
class Person(models.Model):
    cars = models.ManyToMany(Car)

rawDescription: Check if user has chosen a value from many to many field


code:
import pygame
from pygame.locals import *
pygame.init()
WIDTH = 1280
HEIGHT = 1080
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
img = pygame.image.load("myimage.jpg")
while True:
        events = pygame.event.get()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        windowSurface.blit(img, (0, 0)) #Replace (0, 0) with desired coordinates
        pygame.display.flip()

rawDescription: Simple example of displaying an image fullscreen in Python


code:
class ModelViewSet(
        mixins.CreateModelMixin,
        mixins.RetrieveModelMixin,
        mixins.UpdateModelMixin,
        mixins.DestroyModelMixin,
        mixins.ListModelMixin,
        GenericViewSet):
    pass

rawDescription: How to limit actions in django rest framework

description: Limit actions in django rest framework


code: page = urlparse.urljoin(response.url, formdata.pop('page'))

rawDescription: Scrapy Post Request with payload

description: Scrapy Post Request with payload


code:
def foo( z_default = None):
   # plug in whatever default makes sense in place of None
   # and the caller can override the default if he wants to
   if x:
       return y, z_default
   else:
       return y, z

rawDescription: Is it possible to detect the number of return values of a function in python?


code:
element = driver.find_element_by_xpath("//div[@id='sendMessage']")
element.click()
element.send_keys("testing")

rawDescription: How to add text to a page using python selenium?

description: Add text to a page using python selenium


code:
X = np.random.randn(10, 3)                              # random 3-d points
center = np.random.randn(3)
scipy.spatial.distance.cdist(X, np.atleast_2d(center))  # both must be 2-d

rawDescription: Creating a 2-dimensional Numpy array with the euclidean distance from the center


code:
data['State1']['Landon']['abc Area'].append('BOB')
data['State1']['Landon']['abc Area'].append('SAM')
data['State1']['Landon']['xyz Area'].append('John')
data['State2']['New York']['hjk Area'].append('Ricky')

def items_in(d):
    res = []
    if isinstance(d, list):
        res.extend(d)
    elif isinstance(d, dict):
        for k, v in d.items():
            res.extend([k] * len(items_in(v)))
    else:
        raise ValueError('Unknown data')
    return res

print(items_in(data['State1']))  # ['Landon', 'Landon', 'Landon']
print(items_in(data['State1']['Landon']))  # ['xyz Area', 'abc Area', 'abc Area']
print(items_in(data['State1']['Landon']['abc Area']))  # ['BOB', 'SAM']
print(items_in(data['State1']['Landon']['xyz Area']))  # ['John']

print(items_in(data['State2']))  # ['New York']
print(items_in(data['State2']['New York']))  # ['hjk Area']

rawDescription: How to create nested dictionaries with duplicate keys in python

description: Create nested dictionaries with duplicate keys in python


code:
#      g
#     / \
#    /   \
#   e     f
#  /\    /\
# a  b  c  d

a, b, c, d = [Node(name, None) for name in 'abcd']
e = Node('e', (a,b))
f = Node('f', (c,d))
g = Node('g', (e,f))

rawDescription: Mapping a list of inputs to the lowest level of nested lists


rawDescription: variable +=% possible or how to get the next interval of a number after another number

description: Variable +=% possible or how to get the next interval of a number after another number


rawDescription: How to apply piecewise linear fit for a line with both positive and negative slopes in Python?

description: Apply piecewise linear fit for a line with both positive and negative slopes in Python


code:
CC = AA.merge(B, left_on='a', right_index=True)
CC[CC.ts_x <= CC.ts_y].groupby(['a', 'b']).first()

rawDescription: Non standard interaction among two tables to avoid very large merge


code: sys.stdout = codecs.EncodedFile(sys.stdout, 'utf8')

rawDescription: Python 3, is using sys.stdout.buffer.write() good style?


code:
question = Question.objects.order_by('?')[0]
form = QuestionForm(instance=question)

rawDescription: how to create a dynamically-created radio buttons form in django

description: Create a dynamically-created radio buttons form in django


code:
def gt2(x):
    return (x>2)

rawDescription: Pass conditional expression as function argument


code:
False == 0
True == 1
isinstance(False, int)

rawDescription: Changing a list with a twist: whats going on behind the scenes


rawDescription: Selected character maps within utf-8

description: Selected character maps within utf-8


code:
taus = np.arange(-taup,taup,del1)
fd = np.linspace(-5/taup,5/taup,151);
x = np.empty((taus.size, fd.size))
for tau_i, tau in enumerate(taus):
# or:
# for tau_i in range(taus.size):
#     tau = taus[tau_i]
    i = i + 1;
    j = 0;

    val1 = 1. - abs(tau) / taup;
    val2 = pi * taup * (1.0 - abs(tau) / taup) * fd;
    x[tau_i] = np.hstack(abs( val1 * np.sin(val2+eps)/(val2+eps)))

rawDescription: Storing all the outputs of for loop in a matrix python


rawDescription: How to add numbers to be stored in a variable?

description: Add numbers to be stored in a variable


code: [new_filter.fields.append(value) for value in filters['fields']]

rawDescription: python method variables and Objects created in method

description: Python method variables and Objects created in method


code: print ('{0:%m}'.format(a))  # python 2.7+ -- '{:%m}' will work.

rawDescription: datetime objects format

description: Datetime objects format


code: i = pd.MultiIndex.from_product([labels, labels])

rawDescription: cross join/merge to create dataframe of combinations (order doesn't matter)

description: Cross join/merge to create dataframe of combinations (order doesn't matter)


code:
circle1=plt.Circle((0,0),2,color='r')
# now make a circle with no fill, which is good for hilighting key results
circle2=plt.Circle((5,5),.5,color='b',fill=False)
circle3=plt.Circle((10,10),2,color='g',clip_on=False)
ax = plt.gca()
ax.cla() # clear things for fresh plot
# change default range so that new circles will work
ax.set_xlim((0,10))
ax.set_ylim((0,10))
# some data
ax.plot(range(11),'o',color='black')
# key data point that we are encircling
ax.plot((5),(5),'o',color='y')

fig.gca().add_artist(circle1)
fig.gca().add_artist(circle2)
fig.gca().add_artist(circle3)
fig.savefig('plotcircles2.png')

rawDescription: plot a circle with pyplot

description: Plot a circle with pyplot


rawDescription: Place objects in the middle of a frame in tkinter python


rawDescription: Nested python loop revisited

description: Nested python loop revisited


code:
import matplotlib.pyplot as plt
import numpy

# create the data to be shown with "scatter"
yvec, xvec = np.meshgrid(np.linspace(-4.75, 4.75, 20), np.linspace(-4.75, 4.75, 20))
sc_data = random.random((20,20))

# create the data to be shown with "imshow" (20 pixels)
im_data = random.random((20,20))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(im_data, extent=[-5,5,-5,5], interpolation='nearest', cmap=plt.cm.gray)
ax.scatter(xvec, yvec, 100*sc_data)

rawDescription: Aligning two combined plots - Matplotlib


code:
def seq_iter(obj):
    return obj if isinstance(obj, dict) else xrange(len(obj))

x = [1,2,3]
for i in seq_iter(x):
    x[i] = 99

x

x = {1: 2, 2:3, 3:4}
for i in seq_iter(x):
    x[i] = 99

x

rawDescription: Iterate over a dict or list in Python

description: Iterate over a dict or list in Python


code: {'instance': {'environment': 'us-east', 'roles': ['webserver', 'php'], 'awsHostname': 'ip-someip', 'serverName': 'somewebsite.com', 'ipAddr': '192.168.0.1', 'serverId': 'someServer', 'Id': 'i-aaaaaaaa'}}

rawDescription: Converting Python yaml file to dict

description: Converting Python yaml file to dict


code:
import os
os.system('open -a "Microsoft Word.app" path/hello.docx')

rawDescription: How do I open a document (eg. .txt) in another app from a Python Script mac

description: Open a document (eg. .txt) in another app from a Python Script mac


code:
for dir1, dir2 in itertools.product(main_dir, common_dir):
    try: os.makedirs(os.path.join(dir1,dir2))
    except OSError: pass

rawDescription: How to create directories and sub directories efficiently and elegently in Python 2.7?

description: Create directories and sub directories efficiently and elegently in Python 2.7


code:
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

def check_if_merchant(user):
    try:
        user.merchants
    except (AttributeError, ObjectDoesNotExist):
        raise PermissionDenied
    else:
        return True

rawDescription: Restricting User access to different apps in Django


code:
import numpy as np

a = np.array([[0,1,5,6,7],
              [0,4,5,6,8],
              [2,3,5,7,9]])

b = np.array([[5,6],
              [5,7]])

b2 = np.array([[6,7],
               [6,8],
               [7,9]])

def check(a, b, upper_left):
    ul_row = upper_left[0]
    ul_col = upper_left[1]
    b_rows, b_cols = b.shape
    a_slice = a[ul_row : ul_row + b_rows, :][:, ul_col : ul_col + b_cols]
    if a_slice.shape != b.shape:
        return False
    return (a_slice == b).all()

def find_slice(big_array, small_array):
    upper_left = np.argwhere(big_array == small_array[0,0])
    for ul in upper_left:
        if check(big_array, small_array, ul):
            return True
    else:
        return False

rawDescription: Searching a sub-array inside a 2D array (image recognition)


code:
@register.inclusion_tag('Kappa/sidebar.html')
def get_game_list(user):
    return {'game_list': Game.objects.all(),  'user': user}

rawDescription: Template not rendering properly with if user.is_authenticated for Django


code:
def PositiveValuedProperty(name):
    name = "_" + name

    def getter(obj):
        return getattr(obj, name)

    def setter(obj, new_value):
        if new_value < 1:
            new_value = 1
        setattr(obj, name, new_value)

    return property(getter, setter)

rawDescription: Python 3.4 - How to create a template property for many classes


code:
def ibm2ieee(ibm):
    """
    Converts an IBM floating point number into IEEE format.
    :param: ibm - 32 bit unsigned integer: unpack('>L', f.read(4))
    """
    if ibm == 0:
        return 0.0
    sign = ibm >> 31 & 0x01
    exponent = ibm >> 24 & 0x7f
    mantissa = (ibm & 0x00ffffff) / float(pow(2, 24))
    return (1 - 2 * sign) * mantissa * pow(16, exponent - 64)

rawDescription: python: unpack IBM 32-bit float point

description: Python: unpack IBM 32-bit float point


code:
import sys
import os
from stat import *
import pprint

def PathToDict(path):
    st = os.stat(path)
    result = {}
    result['active'] = True
    #result['stat'] = st
    result['full_path'] = path
    if S_ISDIR(st.st_mode):
        result['type'] = 'd'
        result['items'] = {
            name : PathToDict(path+'/'+name)
            for name in os.listdir(path)}
    else:
        result['type'] = 'f'
    return result

pprint.pprint(PathToDict(sys.argv[1]))

rawDescription: Building a dictionary from directory structure


code:
s = input()
s
s.split()
len(s.split())

rawDescription: How to count how many words are in a text string inputted by the user in python

description: Count how many words are in a text string inputted by the user in python


code:
while network.has_key(connections[node1]):
    connections[node1]=network[connections[node1]]

rawDescription: Non Sequential Loop Optimization in Python


code:
class Hidex(object):

    def __init__(self, x):
        self.__x = x

    @property
    def x(self):
            return ~self.__x

    @x.setter
    def x(self, x):
        assert isinstance(x, int), 'val must be int'
        self.__x = ~x

rawDescription: if a property sample work

description: If a property sample work


code:
import datetime
from dateutil import rrule

a = datetime.datetime(2011,8,1)
b = datetime.datetime(2011,8,29)

diff_business_days = len(list(rrule.rrule(rrule.DAILY,
                                          dtstart=a,
                                          until=b - datetime.timedelta(days=1),
                                          byweekday=(rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR))))

rawDescription: Find day difference between two datetimes (excluding weekend days) in Python?


rawDescription: comparing numpy structured arrays

description: Comparing numpy structured arrays


code:
b, val = (True, '123X')
b
val

rawDescription: Check multiple bool values with tuples in python


code:
import ast
datastring = "[{'status': 'Unshipped', 'city': 'New Delhi', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'y_id': 'xxx', 'phone': 'xxx', 'state': 'New Delhi', 'service': 'Expedited', 'amout': '425.00', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '110018', 'shipped_by_y': 'false', 'channel': 'MFN', 'order_type': 'StandardOrder'}, {'status': 'Unshipped', 'city': 'thane', 'buyer_name': 'xxx', 'name': 'xxx', 'countryCode': 'IN', 'payment_method': 'COD', 'y_id': 'xxx', 'phone': 'xxx', 'state': 'Maharashtra', 'service': 'Expedited', 'amout': '350.00', 'address_1': 'xxx', 'address_2': 'xxx', 'postalCode': '400607', 'shipped_by_y': 'false', 'channel': 'MFN', 'order_type': 'StandardOrder'}]\n"
ast.literal_eval(datastring)

rawDescription: Convert string to array of dictionaries

description: Convert string to array of dictionaries


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

rawDescription: Some nudges for a first-time scraper

description: Some nudges for a first-time scraper


code: target_dir = os.path.join(current_dir, '..', '..')

rawDescription: Pull files into script from two directories back


code:
functions = [(foo, foo_kill), (bar, bar_kill), ] # Just append more as needed
while True:
    for f, kf in functions:
        f()
        time.sleep(1800)
        kf()

rawDescription: Python: Alternating functions every x minutes


code:
events = []
for l in Location.objects.select_related().all():
    events.append( l.event_set.order_by( start_date ).all()[0] )

rawDescription: Problem writing a database query

description: Problem writing a database query


code:
columns_to_drop = ['a.1', 'b.1', ... ]
df = df[[col for col in df.columns if col not in columns_to_drop]]

rawDescription: how to delete a duplicate column read from excel in pandas

description: Delete a duplicate column read from excel in pandas


rawDescription: join two pandas dataframe using a specific column

description: Join two pandas dataframe using a specific column


code:
[constants]
key = value
x = 0
y = 1

rawDescription: python initialization of constants in separate file

description: Python initialization of constants in separate file


rawDescription: Scrapy scraping content of td with multiple td's of same class


code: [input_string.split().index(i) for i in keywords if i in input_string.split()]

rawDescription: Finding an index of one of alternative keywords


code: data = dict({dict_key: value})

rawDescription: python dictionary keys

description: Python dictionary keys


code:
import  csv
from operator import itemgetter
from tempfile import NamedTemporaryFile
from shutil import move

with open("edsa_data.csv") as f, NamedTemporaryFile(dir=".", delete=False) as tmp:
    # itertools.imap python2
    csv.writer(tmp).writerows(map(itemgetter(3, 5, 7, 9), csv.reader(f)))
move(tmp.name, "edsa_data.csv")

rawDescription: fast, accurate, reliable way to remove undesirable values from a csv file

description: Fast, accurate, reliable way to remove undesirable values from a csv file


code: [do_stuff(a, b) for a, b in itertools.permutations(A, 2)]

rawDescription: How to do C++ style(indexed) nested loops in python?

description: Do C++ style(indexed) nested loops in python


code:
create_OuterClass: {u'__InnerClass__': True, u'name': u'Joe', u'value': 12}
create_OuterClass: {u'__InnerClass__': True, u'name': u'Jimmy', u'value': 7}
create_OuterClass: {u'__OuterClass__': True, u'InnerClass_instances': [{u'__InnerClass__': True, u'name': u'Joe', u'value': 12}, {u'__InnerClass__': True, u'name': u'Jimmy', u'value': 7}], u'arg': 4}

rawDescription: Python and JSON: using object_hook to do class hinting for multiple different classes


code:
def min_change(V, C):
    table, solution = min_change_table(V, C)
    num_coins, coins = table[-1], []
    if num_coins == float('inf'):
        return []
    while C > 0:
        coins.append(V[solution[C]])
        C -= V[solution[C]]
    return coins

def min_change_table(V, C):
    m, n = C+1, len(V)
    table, solution = [0] * m, [0] * m
    for i in xrange(1, m):
        minNum, minIdx = float('inf'), -1
        for j in xrange(n):
            if V[j] <= i and 1 + table[i - V[j]] < minNum:
                minNum = 1 + table[i - V[j]]
                minIdx = j
        table[i] = minNum
        solution[i] = minIdx
    return (table, solution)

rawDescription: Finding shortest combinations in array/sequence that equals sum


code:
def foo(bar):
    globals()['bar'] = bar + 1
foo(1)
print(bar) # prints 2

rawDescription: Why would people use globals() to define variables


code:
ul = soup.find(attrs={"id": "mgioLangList"})
items = [li.extract() for li in ul.find_all("li")]
items.sort(key=lambda e: e.find(attrs={"class": "mgioAutonymEnglish"}).string)
for linebreak, li in reversed(list(zip(ul.contents, items))):
    linebreak.insert_after(li)

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


code:
def normalizeangle(radians):
    return divmod(radians, math.pi*2)[1]

def arclength(radians1, radians2 = 0):
    radians1, radians2 = normalizeangle(radians1), normalizeangle(radians2)
    return min(normalizeangle(radians1 - radians2), normalizeangle(radians2 - radians1))

def arcdir(radians1, radians2 = 0):
    radians1, radians2 = normalizeangle(radians1), normalizeangle(radians2)
    return cmp(normalizeangle(radians1 - radians2), normalizeangle(radians2 - radians1))

rawDescription: Gift Wrapping Algorithm in Python never terminating


code:
import pandas as pd
import csv
import time
def procedure():
    time.sleep(0)
start_time = time.time()
y=pd.DataFrame({'one':[1,2,3,4],'two':[3,5,7,5],'three':[2,3,4,9],'four':[4,3,1,0],})
y.to_csv('temp1.csv')
procedure()
finish_time = time.time() - start_time
print (finish_time)

rawDescription: Python: Add Processing Time to Output CSV File


code:
mask = ~np.in1d(df.index.date, pd.to_datetime(removelist).date)
df = df.loc[mask, :]

rawDescription: Fastest way to eliminate specific dates from pandas dataframe


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

# some data (512x512)
import scipy.misc
data = scipy.misc.lena()

# a colormap and a normalization instance
cmap = plt.cm.jet
norm = plt.Normalize(vmin=data.min(), vmax=data.max())

# map the normalized data to colors
# image is now RGBA (512x512x4)
image = cmap(norm(data))

# save the image
plt.imsave('test.png', image)

rawDescription: Saving an imshow-like image while preserving resolution


code:
from urlparse import parse_qsl
s = '127.0.0.1 - - [24/Feb/2014:03:36:46 +0100] "POST /info HTTP/1.1" 302 0 "http://website.com" "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36" "name=josh&zipcode=12345"'
params = parse_qsl(s.split()[-1].strip('"'))
params

rawDescription: Get string inbetween text Python

description: Get string inbetween text Python


rawDescription: Convert BNF grammar to pyparsing

description: Convert BNF grammar to pyparsing


code: "Financial Assets:" in searchlines[m-5:m+5]

rawDescription: How can I search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python?

description: Search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python


code:
from __future__ import print_function  #same code for Py2 Py3
import timeit
import collections

z='string'*10
def f1(tgt,rot=3):
    return tgt[rot:]+tgt[:rot]

def f2(tgt,rot=3):
    y=collections.deque(tgt)
    y.rotate(rot)
    return ''.join(y)

print(f1(z)==f2(z))    # Make sure they produce the same result
t1=timeit.timeit("f1(z)", setup="from __main__ import f1,z")
t2=timeit.timeit("f2(z)", setup="from __main__ import f2,z")
print('f1: {:.2f} secs\nf2: {:.2f} secs\n faster is {:.2f}% faster.\n'.format(
           t1,t2,(max(t1,t2)/min(t1,t2)-1)*100.0))

rawDescription: How to "convert" a dequed object to string in Python?


code:
class NewsletterSubscriber(...):
    ...
    hash = models.CharField(blank=True, max_length=150)

    def save(self, *args, **kwargs):
        if not self.pk: # this will ensure that the object is new
            self.hash = createNewsLetterHash(self.email)
        super(NewsletterSubscriber, self).save(*args, **kwargs)

rawDescription: How to pass django model field value as an argument to callable which is default of field in the same model?

description: Pass django model field value as an argument to callable which is default of field in the same model


code:
from PyQt4 import QtGui, QtCore

class TestWidget(QtGui.QWidget):
    textSaved = QtCore.pyqtSignal(str)

    def __init__( self, parent = None ):
        super(TestWidget, self).__init__(parent)

        # create the ui (or load it)
        self.__edit   = QtGui.QTextEdit(self)
        self.__button = QtGui.QPushButton(self)
        self.__button.setText('Save')

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.__edit)
        layout.addWidget(self.__button)
        self.setLayout(layout)

        # create connections
        self.__button.clicked.connect(self.emitTextSaved)

    def emitTextSaved( self ):
        # allow Qt's blocking of signals paradigm to control flow
        if ( not self.signalsBlocked() ):
            self.textSaved.emit(self.__edit.toPlainText())

rawDescription: PyQt Multiple Windows - how to pass functions between modules Qt Designer


code: mydict = {'5min': '5-Min', '1hour': 'Hour', '1day': 'Day'}

rawDescription: Jinja2 to put a whole element in <option>


code:
with open('data.json') as datafile:
    data = json.loads(datafile.read())

rawDescription: diagnosing when I'm being limited by disk i/o

description: Diagnosing when I'm being limited by disk i/o


rawDescription: how do I parse a specific string in python

description: Parse a specific string in python


code: vim.command("normal! V")

rawDescription: "scripting" vim using python with greater granularity


code:
with open('spam.txt', 'w') as f:
    pickle.dumps(f)

rawDescription: Create object that cannot be pickled

description: Create object that cannot be pickled


code:
from itertools import izip, chain

def replace2copy(lst):
    lst1, lst2 = tee(iter(lst), 2)
    return list(chain.from_iterable(izip(lst[1::2], lst[::2])))

rawDescription: Python list: exchange every n-th value with the (n+1)th


code:
machList = [1,5,3]

def machToFPS(machList):
    FPS = map(lambda x: x*1116.4370079,machList)
    for i,x in enumerate(FPS):
        print('{} mach(s) is equivalent to {} feet per second.'.format(machList[i], x))

machToFPS(machList)

rawDescription: Formatting with the map() function in Python


code:
class App(...):
    ...
    def compute():
        ...
        result = self.square(self.var.get())
        self.results.append(result)

rawDescription: Python - returning from a Tkinter callback


code: env = Environment(variable_start_string="{", variable_end_string="}")

rawDescription: Python 3 - Replacing part of a string with imformation from the string


code:
top6 = totals.order(ascending=False).head(6)
top6

rawDescription: What is the fastest way to do greedy set cover with Pandas?


code:
def hello():
    print('hello')

rawDescription: How to import all imports of another .py file

description: Import all imports of another .py file


rawDescription: Pandas calcuating percentage in data summary


code:
#File1.py
import os

#use os somewhere:
os.path.chdir(some_dir)
...
...
#use os somewhere else, you don't need to "import os" everywhere
os.environ.update(some_dict)

rawDescription: import module_name Vs __import__('module_name')

description: Import module_name Vs __import__('module_name')


code:
import code
console = code.InteractiveConsole()
r = console.push('1+1')
r = console.push('x = 4 + 1')
r = console.push('x + 10')
r = console.push('def test(n):')
r = console.push('  return n + 5')
r = console.push('')
r = console.push('test(10)')

rawDescription: Make Python's Interactive Interpreter Class Print Evaluated Expressions


code: stations = [x for x in (x.strip() for x in data) if x]

rawDescription: Pythonic list comprehension possible with this loop?


code:
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.integrate

tmax = 10.0

def a(t):
    if t < tmax / 2.0:
        return ((tmax / 2.0) - t) / (tmax / 2.0)
    else:
        return 1.0

def func(x, t, a):
    return - (x - a(t))

x0 = 0.8
t = np.linspace(0.0, tmax, 1000)
args = (a,)
y = sp.integrate.odeint(func, x0, t, args)

fig = plt.figure()
ax = fig.add_subplot(111)
h1, = ax.plot(t, y)
h2, = ax.plot(t, [a(s) for s in t])
ax.legend([h1, h2], ["y", "a"])
ax.set_xlabel("t")
ax.grid()
plt.show()

rawDescription: Solving a system of odes (with changing constant!) using scipy.integrate.odeint?


code:
with (context_manager) as something:
    do_stuff()

try:
    context_manager.__enter__()
    do_stuff()
finally:
    context_manager.__exit__()

rawDescription: Conditionally writing to different output files


code: t = [list(filter(lambda x: len(x) > 2, string)) for string in s]

rawDescription: Converting this filter statement to list comprehension


code:
def biggest_even_number(xs):
    l = [i for i in xs if i % 2 == 0]
    return reduce(max, l, float("-inf"))

rawDescription: Largest even number in a list using fold


code:
def minimun_path(s,G,camino,cMax,cMin):
    if len(camino) == G.number_of_nodes():
        # I found the complete path
        return camino
    temp = []
    for son in G.neighbors(s):
        # I record all path to a node not visited yet
        if son not in camino:
            peso = weight_of(son,G,s)+cMin
            temp.append( (son,peso) )
    if temp:
        # I choose a minimun of those
        sig,w = min( temp, key=lambda x:x[1])
    else:
        # I don't have where to go, so I stay put
        sig = s
    return minimun_path(sig,G,camino+(s,),cMax,cMin)

rawDescription: how to make undo in backtracking? I'm having problems with the recursively backtracking method

description: Make undo in backtracking? I'm having problems with the recursively backtracking method


rawDescription: Finding repeated values in multiple lists


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

# import data with loadtxt, but only the relevant floats.
# data.csv is the file as you have given it above
data = np.loadtxt('data.csv', delimiter=',', skiprows = 1, usecols = range(1,5))
data = data.transpose()

# import the tick labels
xt = np.loadtxt('data.csv', dtype='str', delimiter=',', skiprows = 1, usecols = (0,))

rawDescription: Creating bar chart with CSV data

description: Creating bar chart with CSV data


code:
wavelengths = data[0]
intensities = data[1:]

rawDescription: Loading .txt data into 10x256 3d numpy array


code:
class return_t:
  pass
def analyze(log):
  ret_val = return_t()
  ret_val.values = list_of_values
  ret_val.timestamps = list_of_timestamps
  ret_val.avg_coffee_consumption = 12e9
  return ret_val
...
result = analyze(l)
coffee_used = ret_val.avg_coffee_consumptions * (max(ret_val.timestamps) - min(ret_val.timestamps))

rawDescription: Best approach for extensible return object in python


code:
# recompress
compressed[:] = expanded.view('uint8').reshape(-1,4)[:,:3]

rawDescription: Custom size array

description: Custom size array


code: { p.id : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}

rawDescription: How can I get the index value of a list comprehension?

description: Get the index value of a list comprehension


code:
from itertools import imap
r = imap(lambda x: x+1, [1,2,3])
r
list(r)
r = map(lambda x: x+1, [1,2,3])
r

rawDescription: multiprocessing imap suprress child process print

description: Multiprocessing imap suprress child process print


code:
from random import randint

def dice(trials, numbers):
    results = {} #createe empty dictionary
    for throw in range(trials):
        thrown = randint(1, numbers)
        try:
            results[thrown] += 1
        except:
            results[thrown] = 1
    return results

def histogram(d):
    keylist=sorted(d)
    lo=keylist[0]
    while d[lo]==0:
        lo+=1
    hi=keylist[-1]
    while d[hi]==0:
        hi -=1
    for k in range (lo,hi+1):
        print("%3i : %3i : %s" % (k,d[k],d[k]*"*"))

histogram(dice(10, 6))

rawDescription: Performing sum of dice and generating the percentage with histogram


code: isinstance(a, tuple)

rawDescription: Python does not recognize the type of a namedtuple


code: reduce(operator.getitem, index, mylist)

rawDescription: Using a list as "list of indexes" to address elements of another list


code:
def round(x):
    return (x//10)*10

round(15.)
round(25.)

rawDescription: Round integer in python without using round()


code:
# -*- coding: iso-8859-1 -*-
import subprocess, sys

p = subprocess.Popen(["powershell.exe",
              "C:\\Users\\USER\\Desktop\\helloworld.ps1"],
              stdout=sys.stdout)
p.communicate()

rawDescription: Running powershell script within python script, how to make python print the powershell output while it is running


rawDescription: Benefits of panda's multiindex?

description: Benefits of panda's multiindex


code:
ans = []

ans

rawDescription: In python, how to group elements together, based on a key (group adjacent)?


code:
mergelist = lambda lVals: reduce(lambda res,x: res + x, map(tuple, lVals))
diff = set(a) ^ set(b) # would contains difference between two initial lists

rawDescription: Find a particular list inside a list of lists


rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


code:
import MyFuncs.utilFunctions
from MyFuncs.Views import views
import MyFuncs.uselessFunctions as nonsenseFunctions

rawDescription: How to create a functions py and call those functions?

description: Create a functions py and call those functions


code:
#-*- coding: UTF-8 -*-
from gi.repository import Gtk

class App(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title='ComboBox Test')

        model = Gtk.ListStore(int, str, str)
        for i in [[1, 'One', '#FF0000'], [2, 'Two', '#00FF00'], [3, 'Three', '#0000FF'], [4, 'Four', '#FFFF00']]:
            model.append(i)

        combo = Gtk.ComboBox.new_with_model(model)
        renderer = Gtk.CellRendererText()

        combo.set_active(0)
        combo.pack_start(renderer, True)
        combo.add_attribute(renderer, 'text', 1)
        combo.add_attribute(renderer, 'foreground', 2)
        combo.connect('changed', self._changed_cb)

        self.add(combo)

    def _changed_cb(self, combo, param=None):
        comboiter = combo.get_active_iter()
        if comboiter:
            print("Changed to {}".format(
                     combo.get_model().get_value(comboiter, 0)
            ))
        else:
            print("Nothing selected!")

win = App()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: Show drop-down list without entry by using PyGObject ComboBox


code:
from collections import OrderedDict
dct = OrderedDict({'name1':[3],'name2':[1],'name3':[2]})
dct = OrderedDict(sorted(dct.items(), key=lambda t: t[1][0], reverse = True))
print(dct)

rawDescription: How to sort a dictionary by descending order numerically

description: Sort a dictionary by descending order numerically


code: d.groupby(level=[0, 1]).apply(lambda t: stats.mannwhitneyu(t.course1, t.course2))

rawDescription: Mann–Whitney U test on Pandas dataframe

description: Mann–Whitney U test on Pandas dataframe


rawDescription: How to use a bash variable in python

description: Use a bash variable in python


code: [name for name in starring if name.strip()]

rawDescription: Remove strings containing only white spaces from list


code: myvar =  request.form["myvar"]

rawDescription: How to obtain values of request variables using Python and Flask

description: Obtain values of request variables using Python and Flask


code:
import re
splitter = re.compile(r'\n')

bash_history_array = splitter.split(bash_history_text)

rawDescription: reading .bash_history file through python script

description: Reading .bash_history file through python script


code:
ax.fill_between( temps.index, y1=temps.T.max(), y2=temps.T.min(), color='gray', alpha=0.5)

ax.set_ylabel('temperature [°C]')
ax.set_xlabel('measuring date')
ax.set_ylim([15,25])

plt.savefig('plot.png')

rawDescription: python plot distribution across mean

description: Python plot distribution across mean


rawDescription: Python urllib requesting multiple times

description: Python urllib requesting multiple times


code:
get_x = lambda: foo_instance.bar
get_x() # yahoo!

rawDescription: Create a reference to a variable (similar to PHP's "=&")?


code:
for r1, r2 in window(dm_revisions):
    summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)

rawDescription: Python looping: idiomatically comparing successive items in a list


code:
def parse(s):
    return [slice(*map(int, x.split(':'))) for x in s.split(',')]

rawDescription: pythonic format for indices

description: Pythonic format for indices


code:
def my_average(a, b):
    return div(add(a, b), 2)

rawDescription: Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins


code:
packed_data = ''.join(chr(int(asciiString[i:i+8], 2))
                         for i in range(0, len(asciiString), 8))

rawDescription: Huffman encoding: how to write binary data in Python


code:
# we don't actually do this:
combination[r-1] += 1

rawDescription: Generating non-consecutive combinations

description: Generating non-consecutive combinations


code:
df.groupby('team').apply(lambda x: ', '.join(x.user))
df.groupby('team').apply(lambda x: list(x.user))

rawDescription: Replicating GROUP_CONCAT for pandas.DataFrame


code:
if len(line) <= int(maxLength):
    match = True
    for l, c in counter.items():
        if line.count(l) < c:
            match = False
            break
    if match:
        listOfWords.append(line)

rawDescription: Compare two strings, including duplicate letters?


code:
struct.unpack('>I', '\xFF\xFF\xFF\xFF')  # >, !: big (network) endian
hex(struct.unpack('>I', '\xFF\xFF\xFF\xFF')[0])
struct.unpack('>H', '\x00\xff')
'0x{:04x}'.format(struct.unpack('>H', '\x00\xff')[0])
'0x{:04X}'.format(struct.unpack('>H', '\x00\xff')[0])

rawDescription: Convert a string of escaped hex to a hex number in Python


code:
hand=urllib.request.urlopen("http://www.pythonlearn.com/code/mbox-short.txt")
qq = hand.read().decode('utf-8')
max(re.findall("^X-DSPAM-Confidence: ([0-9.]+)",qq, re.M),key=float)

rawDescription: Reading Text File From Webpage by Python3


code:
import pyparsing
strings = pyparsing.Word(pyparsing.alphanums)
parens  = pyparsing.nestedExpr( '(', ')', content=strings)
parens.parseString('(NP (NNP Hoi) (NN Hallo) (NN Hey) (NNP (NN Ciao) (NN Adios)))').asList()

rawDescription: How to find all possible regex matches in python?

description: Find all possible regex matches in python


code: myOutput=subprocess.Popen("C:\\usr\\local\\bin\\att\\compare.exe -metric AE -fuzz 100 1.png 2.png mask.png", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

rawDescription: Problem getting terminal output from ImageMagick's compare.exe ( Either by pipe or Python )


code:
def to_sql_k(self, frame, name, if_exists='fail', index=True,
           index_label=None, schema=None, chunksize=None, dtype=None, **kwargs):
    if dtype is not None:
        from sqlalchemy.types import to_instance, TypeEngine
        for col, my_type in dtype.items():
            if not isinstance(to_instance(my_type), TypeEngine):
                raise ValueError('The type of %s is not a SQLAlchemy '
                                 'type ' % col)

    table = pd.io.sql.SQLTable(name, self, frame=frame, index=index,
                     if_exists=if_exists, index_label=index_label,
                     schema=schema, dtype=dtype, **kwargs)
    table.create()
    table.insert(chunksize)

rawDescription: Python Pandas to_sql, how to create a table with a primary key?


code:
import numpy as np
from numpy.random import rand

def pylu3d(A):
    N = A.shape[1]
    for j in xrange(N-1):
        for i in xrange(j+1,N):
            #change to L
            A[:,i,j] /= A[:,j,j]
            #change to U
            A[:,i,j+1:] -= A[:,i,j:j+1] * A[:,j,j+1:]

def pylusolve(A, B):
    N = A.shape[1]
    for j in xrange(N-1):
        for i in xrange(j+1,N):
            B[:,i] -= A[:,i,j] * B[:,j]
    for j in xrange(N-1,-1,-1):
        B[:,j] /= A[:,j,j]
        for i in xrange(j):
            B[:,i] -= A[:,i,j] * B[:,j]

#usage
A = rand(1000000,3,3)
b = rand(3)
b = np.tile(b,(1000000,1))
pylu3d(A)
# A has been replaced with the LU decompositions
pylusolve(A, b)
# b has been replaced to the solutions of
# A[i] x = b[i] for each A[i] and b[i]

rawDescription: Vectorized (partial) inverse of an N*M*M tensor with numpy


code:
outFileContents = {} # This will be a dict, where number -> content of test_number.dat
for outFileName in range(1,41): #outFileName will be the number going after the _ in your filename
    outFileContents[outFileName] = []
    for n in range(40): # Counting through the time blocks
        currentRowIndex = (42 * n) + outFileName # 42 to account for the Time = and blank row
        outFileContents[outFileName].append(fileList[currentRowIndex])

rawDescription: Complex parsing query

description: Complex parsing query


code:
xyslice = slice(x,15), slice(y,15)
empty_lattice[xyslice] = fill_cell(empty_lattice[xyslice],...)

rawDescription: Python: how to create a submatrix discretizing a circle?


code:
data = [df.iat[i, j]
        for i in range(len(conds))
        for j in range(i + 1, len(conds))]

rawDescription: Improvement in pandas dataframe conversion in Python


code: list(map(hash, range (1 , 6)))

rawDescription: How to get values from a map and set them into a numpy matrix row?

description: Get values from a map and set them into a numpy matrix row


code: Comp_Key, x, y, z= dict((A, B, C, [x,y,z]) for A, B, C, x, y, z in result)

rawDescription: AMPL vs. Python - Importing tables (multi-dimensional dictionaries?)


rawDescription: sort list of objects by return of object method

description: Sort list of objects by return of object method


code: d["gymnasium"]["weights"] = 15

rawDescription: Python: Dictionary within dictionary?

description: Python: Dictionary within dictionary


code:
zipped = itertools.chain.from_iterable(zip(*[part.split("|") for part in group]) for group in hapts)
["|".join(values) for values in zipped]

rawDescription: Zip string-subset from tuples in a list

description: Zip string-subset from tuples in a list


code:
words = ['hey', 'hi', 'hello', 'hi']
result = []
for word in reversed(words):
    if word not in result:
        result.append(word)
print(result)

rawDescription: Making a new list from an existing list

description: Making a new list from an existing list


code: a = {k: v / total for total in (sum(a.itervalues(), 0.0),) for k, v in a.iteritems()}

rawDescription: Divide each python dictionary value by total value


code:
for d in result:
    d.update((k, {1:"Yes", 0:"No"}[v]) for k, v in d.iteritems() if v in (1,0) and k in ("is_diabetic", "is_inpatient"))

rawDescription: Updating values for only certain keys in a list of dicts in python


rawDescription: Best way to show a list of empty tuples

description: Show a list of empty tuples


code:
def groupTPL(TPL, distance=1):
    U = UnionFind()

    for (i, x) in enumerate(TPL):
        for j in range(i + 1, len(TPL)):
            y = TPL[j]
            if max(abs(x[0] - y[0]), abs(x[1] - y[1])) <= distance:
                U.union(x, y)

    disjSets = {}
    for x in TPL:
        s = disjSets.get(U[x], set())
        s.add(x)
        disjSets[U[x]] = s

    return [list(x) for x in disjSets.values()]

rawDescription: Group a list of points/tuples

description: Group a list of points/tuples


code:
[i for i, t in enumerate(zip(tuple1, tuple2), 1) if t[0]!=t[1]]
[i for i, t in enumerate(zip(tuple1, tuple3), 1) if t[0]!=t[1]]
[i for i, t in enumerate(zip(tuple2, tuple3), 1) if t[0]!=t[1]]

rawDescription: Element by element comparison in tuple to return set of sets - python


code:
src_match('

','myfile.png')
src_match('
<img src="myfile.anotherword.png" alt="beat-divisions.tiff"
\n','myfile.anotherword.png')

rawDescription: how to match an image tag's link with regex

description: Match an image tag's link with regex


code:
import pandas.io.data as web
import datetime as dt
import pandas as pd

end_date = dt.datetime.now().date()
start_date = end_date - pd.DateOffset(years=5)

symbols = ['AAPL', 'IBM', 'GM']
prices = web.get_data_yahoo(symbols=symbols, start=start_date, end=end_date)['Adj Close']
returns = prices.pct_change()
rolling_corr = pd.rolling_corr_pairwise(returns, window=20)

rawDescription: Rolling Mean of Rolling Correlation dataframe in Python?


code:
sql = '''select * from  Table-A a
         left join Table-B b
         on (a.sec1 = b.sec1)
         where DATE_SUB(CURDATE(),INTERVAL 12 MONTH) <= dt
         group by 1,2,3,4,5,6,7'''
result = pd.read_sql(sql, engine)

rawDescription: pass pandas dataframe as parameter in mysql query

description: Pass pandas dataframe as parameter in mysql query


code:
threading.current_thread().__class__.__name__ = 'Grrrr'
assert threading.current_thread().__class__.__name__ == '_MainThread' # will fail

rawDescription: Check if current thread is main thread, in Python


code:
[k for k,g in groupby(a) if len(list(islice(g,0,2)))==2]
['a', 'c']

rawDescription: Repeating elements in list Python

description: Repeating elements in list Python


rawDescription: Print current call stack from a method in Python code


code: locations = [results['moments'][i][5] for i in xrange(len(results['moments']))]

rawDescription: getting JSON data from python several levels deep without names

description: Getting JSON data from python several levels deep without names


code:
# parse the 3rd column (index 2) as dates
df = pd.read_csv('import.csv', skipinitialspace=True, usecols=fields, parse_dates=[2])
last_movement = df.sort_values('Posting date').groupby('Serial number').last()

rawDescription: Python CSV data analysis based on date time


code:
class MyWorksheet(xlsxwriter.Workbook):

    def __init__(self, *args, **kwargs):
        [...]
        super(MyWorksheet, self).__init__(*args, **kwargs)
        self.sheets = {}
        [...]

    def add_worksheet(self, name):
        [...]
        self.sheets[name] = super(MyWorksheet, self).add_worksheet(name)
        [...]

    def create_footer(self, sheet_name, suma_cell, starting_row, flag):
        [...]
        self.sheets[sheet_name].write(row, 4, "Test")
        [...]

rawDescription: Using "object" of mainfile, in function saved in other file


code:
@memoize
class Test(object):
    def __init__(self, somevalue):
        self.somevalue = somevalue

rawDescription: How can I memoize a class instantiation in Python?

description: Memoize a class instantiation in Python


code:
import tkinter as tk
import time

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.frame = tk.Frame(self)
        self.frame.pack(side="top", fill = "both", expand=True)

        self.label = tk.Label(self, text = "Hello, world")
        button1 = tk.Button(self, text = "Start to do something",
                                  command = self.do_something)
        self.label.pack(in_=self.frame)
        button1.pack(in_=self.frame)

    def do_something(self):
        self.label.config(text = "Wait till I'm done...")
        self.label.update_idletasks()
        time.sleep(2)
        print ("end sleep")
        self.label.config(text = "I'm done doing...")

def main():
    app = SampleApp()
    app.mainloop()
    return 0

if __name__ == '__main__':
    main()

rawDescription: how to show a loading message in tkinter

description: Show a loading message in tkinter


code:
from functools import singledispatch
@singledispatch
def fun(arg, verbose=False):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)
@fun.register(int)
def _(arg, verbose=False):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)
@fun.register(list)
def _(arg, verbose=False):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)

rawDescription: Proper way to make functions extensible by the user


code:
with  open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
    players = {}
    for row in csv.reader(pf):
        key = row[0]
        if key in players:
            continue
        players[key] = row
    rankings = csv.reader(rf)
    for i in islice(rankings, None, 10):
        player = players.get(i[2])

rawDescription: Python large multi-list efficient query

description: Python large multi-list efficient query


code:
def search_filter(src, term):
    term = term.lower()
    for s in src:
        if any(term in v.lower() for v in s.values()):
            yield s

rawDescription: Finding a small list of strings in a large list of strings (Python)


code: fn(installation_name, *args, **kwargs)

rawDescription: Creating a Decorator

description: Creating a Decorator


rawDescription: Complicated sorting in Python

description: Complicated sorting in Python


code:
from itertools import product
one_hot_interaction_names = ["%s___%s" % (column1, column2)
                             for column1, column2 in product(state_names, state_names)]

rawDescription: How can an interaction design matrix be created from categorical variables?


code:
def download_image(url):
    # code to get image goes here
    # save image to disk
    # get file size or check if it exists
    if file_ok:
        return True
    else:
        return False

rawDescription: Different statements depending on exit status of code


code: plot_tree(P, range(10))

rawDescription: how do I get the subtrees of dendrogram made by scipy.cluster.hierarchy

description: Get the subtrees of dendrogram made by scipy.cluster.hierarchy


rawDescription: Combinations between values of lists

description: Combinations between values of lists


code:
# everything here is the same
def foo():
    return 'foo'

def bar():
    return foo(), 'bar'

rawDescription: Wrapping a function imported with import *?


rawDescription: Ensuring Unique Fields when Randomly Generating MySQL rows


code: zf.extract(filename, path)

rawDescription: Python opening a File within a Zip File

description: Python opening a File within a Zip File


code:
import random
r = random.SystemRandom()
bin(r.getrandbits(2000))[2:].zfill(2000)
bin(r.getrandbits(2000))[2:].zfill(2000)
bin(r.getrandbits(2000))[2:].zfill(2000)

rawDescription: Multiplying a huge number times random() (Python)


code: b is a

rawDescription: What does python sys.intern do, and when should it be used?


code: element = browser.find_elements_by_xpath("//div[@style='visibility: visible; display: block;']/iframe[@style='height: 600px;']")

rawDescription: Best way to locate this element in selenium?

description: Locate this element in selenium


rawDescription: Defining a function from IDL in Python

description: Defining a function from IDL in Python


code:
# Generic tokenizer (if you don't use NLTK's)
def word_tokenize(raw):
    return raw.split()

rawDescription: Match items in list to string: How to evaluate the F1 ratio of Alchemy API NER result? Python


code:
Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1

rawDescription: Python Reading a file and printing

description: Python Reading a file and printing


code: plt.plot(a, mlab.normpdf(a, np.mean(a), np.std(a)), 'o')

rawDescription: Smoothening a normal/gaussian plot in matplotlib


code: [t[1] for t in inputlist]

rawDescription: Python values out of list

description: Python values out of list


code:
import csv
func(**{k: int(v) for k, v in csv.reader(sys.argv[1:], delimiter='=')})

rawDescription: Python: Using run time inputs to change key values in a function


code:
for cell_entry in cells.entry:
    row = int(cell_entry.cell.row) - 2
    col = int(cell_entry.cell.col)

    if 0 <= row < len(events_map):
        cell_entry.cell.inputValue = rows_map[row][col]
    else:
        cell_entry.cell.inputValue = ''

    batch_request.AddUpdate(cell_entry)

rawDescription: Add multiple rows into google spreadsheet using API


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cherrypy

class App:

  @cherrypy.expose
  def index(self):
    '''Make some traffic'''
    return ('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean quis laoreet urna. '
      'Integer vitae volutpat neque, et tempor quam. Sed eu massa non libero pretium tempus. '
      'Quisque volutpat aliquam lacinia. Class aptent taciti sociosqu ad litora torquent per '
      'conubia nostra, per inceptos himenaeos. Quisque scelerisque pellentesque purus id '
      'vulputate. Suspendisse potenti. Vestibulum rutrum vehicula magna et varius. Sed in leo'
      ' sit amet massa fringilla aliquet in vitae enim. Donec justo dolor, vestibulum vitae '
      'rhoncus vel, dictum eu neque. Fusce ac ultrices nibh. Mauris accumsan augue vitae justo '
      'tempor, non ullamcorper tortor semper. ')

cherrypy.tree.mount(App(), '/')

rawDescription: Python web server (CherryPy) scaling concurrent requests on AWS


rawDescription: How to print 3 lines with the highest values

description: Print 3 lines with the highest values


code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.rcParams['legend.handlelength'] = 0
x1 = y1 = np.linspace(0, 10, 100)
x2 = np.sin(x1)
y2 = np.cos(y1)
plt.plot(x1,x2,'g--^', label='regional')
plt.plot(y1,y2,'b-o', label='local')
plt.legend(loc='best', numpoints=1)
plt.show()

rawDescription: Python plot legend : markers appear twice


code: [{'id1': k, 'price': v['price'], 'colors': v['colors']} for k, v in temp.items()]

rawDescription: Merge values of same key, in list of dicts


rawDescription: Tkinter: How can I dynamically create a widget that can then be destroyed or removed?


code:
import re
str = 'name: phil age : 23 range: 33, 45 address: "main ave US"'
re.findall(r'\w+\s*:\s*(?:"[^"]*"|.*?(?=\w+\s*:\s*|$))', str)

rawDescription: Split on space but not if there is a colon followed by space or if there is a space in quotes


rawDescription: Best way to turn a list of lists into a more nested list of lists of lists with equal length?

description: Turn a list of lists into a more nested list of lists of lists with equal length


code:
csvfile = csv.reader(open('foo.csv', 'rb'))
set1 = set(rec[3] for rec in csvfile)   # Assuming mac-address is the 4th column.

rawDescription: Script to compare a string in two different files


code:
my_list.sort(key=lambda x: x[2])

my_list.sort(key=lambda x: x.method())

rawDescription: Order list by queryset count in Django/Python


rawDescription: Assigning int values to each dictionary entry as well as having reference numbers?


code:
import numpy as np

data = np.genfromtxt('data')
data[data == 0] = np.nan
means = np.nanmean(data[:, 1:], axis=1)

rawDescription: Finding an average but ignoring any zero in a list [Python]


code:
user_profile = service.users().getProfile(userId='me').execute()
user_email = user_profile['emailAddress']

rawDescription: Get Google Account email address based on user_id


code: df = df.fillna(0)

rawDescription: Handle Nan when using Pandas ExcelWriter in python


code:
l = [x for y in range(3) for x in list(permutations('1397', y))]
l

rawDescription: Multi-variable List Comprehension

description: Multi-variable List Comprehension


code: crdscl = thescale[:]

rawDescription: list[i] in "for" statement does not return the right values

description: List[i] in "for" statement does not return the right values


code:
import csv, os

with open('path/to/filename') as inf, open('path/to/filename_temp', 'w') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for line in reader:
        if line[1] == '0':
           ...
        ... # as above

os.remove('path/to/filename')
os.rename('path/to/filename_temp', 'path/to/filename')

rawDescription: Python - Replacing value of a row in a CSV file


rawDescription: Python: Cyrllic handling

description: Python: Cyrllic handling


code:
mydf["Campaign"]
dict(mydf["Campaign"])
2 in dict(mydf["Campaign"])
"Campaign X" in dict(mydf["Campaign"])
2 in mydf["Campaign"]
"Campaign X" in mydf["Campaign"]

rawDescription: Why is get_values() needed in a membership test on a pandas DataFrame column?


code: ['hattrick', 'google', 'wampum', 'newcom']

rawDescription: removing first four and last four characters of strings in list, OR removing specific character patterns

description: Removing first four and last four characters of strings in list, OR removing specific character patterns


code:
from django import forms
class MyForm(forms.Form):
    ReadonlyBoolField = forms.BooleanField(initial = True)
    ReadonlyBoolField.widget.attrs['readonly'] = True

rawDescription: Disabling BooleanField's change in django forms


code:
from time import strptime

def transform(data_frame):
    time = strptime(data_frame, "%I:%M %p")
    hour = time.tm_hour
    if time.tm_min >= 30:
        if hour < 23:
            hour += 1
        else:
            hour = 0
    return hour

values = "12:51 AM", "1:51 AM", "2:03 AM", "4:23 PM"

for value in values:
    print(transform(value))

rawDescription: Python datetime transform

description: Python datetime transform


code:
AUTHENTICATION_BACKENDS = (
    'my_website.my_app.my_file.MyUserAuthBackend',
)

rawDescription: Migrating a password field to Django

description: Migrating a password field to Django


rawDescription: Creating a 3-dimensional OrderedDict with natural subscripting


rawDescription: how to create a group ID based on 5 minutes interval in pandas timeseries?

description: Create a group ID based on 5 minutes interval in pandas timeseries


code:
from bs4 import BeautifulSoup
html3= """

3.342.2323 Content Logical Definition

<p from the following

Include these codes as defined in http://snomed.info/sct

Code	Display

34353553	Examination / signs

35453453453	History/symptoms

"""
soup = BeautifulSoup(html3, "lxml")
h2 = soup.find(lambda elm: elm.name == "h2" and "Content Logical Definition" in elm.text)
for sibling in h2.next_siblings:
    print(sibling)

rawDescription: using bs4 to find a html tag (h2) having text

description: Using bs4 to find a html tag (h2) having text


code: a

rawDescription: Comparing a numpy array object to multiple conditions


code:
df1.columns
df1.columns.map(lambda x: x.strip())
df1.columns = df1.columns.map(lambda x: x.strip())

rawDescription: Splitting dataframe and saving to txt files


code:
def threadme(infiles,threadlimit=None,timeout=0.01):
    assert threadlimit is None or threadlimit > 0, \
           "need at least one thread";
    printlock = threading.Lock()
    srcfiles = list(infiles)
    threadpool = []

    # keep going while work to do or being done
    while srcfiles or threadpool:

        # while there's room, remove source files
        # and add to the pool
        while srcfiles and \
           (threadlimit is None \
            or len(threadpool) < threadlimit):
            file = srcfiles.pop()
            wrkr = Worker(file,printlock)
            wrkr.start()
            threadpool.append(wrkr)

        # remove completed threads from the pool
        for thr in threadpool:
            thr.join(timeout=timeout)
            if not thr.is_alive():
                threadpool.remove(thr)

    print("all threads are done")

if __name__ == "__main__":
    for lim in (1,2,3,4):
        print("--- Running with thread limit %i ---" % lim)
        threadme(("abc","def","ghi"),threadlimit=lim)

rawDescription: Python - Using threads or a queue to iterate over a for loop that calls a function


code: contentType = contentType|8

rawDescription: Cleaning a multiple checkbox field into a bitwise operation output in django?


code:
from glob import glob
from shutil import copyfileobj

with open('all.txt', 'ab') as output_file:
    for filename in glob("*.txt"):
        with open(filename, 'rb') as file:
            copyfileobj(file, output_file)

rawDescription: Concatenating text files creates file with space between each letter


code:
url = 'http://www.arch.gob.ec/index.php/descargas/doc_download/478-historial-de-produccion-nacional-de-crudo-2011.html'

(pdfFile, headers) = urllib.request.urlretrieve(url)
print(os.path.abspath(pdfFile))
s = pdf_convert(str(os.path.abspath(pdfFile)))

rawDescription: How open and read pdf (originally .html) file using Python3


code:
for row in depth:
   for v in row:
      print

rawDescription: Iterating within bounds of a 2D list (matrix) in python


code:
class MyScreen(Screen):
    entered = StringProperty()
    entered = "Not Entered"

rawDescription: Kivy language function call on button press using screens


code:
from collections import defaultdict

cats_by_color = defaultdict(list)

for cat in cats:
    cats_by_colors[cat.color].append(cat)

rawDescription: Create dictionary of lists by object feature


code: combos = list(chain.from_iterable(product(*c) for c in combinations(x,2)))

rawDescription: Python: 2-item combinations from list of lists containing 1 or more items


code:
l = [None]
l[0] = l

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


code:
from sqlalchemy.sql.expression import func

select([tabledef]).where(func.right(tabledef.c.column_code, 2) == 'AX')

rawDescription: RIGHT() function in sqlalchemy

description: RIGHT() function in sqlalchemy


rawDescription: Python - Extract folder path from file path


code: json_data = [{'data': list(value.values), 'name': key} for key, value in data_df.items()]

rawDescription: Formatting JSON from a Pandas data frame for Highcharts within a Django template


code:
def foobar(s):
    return "".join(set(s.replace(" ","")))

In [4]: foobar("what a nice day")
Out[4]: 'acedihntwy'

rawDescription: How to list the used chars in a text in Python?

description: List the used chars in a text in Python


code: items = itemList.split("\n")

rawDescription: Read each line of HTML form submission Python


code:
for i, d in enumerate(D):
    for j in d:
        d[j] = X[i, j]

rawDescription: How to cross check a python list of dictionaries against a csr matrix

description: Cross check a python list of dictionaries against a csr matrix


code:
@app.route('/end_point_for_your_fn', methods=["POST"])
def your_fn():
    data = request.form['input']

rawDescription: Execute a Python script in Flask

description: Execute a Python script in Flask


rawDescription: Creating an empty object in Python

description: Creating an empty object in Python


code:
labels = ['', 'blue', 'red', 'yellow', ...]
labels_to_idx = dict(zip(labels, range(len(labels))))
cond = " | ".join(["col{0} == '{1}'".format(i, labels_to_idx['blue'])
                   for i in range(10)])
rows = [[labels[x] for x in row[:]] for row in table.where(cond)]

rawDescription: Set type in pytables

description: Set type in pytables


rawDescription: Why are slices in Python 3 still copies and not views?


code: control_frame = my_bytes[0] & 128

rawDescription: Sending binary data over sockets with Python


rawDescription: pandas row specific apply

description: Pandas row specific apply


code:
from numpy import dot
dot(list1, list2) / sum(list1)

rawDescription: Pythonic way for calculating

description: Pythonic way for calculating


code:
utf_8_bytes = u'걸스데이미니앨범 3집'.encode('utf-8')
utf_8_bytes.decode('latin1')

rawDescription: what if a python unicode object has been decoded incorrectly

description: What if a python unicode object has been decoded incorrectly


code:
def HandleAuthAndReturnResult(self, method, arg):
    mc = xmlrpclib.MultiCall(self.wiki)
    if self.token:
        mc.applyAuthToken(self.token)
    method(mc, arg)
    return mc()[-1]
def fooMethod(self, x):
    HandleAuthAndReturnResult(xmlrpclib.MultiCall.fooMethod, x)

rawDescription: pythonic way to wrap xmlrpclib calls in similar multicalls

description: Pythonic way to wrap xmlrpclib calls in similar multicalls


code: runnerData = [("TestName1", 70),("TestName2", 50), ("TestName3", 60)]

rawDescription: Python Lists/ Tuples in terms of sorting


code:
spans = [(p.find('span', {'class': 'i'}), p.find('span', {'class': 'vi'})) for p in ps]
spans

rawDescription: Parsing web page in python using Beautiful Soup


code:
from itertools import groupby, chain

def get_sections(fle):
    with open(fle) as f:
        grps = groupby(f, key=lambda x: x.lstrip().startswith("#TYPE"))
        for k, v in grps:
            if k:
                yield chain([next(v)], (next(grps)[1]))  # all lines up to next #TYPE

rawDescription: How to split file into chunks by string delimiter in Python

description: Split file into chunks by string delimiter in Python


code:
rng
len(rng)
rng.freq
rng.freqstr

rawDescription: pandas retrieve the frequency of a time series

description: Pandas retrieve the frequency of a time series


code:
def setup_view(view, request, *args, **kwargs):
    """Mimic ``as_view()``, but returns view instance.
    Use this function to get view instances on which you can run unit tests,
    by testing specific methods."""

    view.request = request
    view.args = args
    view.kwargs = kwargs
    return view

rawDescription: How to unit test methods inside django's class based views?

description: Unit test methods inside django's class based views


code: element.send_keys("some text")

rawDescription: Input html form data from python script

description: Input html form data from python script


code:
idx1 = pd.Index([0, 1, 2, 3, 4])             # int64 dtype
idx2 = pd.Index(['0','1','2','3','4'])       # object dtype, strings
idx3 = pd.Index([0,'1',2,'3',4])             # object dtype, ints and strings
idx4 = pd.Index([0, 1, 2, 3, 4], dtype='O')  # object dtype, holds ints

rawDescription: pandas object indexes can be either string or int, how can I tell them apart?

description: Pandas object indexes can be either string or int, how can I tell them apart


code: {{ url_for('view_user_post', username=user.name, postname=post.name) }}

rawDescription: Flask URL Routing

description: Flask URL Routing


code:
from datetime import datetime, timedelta
import operator

from django.db.models import Q

def birthdays_within(days):

    now = datetime.now()
    then = now + timedelta(days)

    # Build the list of month/day tuples.
    monthdays = [(now.month, now.day)]
    while now <= then:
        monthdays.append((now.month, now.day))
        now += timedelta(days=1)

    # Tranform each into queryset keyword args.
    monthdays = (dict(zip(("birthday__month", "birthday__day"), t))
                 for t in monthdays)

    # Compose the djano.db.models.Q objects together for a single query.
    query = reduce(operator.or_, (Q(**d) for d in monthdays))

    # Run the query.
    return Person.objects.filter(query)

rawDescription: Queryset of people with a birthday in the next X days


code:
a.py
import ast
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)

def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
    if isinstance(s, bool): # make boolean into a 0/1 value
            if s:
                result = 1
            else:
                result = 0
    elif isinstance(s, NumberTypes): # keep numbers as/is
        result = s
    else: # convert a string
        # prepare the string for conversion
        if currency_sign != '':
            s = s.replace(currency_sign, '')
        if thousand_sep != '':
            s = s.replace(thousand_sep, '')
        if decimal_sep != '.':
            s = s.replace(decimal_sep, '.')
        s = s.strip()
        # convert the string
        if s == '':
            result = None
        else:
            try:
                # convert the string by a safe evaluation
                result = ast.literal_eval(s)
                # check if result of the evaluation is a number type
                if not isinstance(result, NumberTypes):
                    result = None
            except ValueError:
                # if the conversion gave an error, the string is not a number
                result = None
    return result

rawDescription: Fastest and/or most pythonic way to convert string into a number


code:
import example
h1 = example.Holder(10)
h2 = example.Holder(20)
assert(h1.value == 10)
assert(h2.value == 20)
h1.value = h2.value
assert(h1.value == 20)
h1.value += 22
assert(h1.value == 42)
assert(h2.value == 20)

rawDescription: How to export a shared_ptr of a fundamental type to python

description: Export a shared_ptr of a fundamental type to python


code:
class UpdatedSignal(QtCore.QObject):
    updatedSignal = QtCore.Signal(str)

rawDescription: Draggable point in matplotlib - How to retrieve point coordinates


code:
last_name_node = soup.find('last_name')
last_name = last_name_node and last_name_node.string

rawDescription: Parsing XML with BeautifulSoup and handling missing element


code:
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

rawDescription: Python concatenate text files

description: Python concatenate text files


code:
def switches(n, num=4):
    return [n & (2**i) > 0 for i in range(num)]

rawDescription: Algebra in Python (something better than a switch?)


code:
from collections import deque
N = 100
last_lines = deque(maxlen=N)

with open("file.txt") as f:
    for i, line in enumerate(f):
        last_lines.append(line)
        if 'development' in line:
            do_something(last_lines)

rawDescription: How to search backward several lines in Python 3?

description: Search backward several lines in Python 3


code:
import  wx.lib.newevent

OvlCheckEvent, EVT_OVL_CHECK_EVENT = wx.lib.newevent.NewEvent()

class MyOvl(ObjectListView):
    def SetCheckState(self, modelObject, state):
        """
        This is the same code, just added the event inside
        """
        if self.checkStateColumn is None:
            return None
        else:
            r = self.checkStateColumn.SetCheckState(modelObject, state)

            # Just added the event here ===================================
            e = OvlCheckEvent(object=modelObject, value=state)
            wx.PostEvent(self, e)
            # =============================================================

            return r

    def _HandleLeftDownOnImage(self, rowIndex, subItemIndex):
        """
        This is the same code, just added the event inside
        """
        column = self.columns[subItemIndex]
        if not column.HasCheckState():
            return

        self._PossibleFinishCellEdit()
        modelObject = self.GetObjectAt(rowIndex)
        if modelObject is not None:
            column.SetCheckState(modelObject, not column.GetCheckState(modelObject))

            # Just added the event here ===================================
            e = OvlCheckEvent(object=modelObject, value=column.GetCheckState(modelObject))
            wx.PostEvent(self, e)
            # =============================================================

            self.RefreshIndex(rowIndex, modelObject)

rawDescription: Python create an event to an ObjectListView check box


code:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

rawDescription: how to represent a item in a list python

description: Represent a item in a list python


code:
d2 = {}

with open('file2.txt', 'r') as file2:
    for row in file2:
        cols = row.strip().split()
        d2[cols[1]] = cols[0]

with open('file1.txt', 'r') as file1:
    for row in file1:
        cols = row.strip().split()
        print ("%s\t%s" % (d2[cols[0]], d2[cols[1]]))

rawDescription: Dict Manipulation

description: Dict Manipulation


code:
import csv
from collections import defaultdict

with open('foo.txt') as f:
    reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
    d = defaultdict(list)
    next(reader)
    next(reader)
    for row in reader:
        k, v = row[0], map(int, row[1:3])
        d[k].append(v)

print(d)

rawDescription: How to put in a bidimensional array, two columns of a csv list, for each field data

description: Put in a bidimensional array, two columns of a csv list, for each field data


code:
class ProfileForm(forms.ModelForm):
    """Profile form"""
    class Meta:
        model = Profile
        exclude = ('user',)

rawDescription: Populating Django Templates from retrieved records


code:
for x in func(*a, **ka):
    yield x

rawDescription: Using decorator to turn function into generator in python


code:
class CommonParent(object):

    @property
    def format_field(self):
        return u'parent_format'

    @property
    def mutable_field(self):
        return u'parent_replace'

    @property
    def result_string(self):
        return '{0} {1}'.format(self.mutable_field, self.format_field)

class Child1(CommonParent):
    @property
    def mutable_field(self):
        return u'child1_replace'

class Child2(CommonParent):
    @property
    def format_field(self):
        return u'child2_format'

    @property
    def mutable_field(self):
        return u'child2_replace'

class Result1(Child1):
    pass

class Result2(Child2):
    pass

if __name__ == '__main__':
    r1 = Result1()
    print(getattr(r1, 'result_string'))

    r2 = Result2()
    print(getattr(r2, 'result_string'))

rawDescription: Python: classes handling mutable variables in inherited classes which depend on parent class


code:
d
d[['lat', 'long']] #get the first column if you know their names
d[list(d.dtype.names[:2])] #get the first column by index

rawDescription: effectively preprocessing record array from genfromtxt

description: Effectively preprocessing record array from genfromtxt


rawDescription: Summing values of numpy array based on indices in other array


code: el.set('id', to)  # isntead of  el.attrib['id'] = to

rawDescription: Replace contents of lxml StringElement with starting a namespace war?


code:
def do_stuff_with_files(infile, outfile):
    out = open(infile,'w')
    infile = open(outfile,'r')
    # the rest of your script

rawDescription: python multiple inputs and multiple outputs

description: Python multiple inputs and multiple outputs


rawDescription: Adding calculated column(s) to a dataframe in pandas


code:
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

rawDescription: Writing header with DictWriter from Python's csv module


rawDescription: What char can be used to seperate binary data in a python 2.7 string?


code:
import json
with open("Tamaguchis.txt","w") as file:
    date = time.strftime("%c")
    dictionary = {"size":tamaguchin.size,"date":date,"order":lista}
    file.write(json.dumps(dictionary))

rawDescription: Exporting a dictionary into a text-file

description: Exporting a dictionary into a text-file


rawDescription: Intersection between all elements of same list where elements are set


rawDescription: Convert numpy array from values to indices


rawDescription: Yielding sub combinations

description: Yielding sub combinations


rawDescription: accessing columns within an array within a for loop

description: Accessing columns within an array within a for loop


code: self.getButton(0, 0).buttonMethod()

rawDescription: Recognition source of event in PyQT

description: Recognition source of event in PyQT


code:
self.e = Tkinter.Entry(self)
self.e.pack()
self.e.focus_set()

rawDescription: Tkinter, Python: How do I save text entered in the Entry widget? How do I move a label?


code:
def create_grades_dict(file_name):
    my_dictionary = {}
    file_pointer = open(file_name, 'r')
    data = file_pointer.readlines()
    for line in data:
        student_row = map(str.strip, line.strip().split(','))
        student_id = student_row.pop(0)
        student_lastname = student_row.pop(0)
        student_data = [student_lastname]
        for valid_test in ['Test_1', 'Test_2', 'Test_3', 'Test_4']:
            if valid_test in student_row:
                student_data.append(int(student_row[student_row.index(valid_test) + 1]))
            else:
                student_data.append(0)
        student_data.append(sum(student_data[-4: ])/4)
        my_dictionary[student_id] = student_data
    return my_dictionary

rawDescription: Getting a perfect output using .format()


rawDescription: How to find the sum of number layer in ndarray

description: Find the sum of number layer in ndarray


code: Clock.schedule_interval(game.update, 1.0 / 60.0)

rawDescription: Kivy - adding and removing labels

description: Kivy - adding and removing labels


code:
outData = pd.DataFrame(bigList)
outData.to_csv('myFile.csv', index=False)

rawDescription: writing pandas dataframe columns to csv rows staggered

description: Writing pandas dataframe columns to csv rows staggered


code:
from collections import defaultdict
def popular(letter):
    my_dictionary = defaultdict(int)
    for alphabet, picks in letter.items():
        my_dictionary[alphabet[0]] += picks
    return dict(my_dictionary)

rawDescription: How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x

description: Add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x


code:
import os
import sys

def like_cheese():
    var = input("Hi! I like cheese! Do you like cheese?").lower()
    if var == "yes":
        print("That's awesome!")

if __name__ == '__main__':
    like_cheese()
    os.execv(__file__, sys.argv)  # Run a new iteration of the current script, providing any command line args from the current iteration.

rawDescription: How To Make a Python Program Automatically Restart Itself


code:
r = Randomizer()
r.func_A()
r.func_B()

rawDescription: Randomizer function/global variables trouble in python?


code:
def __hash__(self):
    return hash((self.data[0],self.data[1]))

rawDescription: Removing duplicates from list based on custom definition of duplicate


code:
import time

t0 = time.time()
code_block
t1 = time.time()

total = t1-t0

rawDescription: How can I time a code segment for testing performance with Pythons timeit?

description: Time a code segment for testing performance with Pythons timeit


code: [''] * len(myList)

rawDescription: How can I get around declaring an unused variable in a for loop?

description: Get around declaring an unused variable in a for loop


code:
mac = "1a:2b:3c:4d:5e:6f".split(':')
hex_mac = [m.decode('hex') for m in mac]
hex_mac

rawDescription: How to generate ODIN-1 in Python

description: Generate ODIN-1 in Python


code: from class1 import obj1

rawDescription: How can Blueprint Flask routes in different files access shared objects


code: choices = [(0, 'create new folder'), (1, 'delete'), (2, 'read'), (3, 'unread')]

rawDescription: django submit form on change

description: Django submit form on change


code:
#All the stuff earlier in the program
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean,
    extent=(0.5,numpy.shape(matrix)[0]+0.5,0.5,numpy.shape(matrix)[1]+0.5))
plt.colorbar()
plt.show()

rawDescription: Matplotlib plot numpy matrix as 0 index

description: Matplotlib plot numpy matrix as 0 index


code:
for id in list_ids:
    Return_Name(id)

rawDescription: I'd'd like to take a list of strings, find them in another csv file and print a field from the matching line


code: slice = [arr[i][0:2] for i in range(0,2)]

rawDescription: Python: slicing a multi-dimensional array


code:
import json
list2 = [json.loads(item) for item in list1]

rawDescription: replace text from list of dictionary python

description: Replace text from list of dictionary python


rawDescription: Loading Flask Models from Postgres

description: Loading Flask Models from Postgres


code:
import ast
with open('file_name.txt') as f:
    D = ast.literal_eval(f.read())
with open('file_write.txt','w') as f:
    for k,v in D.items():
        f.write('{} {}\n'.format(k,v))

rawDescription: how can i change key,value format back to lines?

description: Change key,value format back to lines


code:
def newFrame(self, event):
    self.new_window = wx.Frame(self, title='frame2', pos=(800,0))

    self.scroll = wx.ScrolledWindow(self.new_window, -1,size=(500,500))
    self.scroll.SetScrollbars(1, 1, 1600, 1400)
    self.new_window.Layout()
    self.new_window.Fit()
    self.new_window.Show()

rawDescription: creating a wxpython scrolled window (frame) by an event

description: Creating a wxpython scrolled window (frame) by an event


code:
def fibTimeLimited(limit):
  start = time.time()
  n, f0, f1 = 1, 0, 1
  while time.time() < start + limit:
    n += 1
    f0, f1 = f1, f0+f1
  return (n, f1)

rawDescription: finding the greatest Fibonacci number within limited time in python

description: Finding the greatest Fibonacci number within limited time in python


code: df.columns = range(4)

rawDescription: pandas plot function gives ValueError: x and y must have same first dimension

description: Pandas plot function gives ValueError: x and y must have same first dimension


code:
import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data

test_df = data.get_data_yahoo('AAPL', start='2015-10-01')
fig, ax = plt.subplots(nrows=2)
test_df['Adj Close'].plot(ax=ax[0])
test_df['Volume'].plot(kind='bar', ax=ax[1])

# show every Nth label
locs, labels = plt.xticks()
N = 10
plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d'))

# autorotate the xlabels
fig.autofmt_xdate()
plt.show()

rawDescription: Pandas matplotlib plotting, irregularities in time series labels between bar graph and line graph


code:
a = np.array([100, 200, 250], dtype=np.uint8)
b = np.array([50, 50, 50], dtype=np.uint8)
b = 255 - b  # old b is gone shortly after new array is created
np.putmask(a, b < a, b)  # a temp bool array here, then it's gone
a += 255 - b  # a temp array here, then it's gone

rawDescription: Avoid overflow when adding numpy arrays

description: Avoid overflow when adding numpy arrays


code:
for line in f.readlines():
    student, score = line.split(':')
    scores[student].append(int(score))

rawDescription: Python - Highest with alphabetical order from text file


code: lemmas_in_wordnet = set(chain(*[ss.lemma_names() for ss in wn.all_synsets()]))

rawDescription: How can I print the entire contents of Wordnet (preferably with NLTK)?

description: Print the entire contents of Wordnet (preferably with NLTK)


code:
################################################################################
import threading
import time
import Queue
import Tkinter      as Tk
import Tkconstants  as TkConst
from ScrolledText import ScrolledText
from tkFont       import Font

global top
global dataQ
global scrText

def thread_proc():
    x = -1
    dataQ.put(v)
    x = 0
    for i in xrange(5):
        for j in xrange(20):
            dataQ.put(v)
            time.sleep(0.1)
            x += 1
        time.sleep(0.5)
    dataQ.put(v)

def on_after_elapsed():
    while True:
        try:
            v = dataQ.get(timeout=0.1)
        except:
            break
        scrText.insert(TkConst.END, "value=%d\n" % v)
        scrText.see(TkConst.END)
        scrText.update()
    top.after(100, on_after_elapsed)

top     = Tk.Tk()
dataQ   = Queue.Queue(maxsize=0)
f       = Font(family='Courier New', size=12)
scrText = ScrolledText(master=top, height=20, width=120, font=f)
scrText.pack(fill=TkConst.BOTH, side=TkConst.LEFT, padx=15, pady=15, expand=True)
th = threading.Thread(target=thread_proc)
th.start()
top.after(100, on_after_elapsed)
top.mainloop()
th.join()
## end of file #################################################################

rawDescription: Tkinter: Wait for item in queue

description: Tkinter: Wait for item in queue


code:
def put(self, request, format=None):
    """
    This text is the description for this API.

    ---
    parameters:
    - name: username
      description: Foobar long description goes here
      required: true
      type: string
      paramType: form
    - name: password
      paramType: form
      required: true
      type: string
    """
    username = request.DATA['username']
    password = request.DATA['password']

rawDescription: django-rest-swagger: How can I specify the parameter type in the docstring

description: Django-rest-swagger: How can I specify the parameter type in the docstring


code:
txn = txn.sort_values(by='Send_Agent')
txn['repeat'] = ((txn['Send_Agent'].shift() == txn['Send_Agent'])
                 & (txn['Send_Agent'].shift() == txn['Send_Agent']))

grouped = txn.groupby('Send_Agent')
result = grouped.agg(
    {'Pay_Amount':'mean',
     'time_diff':'min',
     'MTCN':'size',
     'Send_Phone':'nunique',
     'Refund_Flag':'count',
     'Send_Amount': 'mean',
     'repeat':'sum'})
print(result)

rawDescription: python Pandas calling a complex function in groupby.agg

description: Python Pandas calling a complex function in groupby.agg


rawDescription: django create object without affecting database

description: Django create object without affecting database


code:
# ...
plt.plot(x,y, color='black')
plt.plot(x,y1, color='pink')
plt.plot(x,y2, color='green')
plt.show()

rawDescription: how to use matplotlib's set_cmap()?

description: Use matplotlib's set_cmap()


code:
def output_nested_parens(s):
    out = ''
    indent = ''
    for c in s:
        if c == '(':
            indent += '  '
            out += '\n' + indent
            out += c
        elif c == ')':
            indent = indent[2:]
            out += c
            out += '\n' + indent
        else:
            out += c
    return out

rawDescription: Parser failing - pyparsing

description: Parser failing - pyparsing


code:
import pandas as pd

df = pd.DataFrame({'ID':[1,1,3],
                   'Dates':['2015-01-01','2015-01-01','2015-02-01'],
                   'C':[7,8,9]})
df = pd.concat([df]*1000).reset_index(drop=True)
df['Dates'] = pd.to_datetime(df.Dates)
df.set_index(['ID', 'Dates'], inplace=True)
print (df)

df1 = df.copy()
df1.reset_index('ID', inplace=True)

def orig(df):

    return list(df[~df['ID'].duplicated()]['ID'].sort_values().reset_index()['ID'])

print (df.index.get_level_values('ID').unique().tolist())

print (orig(df1))

print (df.index.get_level_values('ID').drop_duplicates().tolist())

rawDescription: Getting the keys out of a Multiindex?

description: Getting the keys out of a Multiindex


code:
import logging

logger = logging.getLogger('my_logger')

logger.error("Your log message here")

rawDescription: How do I test if a certain log message is logged in a Django test case?

description: Test if a certain log message is logged in a Django test case


code:
cmd=subprocess.Popen(["od", "-cx"], stdin=subprocess.PIPE)
data=gzip.open("/tmp/hello.gz")
cmd.stdin.write(data.read())
cmd.stdin.close()

rawDescription: Using a zipped file as a shell stdin

description: Using a zipped file as a shell stdin


code: form = SiteForm(user=request.user)

rawDescription: Only Allow ForeignKey Selection of User Values


code:
Form.full_clean()
def full_clean(self):
    # ..... snip
    self._clean_fields()
    self._clean_form()
    self._post_clean()

rawDescription: Is there any relationship between model's clean() method and form's clean() method?


code:
def bottoms_matrix(matrix):
    positives = []
    negatives = []
    for i, row_mat in enumerate(matrix):
        tmp_p = []
        tmp_n = []
        for j, cell in enumerate(row_mat):
            if cell >0:
                tmp_p.append(cell)
                tmp_n.append(0.)
            else:
                tmp_p.append(0.)
                tmp_n.append(cell)
        positives.append(tmp_p)
        negatives.append(tmp_n)

    # get cumulative sums
    positives = positives[:-1]
    negatives = negatives[:-1]
    positives.insert(0, [0.] * len (matrix[0]))
    negatives.insert(0, [0.] * len(matrix[0]))
    tmp = swap_matrix(positives)
    tmp = [list(np.cumsum(t)) for t in tmp]
    positives = swap_matrix(tmp)

    tmp = swap_matrix(negatives)
    tmp = [list(np.cumsum(t)) for t in tmp]
    negatives = swap_matrix(tmp)

    final_matrix =[]
    for i, row_mat in enumerate(matrix):
        tmp =[]
        for j, cell in enumerate(row_mat):
            tmp.append(positives[i][j] if cell > 0 else negatives[i][j])
        final_matrix.append(tmp)
    return final_matrix

rawDescription: How to draw 100% stacked bars with mixed +ve and -ve values in matplotlib?

description: Draw 100% stacked bars with mixed +ve and -ve values in matplotlib


code:
mask = (df['column 0'].shift(1) + df['column 3'].shift(2) >= 6)
newdf = df[mask]

rawDescription: Fastest way to iterate through a pandas dataframe?


code:
firstList = ['a','b','c']
secondList = [1,2,3,4]
from itertools import product
list(product(firstList, secondList))

rawDescription: Merge two lists into a list of tuples with custom condition


code:
from __future__ import print_function

lines = (line.strip() for line in open("foo.txt", "r"))
all_names = (line.split(" ", 1)[0] for line in lines if "." not in line)
unique_names = set(all_names)
print("\n".join(unique_names))

rawDescription: Python command(s) to find unique names in long list


rawDescription: Replacing entries of an array with those of different array


code:
True and False
False and True

rawDescription: Need help understanding Booleans?

description: Need help understanding Booleans


code: exit()

rawDescription: why python requires us to use from statement when we have already loaded a module using import

description: Why python requires us to use from statement when we have already loaded a module using import