code:
def env_or_input(var_name, prompt):
    val = os.environ.get(var_name)
    if val is None:  # it was not set, so ask user
        val = input(prompt)
    return val

...

ans = env_or_input("ans", "How you doin' (Say Yes/No)")
if ans == "Yes":
    print("Nice to hear")
elif ans == "No":
    print("Oh Too Bad")

rawDescription: How to make a script auto-provide arguments to another without passing via command line?

description: Make a script auto-provide arguments to another without passing via command line


rawDescription: Generating Difficult List in Python

description: Generating Difficult List in Python


code: "Date range: {dates[0]:{fmt}} to {dates[1]:{fmt}}".format(dates=daterange, fmt=fmt)

rawDescription: Formatting multiple datetimes into a string


code: list

rawDescription: list to string in df.to-csv()

description: List to string in df.to-csv()


rawDescription: Include empty values in a list according to specific positions (Python)


code:
from pandas.util.testing import rands
s = Series([rands(120) for _ in range(10)])
s
s.astype(str).map(len)
map(len, s.values.astype(str))

rawDescription: Why is numpy/pandas returning only the first character when I use .astype(str)


code:
class Category(models.Model):
    parent = models.ForeignKey('self',null=True,blank=True)
    name = models.CharField(max_length=150,null=True)
    description = models.CharField(max_length=255,null=True,blank=True)

    def __unicode__(self):
        return self.name

class ItemManager(models.Manager):
    def get_for_category(self, category):
        return self.filter(categories=category)

class Item(models.Model):
    name = models.TextField(null=True,blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True)
    categories = models.ManyToManyField(Category,null=True)
    objects = ItemManager()

rawDescription: Return Django queryset of items that appear in a single category when items can appear in multiple categories


code: [g for g in nx.clique.find_cliques(G) if len(g) > 2]

rawDescription: completely connected subgraphs from a larger graph in networkx

description: Completely connected subgraphs from a larger graph in networkx


code:
import functools
def compose(*fs):
  return functools.reduce(lambda f, g: lambda x: f(g(x)), fs)

modifier = compose(add_params({'abc':'123'}),
                   add_params({'def':'456'}))

rawDescription: Make callers use functools.partial or call a factory function?


rawDescription: Suppressing Output of Paramiko SSHClient Class


code:
n = len(str_list)
values = unpack("d" * n, "".join(str_list))

# Just to shorten this code sample
q = NBR_DATA_POINTS_PER_BUFFER_INT

data[file_idx] = [values[i:i+q] for i in xrange(0, n, q)]

rawDescription: assigning elements to buffer and specific position in buffer - how to speed up / why are the different implementations so slow?

description: Assigning elements to buffer and specific position in buffer - how to speed up / why are the different implementations so slow


code:
class PriekabosTable(tables.Table):
    class Meta:
        model = Priekabos
        attrs = {"class": "paleblue"}
        fields = ('id', 'sutarties_nr', 'nuomos_pradz', 'max_kada_moketi')

rawDescription: django-tables2 custom column

description: Django-tables2 custom column


code:
def take_single(series):
    return series.unique()[0]

rawDescription: How to summarise data over several years into one dataframe

description: Summarise data over several years into one dataframe


rawDescription: how to goup items in a list of dictionaries by matching values in python

description: Goup items in a list of dictionaries by matching values in python


code:
import pymongo
from pymongo import MongoClient
connection = MongoClient()
db = connection.mydatabase

rawDescription: How do I use pymongo to connect to an existing document collection/db?

description: Use pymongo to connect to an existing document collection/db


code:
import csv
# Open input file for reading and output file for writing.
# It's good practice to use the with open() context manager
with open('sample.csv', 'r') as csv_in, open('results.csv', 'w') as csv_out:
    # The reader will figure out the field names
    # based on the first line in the file.
    reader = csv.DictReader(
        csv_in
    )
    # We have to tell the writer the fields and their order
    # and which dialect of csv we want.
    writer = csv.DictWriter(
        csv_out,
        fieldnames=reader.fieldnames + ['hashtags'],
        dialect=reader.dialect,
        quoting=csv.QUOTE_ALL,
    )
    # write the header line of the output csv
    writer.writeheader()

    # loop over each line in the csv. The header line is not
    # part of this loop when using csv.DictReader
    for row in reader:
        # Split the tweet into words using str.split()
        words = row['tweet'].split()

        # If you need to modify this code, you should turn the
        # following lines into one or two separate functions.
        # This will make debugging and testing easier.

        # Filter and join the words using str.startswith()
        row['tweet'] = ' '.join(
            w for w in words if not w.startswith('#'))

        # Extract the hashtags and remove the initial "#"
        # using string slicing.
        row['hashtags'] = ','.join(
            w[1:] for w in words if w.startswith('#'))

        # write the modified row to the output csv
        writer.writerow(row)

rawDescription: Split the hash-tags from a tweet and then store them and the remaining string in a CSV


code:
import re

soup.find_all("a", text=re.compile(r"^[pP]rice"))

rawDescription: Navigation with BeautifulSoup

description: Navigation with BeautifulSoup


code:
def completefactory(baseclass):
    class AutoComplete(baseclass):
        pass
    return AutoComplete

rawDescription: How to change baseclass

description: Change baseclass


code:
def path_vals(mx, path):
    """
    @param mx    Matrix data
    @param path  List of cell positions

    Return list of values from list of cell positions
    """

    return tuple([mx[x][y] for x,y in path])

rawDescription: All possible combinations of numbers of length 5 in a 4X4 matrix


code:
lst.sort(key=lambda x: x[0])
lst.sort(key=lambda x: x[2], reversed=True)

rawDescription: sorting a graph by its edge weight. python

description: Sorting a graph by its edge weight. python


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


code:
class Thing(object):
    # Prevents duplicating the wrapping of objects:
    def __new__(cls, thing):
        if isinstance(thing, cls):
            return thing
        return object.__new__(cls, thing)

    def __init__(self, thing):
        self.value = thing
        self.name = str(thing)
    id = property(lambda s: id(s))
    #...
    def __repr__(self):
        return "I am a %s" %self.name

def converter(func, cardinality=1):
    def new_func(*args):
        # Pick the last item in the argument list, which
        # for all item setter methods on  a list is the one
        # which actually contains the values
        if cardinality == 1:
            args = args[:-1] + (Thing(args[-1]  ),)
        else:
            args = args[:-1] + ([Thing(item) for item in args[-1]],)
        return func(*args)
    new_func.func_name = func.__name__
    return new_func

my_list_dict = {}

for single_setter in ("__setitem__", "append", "insert"):
    my_list_dict[single_setter] = converter(getattr(list, single_setter), cardinality=1)

for many_setter in ("__setslice__", "__add__", "__iadd__", "__init__", "extend"):
    my_list_dict[many_setter] = converter(getattr(list, many_setter), cardinality="many")

MyList = type("MyList", (list,), my_list_dict)

rawDescription: Can you easily create a list-like object in python that uses something like a descriptor for it's items?

description: Easily create a list-like object in python that uses something like a descriptor for it's items


location: US East (N. Virginia)

operatingSystem: Windows

tenancy: Shared

licenseModel: License Included

rawDescription: Complex JMESPath filter on a large JSON file


rawDescription: Numpy: vectorizing two-branch test (ternary-operator like)


code: longref

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


code: other_matrix = dummy_matrix

rawDescription: Python - Erroneous result for two different matrixes in nested for loop


code:
class Worker(QtCore.QObject):

    madeProgress = QtCore.pyqtSignal([int])
    finished = QtCore.pyqtSignal()

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

    def run(self):
        for icmd, cmd in enumerate(self.cmdlist):
            # execute your work
            # processCommand(cmd)

            # signal that we've made progress
            self.madeProgress.emit(icmd)

        # emit the finished signal - we're done
        self.finished.emit()

rawDescription: Python PyQT: How to call a GUI function from a worker thread?


code:
import unicodedata

def accented_letters(letter):
    accented_chars = []
    for accent_type in "acute", "double acute", "grave", "double grave":
        try:
            accented_chars.append(unicodedata.lookup("Latin small letter {letter} with {accent_type}".format(**vars())))
        except KeyError:
            pass
    return accented_chars

print(accented_letters("e"))

rawDescription: Rules from accented letters to ascii ones


rawDescription: Combine two columns under one header in Numpy array


code:
def get_random_filename(car_picture, filename):
    extension = filename.split('.')[-1]
    return u'_%s_%s.%s' % (random.randint(0,10000000),
                           random.randint(0,10000000),
                           extension)

class CarPicture(models.Model):
    title = models.TextField()
    image = models.ImageField(upload_to=get_random_filename)

rawDescription: moving a function out of my method in django

description: Moving a function out of my method in django


code:
while True:
   AClass.objects.update()
   updated_results = AClass.objects.all().order_by('-id')[:5]
   sleep(300)

rawDescription: Django ORM queries fail to select new objects


rawDescription: Is it plausible to plug in equations for series in python?


code:
import pygtk
pygtk.require20()
import gtk

data = [['1', '!help',    '1', '0', 'blabla'],
        ['2', '!version', '1', '1', 'blabla'],
        ['3', '!tp',      '0', '1', 'blabla']]

def main():
    window = gtk.Window()
    window.set_title('Dynamic controls')
    window.connect("delete_event", gtk.main_quit)

    vbox = gtk.VBox()
    window.add(vbox)

    for row in data:
        hbox = gtk.HBox(homogeneous=True)
        hbox.pack_start(gtk.Label(row[1]))
        enabled_checkbox = gtk.CheckButton('Enabled')
        enabled_checkbox.set_active(row[2] is '1')
        hbox.pack_start(enabled_checkbox)
        op_checkbox = gtk.CheckButton('OP')
        op_checkbox.set_active(row[3] is '1')
        hbox.pack_start(op_checkbox)
        hbox.pack_start(gtk.Label(row[4]))
        vbox.pack_start(hbox)

    window.show_all()
    gtk.main()

if __name__ == '__main__':
    main()

rawDescription: Python + pygtk generate table of checkboxes from database


code:
browser.form['__ac_name'] = Username
browser.form['__ac_password'] = Password

rawDescription: Creme 96, Python, Mechanize.py

description: Creme 96, Python, Mechanize.py


code:
def new_way(A,B):
    C = np.empty((A.shape[0],B.shape[0]))
    for rowind, row in enumerate(A):
        C[rowind,:] = np.sum((row - B)**2/(row + B), axis=-1)/2.
    return C

rawDescription: Optimizing histogram distance metric for two matrices in python


code:
import sys, os, fcntl, struct

if os.geteuid() >  0:
    print("ERROR: Must be root to use")
    sys.exit(1)

with open(sys.argv[1], "rb") as fd:
    # tediously derived from the monster struct defined in <hdreg.h>
    # see comment at end of file to verify
    hd_driveid_format_str = "@ 10H 20s 3H 8s 40s 2B H 2B H 4B 6H 2B I 36H I Q 152H"
    # Also from <hdreg.h>
    HDIO_GET_IDENTITY = 0x030d
    # How big a buffer do we need?
    sizeof_hd_driveid = struct.calcsize(hd_driveid_format_str)

    # ensure our format string is the correct size
    # 512 is extracted using sizeof(struct hd_id) in the c code
    assert sizeof_hd_driveid == 512

    # Call native function
    buf = fcntl.ioctl(fd, HDIO_GET_IDENTITY, " " * sizeof_hd_driveid)
    fields = struct.unpack(hd_driveid_format_str, buf)
    serial_no = fields[10].strip()
    model = fields[15].strip()
    print("Hard Disk Model: %s" % model)
    print("  Serial Number: %s" % serial_no)

