code:
bar.next_bar = next_bar
bar = next_bar

rawDescription: Why is assigning to multiple targets (identifier/attribute) producing strange results?


code:
from openerp import api
from datetime import date
from dateutil.relativedelta import relativedelta

rawDescription: Automated Action Birthday =19

description: Automated Action Birthday =19


rawDescription: How to insert unescaped html fragment in Beautiful Soup 4

description: Insert unescaped html fragment in Beautiful Soup 4


code: list_as_strings = [str(name) for name in [company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax]]

rawDescription: Change type of group of objects

description: Change type of group of objects


code:
i = df.index.get_level_values(1).isin(['AR','CN','SC'])
j = df.index.get_level_values(0) == 0
df.loc[i & j]

rawDescription: Multi-index slicing of dataframe with list


code:
from itertools import permutations

def dedup(lst):
    seen = set()
    result = []
    for item in lst:
        fs = frozenset(item)
        if fs not in seen:
            result.append(item)
            seen.add(fs)
    return result

res = []
s = "accggt agctta gggatc gactta ccttgg"
chks = s.split(" ");

perms = [p for p in permutations(chks, 3)]

for perm in perms:
    if [(x == y or y == z or x == z) for (x, y, z) in zip(*perm)].count(True) == 0:
        res.append(perm)

print(dedup(res))

rawDescription: Compare strings and just keep those who have on same positions different characters


rawDescription: In Python, what are some examples of when decorators greatly simplify a task?


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


code: (lambda x,y=None: (x, [1]*x if y is None else y))(input("x? : "))

rawDescription: Defining a Variable Inside a Lambda

description: Defining a Variable Inside a Lambda


rawDescription: Python Twisted Conch - How to stop Reactor with multiple Connections?


code:
def compareview(request, id1, id2):
    # in_bulk returns a dict: { obj_id1: <MyModel instance>,
    #                           obj_id2: <MyModel instance> }
    # the SQL pulls all at once, rather than sequentially... arguably
    # better than async as it pulls in one DB hit, rather than two
    # happening at the same time
    comparables = MyModel.objects.in_bulk([id1, id2])
    o1, o2 = (comparables.get(id1), comparables.get(id2))

rawDescription: Are asynchronous Django model queries possible?


rawDescription: How do you get total directory size in the same function that is getting all file sizes? (Python)

description: Get total directory size in the same function that is getting all file sizes? (Python)


rawDescription: Reading a filename and applying part of that name to a variable


rawDescription: looping over two fields of a big table

description: Looping over two fields of a big table


code:
with open('newCIK.csv', newline='') as reader2:
    reader2 = csv.reader(reader2)
    cik_values = next(reader2)  # first row

with open('search.file', newline='') as f_in, open('SP500_10K.csv', 'w', newline='') as f_out:
    reader = csv.reader(f_in, delimiter='|')
    writer = csv.writer(f_out, delimiter='|')

    for line in reader:
        for cik in cik_values:
            if cik in line[-1]:  # test only the last column
                writer.writerow(line)

rawDescription: Python 3.4 : match from csv and return new csv with matched values


code:
form1 = SQLFORM.factory(Field('cards',
    requires=IS_IN_DB(db, 'tbl_card.id', '%(name)s')))
form1.process(formname='form1')

rawDescription: web2py: multiple forms in a view

description: Web2py: multiple forms in a view


rawDescription: iterating over a tuple of iterables returned from a function

description: Iterating over a tuple of iterables returned from a function


code:
@pytest.fixture(scope='module', params=[load_dataset1, load_dataset2])
def data(request):
    loader = request.param
    dataset = loader()
    def fin():
        # finalize dataset-related resource
        pass
    request.addfinalizer(fin)
    return dataset

rawDescription: Run same test on multiple datasets

description: Run same test on multiple datasets


code:
for e in list2:
    if e[0] in list1:
        list3.append(e)

rawDescription: Find matching values in a list of lists using python


code: func_proto = ctypes.WINFUNCTYPE(HRESULT, c_long, HWND)

rawDescription: Windows Common Item Dialog: ctypes + COM access violation


code:
@someDecorator
def someMethod():
    pass

rawDescription: Using python decorator with or without parentheses


code:
from django.contrib.flatpages import views

# Your other patterns here
urlpatterns += [
    url(r'^(?P<url>.*/)$', views.flatpage, name='flatpage'),
]

rawDescription: What is the correct way to link Django Flatpages?


code: parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)

rawDescription: Python's argparse to show program's version with prog and version string formatting