## For documentation purposes, this is the struct copied from <hdreg.h>
# struct hd_driveid {
#   unsigned short  config;     /* lots of obsolete bit flags */
#   unsigned short  cyls;       /* Obsolete, "physical" cyls */
#   unsigned short  reserved2;  /* reserved (word 2) */
#   unsigned short  heads;      /* Obsolete, "physical" heads */
#   unsigned short  track_bytes;    /* unformatted bytes per track */
#   unsigned short  sector_bytes;   /* unformatted bytes per sector */
#   unsigned short  sectors;    /* Obsolete, "physical" sectors per track */
#   unsigned short  vendor0;    /* vendor unique */
#   unsigned short  vendor1;    /* vendor unique */
#   unsigned short  vendor2;    /* Retired vendor unique */
#   unsigned char   serial_no[20];  /* 0 = not_specified */
#   unsigned short  buf_type;   /* Retired */
#   unsigned short  buf_size;   /* Retired, 512 byte increments
#                    * 0 = not_specified
#                    */
#   unsigned short  ecc_bytes;  /* for r/w long cmds; 0 = not_specified */
#   unsigned char   fw_rev[8];  /* 0 = not_specified */
#   unsigned char   model[40];  /* 0 = not_specified */
#   unsigned char   max_multsect;   /* 0=not_implemented */
#   unsigned char   vendor3;    /* vendor unique */
#   unsigned short  dword_io;   /* 0=not_implemented; 1=implemented */
#   unsigned char   vendor4;    /* vendor unique */
#   unsigned char   capability; /* (upper byte of word 49)
#                    *  3:  IORDYsup
#                    *  2:  IORDYsw
#                    *  1:  LBA
#                    *  0:  DMA
#                    */
#   unsigned short  reserved50; /* reserved (word 50) */
#   unsigned char   vendor5;    /* Obsolete, vendor unique */
#   unsigned char   tPIO;       /* Obsolete, 0=slow, 1=medium, 2=fast */
#   unsigned char   vendor6;    /* Obsolete, vendor unique */
#   unsigned char   tDMA;       /* Obsolete, 0=slow, 1=medium, 2=fast */
#   unsigned short  field_valid;    /* (word 53)
#                    *  2:  ultra_ok    word  88
#                    *  1:  eide_ok     words 64-70
#                    *  0:  cur_ok      words 54-58
#                    */
#   unsigned short  cur_cyls;   /* Obsolete, logical cylinders */
#   unsigned short  cur_heads;  /* Obsolete, l heads */
#   unsigned short  cur_sectors;    /* Obsolete, l sectors per track */
#   unsigned short  cur_capacity0;  /* Obsolete, l total sectors on drive */
#   unsigned short  cur_capacity1;  /* Obsolete, (2 words, misaligned int)     */
#   unsigned char   multsect;   /* current multiple sector count */
#   unsigned char   multsect_valid; /* when (bit0==1) multsect is ok */
#   unsigned int    lba_capacity;   /* Obsolete, total number of sectors */
#   unsigned short  dma_1word;  /* Obsolete, single-word dma info */
#   unsigned short  dma_mword;  /* multiple-word dma info */
#   unsigned short  eide_pio_modes; /* bits 0:mode3 1:mode4 */
#   unsigned short  eide_dma_min;   /* min mword dma cycle time (ns) */
#   unsigned short  eide_dma_time;  /* recommended mword dma cycle time (ns) */
#   unsigned short  eide_pio;       /* min cycle time (ns), no IORDY  */
#   unsigned short  eide_pio_iordy; /* min cycle time (ns), with IORDY */
#   unsigned short  words69_70[2];  /* reserved words 69-70
#                    * future command overlap and queuing
#                    */
#   unsigned short  words71_74[4];  /* reserved words 71-74
#                    * for IDENTIFY PACKET DEVICE command
#                    */
#   unsigned short  queue_depth;    /* (word 75)
#                    * 15:5 reserved
#                    *  4:0 Maximum queue depth -1
#                    */
#   unsigned short  words76_79[4];  /* reserved words 76-79 */
#   unsigned short  major_rev_num;  /* (word 80) */
#   unsigned short  minor_rev_num;  /* (word 81) */
#   unsigned short  command_set_1;  /* (word 82) supported
#                    * 15:  Obsolete
#                    * 14:  NOP command
#                    * 13:  READ_BUFFER
#                    * 12:  WRITE_BUFFER
#                    * 11:  Obsolete
#                    * 10:  Host Protected Area
#                    *  9:  DEVICE Reset
#                    *  8:  SERVICE Interrupt
#                    *  7:  Release Interrupt
#                    *  6:  look-ahead
#                    *  5:  write cache
#                    *  4:  PACKET Command
#                    *  3:  Power Management Feature Set
#                    *  2:  Removable Feature Set
#                    *  1:  Security Feature Set
#                    *  0:  SMART Feature Set
#                    */
#   unsigned short  command_set_2;  /* (word 83)
#                    * 15:  Shall be ZERO
#                    * 14:  Shall be ONE
#                    * 13:  FLUSH CACHE EXT
#                    * 12:  FLUSH CACHE
#                    * 11:  Device Configuration Overlay
#                    * 10:  48-bit Address Feature Set
#                    *  9:  Automatic Acoustic Management
#                    *  8:  SET MAX security
#                    *  7:  reserved 1407DT PARTIES
#                    *  6:  SetF sub-command Power-Up
#                    *  5:  Power-Up in Standby Feature Set
#                    *  4:  Removable Media Notification
#                    *  3:  APM Feature Set
#                    *  2:  CFA Feature Set
#                    *  1:  READ/WRITE DMA QUEUED
#                    *  0:  Download MicroCode
#                    */
#   unsigned short  cfsse;      /* (word 84)
#                    * cmd set-feature supported extensions
#                    * 15:  Shall be ZERO
#                    * 14:  Shall be ONE
#                    * 13:6 reserved
#                    *  5:  General Purpose Logging
#                    *  4:  Streaming Feature Set
#                    *  3:  Media Card Pass Through
#                    *  2:  Media Serial Number Valid
#                    *  1:  SMART selt-test supported
#                    *  0:  SMART error logging
#                    */
#   unsigned short  cfs_enable_1;   /* (word 85)
#                    * command set-feature enabled
#                    * 15:  Obsolete
#                    * 14:  NOP command
#                    * 13:  READ_BUFFER
#                    * 12:  WRITE_BUFFER
#                    * 11:  Obsolete
#                    * 10:  Host Protected Area
#                    *  9:  DEVICE Reset
#                    *  8:  SERVICE Interrupt
#                    *  7:  Release Interrupt
#                    *  6:  look-ahead
#                    *  5:  write cache
#                    *  4:  PACKET Command
#                    *  3:  Power Management Feature Set
#                    *  2:  Removable Feature Set
#                    *  1:  Security Feature Set
#                    *  0:  SMART Feature Set
#                    */
#   unsigned short  cfs_enable_2;   /* (word 86)
#                    * command set-feature enabled
#                    * 15:  Shall be ZERO
#                    * 14:  Shall be ONE
#                    * 13:  FLUSH CACHE EXT
#                    * 12:  FLUSH CACHE
#                    * 11:  Device Configuration Overlay
#                    * 10:  48-bit Address Feature Set
#                    *  9:  Automatic Acoustic Management
#                    *  8:  SET MAX security
#                    *  7:  reserved 1407DT PARTIES
#                    *  6:  SetF sub-command Power-Up
#                    *  5:  Power-Up in Standby Feature Set
#                    *  4:  Removable Media Notification
#                    *  3:  APM Feature Set
#                    *  2:  CFA Feature Set
#                    *  1:  READ/WRITE DMA QUEUED
#                    *  0:  Download MicroCode
#                    */
#   unsigned short  csf_default;    /* (word 87)
#                    * command set-feature default
#                    * 15:  Shall be ZERO
#                    * 14:  Shall be ONE
#                    * 13:6 reserved
#                    *  5:  General Purpose Logging enabled
#                    *  4:  Valid CONFIGURE STREAM executed
#                    *  3:  Media Card Pass Through enabled
#                    *  2:  Media Serial Number Valid
#                    *  1:  SMART selt-test supported
#                    *  0:  SMART error logging
#                    */
#   unsigned short  dma_ultra;  /* (word 88) */
#   unsigned short  trseuc;     /* time required for security erase */
#   unsigned short  trsEuc;     /* time required for enhanced erase */
#   unsigned short  CurAPMvalues;   /* current APM values */
#   unsigned short  mprc;       /* master password revision code */
#   unsigned short  hw_config;  /* hardware config (word 93)
#                    * 15:  Shall be ZERO
#                    * 14:  Shall be ONE
#                    * 13:
#                    * 12:
#                    * 11:
#                    * 10:
#                    *  9:
#                    *  8:
#                    *  7:
#                    *  6:
#                    *  5:
#                    *  4:
#                    *  3:
#                    *  2:
#                    *  1:
#                    *  0:  Shall be ONE
#                    */
#   unsigned short  acoustic;   /* (word 94)
#                    * 15:8 Vendor's recommended value
#                    *  7:0 current value
#                    */
#   unsigned short  msrqs;      /* min stream request size */
#   unsigned short  sxfert;     /* stream transfer time */
#   unsigned short  sal;        /* stream access latency */
#   unsigned int    spg;        /* stream performance granularity */
#   unsigned long long lba_capacity_2;/* 48-bit total number of sectors */
#   unsigned short  words104_125[22];/* reserved words 104-125 */
#   unsigned short  last_lun;   /* (word 126) */
#   unsigned short  word127;    /* (word 127) Feature Set
#                    * Removable Media Notification
#                    * 15:2 reserved
#                    *  1:0 00 = not supported
#                    *  01 = supported
#                    *  10 = reserved
#                    *  11 = reserved
#                    */
#   unsigned short  dlf;        /* (word 128)
#                    * device lock function
#                    * 15:9 reserved
#                    *  8   security level 1:max 0:high
#                    *  7:6 reserved
#                    *  5   enhanced erase
#                    *  4   expire
#                    *  3   frozen
#                    *  2   locked
#                    *  1   en/disabled
#                    *  0   capability
#                    */
#   unsigned short  csfo;       /*  (word 129)
#                    * current set features options
#                    * 15:4 reserved
#                    *  3:  auto reassign
#                    *  2:  reverting
#                    *  1:  read-look-ahead
#                    *  0:  write cache
#                    */
#   unsigned short  words130_155[26];/* reserved vendor words 130-155 */
#   unsigned short  word156;    /* reserved vendor word 156 */
#   unsigned short  words157_159[3];/* reserved vendor words 157-159 */
#   unsigned short  cfa_power;  /* (word 160) CFA Power Mode
#                    * 15 word 160 supported
#                    * 14 reserved
#                    * 13
#                    * 12
#                    * 11:0
#                    */
#   unsigned short  words161_175[15];/* Reserved for CFA */
#   unsigned short  words176_205[30];/* Current Media Serial Number */
#   unsigned short  words206_254[49];/* reserved words 206-254 */
#   unsigned short  integrity_word; /* (word 255)
#                    * 15:8 Checksum
#                    *  7:0 Signature
#                    */
# };

rawDescription: How to get hard disk serial number using Python

description: Get hard disk serial number using Python


code: System.out.println("category:buffer overflow  analyzer:data flow analyzer:buffer".replaceAll("\\s([^\\s]+:)", "\n$1"));

rawDescription: Read a file and cut each line based on multiple criteria


code:
from itertools import product
map("".join, product(*[['A', 'C'] if x == "M" else [x] for x in "GMTTMCA"]))

rawDescription: Looking for elegant glob-like DNA string expansion


code: return True

rawDescription: Credit card check exercise python

description: Credit card check exercise python


code:
list(binomial_choice(range(100), 0.05))
list(binomial_choice(range(5), 1))

rawDescription: Given iterable, select each element independently with probability p