code: rounded_ten = lambda t: (t+pd.Timedelta('5 minutes')).replace(minute=(t+pd.Timedelta('5 minutes')).minute//10*10).replace(second=0)

rawDescription: How to round a datetime to ten minute datetime in a dataframe in Python

description: Round a datetime to ten minute datetime in a dataframe in Python


code:
import pandas as pd
pd.to_pickle(df, "/path/to/pickle/My_pickle")

rawDescription: How to_csv in Bluemix

description: How to_csv in Bluemix


code: ['Hello', 'Hello2', 'Hello3', 'go home, dude!']

rawDescription: match string pattern in python

description: Match string pattern in python


code:
fig = plt.figure()
ax = plt.gca()
ax.scatter(data['o_value'] ,data['time_diff_day'] , c='blue', alpha=0.05, edgecolors='none')
ax.set_yscale('log')
ax.set_xscale('log')

rawDescription: python: scatter plot logarithmic scale

description: Python: scatter plot logarithmic scale


code:
x1 = []
for i in x:
    x1.append('{0:5.4f}'.format(i))

x1

rawDescription: How to apply formatted printing to a python list?

description: Apply formatted printing to a python list


code:
def AddList(self, evt):
    # PageOne -> Notebook -> Panel -> MyFrame ( 3x GetParent() )
    self.GetParent().GetParent().GetParent().SecondFrame.list1.InsertStringItem(0,'Hello')

rawDescription: using listctrl in notebook wxPython

description: Using listctrl in notebook wxPython


code:
for msg in Mailbox.retr(i+1)[1]:
    file.write(msg)

rawDescription: Open mail in python

description: Open mail in python


code:
from flask import Blueprint
api = Blueprint('api', __name__)
@api.route('/')
def call_api():
        return ""

rawDescription: How to use url_map.iter_rules with blueprint object instead of app

description: Use url_map.iter_rules with blueprint object instead of app


code: xy = [(o, t) for (_, o, t) in df[['one', 'two']].to_records()]

rawDescription: select rows in pandas DataFrame using comparisons against two columns

description: Select rows in pandas DataFrame using comparisons against two columns


code: x = 'True and True'

rawDescription: Python: Read the content of a variable

description: Python: Read the content of a variable


rawDescription: League fixture generator in python

description: League fixture generator in python


code:
class Price(object):
    def __init__(self, dollars):
        self.dollars = dollars

    class Convert(object):
        def __init__(self, rate):
            self.rate = rate

        def __get__(self, instance, owner):
            if instance is None:
                # Accessed through class, return the descriptor instead.
                return self
            return instance.dollars * self.rate

    euros = Convert(0.75)

rawDescription: How can state stored in a python descriptor object be accessed outside the descriptor?


code:
import pytest

def pytest_generate_tests(metafunc):
    idlist = []
    argvalues = []
    for scenario in metafunc.cls.scenarios:
        idlist.append(scenario[0])
        items = scenario[1].items()
        argnames = [x[0] for x in items]
        argvalues.append(([x[1] for x in items]))
    metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")

scenario1 = ('itemNo = 0', {'itemNo': 0})
scenario2 = ('itemNo = 11', {'itemNo': 11})
scenario3 = ('itemNo = 33', {'itemNo': 33})

class TestSeries:
    scenarios = [scenario1, scenario2, scenario3]

    def test_greater_than_30(self, itemNo):
        assert (itemNo > 30), "not greather than 30"
    def test_lesser_than_30(self, itemNo):
        assert (itemNo < 30), "not lesser thant 30"
    def test_modulo_2(self, itemNo):
        assert (itemNo % 2) == 0, "not divisible by 2"

rawDescription: how to execute multiple tests on multiple items with py.test

description: Execute multiple tests on multiple items with py.test


code:
def main():
    # load per-city data
    city_info = list(city_data("miles.dat"))
    # transpose into separate lists
    cities, coords, pops, dists = list(zip(*city_info))

if __name__=="__main__":
    main()

rawDescription: Regular Expressions in data parsing Python


code:
import pip

package = [pckg for pckg in pip.get_installed_distributions()
            if pckg.project_name == 'package_name'][0]
#  package var will contain some metadata: version, project_name and others.

rawDescription: How to access python package metadata from within the python console?

description: Access python package metadata from within the python console


code:
X = X.tocsr()
model = lda.LDA(n_topics=2, random_state=0, n_iter=100)
model.fit(X)
# INFO:lda:n_documents: 4
# INFO:lda:vocab_size: 13
# INFO:lda:n_words: 21
# INFO:lda:n_topics: 2
# INFO:lda:n_iter: 100
# INFO:lda:<0> log likelihood: -126
# INFO:lda:<10> log likelihood: -102
# INFO:lda:<20> log likelihood: -99
# INFO:lda:<30> log likelihood: -97
# INFO:lda:<40> log likelihood: -100
# INFO:lda:<50> log likelihood: -100
# INFO:lda:<60> log likelihood: -104
# INFO:lda:<70> log likelihood: -108
# INFO:lda:<80> log likelihood: -98
# INFO:lda:<90> log likelihood: -98
# INFO:lda:<99> log likelihood: -99

rawDescription: Is there a more efficient way to append lines from a large file to a numpy array? - MemoryError


code:
task = ["svn",  "move",  "folder/hello world anotherfolder/hello world"]
subprocess.check_call(task)

rawDescription: Handling directories with spaces Python subprocess.call()


code:
x = dict.fromkeys(range(0, 10), 0)
x

rawDescription: Creating a dictionary from an iterable

description: Creating a dictionary from an iterable


code:
some_label = Label(...)
my_slider = Slider(...)
def OnSliderValueChange(instance,value):
    some_label.text = str(value)

my_slider.bind(value=OnSliderValueChange)

rawDescription: Display kivy slider value as it changes

description: Display kivy slider value as it changes


code: cards = {card['name']: Card(**card) for card in card_list if card['name'] in names_of_cards}

rawDescription: Creating multiple class instances from a list of names in Python?


code:
import wx
import wx.lib.scrolledpanel

class GUI(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Test app v1.0", style = wx.DEFAULT_FRAME_STYLE )
        self.Center()
        self.CreateStatusBar()
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1, style=wx.SIMPLE_BORDER, size=(400, 200))
        mainPanel.SetupScrolling()
        mainPanel.SetBackgroundColour('#00000')
        panelA = wx.lib.scrolledpanel.ScrolledPanel(mainPanel, -1, style=wx.SIMPLE_BORDER, size=(300,200))
        panelA.SetupScrolling()
        panelA.SetBackgroundColour('#EEE111')
        panelB = wx.lib.scrolledpanel.ScrolledPanel(mainPanel, -1, style=wx.SIMPLE_BORDER, size=(200,200))
        panelB.SetupScrolling()
        panelB.SetBackgroundColour('#Eaa222')
        mainSizer.Add(panelA, 1, wx.ALL|wx.EXPAND, 5)
        mainSizer.Add(panelB, 1, wx.ALL|wx.EXPAND, 5)
        mainPanel.SetSizer(mainSizer)

if __name__=='__main__':
    app = wx.App(0)
    frame = GUI().Show()
    app.MainLoop()

rawDescription: Add a vertical scrollbar to a wxFrame accross multiple wxPanels


code:
from itertools import product
list(product(range(2), range(3), range(4)))

rawDescription: Python: how to get this elegantly?

description: Python: how to get this elegantly


code: ['totalItems', 'items', ['kind', 'etag', 'volumeInfo', ['publisher', 'publishedDate', 'authors', None, 'description', 'title'], 'id', 'selfLink'], 'kind']

rawDescription: Parse an entire JSON object looking for a key in python


code:
import testb
import testc

rawDescription: How to set dynamic global variables in Python?

description: Set dynamic global variables in Python


code:
def GetMonday(firstDay, forward=False):
    firstEntry = firstDay.astype('M8[D]')
    beforeMonday = np.busday_offset(firstEntry, forward*2-1, 'forward', [1,0,0,0,0,0,0])
    if abs(firstEntry-beforeMonday) == np.timedelta64(7, 'D'):
        return firstEntry.astype('M8[s]')
    else:
        return beforeMonday.astype('M8[s]')

rawDescription: numpy: get rid of loop

description: Numpy: get rid of loop


rawDescription: Put counter into a frequency ordered list


code:
def replace_in_config(old, new):
    with open('config.xml', 'r') as f:
        text = f.read()

    with open('config.xml', 'w') as f:
        f.write(text.replace(old, new))

rawDescription: How to parse the xml to find the text value of the following node in python?

description: Parse the xml to find the text value of the following node in python


code:
import re
inputstring = "hello hello hello 123"
re.sub("\bhello\b", '<>', inputstring)
re.sub(r"\bhello\b", '<>', inputstring)

rawDescription: Regular Expressions working differently in Python and Ruby


rawDescription: How to reorder columns under multiple indexes in Pandas

description: Reorder columns under multiple indexes in Pandas


code:
width = 5
value = 2
'%0*d' % (width, value)

rawDescription: How to pad leading zero (in a function) dynamically?

description: Pad leading zero (in a function) dynamically


code:
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

rawDescription: How do you calculate the greatest number of repetitions in a list?

description: Calculate the greatest number of repetitions in a list


rawDescription: How to get the related_name for a foreign key?

description: Get the related_name for a foreign key


code:
my_ordered_dict = OrderedDict()
my_ordered_dict.update(( (key1, value1), (key2, value2), (key3, value3) ))

rawDescription: Python: Writing an empty dictionary with strings thats ordered


code: buffer1[:] = buffer2

rawDescription: How to copy a python bytearray buffer?

description: Copy a python bytearray buffer


code:
from package_p import PluginBase
class ModM(PluginBase):
    def __init__(self):
        super(ModM, self).__init__()

rawDescription: least burdensome technique for package submodule to see all classes of importer

description: Least burdensome technique for package submodule to see all classes of importer


code: property

rawDescription: Python: a better way to write a if-then block with join?


code:
import subprocess

ppid = '7773'
subprocess.call(['pkill', '-STOP', '-P', ppid])

rawDescription: Kill process by ppid in python?

description: Kill process by ppid in python


code:
@api_view(['GET'])
def get_user_details(request):
    """
    API View that gives a user detail

    ---

    parameters:
        - name: email
          description: The email of the user based on which his/her information has been extracted
          required: true
          type: string

    responseMessages:
        - code: 400
          message: Email required as GET parameters.
          message: User not found.
        - code: 200
          mesage: User details sent successfully

    consumes:
        - application/json
        - application/xml
    produces:
        - application/json
        - application/xml

    """

    email = request.query_params.get('email', None)

    if email is None:
        return HttpResponseBadRequest("Email required as GET parameters.")

    try:
        user = User.objects.get(username=email)
    except User.DoesNotExist:
        return HttpResponseBadRequest("User not found.")

    response_data = {'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name,}

    return HttpResponse(json.dumps(response_data), content_type="application/json")

rawDescription: Send data from django views to angularjs controller


code:
listC = listA[:]
for index in listB:
    listC[index] = 0

rawDescription: Update list elements based on a second list as index


code:
from xml.dom import minidom

source = """<?xml version="1.0" ?>
<root/>"""
doc = minidom.parseString(source)
pi = doc.createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="form.xslt"')
doc.insertBefore(pi, doc.firstChild)
print(doc.toprettyxml())

rawDescription: How to access the XML declaration with minidom (python)

description: Access the XML declaration with minidom (python)


code:
import collections
d = {2:3, 1:89, 4:5, 3:0}
od = collections.OrderedDict(sorted(d.items()))
od

rawDescription: How can I sort a dictionary by key?

description: Sort a dictionary by key


code:
from bitstring import BitArray
b = BitArray(uint=s, length=10000)
p, = b.find('0b000000')
if b[99]:
    b[100] = False
...

rawDescription: Generating a 10000 bit random sequence

description: Generating a 10000 bit random sequence


code: output = [n for n in literal_list if str(abs(int(n))) in needed_literals]

rawDescription: Edit a list while comparing it to another list as constraints


code:
if '+' in params['charge']:
    z = int(params['charge'].replace('+',''))
else:
    z = -int(params['charge'].replace('-',''))

rawDescription: can't convert string to integer-python

description: Can't convert string to integer-python


rawDescription: Extract integer part from String in python


code:
widths = np.linspace(0, 2, X.size)
plt.quiver(X, Y, cos(deg), sin(deg), linewidths=widths)

rawDescription: Change size of arrows using matplotlib quiver


code:
for item in fulllist:
    span = item.find("span", class_="modelYearSort")
    if span:
        item_print = span.string
        item_print=item_print + "|" + item.find("span", class_="mmtSort").string
        seller_phone=item.find("span", class_="seller-phone")
        print(seller_phone)
        # item_print=item_print + "|" + item.find("span", class_="seller-phone").string
        item_print=item_print + "|" + item.find("span", class_="priceSort").string
        item_print=item_print + "|" + item.find("span", class_="milesSort").string
        print(item_print)
    else:
        continue #It's empty, go on to the next loop.

rawDescription: BeautifulSoup - Handing of cases where variable.find( ).string returns empty


rawDescription: Html file writing from a for loop's output


code:
class ChoiceAdmin(admin.ModelAdmin):
    list_display = ['name', 'rating', 'get_photo']

    def get_photo(self, obj):
        return obj.photo_other
    get_photo.short_description = 'Photo'

rawDescription: Django multiple Foreign Key - Display related field in details admin page for add/edit


rawDescription: Get the string within brackets in Python


code:
s_conn = sqlite3.connect('foo.db')
get_dbname(s_conn)
get_dbname(s_conn.cursor())
p_conn = psycopg2.connect('host=localhost user=postgres')
get_dbname(p_conn)
get_dbname(p_conn.cursor())

rawDescription: Find databasetype ( SQlite, Mysql, PostgreSQL ) from dbapi in python


code:
START_ELEMENT
CHARACTERS
END_ELEMENT

rawDescription: Python XML Pull Parser

description: Python XML Pull Parser


code:
get_ancestors(ascending=False, include_self=False)
get_children()
get_descendants(include_self=False)
get_descendant_count()
get_next_sibling()
get_previous_sibling()
get_root()
get_siblings(include_self=False)
insert_at(target, position='first-child', save=False)
is_child_node()
is_leaf_node()
is_root_node()
move_to(target, position='first-child')

rawDescription: In Django how can I search for related models based on the order they were added to a ManyToMany Field?


code:
def SetProperties( ItemObject ):
    for propName, cls in AttrContainer.__dict__.iteritems():
        if propName in ItemObject.properties:
            setattr(ItemObject, propName, cls.__dict__[propName])
    return ItemObject()

rawDescription: Python: Copy properties with it's functions (fget, fset, fdel) from one class to another


code:
f = open('your-file.txt', 'rU') # U is for Unicode
raw = f.read()
tokens = nltk.word_tokenize(raw)

rawDescription: NLTK tagger reading from txt

description: NLTK tagger reading from txt


rawDescription: Is there a way to create argument in python's argparse that returns true in case no values given


code:
import random

celebs = [
    "a", "b", "c", "d", "e", "f",
    "g", "h", "i", "j", "k", "l",
    "m", "n", "o", "p", "q", "r"    # need at least 15
]

chosen = random.sample(celebs, 15)
for round,celeb in enumerate(chosen, 1):
    print("{}: {}".format(round, celeb))

rawDescription: Permanently remove an element from a list in Python?


code:
INPUTSCRIPT="CLOSEDLOOP{DCSOURCE1|VOLTAGE|0.1|-1|5|1000}"
TEMPSCRIPT=INPUTSCRIPT.split('|')
TEMPSCRIPT
TEMPSCRIPT[5]

rawDescription: How to filter a "}"

description: Filter a "}"


code:
last_id = IDs[0][0]
res = [sequences[0]]
for index, (id_, _) in enumerate(IDs[1:], 1):
    if id_ == last_id:
        res[-1] += sequences[index]
    else:
        res.append(sequences[index])
    last_id = id_

rawDescription: Assemble strings for particular ID by order of index. Python


code:
def excercise13():

    currentnumber = 0

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

description: Add numbers to be stored in a variable


code:
from Tkinter import *
import Tkinter as tk

class App(Tk):
  def __init__(self):
    Tk.__init__(self)

    self.title("Periodic Table of the Elements")

    self.topLabel = Label(self, text = "Click the element you would like information about.", font=20)
    self.topLabel.grid(row=0,column=0,columnspan=18)

    column1 = [
    'H',
    'Li',
    'Na',
    'K',
    'Rb',
    'Cs',
    'Fr']
    # create all buttons with a loop
    r = 1
    c = 0
    for b in column1:
        tk.Button(self,text=b,width=5,height=2, bg="grey",command=lambda text=b:self.info(text)).grid(row=r,column=c)
        r += 1
        if r > 7:
            r = 1
            c += 1

    column2 = [
    'Be',
    'Mg',
    'Ca',
    'Sr',
    'Ba',
    'Ra']
    r = 2
    c = 1
    for b in column2:
        tk.Button(self,text=b,width=5,height=2, bg="green",command=lambda text=b:self.info(text)).grid(row=r,column=c)
        r += 1
        if r > 7:
            r = 1
            c += 1

    column3 = [
    'Sc',
    'Y',
    'La   >|',
    'Ac   >|']
    r = 4
    c = 2
    for b in column3:
        tk.Button(self,text=b,width=5,height=2, bg="yellow",command=lambda text=b:self.info(text)).grid(row=r,column=c)
        r += 1
        if r > 7:
            r = 1
            c += 1

    self.mainloop()

  def info(self, text):
     #print text
     self.topLabel.config(text=text)

def main():
  a = App()

if __name__ == "__main__":
  main()

rawDescription: Python: Changing label depending which button is pressed


code:
class Person:
    greeting = 'Hello'
    def __repr__(self):
        return repr(self.greeting)

Sam = Person()
Sam

rawDescription: Why doesn't this __repr__ function return a string?


code:
import collections
import functools

class memoized(object):
   '''Decorator. Caches a function's return value each time it is called.
   If called later with the same arguments, the cached value is returned
   (not reevaluated).
   '''
   def __init__(self, func):
      self.func = func
      self.cache = {}
   def __call__(self, *args):
      if not isinstance(args, collections.Hashable):
         # uncacheable. a list, for instance.
         # better to not cache than blow up.
         return self.func(*args)
      if args in self.cache:
         return self.cache[args]
      else:
         value = self.func(*args)
         self.cache[args] = value
         return value
   def __repr__(self):
      '''Return the function's docstring.'''
      return self.func.__doc__
   def __get__(self, obj, objtype):
      '''Support instance methods.'''
      return functools.partial(self.__call__, obj)

rawDescription: Memoizing Coin Change

description: Memoizing Coin Change


rawDescription: How do I fill two (or more) numpy arrays from a single iterable of tuples?

description: Fill two (or more) numpy arrays from a single iterable of tuples


code:
latitude = "20-55-70.010N"
longitude = "32-11-50.000W"

##assuming N latitude and W longitude
latitude = sum(float(x) / 60 ** n for n, x in enumerate(latitude[:-1].split('-')))  * (1 if 'N' in latitude[-1] else -1)
longitude = sum(float(x) / 60 ** n for n, x in enumerate(longitude[:-1].split('-'))) * (1 if 'E' in longitude[-1] else -1)

rawDescription: How to convert latitude longitude to decimal in python?

description: Convert latitude longitude to decimal in python


code: people.groupby(lambda x: GroupColFunc(people, x, 'a')).sum()

rawDescription: Groupby with User Defined Functions Pandas


code:
strs = '(0,0) (0,1) (1,1) (1,0)'
from ast import literal_eval
literal_eval(strs.replace(' ',','))

rawDescription: input a list of 2D coordinates in python from user

description: Input a list of 2D coordinates in python from user


rawDescription: How can I merge one dataframe into another, inserting rows that do not exist?

description: Merge one dataframe into another, inserting rows that do not exist


code: from ark_tweet_nlp_python import CMUTweetTagger

rawDescription: Add Python script so can be imported in another Python script


rawDescription: two dimensional array for encryption in python

description: Two dimensional array for encryption in python


code:
with open('file.dat', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print(codecs.encode(chunk, 'hex'))

rawDescription: pythonic way to hex dump files

description: Pythonic way to hex dump files


code:
def runCallback(uniqueId, funcs):
    f = funcs.pop(uniqueId, None) # GIL protects this code with some caveats
    if f is not None:
       f()

rawDescription: Python and multiprocessing... how to call a function in the main process?


code:
def reduce(self, key, values, output, reporter):
    sum = 0
    while values.hasNext():
        sum += values.next().get()
    output.collect(key, IntWritable(sum))

rawDescription: Map Reduce Simple score aggregating for common queries


code:
bucket = s3.Bucket(bucket_name)

response = bucket.put(
    Policy = '<policy string here>'
)

rawDescription: Using Boto3 and Python How Make a Folder Public


code: rollaxis(im, 2)

rawDescription: reordering of numpy arrays

description: Reordering of numpy arrays


code:
import functools

def memoize(func):
    cache = {}
    sentinel = object()

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        key = (args, tuple(kwargs.items()))
        result = cache.get(key, sentinel)
        if result is not sentinel:
            return result
        result = func(*args, **kwargs)
        cache[key] = result
        return result
    return wrapper

rawDescription: Efficient pooling/caching of expensive objects


code:
class Meta:
    app_label = 'db_b'

rawDescription: Want to implement multiple database in django project


rawDescription: How to extract last set of parentheses in a string

description: Extract last set of parentheses in a string


code: x = 'bar'

rawDescription: Constants - How do you know what a constant is?


code:
merge_d = {d1k: d1v+Data2Dict.get(d1k[-5:]) for d1k,d1v in Data1Dict.items()
           if d1k[-5:] in Data2Dict }

rawDescription: Merge Dictionaries with different TimeStamp


code:
class Printer(dict):
    def __missing__(self, key):
        def wrapped(*args, **kwargs):
            print('{} called: args={}, kwargs={}'.format(key, args, kwargs))
        return wrapped

code = '''
foo()
bar(1, 2, baz=3)
'''

exec(code, Printer())

rawDescription: How can I list function calls by using exec in python?

description: List function calls by using exec in python


code:
from sympy.matrices import DeferredVector
v = DeferredVector('v')
func = lambdify(v, Matrix([v[1], 2*v[2]]))
func(np.array([10,20,30]))

rawDescription: Combining numpy with sympy

description: Combining numpy with sympy


code:
x="I c RT @iamFink: @SamanthaSpice that's my excited face and my regular face. The expression never changes."
' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
x="RT @AstrologyForYou: #Gemini recharges through regular contact with people of like mind, and social involvement that allows expression of their ideas"
' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
# Though after you add # to the regex expression filter, results become a bit better
' '.join(re.sub("([@#][A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
x="New comment by diego.bosca: Re: Re: wrong regular expression? http://t.co/4KOb94ua"
' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
#See how miserably it performed?

rawDescription: how to remove hashtag, @user, link of a tweet using regular expression

description: Remove hashtag, @user, link of a tweet using regular expression


code:
import re
city, state = re.split(r' ?,? ?', location)

rawDescription: Separate city and state in string?

description: Separate city and state in string


code: is_of_appropriate_length = 1 <= len(val) <= 255

rawDescription: python regular expression to validate types of strings

description: Python regular expression to validate types of strings


code:
from PIL import ImageColor, ImageDraw
draw = ImageDraw.Draw(pic)

point_inside_digit = (some_x, some_y)

ImageDraw.floodfill(im, point_inside_digit, ImageColor.getrgb("black"))

del draw

rawDescription: How to fill the outline text by PIL to using tesseract?

description: Fill the outline text by PIL to using tesseract


code: cons = tuple(cons)

rawDescription: Generating a 'sequence of dicts' for scipy.optimize.minimize


rawDescription: student t confidence interval in python

description: Student t confidence interval in python


rawDescription: regular expression in python for 'month year'

description: Regular expression in python for 'month year'


code:
config = ruamel.yaml.load(open(file_name), ruamel.yaml.RoundTripLoader)
ind = 6
bsi = 4

rawDescription: How to update yaml file using python

description: Update yaml file using python


code:
class foo(object):
    @property
    def myAttr(self):
        return 2

rawDescription: Confused with getattribute and setattribute in python


code:
class WeakCallback (object):
    """A Weak Callback object that will keep a reference to
    the connecting object with weakref semantics.

    This allows object A to pass a callback method to object S,
    without object S keeping A alive.
    """
    def __init__(self, mcallback):
        """Create a new Weak Callback calling the method @mcallback"""
        obj = mcallback.im_self
        attr = mcallback.im_func.__name__
        self.wref = weakref.ref(obj, self.object_deleted)
        self.callback_attr = attr
        self.token = None

    def __call__(self, *args, **kwargs):
        obj = self.wref()
        if obj:
            attr = getattr(obj, self.callback_attr)
            attr(*args, **kwargs)
        else:
            self.default_callback(*args, **kwargs)

    def default_callback(self, *args, **kwargs):
        """Called instead of callback when expired"""
        pass

    def object_deleted(self, wref):
        """Called when callback expires"""
        pass

rawDescription: How to store callback methods?

description: Store callback methods


rawDescription: cipher exceeds the 4X4 grid and prints out wrong cipher

description: Cipher exceeds the 4X4 grid and prints out wrong cipher


code:
peek: 1
iterable: [1, 2, 3]

rawDescription: How do I check the content of iterable object?

description: Check the content of iterable object


code: codemap_index = pd.MultiIndex.from_arrays([codemap.values(), codemap.keys()])

rawDescription: Fancy indexing in pandas

description: Fancy indexing in pandas


code:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("http://www.hltv.org/match/2296366-gplay-gamers2-acer-predator-masters-powered-by-intel")
driver.title

rawDescription: Using selenium at hosted app?

description: Using selenium at hosted app


rawDescription: permutations with unique values

description: Permutations with unique values


code:
admin = Admin(app)
admin.add_view(MyView(endpoint='testadmin'))

rawDescription: url_for for class-based views in Flask-Admin

description: Url_for for class-based views in Flask-Admin


code:
import multiprocessing

def thirty_second_function(q):
    q.put(["mango", "habanero", "salsa"])

def five_second_function(q):
    q.put({"beans": "8 oz", "tomato paste": "16 oz"})

if __name__ == '__main__':
    q1 = multiprocessing.Queue()
    p1 = multiprocessing.Process(target=thirty_second_function, args=(q1,))
    p1.start()

    q2 = multiprocessing.Queue()
    p2 = multiprocessing.Process(target=five_second_function, args=(q2,))
    p2.start()

    print(q1.get())
    print(q2.get())

rawDescription: Multiprocessing and variable return?

description: Multiprocessing and variable return


code:
num1, num2, num3 = re.findall(r'\d+', 'numberone=1,'
                                      'numbertwo=2,'
                                      'numberthree=3')

rawDescription: python how to extract a number from a variable

description: Python how to extract a number from a variable


code:
import pandas as pd

cdf = pd.DataFrame({'color1': {0: 'Red', 1: 'Blue', 2: 'Yellow', 3: 'Blue'},
 'color2': {0: 'Red', 1: 'Green', 2: 'Blue', 3: 'Blue'},
 'color3': {0: 'Red', 1: 'Red', 2: 'Red', 3: 'Blue'},
 'color4': {0: 'Red', 1: 'Blue', 2: 'White', 3: 'Blue'},
 'form': {0: 'circle', 1: 'circle', 2: ' square', 3: 'circle'},
 'imageName': {0: 'img1', 1: 'img2', 2: 'img3', 3: 'img4'}})

colorcols = []
for i in range(1,5):
    colorcols.append('color%d'%i)

for color in set(cdf[colorcols].values.flatten()):
    mask = (cdf==color)
    print('%s: '%color),
    colors = (mask.sum(axis=1) > 0)

    print(cdf[colors].imageName.values)

rawDescription: Python: Saving all instances from inside a loop to variable to call later


code:
import pprint
import string

from pyparsing import Word, nums, Literal, opAssoc, operatorPrecedence

course_name = Word(string.ascii_uppercase + nums + "/") | Literal("instructor permission")
comma_separator = Literal(',')
comma_separator.setParseAction(lambda t:"&&")

and_separator = Literal(', and') | Literal(', AND') | Literal('and')  | Literal('AND')
and_separator.setParseAction(lambda t:"&&")

or_separator = Literal('or') | Literal("OR")
or_separator.setParseAction(lambda t:"||")

course_line = operatorPrecedence(course_name,
                            [
                                (and_separator, 2, opAssoc.LEFT,),
                                (or_separator, 2, opAssoc.LEFT),
                                (comma_separator, 2, opAssoc.LEFT,),
                            ])

data = """AAAA111, BBB111, CCC101, and DDD104
AAAA111, BBB111, CCC101 or DDD104
AAAA111, AAAA112 or AAAA113, BBB333
AAA111 or BBB111, AND CCC111
AAA111 or BBB111 or CCC111 or DDD111
AAA111 or 112 or 222 or 333
AAA111 or instructor permission
AAA111/221
"""

for line in data.splitlines():
    results = course_line.parseString(line)
    print(line)
    pprint.pprint(results.asList()[0])
    print()

rawDescription: Parse parts of sentence while preserving context in Python with regex


code:
def callback(text):
    entry.insert(0, text)

rawDescription: Make a button's command cause the button's text to be inserted into an entry


rawDescription: How to get the end of a url in Django?

description: Get the end of a url in Django


code:
s = df.stack()
s = s[s>0]
s

rawDescription: Python Pandas Pivot tables to pie chart

description: Python Pandas Pivot tables to pie chart


code:
def reverse(self):
    if not self.__items:
        return ""

    def recur(s):
        if not s:
            return ""
        return s[-1] + recur(s[:-1])
    return " ".join(recur(w) for w in self.__items)

rawDescription: Reverse Class Method Not Working

description: Reverse Class Method Not Working


code:
import numpy as np
m, n = 3, 4
N = 100  # num samples

rng = np.random.RandomState(42)

W = rng.randn(m, n)
X = rng.randn(n, N)
Z_clean = W.dot(X)

Z = Z_clean + rng.randn(*Z_clean.shape) * .001

rawDescription: Fit a linear transformation in python

description: Fit a linear transformation in python


code: return (target in some_string) if target else False

rawDescription: See if string contains substring

description: See if string contains substring


code:
vehicle_list = df.Campaign.str.extract('(Car).Rental|(Motorcycle)|(Hotel)|(.*)')
vehicle = vehicle_list.apply(lambda x: x[x.last_valid_index()], axis=1)
df['vehicle'] = vehicle.map({'Car':'Car campaign', 'Hotel':'Hotel campaign'})

rawDescription: If value contains string, then set another column value


code:
L_b = 2* len(b)
L_a = len(a)
L_b1 = len(b1)

rawDescription: Grouping of element in a list given a list of intervals


code:
from bs4 import BeautifulSoup
import requests

url = "http://be.brammer.biz/product/2716370/name/000300020_30_2_DOORSLAG"
price_url = "http://be.brammer.biz/products/show-price"

with requests.Session() as session:
    soup = BeautifulSoup(session.get(url).content)

    # extract the product code - used in the POST request
    product_code = soup.find(id="localitemid")["value"]

    response = session.post(price_url, data={
        "ids[0][]": product_code
    }, headers={
        "X-Requested-With": "XMLHttpRequest"
    })

    print(response.json())

rawDescription: Python scrape with BeautifulSoup

description: Python scrape with BeautifulSoup


rawDescription: How to get text from dialog box in unix using pexpect?

description: Get text from dialog box in unix using pexpect


rawDescription: How to type annotate overrided methods in a subclass?

description: Type annotate overrided methods in a subclass


code:
def padded_bin(x):
    return bin(x)[2:].zfill(16) # the [2:] strips off the '0b' that bin() returns

rawDescription: Alternative of showbits() in Python to show 16 bit binary representation


code: re.search('\[(.*?)\]', html_template)

rawDescription: Python - re - need help for regular expression


code: myColor = Color('#920310')

rawDescription: Defining a color in python

description: Defining a color in python


rawDescription: Use a loop to plot n charts Python

description: Use a loop to plot n charts Python


code:
mask = np.abs(df) > df.mean()
df[mask] = 2

rawDescription: Transforming outliers in Pandas DataFrame using .apply, .applymap, .groupby


code:
def random_int(value, x, y):
    return "{0}".format(random.randint(x, y))

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


code: table_values = [[col1_value_0, col2_value_0, col3_value_0], [col1_value_1, col2_value_1, col3_value_1], ...]

rawDescription: How to render lists of column values into a table using a template (such as Jinja2)

description: Render lists of column values into a table using a template (such as Jinja2)


code: return Countries, Countries[n]

rawDescription: sorting a list of countries in descending order and returning the nth country

description: Sorting a list of countries in descending order and returning the nth country


code:
color = ['k', 'r','g', 'b']
alist = customfigure() # (customfigure doesn't need to take any
                       # arguments now)
for i in xrange(4):
    s = np.sin(2*(i+1) * np.pi * t)
    alist[i].plot(t, s, '-', color = color[i])

rawDescription: Figure appearance is not preserved when its axes are added to new figure


code: screen

rawDescription: Shell script not executing all commands in background


rawDescription: using Python to generate a C string literal of JSON

description: Using Python to generate a C string literal of JSON


code: df[df.groupby(level=0).bar.transform(lambda x: len(x) >= 2).astype('bool')]

rawDescription: Pandas: Filtering pivot table rows where count is fewer than specified value


code: Foo : 'Hi'

rawDescription: Overwrite built-in function

description: Overwrite built-in function


code: plot(data)

rawDescription: Should I bother for array type in Python?


code:
def name(self):
    return self.__name__

rawDescription: Python3 Classes- Can you change it into a string?


code:
# Read from STDIN into array of lines.
email_input = sys.stdin.readlines()

# email.FeedParser.feed() expects to receive lines one at a time
# msg holds the complete email Message object
parser = email.FeedParser.FeedParser()
msg = None
for msg_line in email_input:
   parser.feed(msg_line)
msg = parser.close()

rawDescription: Python : Postfix stdin

description: Python : Postfix stdin


code:
def change(s):
    return s + "!"

rawDescription: concatenating strings?

description: Concatenating strings


code:
class PrettyXMLAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if not values:
            values = 4
        setattr(namespace, self.dest, values)

parser.add_argument('--pretty-xml', nargs='?', type=int, dest='xml_space', action=PrettyXMLAction)

rawDescription: Option accepted with and without value

description: Option accepted with and without value


code:
from sqlalchemy import func
user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first()

rawDescription: Case Insensitive Flask-SQLAlchemy Query

description: Case Insensitive Flask-SQLAlchemy Query


code:
grade_list = [1, 2, 3, 4, 4, 5, 4, 3, 1, 6, 0, -1, 6, 3]
indices = [index for index, grade in enumerate(grade_list) if grade > 0.0]
print(indices)

rawDescription: How can I convert a list to a numpy array for filtering elements?

description: Convert a list to a numpy array for filtering elements


code: a[::2, ::2]  # get every other element (column-wise and row-wise)

rawDescription: Numpy array slicing using commas

description: Numpy array slicing using commas


code:
import pandas as pd
colnames = ["current_IP", "URI", "current_timestamp", "dummy"]
df = pd.read_csv(filepath, names=colnames)
# Remove incomplete and redundant rows:
df = df[~df.current_timestamp.isnull() & df.dummy.isnull()]

rawDescription: is it easy to modify this python code to use pandas and would it help if i did?

description: Is it easy to modify this python code to use pandas and would it help if i did


code:
from PySide import QtCore, QtGui

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(533, 497)
        self.mplvl = QtGui.QWidget(Form)
        self.mplvl.setGeometry(QtCore.QRect(150, 150, 251, 231))
        self.mplvl.setObjectName("mplvl")
        self.vLayout = QtGui.QVBoxLayout()
        self.mplvl.setLayout(self.vLayout)
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))

rawDescription: Matplotlib in Pyside with Qt designer (PySide)


code:
position=[]
n=2
for i in range(n):
    position.append([])
    for j in range(n):
        position[i].append(some_object)

rawDescription: Store matrix-like data in dictionaries

description: Store matrix-like data in dictionaries


code:
for i in xrange(len(s)/2):
  if s[i] != s[(len(s)-1)-i]:
    return False
return True

rawDescription: Complexity of palindrome test

description: Complexity of palindrome test


rawDescription: Removing all alphabets and commas from a string


code:
import functools

def gen2func(generator):

    gen = []

    @functools.wraps(generator)
    def wrapper(*args):
        if not gen:
            gen.append(generator(*args))
            return next(gen[0])
        return gen[0].send(args)

    return wrapper

@gen2func
def function_with_static_vars(a, b, c):
    # time-consuming initial setup goes here
    # also initialize any "static" vars here
    while True:
        # do something with a, b, c
        a, b, c = yield        # get next a, b, c

rawDescription: Function which computes once, caches the result, and returns from cache infinitely (Python)


code:
back_to_lists = {k:sorted(v) for k,v in d.items()}
back_to_lists

rawDescription: How can I convert a list of maps into a map of sets in python?

description: Convert a list of maps into a map of sets in python


code:
from selenium import webdriver
from pprint import pprint
browser = webdriver.Firefox()
browser.get("https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s")
data = [[td.text for td in row.find_elements_by_tag_name("td")] for row in browser.find_elements_by_xpath("//tbody[@id='mrc_main_table']/tr")]
pprint(data)

rawDescription: How can I make a list of elements Selenium?

description: Make a list of elements Selenium


code:
def get_updates_for_user_Async(userKey, lastSyncDate):
  noteQuery = ndb.gql('...')
  return noteQuery.map_async(lambda note: note.to_dict())

rawDescription: Creating an asynchronous method with Google App Engine's NDB


rawDescription: XML subtree parsing

description: XML subtree parsing


code:
df.registerTempTable("df")
sqlContext.sql(
    "SELECT date_format(vacationdate, 'dd-MM-YYYY') AS date_string FROM df")

rawDescription: Pyspark changing type of column from date to string


code: makesymbexp(makesymbtree(T, L))

rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


code: print("\t ", num, end='')

rawDescription: Printing a list of numbers in python v.3


code:
class Adaptor(object):
    """Any callable can be an adaptor. This base class just proxies calls
    to an appropriately named method."""
    def __call__(self, input):
        return self.adapt(input)

class ObjectAdaptor(Adaptor):
    """Adaptor to create objects adapting the input value to the
    factory function/constructor arguments, and optionally setting
    fields after construction."""
    def __init__(self, factory, args=(), kwargs={}, fields={}):
        self.factory = factory
        self.arg_adaptors = args
        self.kwarg_adaptors = kwargs
        self.field_adaptors = fields

    def adapt(self, input):
        args = (adaptor(input) for adaptor in self.arg_adaptors)
        kwargs = dict((key, adaptor(input)) for key,adaptor in self.kwarg_adaptors.items())
        obj = self.factory(*args, **kwargs)
        for key, adaptor in self.field_adaptors.items():
            setattr(obj, key, adaptor(input))
        return obj

def TypeWrapper(type_):
    """Converts the input to the specified type."""
    return ObjectAdaptor(type_, args=[lambda input:input])

class ListAdaptor(Adaptor):
    """Converts a list of objects to a single type."""
    def __init__(self, item_adaptor):
        self.item_adaptor = item_adaptor
    def adapt(self, input):
        return map(self.item_adaptor, input)

class Pick(Adaptor):
    """Picks a key from an input dictionary."""
    def __init__(self, key, inner_adaptor):
        self.key = key
        self.inner_adaptor = inner_adaptor
    def adapt(self, input):
        return self.inner_adaptor(input[self.key])

rawDescription: What is the pythonic way to add type information to an object's attributes?


code: CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))

rawDescription: How to create a CFuncType in Python

description: Create a CFuncType in Python


code:
all=[]
def frec(word, values=[]):
    global all
    if word == "":  # got result.
        all+=[values]
        return true
    match = False
    for s in subsets:
        if word.startswith(s):
            match = True
            frec(word[len(s):], values+[s])
    if not match:
        return frec(word[1:], values+[word[0]])
frec(word)

rawDescription: Solving jumbled word puzzles with python?


code:
import scipy.sparse
import random
import itertools

def using_nonzero(x):
    rows,cols = x.nonzero()
    for row,col in zip(rows,cols):
        ((row,col), x[row,col])

def using_coo(x):
    cx = scipy.sparse.coo_matrix(x)
    for i,j,v in zip(cx.row, cx.col, cx.data):
        (i,j,v)

def using_tocoo(x):
    cx = x.tocoo()
    for i,j,v in zip(cx.row, cx.col, cx.data):
        (i,j,v)

def using_tocoo_izip(x):
    cx = x.tocoo()
    for i,j,v in itertools.izip(cx.row, cx.col, cx.data):
        (i,j,v)

N=200
x = scipy.sparse.lil_matrix( (N,N) )
for _ in xrange(N):
    x[random.randint(0,N-1),random.randint(0,N-1)]=random.randint(1,100)

rawDescription: Iterating through a scipy.sparse vector (or matrix)


code:
t1.start
t2.start

rawDescription: my python3 threading prog didnt work with fifo-queue

description: My python3 threading prog didnt work with fifo-queue


code:
class UserAccount(ndb.Model):
    provider = ndb.StringProperty(required=True)
    id = ndb.StringProperty(required=True)
    name = ndb.StringProperty()
    email = ndb.StringProperty()

rawDescription: GAE: converting users from users service to oauth2


code:
while True:
    print("\n1. Surname\n2. D.O.B\n3. Quit")
    try:
        select = int(input("Please select an option: "))
        if select == 1:
            surnameSearch()
        elif select == 2:
            DOB_search(BkRdr)
        elif select == 3:
            break
    except:
        print("That was an incorrect option, please try again:")

rawDescription: Breaking out of infinite loop

description: Breaking out of infinite loop


code: ax2.plot(x2, x2, alpha=0)

rawDescription: Matplotlib: one line, plotted against two related x axes in different units?


code:
#remove duplicates
no_dups = {k:list(set(v)) if isinstance(v, list) and k != 'dontCareAboutThisKey' else v
           for k,v in dct.items()}  # or dct.iteritems() if using python2.x

rawDescription: How to append a value to a not yet existing key?

description: Append a value to a not yet existing key


rawDescription: Append to a list using indexes stored in another list


code:
import re
UNIQ='_UNIQUE_STRING_'
class MarkPlaceholders(dict):
    def __getitem__(self, key):
        return UNIQ+('(?P<%s>.*?)'%key)+UNIQ

def format_to_re(format):
    parts = (format % MarkPlaceholders()).split(UNIQ)
    for i in range(0, len(parts), 2):
        parts[i] = re.escape(parts[i])
    return ''.join(parts)

rawDescription: Python: Convert format string to regular expression


code:
import sys
from PySide import QtGui
from PySide import QtCore

class MyRadioButton(QtGui.QPushButton):
    checkSignal = QtCore.Signal(str)

    def __init__(self, text, value=None, label=None):
        QtGui.QPushButton.__init__(self, text)
        self.__value = value
        self.__checked = False
        self.setCheckable(True)
        self.clicked.connect(self.toggleCheck)

    def toggleCheck(self):
        if self.__checked == False:
                self.__checked = True
                self.checkSignal.emit(self.__value)
        else:
                self.__checked = False

class MyRadioGroup(QtGui.QWidget):
    def __init__(self, radios=None):
        QtGui.QWidget.__init__(self)
        self.radios = radios
        for radio in self.radios:
            radio.checkSignal.connect(self.update)

    def update(self, value):
        print("Checked", value)

app = QtGui.QApplication(sys.argv)

radio1 = MyRadioButton('Hello toto', value='toto')
radio2 = MyRadioButton('Hello titi', value='titi')
group = MyRadioGroup(radios=[radio1, radio2])

vbox = QtGui.QVBoxLayout()
vbox.addWidget(radio1)
vbox.addWidget(radio2)
vbox.addStretch(1)
group.setLayout(vbox)
group.resize(250, 150)
group.setWindowTitle('Signals')
group.show()

sys.exit(app.exec_())

rawDescription: Custom signal not working in PySide

description: Custom signal not working in PySide


code:
import logging

logging.basicConfig(filename='db.log')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

rawDescription: How to retrieve executed SQL code from SQLAlchemy

description: Retrieve executed SQL code from SQLAlchemy


rawDescription: pythonic format for indices

description: Pythonic format for indices


code:
from search_doubly_sorted import search_doubly_sorted
print(all(search_doubly_sorted(values, items) == values.searchsorted(items)))

rawDescription: searching sorted items into a sorted sequence

description: Searching sorted items into a sorted sequence


code:
tol = 1e-5 # Edit this to change tolerance
R,C = np.where(np.abs(random_y[:,None] - y)<=tol)

first_output = x[C]
second_output = random_y[R]

rawDescription: Numpy.where() with an array in its conditional


code:
surf = mlab.triangular_mesh(x,y,z,triangles)
surf.mlab_source.scalars = t

rawDescription: generating a hemispherical surface with triangular_mesh and representing a data( as value or as colors) at each vertex

description: Generating a hemispherical surface with triangular_mesh and representing a data( as value or as colors) at each vertex


rawDescription: Cascaded string split, pythonic way

description: Cascaded string split, pythonic way


rawDescription: Make single column of numpy array another datatype


code:
import os
import csv

path = '/tmp/SSH/Testenv'

with open('/tmp/output.csv', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['Project Name', 'Documents'])
  for dirpath, _, filenames in os.walk(path):
    if filenames:
      writer.writerow([os.path.basename(dirpath)] + filenames)

rawDescription: Python script to generate CSV file with foldernames including their associated files


code:
class UserForm(forms.Form):
    class Meta:
        model = User

class ProfileForm(forms.Form):
    class Meta:
        model = Profile

rawDescription: Authentication is not working for custom authentication


rawDescription: From list of dictionaries to np array of arrays and vice-versa


code:
# Approach 1(a)
p = subprocess.Popen(['python', mySubprocessPath], shell = True)

# Approach 1(b) (J.F. Sebastian)
p = subprocess.Popen([sys.executable, mySubprocessPath])

# Approach 2
p = multiprocessing.Process(target=foo, args=(q,))

rawDescription: On what CPU cores are my Python processes running?


rawDescription: Reading Text File From Webpage by Python3


code:
import re

soup.find_all('div', id=re.compile('^content'))

rawDescription: How to get scrape DIV having Class or ID containing specific text

description: Get scrape DIV having Class or ID containing specific text


code:
def named_parameter(label, paramtype):
    expr = Literal(label) + Suppress('=') + paramtype(label)
    return expr

rawDescription: PyParsing a string representing a function


code:
lession1 = [category1, category2, ...]
lession2 = [category10, category11, ...]

rawDescription: Python in HTML: Iterating over several lists by changing the name of a variable


code:
age = raw_input('How old are you? ')
age

rawDescription: Why does LPTHW call "print 'How old are you?', raw_input()" invalid?


code: linestyle='-'

rawDescription: plotting numpy.ndarray

description: Plotting numpy.ndarray


code:
import numpy as np
import pandas as pd
np.random.seed(2015)
N = 15

states = ['NY','NJ','DE']
years = range(2009, 2013)
contracts = pd.DataFrame({
    'State': np.random.choice(states, size=N),
    'Year': np.random.choice(years, size=N),
    '$': np.random.randint(10, size=N)})

means = contracts.groupby(['State', 'Year'])['$'].mean()
result = means.groupby(level='State').filter(lambda x: len(x)>=len(years))

print(result)

rawDescription: Pandas Groupby with multiple columns selecting rows with full range of values


code:
NN = N/2.0
for kx, ky, kz in product(freq, freq, freq):
    k = int(np.sqrt(kx**2 + ky**2 + kz**2) + 0.5)
    if k < NN:
        yaxes[field][k] += A[kx][ky][kz]

rawDescription: python: nested loop over 3d

description: Python: nested loop over 3d


code:
if not day in d:
    d[day] = []
d[day].append(activity)

rawDescription: Assign many values to an element of a list


code:
M.search("utf-8", "(SUBJECT %s)" % u"réception".encode("utf-8"))
# this also works:
M.search("iso8859-1", "(SUBJECT %s)" % u"réception".encode("iso8859-1"))

rawDescription: Python IMAP search using a subject encoded with iso-8859-1


code:
{'name': 'value'}.keys()
{'name': 'value'}.keys()[0]

rawDescription: How does the `for` loop work on dictionaries specifically


code:
import io
fd = io.FileIO('foo.txt', 'r+')

rawDescription: deleting rows in linux

description: Deleting rows in linux


rawDescription: Improvement in pandas dataframe conversion in Python


code:
import inspect

def find_name(package, name):
    if hasattr(package, name):
        yield package
    for modulename, submodule in inspect.getmembers(package, inspect.ismodule):
        yield from find_name(submodule, name)

rawDescription: How to locate a function in a Python module tree?

description: Locate a function in a Python module tree


code: t2 = re.sub(r'[\n\t\ ]+', ' ', t)  # t is your original text

rawDescription: How to filter the string patterns to match in textlines with regex?

description: Filter the string patterns to match in textlines with regex


code: final_result = {frozenset(A, B, C): [x, y, z] for A, B, C, x, y, z in result}  # more readable than first one

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


code:
from operator import attrgetter

sorted(list_of_objects, key=attrgetter('_variable_name'))

rawDescription: sort list of objects by return of object method

description: Sort list of objects by return of object method


code:
import my_package.my_very_long_module_name as foo
from foo import f1, f2, f3

rawDescription: Importing names from an aliased module. Is it possible?


code:
total = sum([project.projectTotal for project in dict.values()])
success = sum([project.projectSuccess for project in dict.values()])
failed = sum([project.projectFailed for project in dict.values()])

rawDescription: Organizing python code for handling statistic information


code:
arr
results=[]
for x in sorted(np.unique(arr[...,2])):
    results.append([np.average(arr[np.where(arr[...,2]==x)][...,0]),
                    np.average(arr[np.where(arr[...,2]==x)][...,1]),
                    x])

results

rawDescription: Group and Average Numpy Matrix

description: Group and Average Numpy Matrix


code:
y = w()
y.visit(t)

rawDescription: Simple example of how to use ast.NodeVisitor?


code: l = [i for i in range(2, 11, 2)]

rawDescription: Storing values from loop in a list or tuple in Python


code: lis = re.findall(r'[A-Za-z\d]+|[^\w\s]+', string)

rawDescription: Python re.findall with * and **

description: Python re.findall with * and **


code:
import csv
import collections
data = collections.OrderedDict()            # 2
with open("file1.csv", "rU") as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        key = row[3].split('_')[0]
        if key in data:
            del data[key]                   # 1
        else:
            data[key] = row

with open('output.csv', 'w') as f_out:
    writer = csv.writer(f_out, delimiter=',')
    writer.writerows(data.values())

rawDescription: Python exract unique record from csv file


code:
words1 = f1.read().split()
words2 = f2.read().split()
words = set(words1) & set(words2)

rawDescription: compare two text files (order does not matter) and output the words the two files have in common to a third file

description: Compare two text files (order does not matter) and output the words the two files have in common to a third file


rawDescription: Correlating vector data with numpy

description: Correlating vector data with numpy


rawDescription: Managing the paths of a directory tree in python


code:
excludehosts = restAPI.objects.values_list('rest_host', flat=True)
soapAPI.objects.filter(soap_state='Live').exclude(soap_host__in=excludehosts)

rawDescription: Compare two alike fields from two separate models


code:
valueOne = self.newfilename.GetValue()
contents = self.contents.GetValue()

rawDescription: Getting multiple wx widget values with Event Handling


code:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.read_graphml('test.graphml')
nx.draw(G)
plt.show()

rawDescription: Processing XML file with networkx in python


code:
with open("highscores.txt","a+") as f: # a+ will allow us to read and will also create the file if it does not exist
    scores_list = f.readlines()
     # if scores_list is empty this is our first run
    if not scores_list:
        f.write("{},{}\n".format(name, score))
    else:
        # else check for name and update score
        new_names = []
        for ind, line in enumerate(scores_list):
            # if name exists update name and score
            if name.rstrip() in line.split(","):
                scores_list[ind] = "{},{}\n".format(line.rstrip(), score)
                break # break so we don't add existing name to new names
        else:
            # else store new name and score
            new_names.append("{},{}\n".format(name, score))

        # all scores updated so open and overwrite
        with open("highscores.txt","w") as scores_file:
             scores_file.writelines(scores_list + new_names)

rawDescription: Updating a Python list based on a search append


code: mylist = ['id', value]

rawDescription: referencing list object by data python

description: Referencing list object by data python


code:
def merge_subs(L):
    dates = {}
    for sub in L:
        date = sub[0]
        if date not in dates:
            dates[date] = []
        dates[date].extend(sub[1:])
    answer = []
    for date in sorted(dates):
        answer.append([date] + dates[date])
    return answer

rawDescription: Grouping Lists in Python

description: Grouping Lists in Python


code:
for line in old_file:
    if pattern in line:
        new_file.write(subst)
    else:
        new_file.write(line)

rawDescription: Python find pattern and replace entire line


code: s = '''Hello, world! It's great that you're talking to me, and everything, but I'd really rather you just split me on punctuation marks. Okay?'''

rawDescription: What Regex to use in this example

description: What Regex to use in this example


code:
#script.py
import os
os.system('which python')

rawDescription: execute os.system('python ') inside a virtualenv

description: Execute os.system('python ') inside a virtualenv


code:
def setup(self, argument='good', argument2='day', argument3='sir'):
    Sample.__init__(self, argument, argument2, argument3)

myclass = type("TestSample", (Sample,), dict(__init__=setup))

rawDescription: Python27: Subclassing a class by using type


code: [" ".join(filter(lambda x: not x.isupper(),x.translate(None,punctuation).split(" "))) for x in s]

rawDescription: Python how to delete lowercase words from a string that is in a list


code:
from binascii import unhexlify, hexlify
s1 = "48656c6c6f"
s2 = "61736b"
hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(s1[-len(s2):]), unhexlify(s2))))