code:
from collections import Counter
def ModeList(lst):
    return Counter(lst).most_common(1)[0][0]

ModeList( [2,4,6,8,6,8] )

rawDescription: Mode of a List - Python

description: Mode of a List - Python


code:
listSize = int(input("Enter the list size: "))
numbers = []
evenCount = 0

for i in range(listSize):
    number = int(input("Enter a number: "))
    numbers.append(number)

for number in numbers:
    if number % 2 == 0:
        evenCount = evenCount + 1

print(evenCount)

rawDescription: How to count even numbers in a user input list

description: Count even numbers in a user input list


code: print(1, end=' '); print(2)

rawDescription: "print x," equivalent in Python3

description: "print x," equivalent in Python3


code: berries = 'strawberries', 'bilberry', 'blackberry'

rawDescription: Web2py custom forms and for loop

description: Web2py custom forms and for loop


code:
import unittest
from selenium import webdriver

class Login(unittest.TestCase):

    def setUp(self):
        # create a new Firefox session
        self.driver = webdriver.Firefox()
        self.driver.get("http://google.com")
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

    def tearDown(self):
        self.driver.quit()

rawDescription: Python webdriver: reusing setUp and tearDown


code:
def remove_extra(lst):
    lst[:] = set(lst)
    return lst

rawDescription: Remove duplicates in a list and check whether it's the same as another list


code:
myapp/tests.py
from myapp.models import A, B, C

A.objects.values('b__color', 'c__taste', 'c__smell')\
         .order_by('id') \
         .distinct()

rawDescription: Joining multiple tables for a single report in Django


code:
spam = foo + bar + baz + ham + \
       eggs + ham + spam + spam + \
       spam + sausages + spam

rawDescription: Unicode escaped comments in Python

description: Unicode escaped comments in Python


code:
with open("passwdfile") as htpwd:
    usernames = [line.split(":")[0] for line in htpwd.readlines()]

rawDescription: How to access the value of username from htpasswd file using python script

description: Access the value of username from htpasswd file using python script


code: {'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.3.0 CPython/2.7.6 Darwin/14.1.0'}

rawDescription: Extracting string with BeautifulSoup

description: Extracting string with BeautifulSoup


code:
user_scores = {}
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores or user_scores[name] < score:
        user_scores[name] = score

rawDescription: Displaying only a person's highest score from a .txt file (Python 3)


rawDescription: Pandas df.to_records() returns a 1d numpy array


code:
from imaplib import IMAP4, IMAP4_SSL, IMAP4_PORT, IMAP4_SSL_PORT
from socks import sockssocket, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5, PROXY_TYPE_HTTP

class SocksIMAP4(IMAP4):
    def open(self,host,port=IMAP4_PORT):
        self.host = host
        self.port = port
        self.sock = sockssocket()
        self.sock.setproxy(PROXY_TYPE_SOCKS5,'socks.example.com')
        self.sock.connect((host,port))
        self.file = self.sock.makefile('rb')

rawDescription: Python - How can I fetch emails via POP or IMAP through a proxy?


code:
from django.test import TestCase
from django.conf import settings

class CheckSettings(TestCase):

  def test_settings(self):
    self.assertEqual(settings.TEST_VALUE, 'a')

  def test_modified_settings(self):
    with self.settings(TEST_VALUE='b'):
      self.assertEqual(settings.TEST_VALUE, 'b')

rawDescription: Overriding Settings for unit tests in Django doesn't work properly


code:
body=dom.xpath('//ns:Body',namespaces={'ns':'http://www.xxx.com/zzz/yyy'})
print(body)
# [<Element {http://www.xxx.com/zzz/yyy}Body at 90b2d4c>]

rawDescription: lxml etree xmlparser namespace problem

description: Lxml etree xmlparser namespace problem


code:
torrent_file = open(sys.argv[1], "rb")
metainfo = bencode.bdecode(torrent_file.read())
info = metainfo['info']
pieces = StringIO.StringIO(info['pieces'])

rawDescription: Extract the SHA1 hash from a torrent file


code:
from re import sub
docstring("Copyright unknown")(sub)

rawDescription: Setting the docstring to an expression inside def


code:
import operator

x = map(operator.attrgetter("text"), soup.find_all('option'))

rawDescription: Obtain text from all items in list using BeautifulSoup


rawDescription: strip sides of a string in python

description: Strip sides of a string in python


rawDescription: Matpotlib Xtick Overlap

description: Matpotlib Xtick Overlap


code:
pos = pygame.mouse.get_pos()
for rect in rectangles:
    if rect.collidepoint(pos):
        changecolor(rect)

rawDescription: Creating a rect grid in Pygame

description: Creating a rect grid in Pygame


code:
data = numpy.load('test.npz')
a = data['a']

rawDescription: Save vectors to file in Python with NumPy


code:
import datetime
inputstring = '23 Mar'
today = datetime.date.today()
yourdate = datetime.datetime.strptime(inputstring, '%d %b')
yourdate = yourdate.date().replace(year=today.year)
yourdate
yourdate >= today

rawDescription: Python: How can I see if a given month and day have already passed this year?


code:
parser = argparse.ArgumentParser(description='Module to untar TAR files')
parser.add_argument('file', help='File to open')
parser.add_argument('folder', help='Destination to extract to')
args = parser.parse_args()

rawDescription: How do I easily store a file and folder location with argparse and then use those values

description: Easily store a file and folder location with argparse and then use those values


code: 'Nunc dui mi rhoncus ut aliquet'

rawDescription: Python - Conditionally split line

description: Python - Conditionally split line


code:
import datetime
start = datetime.time(23, 0, 0)
end = datetime.time(1, 0, 0)
time_in_range(start, end, datetime.time(23, 30, 0))
time_in_range(start, end, datetime.time(12, 30, 0))

rawDescription: How to check if the current time is in range in python?

description: Check if the current time is in range in python


code: max((digits[i:i+13] for i in xrange(0, len(digits) - 12)), key=lambda x: reduce(mul, map(int, x)))

rawDescription: Largest product in a series in python

description: Largest product in a series in python


rawDescription: Creating Nested Dictionary from File hierarchy


code: {'root': [{'configuration': None, 'field_b': 'bbbb', 'field_a': 'aaaa'}, {'child': [{'configuration': {'field_b': 'bbb1', 'field_a': 'aaa1'}}]}, {'child': [{'configuration': {'field_b': 'bbb2', 'field_a': 'aaa2'}}]}]}

rawDescription: How to parse this special config file in python?

description: Parse this special config file in python


code:
def foo(l1, l2, i, j, k):
    #from itertools import izip
    l2[j:j + k] = map(sum, zip(l1[i: i +k], l2[j: j + k]))
    #l2[j:j + k] = map(sum, izip(l1[i: i +k], l2[j: j + k]))
    return l2

rawDescription: Add lists in a certain range

description: Add lists in a certain range


code:
import pandas as pd
df1 = pd.read_csv("file1.csv", sep=r"\s+")
df2 = pd.read_csv("file2.csv", sep=r"\s+")
df1.head()
df2.head()

rawDescription: Comparing two files and printing similar lines


code:
import re
from django.template.defaultfilters import date as date_filter

# --------------------------------------------------------------------------------
#   |smartdate:"date format" -- new arg 'c' (change) alteras the AM/pm appearance
# --------------------------------------------------------------------------------
@register.filter
def smartdate(value, arg):
    rendered = date_filter(value, arg)
    if 'c' in arg:
        rendered = re.sub('(a|p)\.m\.c', lambda m: '%sm' % m.group(1), rendered)
        rendered = re.sub('(A|P)Mc', lambda m: '%s.M.' % m.group(1), rendered)
    return rendered

rawDescription: Django date filter to output "am" or "A.M."


code:
D2 = (xf[:,None] - xg[None,:])**2 + (yf[:,None] - yg[None,:])**2 + (zf[:,None] - zg[None,:])**2
a1 = np.array([G.epsilon[near_row].mean() for near_row in D2 < 20**2])

rawDescription: Code works but too slow

description: Code works but too slow


code: array = np.column_stack(output)

rawDescription: Appending arrays by array names

description: Appending arrays by array names


code:
OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

rawDescription: Convert a number range to another range, maintaining ratio


code:
from audiolazy import sHz, white_noise, line, resonator, AudioIO

rate = 44100
s, Hz = sHz(rate)

sig = white_noise() # Endless white noise Stream

dur = 8 * s # Some few seconds of audio
freq = line(dur, 200, 800) # A lazy iterable range
bw = line(dur, 100, 240)

filt = resonator(freq * Hz, bw * Hz) # A simple bandpass filter

with AudioIO(True) as player:
  player.play(filt(sig), rate=rate)

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code: browser = webbrowser.get("firefox")

rawDescription: Python code to open image in browser?

description: Python code to open image in browser


rawDescription: How to apply a logical operator to all elements in a python list

description: Apply a logical operator to all elements in a python list


code: as_dict = dict(i.partition('=')[::2] for i in args.D)

rawDescription: python argparse extra args

description: Python argparse extra args


code: temps = [float(s) for s in line[1:] if s]

rawDescription: Inputting data from file into tuple

description: Inputting data from file into tuple


code:
...
def changePixmap(self, img):
    self.pixmap = QtGui.QPixmap(img)
    self.repaint() # repaint() will trigger the paintEvent(self, event), this way the new pixmap will be drawn on the label

rawDescription: Resizing QPixmap while maintaining aspect ratio


code:
timeit.Timer(lambda: sorted(itertools.chain(ll1g, ll2g))).repeat()
timeit.Timer(lambda: list(heapq.merge(ll1g,ll2g)) ).repeat()

rawDescription: Merge two lists with labels

description: Merge two lists with labels


code:
name, weeks_worked, weekly_payment = [], [], []
for line in file.readlines():
    match = line_format.match(line)
    if match:
        name.append(match.group(1))
        weeks_worked.append(match.group(2))
        weekly_payment.append(match.group(3))
    else:
        raise ...

rawDescription: Read from text file and assign data to new variable


code:
df['end_time'] = pd.to_datetime(df['end_time'],unit='s')
df['start_time'] = pd.to_datetime(df['end_time'],unit='s')
df

rawDescription: Converting multiple columns with timestamp values to GMT time without using DateTimeIndex in pandas


code:
import json
json.loads('{"a": "2"}')
json.loads('{"a": "2\""}')

rawDescription: parse special json format with python

description: Parse special json format with python


code:
[(('USA', 'Mac OS X'), 1),
 (('Mexico', 'Windows XP'), 2),
 (('USA', 'Windows XP'), 2),
 (('Mexico', 'iOS'), 3),
 (('Germany', 'Windows XP'), 7),
 (('Germany', 'Windows 7'), 9)]

rawDescription: Python. Get pairs of keys (n0, _), (n1, _) with maximum values for each key pair (n0, a), (n0, b) in a dictionary. Not a trivial task


rawDescription: How to create multiple value dictionary from pandas data frame

description: Create multiple value dictionary from pandas data frame


code:
def regressionTest():
   path = os.path.abspath(os.path.dirname(sys.argv[0]))

rawDescription: How can i make the attached pyunit python script search for tests in subfolders

description: Make the attached pyunit python script search for tests in subfolders


rawDescription: Query on local frame and global frame in python Environment


code:
with open(secondfile) as f:
    with open(outputfile, 'w') as f1:
        for key in order:
            f.seek(key2offset[key])
            line = f.readline()
            f1.write(line)

rawDescription: Iterate through a file multiple times

description: Iterate through a file multiple times


Avro

ActionOnFailure: CONTINUE

Type: STREAMING

rawDescription: How to load additional JARs for an Hadoop Streaming job on Amazon EMR

description: Load additional JARs for an Hadoop Streaming job on Amazon EMR


code:
points = np.array([[0, 0], [45, 0], [45, 45], [90, 0]], dtype=float)
dist(points, points)
np.max(_)

rawDescription: Speed up python code - can I vectorize double for loop?


rawDescription: convert string into int()

description: Convert string into int()


code:
A1averaged['temp'] = A1averaged['temp'] * 10
A1indexed['temp'] = A1indexed['temp'] / 10

rawDescription: Inserting rows into dataframe by reindexing


code:
class RelatedResource(ModelResource):
    class Meta:
        ...

class MyResource(ModelResource):
    related = fields.ForeignKey(RelatedResource, full=True)

    class Meta:
        ...

rawDescription: How to load the foreign keys elements in Tastypie

description: Load the foreign keys elements in Tastypie


code:
import numpy as np
np.random.seed(1)

x, y, z = np.random.random((3, 20))

# Note that we've remove the `x` and `y` terms.
# We're solving `z = a + cx^2 + ey^2`
A = np.column_stack([np.ones(len(x)), x**2, y**2])
B = z

# Solve the system of equations.
result, _, _, _ = np.linalg.lstsq(A, B)
a, c, e = result

rawDescription: Fit data to curve using polyfit with multiple variables in python using numpy polyfit


rawDescription: How to use regex substitute using different capture and match strings?

description: Use regex substitute using different capture and match strings


code:
ROSTER = []

class Player():
    def __init__(self, name, score = 0):
        self.name = name
        self.score = score
        ROSTER.append(self)

rawDescription: Simple OOP query. Python: saving object names in __init__


code: #See example above

rawDescription: How can I make my code more readable and DRYer when working with XML namespaces in Python?

description: Make my code more readable and DRYer when working with XML namespaces in Python


rawDescription: How to find all divs who's class starts with a string in BeautifulSoup?

description: Find all divs who's class starts with a string in BeautifulSoup


rawDescription: Simple cross-tabulation in pandas

description: Simple cross-tabulation in pandas


code:
def in_trie(trie, word):
    current_dict = trie
    for letter in word:
        if letter in current_dict:
            current_dict = current_dict[letter]
        else:
            return False
    else:
        if _end in current_dict:
            return True
        else:
            return False

in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'baz')
in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barz')
in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barzz')
in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'bart')
in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'ba')

rawDescription: How to create a TRIE in Python

description: Create a TRIE in Python


code:
s[4:]
s[4:].first_valid_index()

rawDescription: How can I get the index of next non-NaN number with series in pandas?

description: Get the index of next non-NaN number with series in pandas


code:
class SingleCat(DetailView):
    model = Category
    template = 'category_single.html'

    def get_context_data(self, **kwargs):
       context = super().get_context_data(**kwargs)
       current_category = context['object']
       context['products'] = current_category.product_set.all()
       return context

rawDescription: Make that my categories displays each respective content isolatedly


code: ax.legend(lines, my_legends)

rawDescription: Adding legends to plots when not using the pyplot interface


code:
checkNameArr = [['551002', 'Derek Jones'],
                ['940874', 'Hugh Lunny'],
                ['104741', 'Richard Plaith'],
                ['310125', 'Aideen Toner'],
                ['305795', 'Vikki Trench'],
                ['218714', 'Paul Cutland'],
                ['401741', 'Russell Smith'],
                ['223996', 'Chloe Green'],
                ['845216', 'Simon Fallon'],
                ['402258', 'Chris Worth']]
queryNameArr = [['551002', 'Derek Jones'],
                ['940874', 'Hugh Lunny'],
                ['823085', 'Brian Deans'],
                ['310125', 'Aideen Toner'],
                ['571454', 'Pam Scales'],
                ['967825', 'Una Lingus'],
                ['401741', 'Russell Smith'],
                ['682301', 'Hannah Jacobs'],
                ['914774', 'Elaine Glass'],
                ['402258', 'Chris Worth']]
checkNameSet = set(map(tuple, checkNameArr))
found = []
notfound = []
for i in queryNameArr:
    if tuple(i) in checkNameSet:
            found.append(i)
    else:
            notfound.append(i)
found
notfound

rawDescription: Iterating and comparing list of lists in Python


code:
def obsfucate(word):
    return ''.join([random.choice(["!", "%", "*", "#", "@"]) if random.random() > 0.1 else char for char in word])

rawDescription: Python, obfuscating letters in a list

description: Python, obfuscating letters in a list


code: print("You know {} unique word(s)!".format(len(words)))

rawDescription: How to not count the duplicates from an user input?

description: Not count the duplicates from an user input


code:
def addTags(functionHere):
    def wrapper(*args, **kw):
        return "NumberTag" + functionHere(*args, **kw) + "NumberTagOver"
    return wrapper

rawDescription: Decorators in Python

description: Decorators in Python


rawDescription: get intersection of list of sets

description: Get intersection of list of sets


code: arr = np.matrix(arr)

rawDescription: Efficient manipulations of binary matrix in numpy


code: goodFiles = filter(fileFilter, htmlfiles)

rawDescription: How do I match items in one list against items in another list in Python

description: Match items in one list against items in another list in Python


code:
import numpy as np
x = np.arange(20).reshape((4,5))
np.savetxt('test.txt', x)

rawDescription: How to write a multidimensional array to a text file?

description: Write a multidimensional array to a text file


code:
import httplib
conn = httplib.HTTPConnection('127.0.0.1')
conn.send(open(filename))
response = conn.getresponse()

rawDescription: Python send packet over 443

description: Python send packet over 443


code: timeit(bar, number=10000)

rawDescription: Why is Python 3 is considerably slower than Python 2?


rawDescription: Python metaclass arguments

description: Python metaclass arguments


code:
yourBinNumber = 1010
paddedString = "%013d" % yourBinNumber

rawDescription: Checking where 1 occurs in a Binary Number


code:
import psutil

def get_pid(process_name):
    pid = None
    for proc in psutil.process_iter():
        try:
            if (proc.name() == process_name):
                pid = proc.pid
        except (PermissionError, psutil.AccessDenied):
            pass
    return pid

rawDescription: How do I look up the value of a multi-level pointer inside a process in Python?

description: Look up the value of a multi-level pointer inside a process in Python


code:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)

rawDescription: How to pass SOAP headers into python SUDS that are not defined in WSDL file

description: Pass SOAP headers into python SUDS that are not defined in WSDL file


code:
from suds.client import Client
from suds.xsd.doctor import Import, ImportDoctor
url = 'http://data.opensolution.se/index.php?wsdl'
imp = Import('http://www.w3.org/2001/XMLSchema')
doctor = ImportDoctor(imp)
client = Client(url, doctor=doctor)

rawDescription: suds.TypeNotFound error

description: Suds.TypeNotFound error


code:
from datetime import datetime
dates = [datetime.strptime(item, '%Y-%m-%dA%H:%M') for item in list2]

rawDescription: Remove certain dates in list. Python 3.4


code:
films = Film.objects.filter(Q(actors__in=Actor.objects.filter(follow_set__user=request.user)) |
                Q(genres__in=Genre.objects.filter(follow_set__user=request.user))).distinct()

rawDescription: Find related objects and display relation


code:
def floatInput():
    done = False
    while not done:
        integerIn = input("Please enter an integer < 0 to finish >: ")
        try:
            integerIn = int(integerIn)
        except:
            print("I was expecting an integer number, please try again...")
            import sys
            sys.exit()

rawDescription: Python While loop won't exit when asked to


code:
# Perform "np.einsum('ijk,isl->jksl', v, a)"
p1 = np.tensordot(v,a,axes=([0],[0]))         # shape = jksl

# Perform "np.einsum('jksl,jstm->kltm', p1, w)"
p2 = np.tensordot(p1,w,axes=([0,2],[0,1]))    # shape = kltm

# Perform "np.einsum('kltm,ktn->lmn', p2, w)"
z = np.tensordot(p2,x,axes=([0,2],[0,1]))     # shape = lmn

rawDescription: Efficient reduction of multiple tensors in Python


code:
for i in range(5):
    response.xpath('//*[@id="mw-content-text"]/table[{}]/tr/td[1]/a/@href'.format(str(i))).extract()

rawDescription: how to select tables with scrapy?

description: Select tables with scrapy


code: df[['A', 'B', 'C']].apply(lambda x: x.fillna(value=df['D']))

rawDescription: Row-by-row fillna with respect to a specific column?


code:
import unittest
from ..mydir1 import mymodule1

class Test1(unittest.TestCase):
    def test1(self):
        self.assertEqual(mymodule1.x,1) # mymodule1 trivially contains x=1

rawDescription: Python3 Relative Imports inside a package


code:
it = graph.depth_first_search()
for node, depth in it: #this is why there should be pronouns for loop iterables
    stuff(node,depth)
    if quit: it.send(1)
    # it.next() should raise StopIteration on the next for iteration

rawDescription: Stop generator from within block in Python


code:
audio = mutagen.easyid3.EasyID3('./Björk/Albums/1990 - Gling-Gló [mp3-231]/01 - Gling-Gló.mp3')
audio['title']

rawDescription: mutagen and id3 tags - character encoding confusion

description: Mutagen and id3 tags - character encoding confusion


rawDescription: How to import efficiently values in Python from a list of global variables in a C header file

description: Import efficiently values in Python from a list of global variables in a C header file


rawDescription: Getting values out of a python dictionary


code:
s1 = "The weather is 75 degrees with a humidity of 13%"
m = re.search("The weather is (\d+) degrees with a humidity of (\d+)%", s1)
m.groups()

rawDescription: How to use regex to reference specific parts?

description: Use regex to reference specific parts


code:
import operator

def sort_multi(L,*operators):
    L.sort(key=operator.itemgetter(*operators))

rawDescription: Stable sorting in Jinja2

description: Stable sorting in Jinja2


code:
class example:
    a = somevalue

rawDescription: Access a Python variable which is inside a function, in another function


code:
f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)

with f as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')

rawDescription: Create an interactive command loop using inheritance python34


rawDescription: Finding files in directories in Python

description: Finding files in directories in Python


code: flierprops = dict(marker='o', fillstyle='full', markeredecolor='red', markeredgewidth=0.0)

rawDescription: Remove edgewidth of matplotlib boxplot flier


code:
def myglob():
    global myurls

rawDescription: How to globally declare this Python list

description: Globally declare this Python list


code:
import Ska.engarchive
Ska.engarchive.__path__.insert(0, 'Ska/engarchive')
import Ska.engarchive.fetch_eng as fetch
fetch.__file__

rawDescription: Import local testing version of a Python namespace package


code:
def jsd_vectorized(A,I):

    # Perform "(x+y)" in a vectorized manner
    AI = A+I[:,None]

    # Calculate d1 and d2 using AI again in vectorized manner
    d1 = A*np.log2(2*A/AI)
    d2 = I[:,None,:]*np.log2((2*I[:,None,:])/AI)

    # Use np.nansum to ignore NaNs & sum along rows to get all distances
    dists = np.nansum(d1,2) + np.nansum(d2,2)

    # Pack the argmax IDs and the corresponding scores as final output
    ID = dists.argmax(0)
    return np.vstack((0.5*dists[ID,np.arange(dists.shape[1])],ID)).T

rawDescription: Applying a function for all pairwise rows in two matrices under Numpy


code:
import collections

def flat_gen(x):
    def iselement(e):
        return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
    for el in x:
        if iselement(el):
            yield el
        else:
            for sub in flat_gen(el): yield sub

print(list(flat_gen(["junk",["nested stuff"],[],[[[],['deep']]]])))
# ['junk', 'nested stuff', 'deep']

rawDescription: Python 3 replacement for deprecated compiler.ast flatten function


code:
application/__init__.py
...
app = Flask(__name__)
...
db  = SQLAlchemy(app) #because I use sqlalchemy
...
import application.core