rawDescription: (Python) How to XOR two hex strings so that each byte is XORed separately?


code:
def filterOut2(line):
    return [x for x in line if x != 2]

filtered_lists = data.map(filterOut2)

rawDescription: How does the pyspark mapPartitions function work?


code:
file = None

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    if file is None:
        file = open("file.txt", "w")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)

rawDescription: Python how to keep writing to a file without erasing what's already there


code:
for column_name in ['name', 'id', 'email', 'login']:
    c = User.__table__.columns.get(column_name)
    print("Column %r has an unique constraint: %s" %(column_name, any([c.primary_key, c.unique])))

rawDescription: SQLAlchemy Determine If Unique Constraint Exists


rawDescription: Variable within a Variable in Python (3)


rawDescription: Create CSV file from dictionary of list of tuples


code:
class TreeNode(dict):
    def __init__(self, name, children=None):
        super().__init__()
        self.__dict__ = self
        self.name = name
        self.children = [] if not children else children

rawDescription: How do I serialize a tree class object structure with python json?

description: Serialize a tree class object structure with python json


code:
def get_scroll_state(self):
    """
    Returns a tuple of scene extents percentages.
    """
    centerPoint = self.mapToScene(self.viewport().width()/2,
                                  self.viewport().height()/2)
    sceneRect = self.sceneRect()
    centerWidth = centerPoint.x() - sceneRect.left()
    centerHeight = centerPoint.y() - sceneRect.top()
    sceneWidth =  sceneRect.width()
    sceneHeight = sceneRect.height()

    sceneWidthPercent = centerWidth / sceneWidth if sceneWidth != 0 else 0
    sceneHeightPercent = centerHeight / sceneHeight if sceneHeight != 0 else 0
    return sceneWidthPercent, sceneHeightPercent

rawDescription: Maintaining view/scroll position in QGraphicsView when swapping images


code:
import subprocess
directories = subprocess.check_output(
    ['find', '/data1/realtime', '-type', 'd', '-mmin', '-60']
).splitlines()
# directories content: ['/data1/realtime/dir1000', ...]

rawDescription: Python: How can i find new folders/directories created in last hour in a specific directory in Linux


rawDescription: python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub

description: Python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub


code: lists = list(set( tuple(sorted(x)) for x in your_list_of_lists ) )

rawDescription: Sort list of lists by unique reversed absolute condition


code:
class Setting(models.Model):
    domain = models.ForeignKey(Domain)
    name = models.CharField(null=False, max_length=255)
    value = models.CharField(null=False, max_length=255)

    objects = SettingManager()

rawDescription: Store form fields as key-values / individual rows


rawDescription: Python: what's the difference - abs and operator.abs


code:
import world
world.show = lambda x: True
execfile('example1.py')

rawDescription: How to suppress execution of statement in script called with execfile?

description: Suppress execution of statement in script called with execfile


code:
import tornado.web
import tornado.httpserver

configs = {'some_data': 1, # etc.
          }

def update_configs():
    print("updating")
    configs['some_data'] += 1

class PageOneHandler(tornado.web.RequestHandler):
    def initialize(self, configs):
        self.configs = configs
    def get(self):
        self.write(str(self.configs) + "\n")