rawDescription: Getting the database connection from application context with Flask-Restful


code:
def bitwise_or(num1, num2):
    new_num1 =list(num1)
    new_num2 = list(num2)
    if len(num1) > len(num2):
        new_num2[2:2] = '0' * (len(num1) - len(num2))
    elif len(num1) < len(num2):
        new_num1[2:2] = '0' * (len(num2) - len(num1))

    new_num = []
    for c1, c2 in zip(new_num1, new_num2):
        if c1 == "1" or c2 == "1":
            new_num.append("1")
        else:
            new_num.append(c1)
    return ''.join(new_num)

rawDescription: What is wrong with this alternative bitwise operator function?


code: url("^portal/forums/showthread.php", thread), #You might want the $ sign at the end.

rawDescription: Django URLConf for former forum URL

description: Django URLConf for former forum URL


rawDescription: In place editing of Python dictionary or parsing json to object


code: "Mary has a {1} and an {0}".format(*np.char.decode(my_array))

rawDescription: Numpy String Encoding

description: Numpy String Encoding


code:
comp == decomp
len(comp)
len(decomp)

rawDescription: How do I iterate through unicode symbols, not bytes in python?

description: Iterate through unicode symbols, not bytes in python


rawDescription: Finding minimum in an array

description: Finding minimum in an array


rawDescription: The most effective way to organize info on Pandas dataframe


code:
class GetPost(webapp2.RequestHandler):
    def get(self, captured_thing):
        self.response.write(captured_thing)

rawDescription: Regular expression app engine

description: Regular expression app engine


code:
from scipy.stats import norm
norm.ppf(.5)  # half of the mass is before zero

rawDescription: python equivalent of qnorm, qf and qchi2 of R

description: Python equivalent of qnorm, qf and qchi2 of R


code:
def binned_statistic(x, values, func, nbins, range):
    '''The usage is approximately the same as the scipy one'''
    from scipy.sparse import csr_matrix
    N = len(values)
    r0, r1 = range

    digitized = (float(nbins) / (r1-r0) * (x-r0)).astype(int)
    S = csr_matrix((values, [digitized, np.arange(N)]), shape=(nbins, N))

    return [func(group) for group in np.split(S.data, S.indptr[1:-1])]

rawDescription: Efficiently get indices of histogram bins in Python


rawDescription: Free up numbers from string

description: Free up numbers from string


code:
import csv

with open('data.txt') as f:
    reader = csv.DictReader(f, delimiter='\t')
    rows = list(reader)

rawDescription: creating lists from text file using pandas in python

description: Creating lists from text file using pandas in python


code:
class Foo:
   def __init__(self, foo, bar):
       self.foo, self.bar = foo, bar

rawDescription: Python 3 object construction: which is the most Pythonic / the accepted way?


code:
s = "abc\u20ac\U00010302\U0010fffd"
len(s)
for c in s:
    print('U+{:04X}'.format(ord(c)))

rawDescription: How to iterate over Unicode characters in Python 3?

description: Iterate over Unicode characters in Python 3


code:
test = list('asdf')
[function(x) for x in test]

rawDescription: python, functions running from a list and adding to a list through functions

description: Python, functions running from a list and adding to a list through functions


code:
the_quick
quick_brown
brown_fox
fox_jumped
jumped_over
over_the
the_lazy
lazy_dog
the
quick
brown
fox
jumped
over
lazy
dog

rawDescription: How to represent bi-grams

description: Represent bi-grams


code:
def multiply_by_2(x):
    return 2*x

x = 1
x = multiply_by_2(x)

rawDescription: Python passing an integer by reference

description: Python passing an integer by reference


rawDescription: How do nested functions work in Python?

description: How do nested functions work in Python


code:
class AccountMapForm(forms.Form):
    account_nagp = forms.CharField()

    def __init__(self, *args, **kwargs):
       super(AccountMapForm, self).__init__(*args, **kwargs)
       self.helper = FormHelper()
       self.helper.form_class = 'form-horizontal'
       self.helper.label_class = 'col-md-4'
       self.helper.field_class = 'col-md-6'
       self.helper.layout = Layout(
           Field('account_nagp', css_class='input-xlarge'),
           FormActions(
              Submit('save_changes', 'Map', css_class='btn-primary col-md-offset-1 col-md-4'),
              Submit('un_map', 'UnMap', css_class='btn-primary col-md-offset-1 col-md-4'),
            )
        )

rawDescription: How to edit/update a model via Django form with manytomany field?

description: Edit/update a model via Django form with manytomany field


code:
import re

text = r'''"This is a string with an \"escaped quote\" inside it". While ""===r?+r:wt.test(r)?st.parseJSON(r)    :r}catch(o){}st.data(e,n,r)}else r=t}return r}function s(e){var t;for(t in e)if(("data" '''

for match in (re.findall(r'''(?x)   # verbose mode
    (?<!\\)    # not preceded by a backslash
    "          # a literal double-quote
    .*?        # 1-or-more characters
    (?<!\\)    # not preceded by a backslash
    "          # a literal double-quote
    ''', text)):
    print(match)

rawDescription: Correctly parsing string literals with python's re module


code: f.append(f.loc[['A', 'B']].sum(), ignore_index=True).drop(f.index.get_indexer(['A', 'B'])).set_index(Index(['C', 'sumAB']))

rawDescription: Pandas: Replace a set of rows by their sum


code:
htmlDoc.close()

html = soup.prettify("utf-8")
with open("output.html", "wb") as file:
    file.write(html)

rawDescription: How to save back changes made to a HTML file using BeautifulSoup in Python?

description: Save back changes made to a HTML file using BeautifulSoup in Python


code:
duple_dict = dict(duple_list)
duple_dict

rawDescription: matching a string to a list of tuples

description: Matching a string to a list of tuples


rawDescription: how to disable windows speech recognition commands?

description: Disable windows speech recognition commands


code:
import os
import re
import base64
from bs4 import BeautifulSoup as BS
from uuid import uuid4

def dump(path, data):
    root = os.path.dirname(path)
    if not os.path.exists(root):
        os.makedirs(root)
    with open(path, 'wb') as f:
        f.write(data)
    # for windows
    return path.replace('\\', '/')

def freeze_html(path):
    '''pass in absolute path of your html'''
    root = os.path.dirname(path)
    with open(path, 'rb') as f:
        soup = BS(f.read())
    for img in soup.find_all('img'):
        m = re.search(r"data:image/png;base64,b'(.*)'", img['src'])
        if m:
            iname = uuid4()
            ipath = os.path.join(root, 'images', '%s.png' % iname)
            # remove '\n'
            s = m.group(1).replace(r'\n', '')
            img['src'] = os.path.relpath(
                dump(ipath, base64.b64decode(s.encode('ascii'))),
                root
            )
    with open(path, 'wb') as f:
        f.write(soup.encode('utf-8'))

rawDescription: ipython notebook .png figures after nbconvert not loaded by latest chrome/firefox

description: Ipython notebook .png figures after nbconvert not loaded by latest chrome/firefox


code: myList = ','.join(map(str, myList))

rawDescription: How would you make a comma-separated string from a list?


code:
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application
from flasky import app

class MainHandler(RequestHandler):
  def get(self):
    self.write("This message comes from Tornado ^_^")

tr = WSGIContainer(app)

application = Application([
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
])

if __name__ == "__main__":
  application.listen(8000)
  IOLoop.instance().start()

rawDescription: using Flask and Tornado together?

description: Using Flask and Tornado together


rawDescription: How can I refresh a select option in a form without resulting loss of form input (Django + jQuery)

description: Refresh a select option in a form without resulting loss of form input (Django + jQuery)


code:
# create an empty dictionary:
my_dict = {}

# open the file:
with open("file.fna") as file:

    # read the file line by line:
    for line in file:

        # split at whitespace and take the last word:
        word = line.split()[-1]

        # add entry to dictionary: all but the last character -> key; last character -> value
        my_dict[word[:-1]] = word[-1]

rawDescription: Create dictionary from Fasta file

description: Create dictionary from Fasta file


code:
for i in range(len(thelist)):
    sub_list = thelist[i]
    current_pay_date = sub_list[1]
    next_sub_list = thelist[i+1]
    next_pay_date = next_sub_list[1]

rawDescription: Python, Get element from list

description: Python, Get element from list


code: get_min_length = enum_mapper(packet_types, pkt_lengths)

rawDescription: How to ensure solid contracts without strong typing?

description: Ensure solid contracts without strong typing


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
np.random.seed(1977)

data = np.random.random((10,25))
data = np.ma.masked_greater(data, 0.8)

fig, ax = plt.subplots()
im = ax.pcolormesh(data, cmap=cm.gray, edgecolors='white', linewidths=1,
                   antialiased=True)
fig.colorbar(im)

ax.patch.set(hatch='xx', edgecolor='black')

plt.show()

rawDescription: Matplotlib grayscale heatmap with visually distinct "NA" squares fields


code: re.split(r'[{}]', str)

rawDescription: Using re.split() for two { } in python

description: Using re.split() for two { } in python


rawDescription: How to create equal spaced values in between unequal spaced values in Python?

description: Create equal spaced values in between unequal spaced values in Python


code:
from difflib import SequenceMatcher

def find_subseq(seq1, seq2):
    """Find matching subsequences of the two argument sequences."""
    matcher = SequenceMatcher(None, seq1, seq2, False)
    out = []
    for start, _, size in matcher.get_matching_blocks():
        if size > 1:
            out.extend(seq1[start:start+size])
    return out

rawDescription: python - comparing order of list without sorting existing data

description: Python - comparing order of list without sorting existing data


code:
from PyQt4 import QtCore, QtGui

class MooGraphicsScene(QtGui.QGraphicsScene):
    def __init__(self, parent = None):
        QtGui.QGraphicsScene.__init__(self, parent)

    def dragMoveEvent(selfs, e):
        pass

    def dropEvent(self, e):
        print("Drop fired!")

    def dragEnterEvent(self, e):
        e.accept()
        print("Drag entered!")

rawDescription: PyQt event emmitted twice

description: PyQt event emmitted twice


rawDescription: How can i append <br> tags after a text element?

description: Append <br> tags after a text element


rawDescription: Every way to organize N objects in M list slots


code: os.system("sudo \"apt-get install snort-mysql\"")

rawDescription: Install a package by launching a new terminal through Python


code:
s = "This is figure 3a. This is fig 4a . I like (figure 5). This is important (fig 6a)."
import re
re.findall(r'[^.]*?fig[^.]*\d[^.]*', s)

rawDescription: Python regex expression to match pattern in sentences


code:
if __name__ == '__main__':
    gevent.signal(signal.SIGINT, teardown_applications)
    http_server = WSGIServer(('', 5000), app)
    http_server.serve_forever()

rawDescription: Flask and Web.py both hang on atexit

description: Flask and Web.py both hang on atexit


code:
numbers = ['Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One', 'no']
# variable to add s when needed
plural = "s"

# loop to all but last elements starting at Ten
for i, n in enumerate(numbers[:-1]):
    # if n is One we we don't need s
    if i > 8:
        plural = ""
    # get next element for second part of string
    nxt = numbers[i+1]
    text_one = '{w} green bottle{pl}\nHanging on the wall'.format(w=n, pl=plural)
    # if the next element is One we also need don't need s for text_two
    if nxt == "One":
        plural  = ""
    text_two = "And if one green bottle\nShould accidentally fall\nThere'll be {nxt} green bottle{pl}"\
        .format(nxt=nxt.lower(),pl=plural)
    print(text_one+text_two+' hanging on the wall\n')

rawDescription: Python 3.x Ten green bottles = fix plurals and capitalization


code:
string = 'Hello %*& World'
repl = ['%','*','&'], ['pct','star','and']
for a, b in zip(*repl):
    string = string.replace(a, b)

rawDescription: Replacing a string's content with something from a list or dictionary in Python 3


rawDescription: Combining rows in pandas

description: Combining rows in pandas


code: indexer = [ slice(None) ] * len(df.index.levels)

rawDescription: Pandas multi-index slices for level names


rawDescription: Fixing faulty unicode strings

description: Fixing faulty unicode strings


code:
bgr_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
img[10:20,10:20] = bgr_mask[10:20,10:20]

rawDescription: opencv python copy mask region (black or white pixels) onto a BGR image region

description: Opencv python copy mask region (black or white pixels) onto a BGR image region


code:
somehtml = 'Hello <b>world!</b>'
# purge element contents
content_tag.text = ''
for child in content_tag.getchildren():
    content_tag.remove(child)

fragments = lxml.html.fragments_fromstring(somehtml)
if type(fragments[0]) == str:
    content_tag.text = fragments.pop(0)
content_tag.extend(fragments)

rawDescription: Python: Injecting HTML content into a tag using `lxml.html`


code:
text = data.text
rows = [line.split(',') for line in text.split("\n") if line]
rows.pop(0)  # get rid of first row from data
max_value = max(row[0] for row in rows)
max_row = max(rows, key=op.itemgetter(0))

rawDescription: CSV find max in column and append new data


rawDescription: Match members of a tuple to members of a list, python


rawDescription: Matplotlib - _tkinter.TclError: bad screen distance "320.0"


code: [v for k, v in sorted(x for x in dict1.items() if x[1])]

rawDescription: Sort dictionary values and discard those which do not have a value


code:
#! /usr/bin/python2.7

from PIL import Image, ImageDraw

im = Image.open ('zGjE6.png')
isize = im.size
walnut = Image.open ('walnut.png')
wsize = walnut.size
x0, y0 = wsize [0] // 2, wsize [1] // 2
pixel = walnut.getpixel ( (x0, y0) ) [:-1]

def diff (a, b):
    return sum ( (a - b) ** 2 for a, b in zip (a, b) )

best = (100000, 0, 0)
for x in range (isize [0] ):
    for y in range (isize [1] ):
        ipixel = im.getpixel ( (x, y) )
        d = diff (ipixel, pixel)
        if d < best [0]: best = (d, x, y)

draw = ImageDraw.Draw (im)
x, y = best [1:]
draw.rectangle ( (x - x0, y - y0, x + x0, y + y0), outline = 'red')
im.save ('out.png')

rawDescription: Finding the position of an object in an image


rawDescription: Drop observations from the data frame in python


code:
def test(obj):
    obj.getNewObject().getNewObject().getNewObject()

rawDescription: Python Class Stack Frame Limitations

description: Python Class Stack Frame Limitations


code: result

rawDescription: Python Pandas compare two dataframes to assign country to phone number


code:
def circle(*args):
    """ Draws a circle using *args """
    pass

def rectangle(*args):
    #  and so on
    pass

rawDescription: How can I organize my functions to get something like class.draw.line() instead of class.drawLine

description: Organize my functions to get something like class.draw.line() instead of class.drawLine


code:
longStr = r"C:\Users\Public\Documents\year 2013\testfiles" \
           r"\testcode\rawstringfiles.txt"
raw_StringFile = open(longStr, 'a')

rawDescription: breaking up long path names

description: Breaking up long path names


code: zippedLists = zip(mylist, mylist[12:], mylist[2:], mylist[13:])

rawDescription: Loop to Match Parts of List

description: Loop to Match Parts of List


rawDescription: Re assign a list efficiently

description: Re assign a list efficiently


code:
from operator import itemgetter

mylist.sort(key=itemgetter("mc_no"))

rawDescription: Group dictionary key values in python

description: Group dictionary key values in python


code:
from itertools import islice
def genIndexList(length, ID):
   id0 = str(ID)[0]
   for i3 in islice(base3sequence(), length):
       p = sum(map(int, id0 + i3[::2])) % 3
       yield '{}{}{}'.format(ID, i3, p)

rawDescription: Improve efficiency of modules

description: Improve efficiency of modules


code:
Requirements
import sys, tty, termios, codecs, unicodedata
from contextlib import contextmanager

rawDescription: Python, "filtered" line editing, read stdin by char with no echo


code:
res['address'] = res.address_y.where(res.address_y, res.address_x)
del res['address_x'], res['address_y']
res

rawDescription: Conditional merge for CSV files using python (pandas)


code:
from itertools import compress
list(compress([1, 2, 3], [1, 0, 1]))

rawDescription: Python reduce list by mask

description: Python reduce list by mask


code:
while True:
    for (x,y,w,h) in faces:
        for (ex, ey, ew, eh) in eyes:
            cv2.imshow('Video', frame)

rawDescription: OpenCV with Python - Trying to overlay an image over the eyes on a webcam feed


code:
class Level1():
    level1_name = CharField()

rawDescription: How can I change the strings as variables in python django?

description: Change the strings as variables in python django


code:
def always(x=None): # x=None when you don't give a argument
    return True

rawDescription: selectively copying from an input file

description: Selectively copying from an input file


rawDescription: numpy array equivalent for += operator

description: Numpy array equivalent for += operator


code:
from sympy import *
from sympy.geometry import *
x1, y1, x2, y2, xc, yc = symbols("x1,y1,x2,y2,xc,yc")
p1 = Point(x1, y1)
p2 = Point(x2, y2)
pc = Point(xc, yc)

line = Line(p1, p2)
pline = line.perpendicular_line(pc)
p = line.intersection(pline)[0]
cse(p, symbols=numbered_symbols("t"))

rawDescription: Circle and line collision detection in python tkinter


code: ['Spectral', 'summer', 'RdBu', 'Set1', 'Set2', 'Set3', 'brg_r', 'Dark2', 'hot', 'PuOr_r', 'afmhot_r', 'terrain_r', 'PuBuGn_r', 'RdPu', 'gist_ncar_r', 'gist_yarg_r', 'Dark2_r', 'YlGnBu', 'RdYlBu', 'hot_r', 'gist_rainbow_r', 'gist_stern', 'gnuplot_r', 'cool_r', 'cool', 'gray', 'copper_r', 'Greens_r', 'GnBu', 'gist_ncar', 'spring_r', 'gist_rainbow', 'RdYlBu_r', 'gist_heat_r', 'OrRd_r', 'bone', 'gist_stern_r', 'RdYlGn', 'Pastel2_r', 'spring', 'terrain', 'YlOrRd_r', 'Set2_r', 'winter_r', 'PuBu', 'RdGy_r', 'spectral', 'flag_r', 'jet_r', 'RdPu_r', 'Purples_r', 'gist_yarg', 'BuGn', 'Paired_r', 'hsv_r', 'bwr', 'YlOrRd', 'Greens', 'PRGn', 'gist_heat', 'spectral_r', 'Paired', 'hsv', 'Oranges_r', 'prism_r', 'Pastel2', 'Pastel1_r', 'Pastel1', 'gray_r', 'PuRd_r', 'Spectral_r', 'gnuplot2_r', 'BuPu', 'YlGnBu_r', 'copper', 'gist_earth_r', 'Set3_r', 'OrRd', 'PuBu_r', 'ocean_r', 'brg', 'gnuplot2', 'jet', 'bone_r', 'gist_earth', 'Oranges', 'RdYlGn_r', 'PiYG', 'YlGn', 'binary_r', 'gist_gray_r', 'Accent', 'BuPu_r', 'gist_gray', 'flag', 'seismic_r', 'RdBu_r', 'BrBG', 'Reds', 'BuGn_r', 'summer_r', 'GnBu_r', 'BrBG_r', 'Reds_r', 'RdGy', 'PuRd', 'Accent_r', 'Blues', 'Greys', 'autumn', 'PRGn_r', 'Greys_r', 'pink', 'binary', 'winter', 'gnuplot', 'pink_r', 'prism', 'YlOrBr', 'rainbow_r', 'rainbow', 'PiYG_r', 'YlGn_r', 'Blues_r', 'YlOrBr_r', 'seismic', 'Purples', 'bwr_r', 'autumn_r', 'ocean', 'Set1_r', 'PuOr', 'PuBuGn', 'afmhot']

rawDescription: How can I use a pre-made color map for my heat map in matplotlib?

description: Use a pre-made color map for my heat map in matplotlib


code:
import numpy
a = numpy.array([1,2,3])

rawDescription: Python - sparse vectors/distance calculation


code:
def match(s1, s2):
    ok = False

    for c1, c2 in zip(s1, s2):
        if c1 != c2:
            if ok:
                return False
            else:
                ok = True

    return ok

rawDescription: Compare strings, allowing one character difference


code:
mc = MyClass()
mc.var
mc.var = 'bar'
mc.var

rawDescription: Python class @property: use setter but evade getter?


rawDescription: python: dividing a number by a numpy array

description: Python: dividing a number by a numpy array


code: np.allclose(sum1, sum2)

rawDescription: How to efficiently sum the upper left coner of a matrix using numpy?

description: Efficiently sum the upper left coner of a matrix using numpy


code:
for upfile in request.FILES.getlist('form_file'):
    filename = upfile.name
    # instead of "filename" specify the full path and filename of your choice here
    fd = open(filename, 'w')
    fd.write(upfile['content'])
    fd.close()

rawDescription: Uploading multiple files in Django without using django.forms


code:
import numpy as np
from scipy import signal

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

# Convert to numpy array
arr = np.asarray(a,float)

# Define kernel for convolution
kernel = np.array([[0,1,0],
                   [1,0,1],
                   [0,1,0]])

# Perform 2D convolution with input data and kernel
out = signal.convolve2d(arr, kernel, boundary='wrap', mode='same')/kernel.sum()

rawDescription: Python get get average of neighbours in matrix with na value


code:
from flask.ext.login import LoginManager
login_manager = LoginManager()

def create_app(config=None):
  # ...
  login_manager.init_app(app)
  return app

rawDescription: Flask display user register, or already login in every template of each module


code:
df = DataFrame({"A": [1,2], "B": [3,4]})
df.rename(columns={"A": "series formerly known as A"})

rawDescription: python pandas: Rename a series within a dataframe?

description: Python pandas: Rename a series within a dataframe


code:
# This will create a list with 5 None values, i.e. variables[0] .. variables[4]
variables = [None] * 5

for i, value in enumerate(values):
    variables[i] = value

rawDescription: Assign a value to a list of variables using a loop


code:
def computeSubtreeSizes(self):
    stack = [(self.rootID, [])] #e.g. rootID = 1
    visited = self.sizes = {}

    while stack:
        nodeID, subnodes = stack[-1]
        size = visited.get(nodeID)
        if size is None:
            # Haven't seen it before.  Set total to 1,
            # and set up the list of subnodes.
            visited[nodeID] = size = 1
            subnodes[:] = self.nodes[nodeID]
        if subnodes:
            # Process all the subnodes one by one
            stack.append((subnodes.pop(), []))
        else:
            # When finished, update the parent
            stack.pop()
            if stack:
                visited[stack[-1][0]] += size

rawDescription: Iteratively compute subtree sizes for all nodes?


code:
def numb(a, b, c, d, e):
    assert all(x in {3, 5, 7} for x in (a, b, c, d, e))

rawDescription: Conditions of a function

description: Conditions of a function


rawDescription: Python: Code to find a number where first N digits are divisible by N (from 0-9)


code:
a = [('The','det'),('beautiful','adj')]
[(y, x.lower()) for x, y in a]

rawDescription: Python list comprehension. Alternative/Better way to write this code?


code:
from nltk.stem.porter import PorterStemmer # $ pip install nltk

stemmer = PorterStemmer()
print(stemmer.stem("pies"))
# -> pie

rawDescription: Classifying List Entries in Python

description: Classifying List Entries in Python