class PageTwoHandler(tornado.web.RequestHandler):
    def initialize(self, configs):
        self.configs = configs

    def get(self):
        self.write(str(self.configs) + "\n")

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [('/pageone', PageOneHandler, {'configs' : configs}),
                ('/pagetwo', PageTwoHandler, {'configs': configs})]
        settings = dict(template_path='/templates',
                    static_path='/static', debug=False)
        tornado.web.Application.__init__(self, handlers, **settings)

# Run the instance
application = Application()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)

# Callback function to update configs
some_time_period = 1000 # Once an second
tornado.ioloop.PeriodicCallback(update_configs, some_time_period).start()
tornado.ioloop.IOLoop.instance().start()

rawDescription: Python Tornado updating shared data between requests


code:
import multiprocessing
import threading
range_limit = 3

class LineProducer(object):
    def __init__(self, msg = ''):
        print(self.prepare_line('Initializing %s%s' % (self.__class__.__name__, msg)))

    def prepare_line(self, line):
        return '%d - %d : %s' % (multiprocessing.current_process().pid, threading.current_thread().ident, line)

    def run(self):
        for line in range(range_limit):
            yield self.prepare_line(line)

class MultiThreadedLineProducer(LineProducer):
    def produce(self, q):
        for line in range(range_limit):
            q.put(self.prepare_line(line))

        q.put(None)

    def run(self):
        q = multiprocessing.Queue()
        threading.Thread(target = self.produce, args = (q,)).start()

        while 1:
            line = q.get(True)

            if line == None:
                break;

            yield line

class MultiProcessedLineProducer(LineProducer):
    def produce(self, q):
        for line in range(range_limit):
            q.put(self.prepare_line(line))

        q.put(None)

    def run(self):
        q = multiprocessing.Queue()
        multiprocessing.Process(target = self.produce, args=(q,)).start()

        while 1:
            line = q.get(True)

            if line == None:
                break;

            yield line

if __name__ == '__main__':
    for line in LineProducer(' inside a separate process').run():
        print(line)

rawDescription: python pass long running process to another script

description: Python pass long running process to another script


rawDescription: Pandas saving and reading DataFrame to json


code:
import pandas as pd
df = pd.read_table('data', sep='\s{2,}')

counts = (df.groupby(['Protein'])['Peptide']
            .apply(lambda x: x.value_counts().nlargest(2)))
counts = counts[counts >= 2]
counts = counts.to_frame()
result = pd.merge(df, counts, left_on=['Protein', 'Peptide'], right_index=True,
                  how='inner')
result = result.groupby(['Protein', 'Peptide'])['Mean intensity'].mean()
result = result.reset_index()
print(result)

rawDescription: Grouping and filtering data

description: Grouping and filtering data


rawDescription: Using argparse to choose a function AND supply options


code:
import settings

EMAIL = settings.EMAIL

rawDescription: Calling a script that contains solely an email address


code: localdt.astimezone(pytz.UTC) == localdt

rawDescription: Python pytz: convert local time to utc. Localize doesn't seem to convert


code:
p1, p2, df_later = find_values('ABC', pd.Timestamp('4:15:03'))
p1, p2
df_later

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


rawDescription: JSON encoding for dict of dicts

description: JSON encoding for dict of dicts


code:
def arg_should_contain(x):
    def wrapper(arg):
        assert str(x) in arg, "'%s' does not contain '%s'" % (arg, x)
    return wrapper

...
database.Query = arg_should_contain(id)
result = database.Query('complicated sql with an id: %s' % id)

rawDescription: unittest.mock: asserting partial match for method argument

description: Unittest.mock: asserting partial match for method argument


code:
def adj_list_to_file(G,file_name):
    f = open('tst.txt', "w")
    for n in G.nodes():
        f.write(str(n) + ' ')
        for neighbor in G.neighbors(n):
            f.write(str(neighbor) + ' ')
        f.write('\n')

N=5  #Number of nodes
v=2  #Number of neighbours
p=.1 #rewiring proba
G = nx.connected_watts_strogatz_graph(N,v,p)
nx.draw(G, with_labels= True)
plt.show()
adj_list_to_file(G.to_undirected(),"tst.txt")

rawDescription: Write a Graph into a file in an adjacency list form [mentioning all neighbors of each node in each line]


code:
[{'comment': ['', 'slang'],
  'language': 'fr',
  'suggestion': ['manger', 'bouffer']},
 {'comment': ['for animals', ''],
  'language': 'de',
  'suggestion': ['fressen', 'essen']}]

rawDescription: Transform dictionaries to a list of dictionaries according to their values


code:
import mock
with mock.patch("__builtin__.open", side_effect = ["kaboom", "more","moremore"]):
    assert "kaboom" == open("stuff.txt")
    assert "more" == open("another_thing.txt")
    assert "moremore" == open("last_one.txt")

rawDescription: Patching one occurrence on the function call in Python's Mock


code:
True
True
True
True
True
True
True
True
False
False
False
False
False

rawDescription: Python regular expression for different words & number


code:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
import subprocess

rawDescription: How can I receive a corresponding percentage when progressbar is clicked python3 gtk3

description: Receive a corresponding percentage when progressbar is clicked python3 gtk3


code:
def recreate_A(a):
    return A(a)

@dill.register(A)
def save_A(pickler, obj):
    pickler.save_reduce(recreate_A, (obj.a,), obj=obj)

rawDescription: How to add a custom type to dill's pickleable types

description: Add a custom type to dill's pickleable types


code:
def insertInHtml(string, insstr, position):
    ctr=0
    insidetag=False
    for ci in range(len(string)):
        if string[ci]=='<':
            insidetag=True
        elif string[ci]=='>':
            insidetag=False
        else:
            if not insidetag: ctr+=1
        if ctr==position+1:
            HTMLIndex=ci
            break
    return string[0:HTMLIndex] + insstr + string[HTMLIndex:]

rawDescription: Calculate a text-position inside a div element into the according position in HTML with Python


code:
person.name = 'foo'
person.age = 12

rawDescription: Can I express named Python string arguments more succintly?

description: Express named Python string arguments more succintly


rawDescription: Comparing a numpy array object to multiple conditions


code:
from mingus.midi import fluidsynth as a
from mingus.midi import fluidsynth as b