code:
from abc import ABCMeta, abstractmethod

class MyAbstractClass(object):
    __metaclass__=ABCMeta
    @abstractmethod
    def my_abstract_method():
        pass

rawDescription: Pure virtual methods in Python

description: Pure virtual methods in Python


code:
file1 = open("example.txt", "w")
file1.write(alldatainfile2)
file1.close()

rawDescription: How to open read-write file and recreate the file?

description: Open read-write file and recreate the file


code:
import struct
struct.pack('<l', 1234) + bytearray([0]*10)

rawDescription: Convert an int and bytearray into a ByteString Python struct Socket


code: ''.join(word) + ": " + str(e)

rawDescription: Treat all Unicode characters as single letters


code: value = info.findNext("b", "Oompa Loompa")

rawDescription: Compressing `x if x else y` statement in Python


rawDescription: Is it possible to add an attribute to a variable in python?


rawDescription: Check if an arbitrary user is in Administrator Group with Python


code:
property_attrs = {'logout': {'1.0': 'logged out', '2.0': 'logged out 2.0'},
                  'logout_message': {'1.0': 'goodbye logger', '2.0': 'goodbye logger 2.0'}}

def add_properties(property_attrs):
    def decorate(cls):
        for name, value in property_attrs.items():
            setattr(cls, name, property(lambda self: value[self.version]))
        return cls
    return decorate

@add_properties(property_attrs)
class A(object):
    def __init__(self):
        self.version = '1.0'
        self.login = 'logged in'
        self.login_message = 'hello logger'

rawDescription: python global decorator for class attributes

description: Python global decorator for class attributes


code:
import sys
from apt.cache import Cache
from apt.debfile import DebPackage

cache = Cache()
deb = DebPackage(sys.argv[1], cache)
deb.check()
print(deb.missing_deps)
print(deb.required_changes)

rawDescription: I am failing to get 'required_changes' with python-apt


code: dir(object)

rawDescription: Why does setattr does not work as a method?


code:
import random

li=[]
for i in range(50):
    li.append('{}-{}-{}'.format(random.randrange(1,999), random.randrange(1,999), random.randrange(100,9999)))

rawDescription: Removing cells/rows that don't contain regex match with Python


code:
def open(fp, mode="r"):
    "Open an image file, without loading the raster data"

rawDescription: Python: Get Image size WITHOUT loading image into memory


code:
def acf(R):
    """
    Calcualte the auto correlation function of a series with lag 0 up to the length
    of the series.
    """
    y = R - R.mean()
    result = np.correlate(y, y, 'full')
    result = result[len(result)//2:]
    result /= result[0]
    return result

rawDescription: how to apply a function which takes the caller as its arugment

description: Apply a function which takes the caller as its arugment


code: print(S.to_string())    # print the entire table

rawDescription: Calculating distance between two elements only in the array in python


code: blogpost.tags[:] = []

rawDescription: How to remove all items from many-to-many collection in SqlAlchemy?

description: Remove all items from many-to-many collection in SqlAlchemy


code:
os = 'Ozzy Santana'
import os as OSMOD

rawDescription: Why doesn't `sys.modules.keys()` include name from `import...as`?


rawDescription: Making a histogram of string values in python


rawDescription: Computing 16-bit checksum of ICMPv6 header


code:
s = '({})'.format('|'.join(w.values))
r = re.compile(s, re.IGNORECASE)
r

re.compile(r'(rigour.*|.*demeanour.*|centre*|\b.*arbour\b|\bfulfil\b)', re.IGNORECASE)

rawDescription: pandas and "re" - search for total and partial strings

description: Pandas and "re" - search for total and partial strings


code:
def bind_main_menu_bar(self, main_menu_bar):
    main_frame = wx.GetApp().GetTopWindow()

    self.main_menu_bar = main_menu_bar

    # Create the edit menu.
    self.edit_menu = edit_menu = shared.create_menu([
        (const.ID_UNDO, self.LABEL_UNDO_EMPTY),
        (const.ID_REDO, self.LABEL_REDO_EMPTY)
    ])

    # Create the tools menu.
    self.tools_menu = tools_menu = shared.create_menu([
        (const.ID_SELECT_ADDRESS_COLUMNS, 'Select address columns...'),
        (),
        (const.ID_VALIDATE_ADDRESSES, 'Validate selected addresses'),
        (const.ID_VALIDATE_ALL_ADDRESSES, 'Validate all addresses')
    ])

    # Bind some menu event handlers to the main frame.
    main_frame.Bind(wx.EVT_MENU, self.on_menu)
    main_frame.Bind(wx.EVT_UPDATE_UI, self.on_menu_update)

    # Insert the new menus into the main menu bar.
    main_menu_bar.Insert(1, edit_menu, 'Edit')
    main_menu_bar.Insert(2, tools_menu, 'Tools')

rawDescription: How do I manage a dynamic, changing main menu in wxPython?

description: Manage a dynamic, changing main menu in wxPython


code:
from string import Template

def iterate_template( template, items):
   AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
   return [ Template(template).safe_substitute(
       dict(zip( AZ, elem ))) for elem in items ]

rawDescription: How can I use a list-like type to generate a markdown with string.Template python?

description: Use a list-like type to generate a markdown with string.Template python


code:
self._morse_char_map = dict()
for letter, code in self._char_morse_map.items():
    self._morse_char_map[code] = letter

rawDescription: How can I analyze or improve my niece's simple compression algorithm that is based on Morse code?

description: Analyze or improve my niece's simple compression algorithm that is based on Morse code


rawDescription: Integrating using scipy's trapz function


code:
df['group'] = df['A'].map(d)
grouped3 = df.groupby('group')

rawDescription: Pandas groupby with dict

description: Pandas groupby with dict


code:
myFTP.retrlines(command, retrlinesCallback)
myFTP.dir(someDir, dirCallback)

rawDescription: Python ftplib - any way to shut it up?

description: Python ftplib - any way to shut it up


code:
lat = 1/3.
lat
str(lat).count('3')
('%.14f' % lat).count('3')
repr(lat).count('3')

rawDescription: Why and how does python truncate numerical data?


code:
# This can also be done in Python 2.6+ with
# from __future__ import print_function

import time

print("begin", flush=True)
time.sleep(10)
print("end", flush=True)

rawDescription: python stdout to file does not respond in real time

description: Python stdout to file does not respond in real time


code: firsWithPath = fileWithPath.strip('"')

rawDescription: Python: Splitting a path string containing double quotes


code:
def show_homepage(request):
    return render(request, 'home/homepage.html')

rawDescription: How to add parameters to the homepage URL in Django

description: Add parameters to the homepage URL in Django


code:
class MetricData:
    def __init__(self, agentName, metricName, metricType, metricValue):
        self.agentName = agentName
        self.metricName = metricName
        self.metricType = metricType
        self.metricValue = metricValue

class DummyObject:
    metricData = []

    def __init__(self):
        self.metricData = []

        self.metricData.append(MetricData(
            agentName = "web01|WEB|instance_01",
            metricName = "WebSpherePMI|orbPerfModule:ConcurrentRequestCount",
            metricType = 258,
            metricValue = "0"
        ))

        self.metricData.append(MetricData(
            agentName = "app01|APP|instnace_03",
            metricName = "WebSpherePMI|beanModule|mobile.jar:ReturnsToPoolCount",
            metricType = 258,
            metricValue = "3"
        ))

        self.metricData.append(MetricData(
            agentName = "app02|APP|instance_02",
            metricName = "JSP|add_client:Stall Count",
            metricType = 385,
            metricValue = "0"
        ))

        self.metricData.append(MetricData(
            agentName = "web05|WEB|instance_02",
            metricName = "WebSpherePMI|beanModule|bizlogic#bizlogic.jar|ejb.entity|WorkStepInstanceEBBBean:ReadyCount",
            metricType = 258,
            metricValue = "0"
        ))

        self.timesliceEndTime = "2015-01-05 16:33:15"
        self.timesliceStartTime = "2015-01-05 16:28:15"

rawDescription: convert json to a data frame like output in python

description: Convert json to a data frame like output in python


code:
# make compound with cell activity (to a target) list first

if os.path.exists(filename):
    with open(filename) as fh:
        out.write(fh.readline()) # ticker
        for line in fh:
            cols = line.split(',')
            if cols[17] == " Cell ":
                cell_comp_id.append(cols[3])

rawDescription: Improve efficiency in Python matching

description: Improve efficiency in Python matching


rawDescription: Python3 for loop with multiprocessing

description: Python3 for loop with multiprocessing


code:
if (sign) == 1 and (answer) == number1*number2:
        score += 1
elif (sign) == 2 and (answer) == number1+number2:
    score += 1
elif (sign) == 3 and (answer) == number1-number2:
    score += 1

rawDescription: Python v3.3.5 maths questions program

description: Python v3.3.5 maths questions program


code:
5
None

rawDescription: Python asyncio: return vs set_result

description: Python asyncio: return vs set_result


code:
vertices = set()
for edge in edges:
    vertices.update(edge.tuple)

rawDescription: Find all vertices with the same edge attribute


code:
name_to_id
getIDs(name_to_id, ["Apple", "Pear", "Banana"])

rawDescription: Input List of Items, Output List of ItemIDs


code:
import ghdiff
diff_as_html = ghdiff.diff(markdown1,markdown2)

rawDescription: How to compare two models to be rendered with Markdown using Django?

description: Compare two models to be rendered with Markdown using Django


code:
class Command:
            def __init__(self, callback, *args, **kwargs):
                    self.callback = callback
                    self.args = args
                    self.kwargs = kwargs

            def __call__(self):
                    return(self.callback(*self.args, **self.kwargs))

rawDescription: How to make a button open a specific .csv file using Python Tkinter?

description: Make a button open a specific .csv file using Python Tkinter


code:
def authenticated(func):
    def wrapped(*args, **kwargs):
        try:
            beaker_session = request.environ['beaker.session']
        except:
            abort(401, "Failed beaker_session in slash")

        try:
            name = beaker_session['name']
            return func(*args, **kwargs)
        except:
            redirect('/login')

    return wrapped

rawDescription: bottle hooks with beaker session middleware and checking logins

description: Bottle hooks with beaker session middleware and checking logins


rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


code:
from numpy import random, histogram2d, diff
import matplotlib.pyplot as plt
from scipy.interpolate import interp2d

# Generate sample data
n = 10000
x = random.randn(n)
y = -x + random.randn(n)

# bin
nbins = 100
H, xedges, yedges = histogram2d(x, y, bins=nbins)

# Figure out centers of bins
def centers(edges):
    return edges[:-1] + diff(edges[:2])/2

xcenters = centers(xedges)
ycenters = centers(yedges)

# Construct interpolator
pdf = interp2d(xcenters, ycenters, H)

# test
plt.pcolor(xedges, yedges, pdf(xedges, yedges))

rawDescription: Return the value of a 2D PDF given x and y in Python?


code:
class ChannelForm(Form):
    _id         = HiddenField()
    name        = TextField(_('channel name'))
    CITY1adapt  = TextField(_('adapt link'))
    CITY2adapt  = TextField(_('adapt link'))
    #and so on

    submit      = SubmitField(_('Save'))

rawDescription: Flask-WTF: how pass structered object to form


code: reduce(np.multiply, np.ix_(*vs))

rawDescription: Numpy: outer product of n vectors

description: Numpy: outer product of n vectors


code:
my_dict = {"Tom": {"name": "Tom Jones", "address": "1 Fairylane", "phone": "911"},
           "Bob": {"name": "Bob Marley", "address": "2 Fairylane", "phone": "0800838383"}
           }

rawDescription: How to create an 'contact book' in python using dictionaries?

description: Create an 'contact book' in python using dictionaries


code:
class Colors(metaclass=EnumMetaclass):
    red = 1
    green = 2
    blue = 3

rawDescription: Unexpected: flufl.enum prints integer value


code:
import unittest
from unittest.mock import patch

class MyClass:

    def __init__(self):
        self.x = 0
        self.y = 0

    def some_method(self):
        self.x = 4
        self.y = 6

class OtherClass:

    def other_method(self):
        self.x = 5
        self.y = 16

class MyTestClass(unittest.TestCase):

    @patch('__main__.MyClass.some_method', new=OtherClass.other_method)
    def test_patched(self):
        a = MyClass()
        a.some_method()
        self.assertEqual(a.x, 5)
        self.assertEqual(a.y, 16)

    def test_not_patched(self):
        a = MyClass()
        a.some_method()
        self.assertEqual(a.x, 4)
        self.assertEqual(a.y, 6)

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

rawDescription: Mocking a class method and changing some object attributes in Python


code:
def scene_startDrag(self, dropActions):
    item = self.listWidget1.currentItem()
    data = QByteArray()
    stream = QDataStream(data, QIODevice.WriteOnly)
    stream.writeQString(item.text())
    mimeData = QMimeData()
    mimeData.setData("application/x-imgname", data)
    drag = QDrag(self)
    drag.setMimeData(mimeData)
    drag.exec() #actually starts the dragging

rawDescription: PyQt: How to transfer text data between widgets?


code:
def main():
    mainwin = tk.Tk()
    mainwin.title("Wave1")
    # ...
    mainwin.mainloop()

rawDescription: Fetching a number from an Entry widget and running it through a function called by a button in Python 2 Tk


code: df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))