rawDescription: How to set more than one instrument by Python plus Mingus?

description: Set more than one instrument by Python plus Mingus


rawDescription: Math operations from string

description: Math operations from string


code:
income = int(input("What is your annual income?"))
pension_contribution = int(input("What is your monthly pension contribution?"))

def pension ():
    global income, pension_contribution
    if pension_contribution > ((income//12) * .075):
        print ("Your pension contribution is too high. Monthly pension contributions may not exceed 7.5% of your gross monthly income")

    else:
        print("Your annual pension contribution is R", pension_contribution * 12)

pension() #still have to call function

rawDescription: Use user input within as input in a function Python


code:
import numpy as np
x = np.array([0.1, 0.2, 0.1, 0.1, 0.2, 0.4])
y = (x.reshape(-1, 3).mean(1)[:, np.newaxis] * np.ones(3)).ravel()

print(y)

rawDescription: Traversing theano vector slice by slice

description: Traversing theano vector slice by slice


code:
with open('spam.txt', 'r') as file:
    file.readline() # skip the first line
    rows = [[int(x) for x in line.split(',')[:-1]] for line in file]
    cols = [list(col) for col in zip(*rows)]

rows
cols

rawDescription: reading a text file columnwise and storing in a list in python

description: Reading a text file columnwise and storing in a list in python


rawDescription: Using linalg.block_diag for variable number of blocks


rawDescription: Converting JSON date string to python datetime


code: nltk.tokenize.word_tokenize("Hello, world. How are you?")

rawDescription: Consequences of abusing nltk's word_tokenize(sent)


code:
def integral(integrand,initial_value,dt):
    value = initial_value
    yield value
    for x in integrand:
        value += dt * x
        yield value

rawDescription: SICP "streams as signals" in Python

description: SICP "streams as signals" in Python


code:
from django.contrib.sessions.backends.cache import SessionStore as CachedSessionStore
from django.core.cache import get_cache
from django.conf import settings

class SessionStore(CachedSessionStore):
    """
    A cache-based session store.
    """
    def __init__(self, session_key=None):
        self._cache = get_cache(settings.SESSION_CACHE_ALIAS)
        super(SessionStore, self).__init__(session_key)

rawDescription: Django Multiple Caches - How to choose which cache the session goes in?


code:
import scipy.io.wavfile as wav
(rate,sig) = wav.read("file.wav")

rawDescription: Read .sph files in Python

description: Read .sph files in Python


code: std_env.Library('bar', Glob('*.cpp'))

rawDescription: Strange behaviour appending/removing from array with SCons


code:
html_string=""
for course in Courses.objects.all():
    html_string += '<option value="%s">%s</option>' % (course.pk, course.name)

rawDescription: Django, ajax populate form with model data


code:
values = {}
values['Hello'] = 'World'
print(values) # Will print out {'Hello': 'World'}

rawDescription: Python number averages using lists and keys


code:
class Container(linkedlist, RemovalAPI):
  def __iter__(self):
    it = super().__iter__()
    last_item = None
    for item in it:
      self.add_removal_info(item, last_item)
      yield item

  def remove(self, item):
    removal_info = self.get_removal_info(item)
    if removal_info is None:
      self.remove_first()
    else:
      self.remove_after(removal_info)

  def insert(self, item):
    self.add_removal_info(item, None)
    self.add_to_front(item)
    # do whatever post-processing I need
    # ...

rawDescription: Generalized reference that allows efficient deletion from a variety of containers


code: return ' '.join(('salad:', str(s), 'hamburger:', str(h), 'water:', str(w)))

rawDescription: how to omit parenthesis in return from a python def

description: Omit parenthesis in return from a python def


code:
...
self.label1 = wx.StaticText(self)
self.fileCtrl = wx.FilePickerCtrl(self)
self.mailRadio = wx.RadioButton(self)
self.uploadRadio = wx.RadioButton(self)
...

rawDescription: wxPython controls not clickable

description: WxPython controls not clickable


code:
def tmp(x,n,cons):
       if cons is False:#case 1
           R, s, a, T = x[0], x[1], x[2], x[3]
       elif cons is True:#case 2
           R=0 #change them if you want
           T=60000
           s, a = x[0], x[1]
       #your calculations
       #...

rawDescription: Minimizing a function while keeping some of the variables constant


code:
class Test:

  def get_dynamic_value():
    return 'dynamic'

  dynamic_value = get_dynamic_value()

rawDescription: Assigning class variable dynamic value from inside a classs


code:
df = DataFrame([[1,2.2,3.5],[6.1,0.4,1.2]], columns=list('abc'))
weight = DataFrame(Series([0.5, 0.3, 0.2], index=list('abc'), name=0))
df
weight
df * weight

rawDescription: How to compute weighted sum of all elements in a row in pandas?

description: Compute weighted sum of all elements in a row in pandas


rawDescription: How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM

description: Calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM


rawDescription: Two ways to join lists in dataframe: as rows and columns


code:
def func(faults):
    return 'YES' if np.any(faults == 'YES') else 'NO'

rawDescription: Downsize series containing boolean data with resample


code:
@app.route('/')
def hello():
    data = {'username': 'Pang', 'site': 'stackoverflow.com'}
    return render_template('settings.html', data=data)

rawDescription: Passing variables from flask to javascript


code:
def draw_circle(event,x,y,flags,param):
    global mouseX,mouseY
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),100,(255,0,0),-1)
        mouseX,mouseY = x,y

rawDescription: Opencv: detect mouse position clicking over a picture


code:
truc = [['12', 'brett', 5548],
       ['22.3', 'troy', 9514],
       ['8.1', 'hings', 12635],
       ['34.2', 'dab', 17666],
       ['4q3', 'sigma', 18065],
       ['4q3', 'delta', 18068]]

truc.sort(key=lambda a:a[-1])
groups = [[]]
last_row = None
for row in truc:
    if last_row is not None and row[-1] - last_row[-1] > 3500:
        groups.append([])
    last_row = row
    groups[-1].append(row)

import pprint
pprint.pprint(groups)

rawDescription: Group data into specified intervals satisfying certain condition


rawDescription: How to use regex with optional characters in python?

description: Use regex with optional characters in python


code:
result = [(text_i.rstrip('.'), text_vi.replace(': ', '')) for text_i, text_vi in texts]
result

rawDescription: Parsing web page in python using Beautiful Soup


code:
In [11]: None == None
Out[11]: True

In [12]: np.nan == np.nan
Out[12]: False

rawDescription: Select rows from a DataFrame based on presence of null value in specific column or columns


code:
import ast
polygon_in = []
with open('polygon.txt', 'r') as f:
    polygon_str = f.readline()
    polygon_in.append(ast.literal_eval(polygon_str))

rawDescription: python asign value of list variable from text file

description: Python asign value of list variable from text file


code:
re.search(r'^word', 'Line one\nword on line two\n', flags=re.M)
re.search(r'\Aword', 'Line one\nword on line two\n', flags=re.M) is None

rawDescription: REGEX - Differences between `^`, `$` and `\A`, `\Z`


code: np.broadcast(x, y, z).shape

rawDescription: Numpy function to get shape of added arrays


code:
import json
sample = '''\
{
    "status": "success",
    "data": [
        {
            "notes": [],
            "handles": {
                "twitter": [
                    {
                        "networkinstance": "twitter",
                        "Uid": "fefewf32ff32f232f3f",
                        "id": "243425324242",
                        "@class": "Provider"
                    }
                ]
            },
            "id": "g43g5434g43f2f3",
            "tags": []
        }
    ]
}
'''
json_result = json.loads(sample)
json_result['data'][0]['id']

rawDescription: Collecting a value from Json

description: Collecting a value from Json


code: df.groupby(['c1', 'c2']).cumcount()+1

rawDescription: best way to add sequential counter column using pandas.groupby

description: Add sequential counter column using pandas.groupby


rawDescription: how to convert all int to str in a nested dict with json.dumps()?

description: Convert all int to str in a nested dict with json.dumps()


code:
pd.options.display.show_dimensions = False
df

rawDescription: Pandas DataFrame Display Without Dimensions


code:
class UserProfile(models.Model):
    # various things ...
    def set_fullname(self, f_name, l_name):
        self.FullName = f_name + ' ' + l_name

rawDescription: Add two form fields in Django

description: Add two form fields in Django


code:
ref_re = [ re.compile(r) for r in ref ]
output = { i : [ r.pattern for r in ref_re if r.match(i) ] for i in input }

rawDescription: Match two Python lists with regular expressions, and create dictionary output


code: indices = ((min_value < a) & (a < max_value)).nonzero()[0]

rawDescription: Filter an array in Python3 / Numpy and return indices


code:
def check(a, b):
    return (a == 0) != (b == 0)

rawDescription: Compare nth elements of multiple lists

description: Compare nth elements of multiple lists


code: print(dict_list[2]["Num"])    # 2

rawDescription: Python: How to access the dictionary that has specific key-values in a list


rawDescription: Better way to shuffle two numpy arrays in unison


rawDescription: How to run one python webdriver test in multiple browsers

description: Run one python webdriver test in multiple browsers


code:
names = ["Almond","Hawthorn","Peach"]
groupDF = pd.DataFrame({'Rank':[1,2,3],'Name':names})

rawDescription: Python Pandas get one text value

description: Python Pandas get one text value


code:
html5lib
reportlab
six
xhtml2pdf

rawDescription: HTML to PDF conversion in app engine python


code: weightvalue = sheet.cell(3, 3).value

rawDescription: Read files from list of files

description: Read files from list of files


code:
import importlib

module = importlib.import_module(modulename)

rawDescription: Instantiating object of a class using the name of the class


rawDescription: Combine date column and time column into index in pandas data frame


code:
class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        questions = kwargs.pop('questions')
        super(MyForm, self).__init__(*args, **kwargs)
        counter = 1
        for q in questions:
            self.fields['question-' + str(counter)] = forms.CharField(label=question)
            counter += 1

rawDescription: How to create a list of fields in django forms

description: Create a list of fields in django forms


code: re.search('<!-- begin staff -->.*?<!-- end staff -->', text, re.DOTALL)

rawDescription: Matching a pair of comments in HTML using regular expressions


code:
(df.groupby(['ID'])
   .filter(lambda x: x['Year'].nunique()>=3))

rawDescription: Pandas: Select based on number of items in a set


code:
import inspect
def func (k = lambda x: x ** 2):
    if not callable(k):
        raise TypeError('k must be callable.')
    argspec = inspect.getfullargspec(k)
    nargs = len(argspec.args)
    ndeft = 0 if argspec.defaults is None else len(argspec.defaults)
    if nargs != ndeft + 1:
        raise TypeError('k must be callable with one argument.')
    # Do whatever you want

rawDescription: Python specify lambda arguments as a function argument


code: used_bytes, total_bytes, aligned_bytes, encodings = zip_longest(*all_results)

rawDescription: Pythonic way to aggregate object properties in memory efficient way?


code:
ast.literal_eval('1')
type(ast.literal_eval('1'))
type(ast.literal_eval('1.0'))
type(ast.literal_eval('[1,2,3]'))

rawDescription: determine "type of value" from a string in python

description: Determine "type of value" from a string in python


code:
df = function_to_load_my_data()
fig, ax = plt.subplots()

rawDescription: How can I overlay two graphs in Seaborn?

description: Overlay two graphs in Seaborn


code:
def lattice():
    code
    return steps, history

steps = []
histories = []
for i in range(0,10):
    num_steps, history = lattice()
    steps.append(num_steps)
    histories.append(history)

rawDescription: python- construction of lattice which traps molecules - doesn't work right

description: Python- construction of lattice which traps molecules - doesn't work right


code:
import subprocess, re

list_of_ips = ["facebook.com", "google.com"]
for ip in list_of_ips:
    ping_process = subprocess.Popen(['ping', '-c', '5', ip], stdout=subprocess.PIPE)
    stdout = ping_process.stdout.read()
    match = re.search(r'\d*\.\d*\/(\d*\.\d*)\/\d*\.\d*\/\d*\.\d*', stdout)
    avg = match.group(1)
    print('{}: {}ms'.format(ip, avg))

rawDescription: Python write stdout to log file

description: Python write stdout to log file


code:
if request.method == 'POST':
    form = AppForm(request.POST)
    rolesFormset = RoleForm(request.POST)
    if form.is_valid() and rolesFormset.is_valid():
        app = form.save()
        roles = rolesFormset.save()
        for role in roles:
            app.roles.add(role)
        return redirect(reverse('index'))

rawDescription: Multiple linked Django forms, one submit


rawDescription: iPython parallel pushing every objects is messy

description: IPython parallel pushing every objects is messy


code:
def check_cog_nog(x):
    if len(x) > 1:
        y = x[1].lower()
        if "nog" in y or "cog" in y:
            return True
    return False

filter(check_cog_nog, values)

rawDescription: Selecting specific lists in a file

description: Selecting specific lists in a file


code: sorted(dict1.values(), key=lambda d: d['Name'])

rawDescription: Worth using sorted( ,key=) on a nested dictionary?


rawDescription: Using matplotlib *without* TCL

description: Using matplotlib *without* TCL


code:
class UnhashableString(str):
    def __hash__(self):
        raise TypeError

class AutoNameValueEnum(enum.Enum):
    def __init__(self):
        self._value_ = UnhashableString(self._name_.lower())

class Color(AutoNameValueEnum):
    RED = ()

rawDescription: How to create an enum that uses the name of the member as the value?

description: Create an enum that uses the name of the member as the value


code:
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(xi, yi, varray)
plt.show()

rawDescription: Generating gradient map of 2D array

description: Generating gradient map of 2D array


code: df[np.logical_and(df.A != 0, df.B != 0)].plot()

rawDescription: Mask zero values from pandas plot

description: Mask zero values from pandas plot


code:
import csv
import numpy
reader=csv.reader(open("test.csv","rb"),delimiter=',')
x=list(reader)
result=numpy.array(x).astype('float')

rawDescription: load csv into 2D matrix with numpy for plotting

description: Load csv into 2D matrix with numpy for plotting


code:
def hey():   # <-- this function was being called not index()
    return 'hey everyone!'

@app.route("/")
@app.route("/index")
def index(): # <-- this function will now be called b/c it is directly under routes
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('layout.html', title='Home', user=user)

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: Basic Flask: Using Helper Function w/in View


code:
#!/usr/bin/python
from flup.server.fcgi import WSGIServer
from api import app as application

if __name__ == '__main__':
    WSGIServer(application, bindAddress='/var/run/fcgi.sock').run()

rawDescription: Running python under nginx

description: Running python under nginx


rawDescription: Why is re.sub is not replacing string with empty string


code:
# Sort X,Y pair
tmp=max(x,y)
x=min(x,y)
y=tmp

# Sort Y,Z pair
tmp=max(y,z)
y=min(y,z)
z=tmp

# Sort X,Y pair again.
tmp=max(x,y)
x=min(x,y)
y=tmp

rawDescription: Number sort using Min, Max and Variables


rawDescription: Can I create an RPG-esque save & quit, and then reload progress?

description: Create an RPG-esque save & quit, and then reload progress


rawDescription: Overload instance[key] += val

description: Overload instance[key] += val


rawDescription: Calculate euclidean distance with numpy

description: Calculate euclidean distance with numpy


code:
f = open('ints','wb')
x = numpy.int16(array([1,2,3]))
f.write(x)
f.close()

rawDescription: How can I read and write binary files?

description: Read and write binary files


rawDescription: Hexlify an integer in Python

description: Hexlify an integer in Python


code:
df = pd.DataFrame(l, columns=l[0]._fields)
df

rawDescription: How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances?

description: Create pandas DataFrame (with index or multiindex) from list of namedtuple instances


code:
df['PriceSquared'] = df['Price'] * 2
dfg = df.groupby(['Sector', 'Price', 'PriceSquared'])

rawDescription: DataFrameGroupBy object Column Name

description: DataFrameGroupBy object Column Name


code: [{a[index]: index} for index in range(len(a))]

rawDescription: Finding Index in string with recurring chars


code: struct.unpack('>h', '\x10\x00')

rawDescription: int to binary python

description: Int to binary python


rawDescription: dictionary help for python writing a code

description: Dictionary help for python writing a code


code:
def hard_maths(name):
    return name, np.dot(np.linalg.inv(matricies[name]),
            matrix).round(0)

pool = mp.Pool()
results = pool.map(hard_maths, matrices.iterkeys())
pool.close()
pool.join()

rawDescription: Return map results as keyed dictionary

description: Return map results as keyed dictionary


code:
str = "13480 D'AAA-BBB CCC..."
result = str.split(' ',1)

print(result[0]) # will print "13480"
print(result[1]) # will print "D'AAA-BBB CCC..."

rawDescription: python and string extraction

description: Python and string extraction


code:
{"number": 0}
{"number": 1}
{"number": 2}
{"number": 3}
{"number": 4}
{"number": 5}
{"number": 6}
{"number": 7}
{"number": 8}
{"number": 9}

rawDescription: Append list of Python dictionaries to a file without loading it


code:
class myclass(object):
    def __init__(self):
        self.__age=None
    @property
    def age(self):
        if self.__age is None:
            self.__age=21  #This can be a long computation
        return self.__age

rawDescription: Pythonic way to only do work first time a variable is called


code:
year, week, dow = datetime.today().isocalendar()
week_start = datetime.strptime(str(year) + "-" + str(week-2) + "-0", "%Y-%W-%w")
result = [(week_start + timedelta(days=x)).day for x in range(0,7)]

rawDescription: Days/dates in a given week

description: Days/dates in a given week


rawDescription: Regex negative matching with python

description: Regex negative matching with python


code:
with mock.patch.object(requests, 'get') as mock_get:
    mock_get.return_value = ' ... '
    mock_storage = mock.Mock()
    obj._fetch_law(some_task, mock_storage)
    mock_storage.extend.assert_called_with(expected_value)

rawDescription: How do you get to the value inside of a python function that returns nothing for unit testing?

description: Get to the value inside of a python function that returns nothing for unit testing


code:
for row_slice, col_slice in clusters:
    start_row = row_slice.start
    end_row = row_slice.stop
    start_col = col_slice.start
    end_col = col_slice.stop
    # draw your rectangle

rawDescription: detect high values from numpy array

description: Detect high values from numpy array


code:
class OfferView(View):

    template_name = "generic_app/offers.html"

    def get(self, request, *args, **kwargs):
        return load_offers(request)

rawDescription: Django Template Page Outputting Nothing

description: Django Template Page Outputting Nothing


code: a = a.split(" ")

rawDescription: Printing long interger in python up to 10 digits


code:
calclists = [[1,2,3], [4,5,6], [7,8,9]] # calclists is a list of calclists
calcset = set()
for calclist in calclists:
    for x in calclist:
        calcset.add(x)
unique_calclist = list(calcset)
for x in unique_calclist:
    for y in unique_calclist[1:]:
        # in your example you didn't use combinations
        # of duplicate valuesso I am skipping that here
        if x != y:
            print (x, y)

rawDescription: Editing script to account for every combination of two lists


rawDescription: numpy element transformation with lambda?

description: Numpy element transformation with lambda


code:
def run(self):
    while True:
        self.buffer += self.ser.read(self.ser.inWaiting()) #read all char in buffer
        while '\n' in self.buffer: #split data line by line and store it in var
            var, self.buffer = self.buffer.split('\n', 1)
            self.queue.put(var) #put received line in the queue
        time.sleep(0.01)   #do not monopolize CPU

rawDescription: PySerial loses data

description: PySerial loses data


code: command=lambda: f(params)

rawDescription: access to top level widget in Tkinter

description: Access to top level widget in Tkinter


code:
txn1.groupby('Send_Agent').apply(
    lambda txn1 : (txn1.Send_Amount.shift() == txn1.Send_Amount).cumsum())

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

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


code: new_list = [''.join([list0[i] for i in indices]) for indices in list1]

rawDescription: concatenate strings based on ints from a list

description: Concatenate strings based on ints from a list


code:
import dateutil.parser as parser
parser.parse('Sunday 31st of July 2005 ( 02:05:50 PM )',fuzzy=True)

rawDescription: Converting string to datetime object in Python (GAE)?


code:
from subprocess import check_output

out = check_output(["ps","-u", numuid])

print(out)

rawDescription: How do I show processes for a specific uid or username using command line in python?

description: Show processes for a specific uid or username using command line in python


code: name = value

rawDescription: How to read the string from an .INI file and then read that string from a text file and print the entire line using Python?

description: Read the string from an .INI file and then read that string from a text file and print the entire line using Python


code:
a = np.argsort(dist, axis=1)
a = np.ravel_multi_index((np.arange(dist.shape[0])[:, None], a), dims=dist.shape)

rawDescription: Using NumPy argsort and take in 2D arrays


code: {k: bigdict.get(k, None) for k in ('l', 'm', 'n')}

rawDescription: best way to extract subset of key-value pairs from python dictionary object

description: Extract subset of key-value pairs from python dictionary object


code:
new_data = np.pad(data, radius, mode='reflect')
new_data

rawDescription: numpy how find local minimum in neighborhood on 1darray

description: Numpy how find local minimum in neighborhood on 1darray


code:
m = range(5)
n = range(6, 11)

rawDescription: Passing multiple value_list in Django

description: Passing multiple value_list in Django


rawDescription: takes exactly 1 positional argument (0 given)

description: Takes exactly 1 positional argument (0 given)


code:
class CompanyInfo(object):
    def __init__(self, name, founded_yr, empl_count):
        self.name = name
        self.founded_yr = founded_yr
        self.empl_count = empl_count

    def __str__(self):
        return 'Name: {}, Founded: {}, Employee Count: {}'.format(self.name, self.founded_yr, self.empl_count)

rawDescription: using a class instead of a list python

description: Using a class instead of a list python


code: paragraph[:5], paragraph[5:]

rawDescription: Python Split string in a certain length

description: Python Split string in a certain length


rawDescription: How to split string by space and treat special characters as a separate word in Python?

description: Split string by space and treat special characters as a separate word in Python


code:
kidshair['allkids', 'child3', 'hair']
mypath = ('allkids', 'child3', 'hair')
kidshair[mypath]

rawDescription: Storing dictionary path in Python

description: Storing dictionary path in Python


code:
import csv
from StringIO import StringIO

import requests

url = "http://www.aemet.es/es/eltiempo/observacion/ultimosdatos_8178D_datos-horarios.csv?k=clm&l=8178D&datos=det&w=0&f=temperatura&x=h24"
r = requests.get(url)

buffer = StringIO(r.text)
cr = csv.reader(buffer)
for row in cr:
    print(row)

rawDescription: I can't read a csv file in Python. The result has many rows instead of cells


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