rawDescription: Pandas groupby: How to get a union of strings


code:
def loop(seq):
    for i in seq:
        try:
            print('before')
            yield i  # with body executes here
            print('after')
        except CustomError as e:
            print(e)

for i in loop([1,2,3]):
    print(i)
    print('code')

rawDescription: How do I make a contextmanager with a loop inside?

description: Make a contextmanager with a loop inside


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

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])

img = mpimg.imread('image.png')
gray = rgb2gray(img)
plt.imshow(gray, cmap = plt.get_cmap('gray'))
plt.show()

rawDescription: How can I convert an RGB image into grayscale in Python?

description: Convert an RGB image into grayscale in Python


rawDescription: Case insensitive sort with peewee

description: Case insensitive sort with peewee


rawDescription: How to get folder name, in which given file resides, from pathlib.path?

description: Get folder name, in which given file resides, from pathlib.path


code:
import logging

# The following line will basicConfig() the root handler
logging.info('DUMMY - NOT SEEN')
ll = logging.getLogger('foo')
ll.setLevel('DEBUG')
ll.addHandler(logging.StreamHandler())
ll.debug('msg1')
ll.propagate = False
ll.debug('msg2')

rawDescription: Logging using elasticsearch-py

description: Logging using elasticsearch-py


code:
from mpl_toolkits.mplot3d import Axes3D
fig = figure()
ax = Axes3D(fig)
xim, yim = meshgrid(xi, yi)
ax.plot_surface(xim, yim, zi)
show()
help(meshgrid(x, y))

rawDescription: Plotting 3-tuple data points in a surface / contour plot using matplotlib


rawDescription: Difference between datetime64[ns] objects returning in nanoseconds


code: musical_chairs(range(1, 11), 4)

rawDescription: Controlling the flow of for loop in python


code:
card_candidates = ['9D', '9S', '3S', '0D']
card_order = ['2', '3', '4', '5', '6', '7', '8', '9', '0', 'J', 'Q', 'K', 'A']
sort_map = {c: i for i, c in enumerate(card_order)}
sorted(card_candidates, key=lambda card: (sort_map[card[0]], card[1]))
sorted(['9D', '9S', '9C', '9H'], key=lambda card: (sort_map[card[0]], card[1]))

rawDescription: sorting list of cards

description: Sorting list of cards


code:
for filename in dictionary.keys():
    path = prefix+[filename]
    if not isinstance(dictionary[filename], dict):

        if rqfile in str(os.path.join(*path)):
            return str(os.path.join(*path))

    return get_path(directory[filename], rqfile, path)

rawDescription: Recursive function returning none in Python


code:
class CallListDescriptor(object):
    def __get__(self, instance, type):
        if instance is None:
            return self

        return instance._call_lists.setdefault(self, CallList())

class State(object):
    def __init__(self):
        # for the instance-level values
        self._call_lists = {}

rawDescription: Class variables and inheritance in Python


code:
contents = []
with open('tables.dat', 'r+') as f:
    for line in f:
        contents.append(line.split(','))

max_name_length = max([len(line[0]) for line in contents])

print("    Team                       Points     Diff      Goals     \n")
print("--------------------------------------------------------------------------\n")
for i, line in enumerate(contents):
    line = [el.replace('\n', '') for el in line]
    print("{i:>3}  {0:<{fill_width}}   {1:>3}   {2:>3}   {3:>3}".format(i=i, *line, fill_width=max_name_length))

rawDescription: Print contents of txt file into Table form


code:
if user is not None:
    # ...
    return JsonResponse({'success': True})
else:
    return JsonResponse({'success': False, 'message': '...'})

rawDescription: Return render_to_response from AJAX call


code:
request.post(
    '.../product_review',
    headers={
        'Authorization': 'Bearer ' + auth_token
    },
    json={'my': 'payload'})  # send data as json

rawDescription: Using Python to test HTTP APIs

description: Using Python to test HTTP APIs


code:
result = list()  # the desired list of 5 creature groups
base   = list()  # the prefix of all 5 creature groups
length = 5       # the number of creatures remaining to create a 5 creature list
for group in reversed([[x for x in g]
              for k,g in itertools.groupby(
                  sorted(map(lambda x: x + [x[2]+x[3]],creatureList),
                         key=operator.itemgetter(4)),
                  key=operator.itemgetter(4))]):
    grouplen = len(group)
    if grouplen <= length:
        base.extend(group)
        length -= grouplen
    elif length:
        for c in itertools.combinations(group,length):
            result.append(base + list(c))
        break

rawDescription: How do I create a group of lists from imported data from access?

description: Create a group of lists from imported data from access


code:
if end is None:
    end = len(items)

rawDescription: How to return the maximum element of a list in Python?

description: Return the maximum element of a list in Python


code: yaxis_label = plt.ylabel('My Y-axis')

rawDescription: Share Y axis label

description: Share Y axis label


rawDescription: Format a number as a string

description: Format a number as a string


code: rev_list = original[::-1]

rawDescription: Reversing order of a list using only the len() function


code: columns = [[] for _ in range(6)]

rawDescription: how to show each element of array separately

description: Show each element of array separately


code:
MANGLE_LEN = 256 # magic constant from compile.c

def mangle(name, klass):
    if not name.startswith('__'):
        return name
    if len(name) + 2 >= MANGLE_LEN:
        return name
    if name.endswith('__'):
        return name
    try:
        i = 0
        while klass[i] == '_':
            i = i + 1
    except IndexError:
        return name
    klass = klass[i:]

    tlen = len(klass) + len(name)
    if tlen > MANGLE_LEN:
        klass = klass[:MANGLE_LEN-tlen]

    return "_%s%s" % (klass, name)

rawDescription: Python name mangling function

description: Python name mangling function


code: ''.join(re.split("[^a-z]", input_str))

rawDescription: python substring with unknown symbol

description: Python substring with unknown symbol


code:
{
    "_id" : 1,
    "entry_date" : ISODate("2011-01-01T05:00:00Z"),
    "title" : "A love supreme",
    "tags" : [
        "music",
        "American",
        "jazz"
    ]
}

rawDescription: How to convert this RDBMS schema to a MongoDB "schema" (and how to query against it)

description: Convert this RDBMS schema to a MongoDB "schema" (and how to query against it)


code:
from xml.dom.minidom import Node
for elem in root.getElementsByTagName('item'):
    for x in elem.childNodes:
        if x.nodeType == Node.ELEMENT_NODE:
            project[x.tagName].append(x.firstChild.data)

rawDescription: Getting list of tags from Python minidom XML


rawDescription: How to compare IPV6 addresses in python

description: Compare IPV6 addresses in python


code: timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)

rawDescription: Create List of Single Item Repeated n Times in Python


code: all_accepted_parts = acceptedFragment.objects.filter(fragment__in = fragment.objects.filter(categories = 1))

rawDescription: Really long query

description: Really long query


rawDescription: String Formatting in Python 3

description: String Formatting in Python 3


code:
lista = ["a","b","c"]
set(message) & set(lista)
lista = ["a","b","e"]
set(message) & set(lista)
set(['test','sentence'])&set(['this','is','my','sentence'])

rawDescription: Fastest way to check does string contain any word from list


code:
key = L2[i]
num = L3[i]

rawDescription: Eliminate dups and sum corresponding terms in lists


code: not {a, b, c}.isdisjoint(X)

rawDescription: python membership testing order by rarity

description: Python membership testing order by rarity


code:
def myview(request):
    context['is_guardian'] = request.user.groups.filter(name='guardian').exists()
    context['is_client'] = request.user.groups.filter(name='client').exists()
    return render(request, 'my_template.html', context)

rawDescription: Lists in Django templates not working as expected


code:
from __future__ import unicode_literals
"sss"
b"x"

rawDescription: List of unicode strings

description: List of unicode strings


code:
import module
name = module.name

rawDescription: Two instances of the same Python module?

description: Two instances of the same Python module


code:
for item in compress(values, selectors):
    ...

rawDescription: Skipping a pattern of elements using itertools and accompanying list


code:
import sys, inspect
clsmembers = inspect.getmembers(sys.modules['testType1'], inspect.isclass)

rawDescription: How do I programatically find what symbols were imported with Python import * command?

description: Programatically find what symbols were imported with Python import * command


code:
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://finance.yahoo.com/q?s=AAPL&q1=1")
soup = BeautifulSoup(html)
my_span = soup.find('span', {'id': 'yfs_l84_aapl'})
print(my_span.text)

rawDescription: Python webscraper outputs brackets with the number


rawDescription: Get working alpha value of scatter points in mpl_toolkits.basemap.Basemap


code: A = np.array([Y, Z, [1]*len(X)]).transpose()

rawDescription: Loops to minimize function of arrays in python


code: fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here

rawDescription: How to make pylab.savefig() save image for 'maximized' window instead of default size

description: Make pylab.savefig() save image for 'maximized' window instead of default size


code:
finder1.apply_freq_filter(2)
bigram_measures = nltk.collocations.BigramAssocMeasures()

rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


rawDescription: Convert empty dictionary to empty string


code:
import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']

def complete(text, state):
    for cmd in COMMANDS:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -= 1

readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')

rawDescription: Tab Completion in Python Command Line Interface - how to catch Tab events


code:
import unicodedata
[ch for ch in '$99.99 / €77' if unicodedata.category(ch) == 'Sc']

rawDescription: What is regex for currency symbol?

description: What is regex for currency symbol


code: big = np.random.randint(-10, 10, size=10000000)

rawDescription: Python code for counting number of zero crossings in an array


rawDescription: How can I use the index of an element in list 1 to change an index in list 2?

description: Use the index of an element in list 1 to change an index in list 2


code:
spices={
'Animals':{1:'Bison', 2:'Panther', 3:'Elephant'},
'Birds':{1:'Duck', 2:'Hawk', 3:'Pigeon'},
'Fish':{1:'Shark', 2:'Salmon', 3:'Piranha'}
}
[v for specie in spices for v in spices[specie].values()]

rawDescription: How to get a simple list from a list comprehension that returns a list of lists

description: Get a simple list from a list comprehension that returns a list of lists


code: list(int(i) if i.isdigit() else i for i in str(7.345))

rawDescription: How to turn a float into a list. (Python)

description: Turn a float into a list. (Python)