code:
from kivy.config import Config
Config.set('graphics', 'fullscreen', 'fake')

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self):
        button = Button(text="Exit", size_hint=(None, None))
        button.bind(on_press=exit)
        return button

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

rawDescription: How can I hide the main window titlebar and place a transparent background in kivy framework?

description: Hide the main window titlebar and place a transparent background in kivy framework


code:
# this is assuming the item is both present,
# and referencing it by its string value
newItem = treeWidget.findItems(text)[0]
treeWidget.scrollToItem(newItem)

rawDescription: Remembering Scroll value of a QTreeWidget in PyQt


code:
NUM_CATEGORIES = 4

# ...

parser.add_option('-c', '--categories', dest='categories', nargs=NUM_CATEGORIES)

# later

if not options.categories:
    options.categories = [raw_input('Enter input: ') for _ in range(NUM_CATEGORIES)]

rawDescription: how to access nargs of optparse-add_action?

description: Access nargs of optparse-add_action


code:
# Send data
socket.sendall(data)

# Look for the response
data = client_socket.recv(128)   # Make sure the buffer is big enough

rawDescription: Two Raspberries communicating each other


code:
url(r'^(?P<account_id>\d+)/$', views.IndexView.as_view(), name='index'),
url(r'^$', views.IndexView.as_view(), name='index'),

rawDescription: Restricting access to Django generic views


code:
import subprocess, Image

fps, duration = 24, 100
for i in range(fps * duration):
    im = Image.new("RGB", (300, 300), (i, 1, 1))
    im.save("%07d.jpg" % i)
subprocess.call(["ffmpeg","-y","-r",str(fps),"-i", "%07d.jpg","-vcodec","mpeg4", "-qscale","5", "-r", str(fps), "video.avi"])

rawDescription: Can you "stream" images to ffmpeg to construct a video, instead of saving them to disk?


code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class CustomTouchMixin(object):

  def __init__(self, *args, **kwargs):
    super(CustomTouchMixin, self).__init__(*args, **kwargs)
    self.register_event_type("on_really_touch_down")

  def on_really_touch_down(self, touch):
    pass

class CustomTouchWidgetMixin(CustomTouchMixin):

  def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
      self.dispatch("on_really_touch_down", touch)
    return super(CustomTouchWidgetMixin, self).on_touch_down(touch)

class CustomTouchLayoutMixin(CustomTouchMixin):

  def on_touch_down(self, touch):
    for child in self.walk():
      if child is self: continue
      if child.collide_point(*touch.pos):
        # let the touch propagate to children
        return super(CustomTouchLayoutMixin, self).on_touch_down(touch)
    else:
      super(CustomTouchLayoutMixin, self).dispatch("on_really_touch_down", touch)
      return True

class TouchHandlerBoxLayout(CustomTouchLayoutMixin, BoxLayout):
  pass

class TouchAwareButton(CustomTouchWidgetMixin, Button):
  pass

class TestApp(App):

  def on_background_touch(self):
    print("Background Touched")

  def on_button_touch(self, button_text):
    print("'{}' Touched".format(button_text))

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

rawDescription: Kivy: How to separate background touch from a widget touch?


code:
Z = scipy.zeros(2*len(X))
Z[::2] = X

rawDescription: Using fourier analysis for time series prediction


code: request.session['account'] = aid

rawDescription: Persisting user selected data in Django application


code:
def is_substr(input_string, substrs):
    return any(strs in input_string for strs in substrs)

def awesome(my_string):
    if is_substr(my_string, ["A", "B", "C"]):
        x = do_something() + complicated_thing()
    elif is_substr(my_string, ["1", "2", "3"]):
        x = do_something_else() + complicated_thing()
    elif is_substr(my_string, ["!", "#", "$"]):
        x = do_another_thing() + complicated_thing()
    return x + ("Hello" if some_condition(x) else "World")

rawDescription: What's the most pythonic way (if any) to refactor these nested for/else loops?


code:
iter0, iter1, iter2 = itertools.tee(input_iter, 3)
ilen, sum_x, sum_x_sq = count(iter0),sum(iter1),sum(map(lambda x:x*x, iter2))

rawDescription: iterating over a single list in parallel in python

description: Iterating over a single list in parallel in python


code: data = [[0] * cols for i in range(rows)]

rawDescription: Python - best way to set a column in a 2d array to a specific value


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([0, 2000, 0, 2e-9])

ax.annotate('Cutoff', xy=(2000, 0), xytext=(0, -15 - ax.xaxis.labelpad),
            xycoords=('data', 'axes fraction'), textcoords='offset points',
            ha='center', va='top',
            bbox=dict(boxstyle='round', fc='none', ec='red'))

plt.show()

rawDescription: Draw box around tick label in Matplotlib


code: d = {key: 0 for (key, value) in unique}

rawDescription: How to merge and convert list of tuples to Dict

description: Merge and convert list of tuples to Dict


code:
my_word_list = ['one', 'two', 'three']
a_string = 'one two three'
if words_in_string(my_word_list, a_string):
    print('One or more words found!')

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


code:
class Auto(object):
    def __get__(self, instance, owner):
        attr_name = (k
            for klass in owner.__mro__
            for (k, v) in klass.__dict__.iteritems()
            if v == self).next()
        return attr_name

rawDescription: How to find the name of a property from a Python class

description: Find the name of a property from a Python class


code:
for i in enemylist:
    i = Enemy(i, 10)
    enemies.append(i)

rawDescription: Python - Can't create instances from a list or random instances


rawDescription: 2D grid data visualization in Python

description: 2D grid data visualization in Python


code:
for event, elem in iterparse(source):
    if elem.tag == "item":
        status = elem.find('status').text
        desc = elem.find('desc').text
        refs = {r.get('source'): r.text for r in elem.findall('./refs/ref')}
        elem.clear()

rawDescription: Parsing XML out of big files with Python


code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from itertools import groupby

alpha_grades = ('A','B','C','D','E','F','G')

color_scheme = {'A':'b','B':'g','C':'r','D':'c','E':'m','F':'y','G':'k'}

fig, axs = plt.subplots(1, 2, figsize=(12*2,9))  # creates two axes

for term, ax in zip([36,60], axs):
    ax.hold(True)
    for grade, color in color_scheme.items():
        df2 = df[(df['grade'] == grade) & (df['term']==term)]
        df3 = groupby('issue_date')['ROI'].mean()
        df3.plot(ax=ax, color=color,
                 label=("Grade: %s" % grade))
    ax.hold(False)
    ax.legend(loc=2)
    ax.set_title("%i Mo Lending Rate by Rating" % term)

fig.show()

rawDescription: Two graphs, two axis, one figure....stumped.


code:
from pyspark.mllib.linalg import DenseVector
rows.mapValues(DenseVector)

rawDescription: RDD to multidimensional array

description: RDD to multidimensional array


code: get_path(data, 156)

rawDescription: Creating a hierarchy path from JSON

description: Creating a hierarchy path from JSON


code:
s="Ford Motors cannot afford Ford Motor Ford Motorway Ford Motor."
import re
def counter(str,term):
   return len(re.findall(r'\b{}\b'.format(term),str))

counter(s,'Ford Motor')
counter(s,'Ford')
counter(s,'Fords')

rawDescription: Python -- Search Subsrtring Full Word(s)


code: print(min(elems, key=items.count)) # b

rawDescription: Python: Find the list element that is contained least times in another list


rawDescription: How to solve several independent time series at the same time using scikit linear regression model

description: Solve several independent time series at the same time using scikit linear regression model


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--rename', type=str, nargs=2, help='some help',
                    metavar=('OLDFILE', 'NEWFILE'))
args = parser.parse_args()
print(args)

rawDescription: Python argparse: name parameters

description: Python argparse: name parameters


code:
def get_apps():
    apps = (
        'apps.store',
        'apps.other',
        ...
    )
    return [__name__ + '.' + x for x in apps]

rawDescription: building reusable package in django

description: Building reusable package in django


code:
qs = 'tags=python&tags=programming'
cgi.parse_qs(qs)

rawDescription: parse query string with urllib in Python 2.4

description: Parse query string with urllib in Python 2.4


code:
output = [False]

button.pressed.connect(lambda: output.__setitem__(0, True))

rawDescription: One-liner to set a variable value with signal handler function in response to a signal from GUI?


code:
iterator = iter(range(10))   # an iterator over the numbers 0 through 9

first_result = any(x == 3 for x in iterator)   # this will be True
second_result = any(x == 3 for x in iterator)  # the same expression will be False this time!

rawDescription: any() function with csv file in python not behaving how I'm expecting it to

description: Any() function with csv file in python not behaving how I'm expecting it to


code: X - w[:,None] # or X - w[:,np.newaxis]

rawDescription: Subtracting numpy arrays of different shape efficiently


code:
file=open(filename,'r')
file.write(' '.join([repr(x) for x in (v1,v2,v3)])+'\n')

rawDescription: How to Open, Read, and Write files in Python 2.7 -- Converting code from fortran 90 to Python


code:
for i in range(3):
    print("Your text here")

rawDescription: Python, Printing multiple times,

description: Python, Printing multiple times,


code: pd.eval('df[df["annual rate"]>0]')

rawDescription: Using dynamic lists in query in Pandas

description: Using dynamic lists in query in Pandas


code: get_fresh_tokens(do_something, a, b, c)

rawDescription: Calling a function with all the original parameters


code:
@login_required
def crave_view(request, id):
    crave = get_object_or_404(crave_data, pk=id)
    if request.method=="POST":
        form=CraveReplyForm(request.POST, request.FILES)
        if form.is_valid():
            reply = form.save(commit=False)
            reply.person=request.user
            reply.crave = crave
            reply.save()
    else:
        form=CraveReplyForm()

    return render(request, "crave/crave_view.html", {'crave': crave, 'form' : form})

rawDescription: while submitting data in first form blank object is getting created for second form django

description: While submitting data in first form blank object is getting created for second form django


rawDescription: Simple way to convert tuple wrapped as a string to a tuple in python


code:
import scrapy
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose

class QuondeItem(scrapy.Item):
    localizacao = scrapy.Field()  #location
    titulo = scrapy.Field()       #title
    subtitulo = scrapy.Field()    #subtitle
    telefone = scrapy.Field()     #phone
    endereco = scrapy.Field()     #address
    categoria = scrapy.Field()    #category
    quadra = scrapy.Field()       #block

class QuondeItemLoader(ItemLoader):
    default_input_processor = MapCompose(unicode.strip)
    default_output_processor = TakeFirst()

rawDescription: Extract information from a div and make some field parent of others


code:
X, Y = np.meshgrid(x, y)
ax.plot_surface(X, Y, f)
plt.show()

rawDescription: Surface where height is a function of two functions, and a sum over the third


code:
test = ""
sys.getsizeof(test)
test = "" + "h"
sys.getsizeof(test)
test = "" + "h" + "h"
sys.getsizeof(test)

rawDescription: How can I construct a Python string that is 16 bytes long?

description: Construct a Python string that is 16 bytes long


code:
from scipy import signal
from scipy import ndimage

# Use a structuring elements with north, west, east and south elements as 1s
strel = ndimage.generate_binary_structure(2, 1)

# 2D Convolve to get 4s at places that are surrounded by 1s
mask = signal.convolve2d((A==100).astype(int),strel,'same')==4

# Use the mask to set corresponding elements in a copy version as 100
out = A.copy()
out[mask] = 100

rawDescription: Replace values in an 2d array according to neighboring values


code: onsubmit="return writeToStorage();"

rawDescription: How do I cancel action of a form after an alert?

description: Cancel action of a form after an alert


code: self._y = y

rawDescription: scipy 0.11.0 to 0.12.0 changes a linear scipy.interpolate.interp1d, breaks my constantly updated interpolator

description: Scipy 0.11.0 to 0.12.0 changes a linear scipy.interpolate.interp1d, breaks my constantly updated interpolator


code:
no_punc = []
for char in usr_list:
    if char not in punctuation:
        no_punc.append(char)

rawDescription: Loop to remove characters from list not working


code:
def my_test_input(retval, message):
  return retval

rawDescription: Python 3 unittest simulate user input

description: Python 3 unittest simulate user input


code:
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours',
 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself',
 'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which',
 'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be',
 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an',
 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for',
 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',
 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all',
 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not',
 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don',
 'should', 'now']

rawDescription: Need String Comparison 's solution for Partial String Comparison in Python


code:
word = "my example"

def convert_letter(word):
    new_word = word
    for i in range(0, len(word)):
        if ord(word[i]) != 32:
            new_word = new_word.replace(word[i], '_ ')
    print(new_word)
convert_letter(word)

rawDescription: How can I replace the letters of a string with underscores?

description: Replace the letters of a string with underscores


rawDescription: How to find the key corresponding to the maximum value in a dictionary of dictionary using max() function?

description: Find the key corresponding to the maximum value in a dictionary of dictionary using max() function


code:
fH = file(os.path.join(os.path.dirname(__file__), 'someFile.txt'), 'w')
fH.write('here is my string')
fH.close()

rawDescription: In a python script, how can I save the contents of a string to file, and the file is in current directory?


code:
w
w.word.unique()

rawDescription: how to check if a column in a data frame contains only a specific set of values

description: Check if a column in a data frame contains only a specific set of values


code:
remove_commas = re.compile(r',(?=\s*FROM\b)', re.IGNORECASE)
str = remove_commas.sub('', str)

rawDescription: Regexp beginner: how to remove comma before a keyword?


code:
sec = 2
chord = waveform(0, sec) # silence
for note in scale:
    chord += waveform(note, sec)
Audio(chord,rate=sample_rate,autoplay=True)

rawDescription: Generate series of audio tones using iPython.display.Audio


code:
uuids = { 'a': [3, 3, 5, 3, 0, 0, 3, 3, 2, 3, 2, 1, 1, 0, 2, 0, 5, 0, 0, 0, 0, 3, 4, 1, 2],
  'b': [1, 2, 3, 1, 0, 0, 2]}

from itertools import groupby

def detect_runs_in_dict(d, n=3):
    return [uuid for uuid, val in d.items() #in python 2, use .iteritems
        if any(len(list(g)) >= n for k,g in groupby(val))]

rawDescription: Detect consecutive identical values in list


code:
file = open('filename.csv', 'w')
for element in list:
    file.write("%s,%d\n" % (element[0], element[1]))
file.close

rawDescription: Paste list to an Excel file

description: Paste list to an Excel file


code:
from api.v1 import api as api_v1
from api.v1_1 import api as api_v1_1
from api.v2 import api as api_v2

app.register_blueprint(api_v1, url_prefix='/v1')
app.register_blueprint(api_v1_1, url_prefix='/v1.1')
app.register_blueprint(api_v2, url_prefix='/v2')

rawDescription: Support multiple API versions in flask

description: Support multiple API versions in flask


rawDescription: Can I delete an item of a queryset in python but without deleting that item on the database?

description: Delete an item of a queryset in python but without deleting that item on the database


code: new_d={key:dict(filter(lambda x:'n' in x[1], value.items())) for key, value in d.items() if dict(filter(lambda x:'n' in x[1], value.items()))}

rawDescription: Fetch only those part in dictionary of dictionary which contains particular string in value


code: get_key = lambda x: int(x[0] / 60)  # truncate timestamp to the minute

rawDescription: Grouping Messages by Time Intervals

description: Grouping Messages by Time Intervals


code:
import numpy as np
x = np.array([47, 21, 16, 19, 38])
cls = np.array([0, 0, 1, 0, 1],dtype=bool)
x[cls]
x[~cls]

rawDescription: Selecting rows from numpy ndarray when groups are known


code: result = Foo.some_method(obj, 1, 3)  # Not encouraged

rawDescription: Does this code imply a class and method "relationship?"


code:
d =  [(u'Code', u'US'), (u'Country', u'United States'), (u'Name', u'Bill')]
d = dict(d)
d
d['Code']

rawDescription: How to access value in list of dictionaries

description: Access value in list of dictionaries


code: reduce(outer_merge, tmp)

rawDescription: How to pass keyword arguments in reduce over Pandas merge function

description: Pass keyword arguments in reduce over Pandas merge function


code: idx = pd.DatetimeIndex(start=min(df.Date), end=max(df.Date), freq='D')

rawDescription: Python Pandas: Inserting new rows for date gaps in data


code:
import subprocess
cmd = 'ssh ubuntu@192.168.56.101 "sed -i -e s/property=\"true\"/property=\"false\"/g ~/cfg.cfg"'
subprocess.call(cmd, shell=True)

rawDescription: How to transport " for remote execution?

description: Transport " for remote execution


rawDescription: Create variable key/value pairs with argparse (python)


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

# create some random data grouped into three groups
x = np.random.random(100)
y = np.random.random(100)
c = np.random.choice(range(3), 100)

# plot the data
fig = plt.figure()
ax = fig.add_subplot(111)
# plot x,y data with c as the color vector, set the line width of the markers to 0
ax.scatter(x, y, c=c, lw=0)

rawDescription: Plot data point according to their class labels in Python


rawDescription: process.call and cmd.exe

description: Process.call and cmd.exe


code:
import random

key = random.choice(list(topic.keys()))
value = random.choice(topic[key])

rawDescription: access random item in list within dictionaries

description: Access random item in list within dictionaries


code:
# client-side
import requests
file = open('/Volumes/Extra/test/my_video.mpg', 'rb')
payload = MultipartEncoder({'uploadedFile': (file.name, file, 'application/octet-stream')})
r = requests.post('http://somewhere/somefile.py', data=payload, headers={'Content-Type': payload.content_type})

# server-side
@view_config(route_name='remote.agent_upload', renderer='json')
def remote_agent_upload(request):

    # Write your actual file contents, not the post data which contains multi part boundary
    uploadedFile = request.POST['uploadedFile']
    fs = uploadedFile.file

    # The file name is insecure. What if the file name comes through as '../../../etc/passwd'
    # If you don't secure this, you've just wiped your /etc/passwd file and your server is toast
    # (assuming the web user has write permission to the /etc/passwd file
    # which it shouldn't, but just giving you a worst case scenario)
    fileName = uploadedFile.filename

    # Secure the fileName here...
    # Make sure it doesn't have any slashes or double dots, or illegal characters, etc.
    # I'll leave that up to you

    # Write the file
    f = open('/Volumes/Extra/tests2/' + fileName, 'wb')
    f.write(fs.read())

rawDescription: Python requests_toolbelt MultipartEncoder filename


rawDescription: Loop through list until value is found then breaking?


code:
import numpy as np
from datetime.datetime import fromtimestamp

filename = 'tmp.txt'

entry_timestamp, entry_close, entry_high, entry_low, entry_open, entry_volume = \
    np.loadtxt(filename, dtype='O,'+'f8,'*5, delimiter=',', unpack=True,
               converters={0: lambda d: fromtimestamp(float(d))})

rawDescription: numpy.loadtxt unix timestamp converter

description: Numpy.loadtxt unix timestamp converter


code:
dict_sum = dict.fromkeys(L1, 0)
dict_count = dict.fromkeys(L1, 0)
for k,n in zip(L1, L2):
   dict_sum[k] += n
   dict_count[k] += 1

dict_sum
dict_count

rawDescription: Python: summarizing data from list using index from another list


code:
randomLen = random.choice( wordsByLength.keys() )
randomWord = random.choice( wordsByLength[ randomLen ] )

rawDescription: Index by word length

description: Index by word length


code:
from bs4 import BeautifulSoup

data = """

    useful text

"""

soup = BeautifulSoup(data, "html.parser")

# find and remove "span" elements with empty contents
for useless in soup.find_all("span", text=lambda text: not text):
    useless.extract()

print(soup.prettify())

rawDescription: Filter out empty <span> tags from html code


code: return (options + [False])[current_option == options[0]]

rawDescription: Python: Pick other value

description: Python: Pick other value


rawDescription: Python: use the same class instance in multiple modules


code:
A
B
A[~np.in1d(A,B).reshape(A.shape)]

rawDescription: Remove numbers from a numpy array

description: Remove numbers from a numpy array


rawDescription: Python max on potential same values

description: Python max on potential same values


code:
df = pd.DataFrame([[['urn:dew_point'], 1]], columns=['properties', 'id'])
df
df[df['properties'].apply(lambda x: 'urn:dew_point' in x)]

rawDescription: Select Pandas rows based on list value

description: Select Pandas rows based on list value


code: send("x * x")

rawDescription: I want to send a function through serial to python on a RPi


code:
if len(my_sep) > 1:
    print(" the delimiter is too long")
    return None

rawDescription: how do i write my function so that when entered it will print the delimeter is too long?

description: Write my function so that when entered it will print the delimeter is too long


rawDescription: How to delete from an arbitrarilly deeply nested dictionary

description: Delete from an arbitrarilly deeply nested dictionary


rawDescription: Run certain no. of threads/processes simultaneously


rawDescription: replacing numpy array values in-place for arrays with custom dtype

description: Replacing numpy array values in-place for arrays with custom dtype


rawDescription: Error in BMI caluclator

description: Error in BMI caluclator


rawDescription: Python: How does inheritance of __slots__ in subclasses actually work?


code: ret_val = Shell("notepad.exe", vbNormalFocus)

rawDescription: Running python script from excel vba using Shell does nothing


rawDescription: If String ONLY contains "-" or "."

description: If String ONLY contains "-" or "."


code:
fm  = pd.fama_macbeth(y=df['y'],x=df[['x']])
fm

rawDescription: Fama Macbeth Regression in Python (Pandas or Statsmodels)


rawDescription: Condensed matrix function to find pairs

description: Condensed matrix function to find pairs


rawDescription: Getting specific field from chosen Row in Pyspark DataFrame


code:
def clean(self):
    # validate parent. Do this first because this method
    # will transform field values into model field values.
    # i.e. instance will reflect the form changes.
    super(SomeForm, self).clean()

    # can we modify drivers?
    canchangedriver = self.instance.somefunc()

    # either we can change the driver, or if not, we require
    # that the two lists are, when sorted, equal (to allow for
    # potential non equal ordering of identical elements).

    # Wrapped code here for niceness
    if (canchangedriver or
                   (sorted(self.instance.drivers.all()) ==
                    sorted(self.instance.olddrivers))):
        return True
    else:
        raise ValidationError() # customise this to your liking.

rawDescription: django: exclude certain form elements based on a condition

description: Django: exclude certain form elements based on a condition


code:
from sys import argv
import csv

if len(argv) == 4:
  script, inputFile, outputFile, cols_str = argv
  cols = [int(i) for i in cols_str.split(",")]

with open(inputFile,"r") as fin:
  with open(outputFile,"w") as fout:
    writer=csv.writer(fout)
    for row in csv.reader(fin):
      sublist = [row[x] for x in cols]
      writer.writerow(sublist)

rawDescription: Remove or keep specific columns in csv file


code:
import glob
all_text_files = glob.glob('/path/to/dir', '*.txt')

with open('output_file.txt', 'w') as fh:
     for text_file in all_text_files:
         data = open(text_file, 'r')
         fh.write(data.read())

rawDescription: How to read multiple(more than 2) .txt files using python

description: Read multiple(more than 2) .txt files using python


code:
import json
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
json.loads('["foo", {"bar": ["baz", null, 1.0, 2]}]')

rawDescription: Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents?


rawDescription: Detect repetitions in string

description: Detect repetitions in string


code:
from django import template as tt
import pytz
import datetime
tt.Template('{{ x|time:"H:i:s" }}').render(
    tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))

rawDescription: Python: convert seconds to hh:mm:ss

description: Python: convert seconds to hh:mm:ss


code:
l = [randint(0, 100000) for _ in range(0, 128*128*128)]
with gzip.open("out.txt.gz", "w") as tfz:
    tfz.write(" ".join([str(i) for i in l]))

rawDescription: Save list as file in python (The file should be accepted in other programming languages as well )


code:
class MySerializer(serializers.ModelSerializer):
    file = FileUrlField()
    class Meta:
        model = MyModel

rawDescription: Django Rest Framework - Downloading files on server


code:
class TestClass(object):
    def __init__(self, value):
        self._value = (value, value)

    def __str__(self):
        return str(self._value)

    @to_class
    def test_func(value):
        return value

rawDescription: Trying to program a "to_class" general decorator


rawDescription: Python finite difference functions?

description: Python finite difference functions


code:
import xml.etree.ElementTree as ET
xml = '<tag>Some example text</tag>'
tree = ET.fromstring(xml)
def itertext(self):
    tag = self.tag
    if not isinstance(tag, str) and tag is not None:
        return
    if self.text:
        yield self.text
    for e in self:
        for s in e.itertext():
            yield s
        if e.tail:
            yield e.tail

print(''.join(itertext(tree)))

rawDescription: Python element tree - extract text from element, stripping tags


code: match_list = map(list, re.findall('\n(\w+)\s+(\d*)\s+(\d*)', output))

rawDescription: Python - Getting user data using regex

description: Python - Getting user data using regex


code:
from matplotlib import gridspec
gs = gridspec.GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(9, 1))

# first graph
axes = plt.subplot(gs[0,0])
pc = plt.pcolor(df1, cmap='jet')

# second graph
axes = plt.subplot(gs[1,0])
plt.pcolor(df2, cmap='Greys')

# colorbar
axes = plt.subplot(gs[0,1])
plt.colorbar(pc, cax=axes)

rawDescription: How to plot pcolor colorbar in a different subplot - matplotlib

description: Plot pcolor colorbar in a different subplot - matplotlib


code: return numpy.all(plane1 * length(plane2) - plane2 * length(plane1) == 0)

rawDescription: coplanar equations of a plane

description: Coplanar equations of a plane


code:
# fix the seed for reproducability
np.random.seed(2)

# create random data
data = np.tile(np.arange(1,8), (3,1)).T
labels = map(lambda x: 'label ' + str(x), data[:,1])
categories = map(lambda x: 'cat ' + str(x), np.arange(data.shape[1])+1)
for i in range(1,data.shape[1]):
    # shuffle all but the first column
    np.random.shuffle(data[:,i])

# call the function and show the plot
sorted_table_plot(data, labels, categories)
plt.show()

rawDescription: Trying to visualize a sorted table with matplotlib (parallel coordinates?)


rawDescription: Inserting a variable in MongoDB specifying _id field


code: heya.a, heya.b = [1, 2]

rawDescription: modify setattr to mass-assign multiple attributes to different values

description: Modify setattr to mass-assign multiple attributes to different values


code:
import re
from django.utils.translation import ugettext as _

def process_image_tags(text, ImageModel):
    '''image tag usage:
        ... some text ... [img=image_name:image_class(optional)] ... some text ...
    '''
    t1 = re.split(r'(\[img=[a-z0-9\-_\:]+\])', text)
    t2 = []
    for i in t1:
        if i[:5] == '[img=':
            attrs = i[5:-1].split(':')
            name_attr = attrs[0] #name attribute
            error = None
            try:
                image = ImageModel.objects.get(name=name_attr)
            except ImageModel.DoesNotExist:
                error = '%s' % _('Image with given name not found')
            except ImageModel.MultipleObjectsReturned:
                error = '%s' % _('More than one image found')
            if not error:
                p = [' 1:
                    p.append('class="%s"' % attrs[1]) #class attribute
                if image.description:
                    p.append('title="%s"' % image.description)
                p.append('alt="%s"' % image.name)
                p.append('/>')
                t2.append(' '.join(p))
            else:
                t2.append(error)
        else:
            t2.append(i)
    return ''.join(t2)

rawDescription: Performing text processing on flatpage content to include handling of custom tag


code: variables = collections.OrderedDict((k, variables[k]) for k in patients)

rawDescription: Create DataArray from Dict of 2D DataFrames/Arrays


code:
yourdict = {}
# ...
items = list(yourdict.items())

rawDescription: Tuple list from dict in Python

description: Tuple list from dict in Python


code:
data = "xxx@yyy.com@zzz.com@___.com"
if data.count("@") > 1:
    data = data.rsplit('@', data.count("@")-1)[0]

rawDescription: How to reformat a string in python?

description: Reformat a string in python


code:
randomword(10)
randomword(10)

rawDescription: Random strings in Python

description: Random strings in Python


code: data = [[int(i) for i in line.split(';')] for line in open(filename)]

rawDescription: How can i split text data to a list?

description: Split text data to a list


code:
output = {}
for entry in input_list:
    entry = entry.copy()  # so we can mangle it
    id = entry.pop('id')
    date = entry.pop('date')
    output.setdefault(id, {})[date] = entry

rawDescription: Reorganize Dictionary

description: Reorganize Dictionary


code:
@patch.object(utils.UdevWrapper,'udevadm_trigger')
def test_trigger_called(self,mock_udevadm_trigger):
    mock_udevadm_trigger.return_value = True

    # name changed for clarity
    ClassWhereTriggerCalled.func()
    assert mock_udevadm_trigger.called

rawDescription: Unit test python udev interaction

description: Unit test python udev interaction


code:
class ks_refs():
    pool = ConnectionPool('TweetsKS')

    @classmethod
    def cf_connect(cls, column_family):
        cf = pycassa.ColumnFamily(cls.pool, column_family)
        return cf

user_name_cf = ks_refs.cf_connect('UserName')
user_tweet_cf = ks_refs.cf_connect('UserTweet')

rawDescription: python static class with static method that uses self?

description: Python static class with static method that uses self


rawDescription: itertools product speed up

description: Itertools product speed up


code:
while element < end_element:
    element += 1
    print(a, end="")
    a,b = b,a+b

rawDescription: Python - value replacement, calculation, and print - simplification


code:
with open('testfile', 'wb') as f:
    f.write('\r\n')
with open('testfile', 'r') as f:
    assert f.read() == '\n' # converted

rawDescription: Python bytearray isn't as long as it should be


code:
x
residuals
rank
s

rawDescription: Apply non-linear regression for multi dimension data samples in Python


code:
class Factor:
    ...

Factor.empty = Factor([], None)

rawDescription: Define a constant object in python

description: Define a constant object in python


code:
s = foo.__doc__  # s now refers to the docstring

lst = s.split("\n* ")
section = [section for section in lst if section.startswith("Developers")][0]
print(section) # prints the "Developers" section

rawDescription: More than 1 docstrings for a single module/function etc.?


code:
from itertools import islice

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

rawDescription: Python - Return first N key:value pairs from dict


code:
sentences
unq_words
out

rawDescription: Efficiently testing if strings are present in 2D numpy arrays


rawDescription: Get first element of sublist as dictionary key in python


code:
regexpHandler = re.compile('(
.*?
)')

rawDescription: Python and web-tags regex

description: Python and web-tags regex


code:
import unittest

class TestNumberParser(unittest.TestCase):
    def test_fp_type_i(self):
        self.assertEqual(NumberParser(float).parse("eight"), 1.)

    def test_fp_type_f(self):
        self.assertEqual(NumberParser(float).parse("eight point one"), 1.)

    def test_fp_str_i(self):
        self.assertEqual(NumberParser("float").parse("eight"), 1.)

    def test_fp_str_f(self):
        self.assertEqual(NumberParser("float").parse("eight point one"), 1.)

    def test_ip_type_i(self):
        self.assertEqual(NumberParser(int).parse("eight"), 1)

    def test_ip_type_f(self):
        self.assertEqual(NumberParser(int).parse("eight point one"), 1)

    def test_ip_str_i(self):
        self.assertEqual(NumberParser("int").parse("eight"), 1)

    def test_ip_str_f(self):
        self.assertEqual(NumberParser("int").parse("eight point one"), 1)

    def test_ap_i(self):
        self.assertEqual(NumberParser().parse("eight"), 1)

    def test_ap_f(self):
        self.assertEqual(NumberParser().parse("eight point one"), 1.)

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

rawDescription: Design pattern - two different return types


code:
newline = " ".join(words)
print(newline)

rawDescription: Python string replacement

description: Python string replacement


code:
def gen():
    with picamera.PiCamera() as camera:
      camera.start_preview()
      # Camera warm-up time
      time.sleep(2)

      while True:
        stream = io.BytesIO()
        camera.capture(stream, 'yuv')
        yield stream.getvalue()
        #perhaps add a time.sleep() here to enforce a constant framerate?

rawDescription: YUV live video streaming using Flask

description: YUV live video streaming using Flask


code:
def prepare_text(dat):
    cpy = BytesIO()
    for row in dat:
        cpy.write('\t'.join([repr(x) for x in row]) + '\n')
    return(cpy)

def prepare_binary(dat):
    pgcopy_dtype = [('num_fields','>i2')]
    for field, dtype in dat.dtype.descr:
        pgcopy_dtype += [(field + '_length', '>i4'),
                         (field, dtype.replace('<', '>'))]
    pgcopy = np.empty(dat.shape, pgcopy_dtype)
    pgcopy['num_fields'] = len(dat.dtype)
    for i in range(len(dat.dtype)):
        field = dat.dtype.names[i]
        pgcopy[field + '_length'] = dat.dtype[i].alignment
        pgcopy[field] = dat[field]
    cpy = BytesIO()
    cpy.write(pack('!11sii', b'PGCOPY\n\377\r\n\0', 0, 0))
    cpy.write(pgcopy.tostring())  # all rows
    cpy.write(pack('!h', -1))  # file trailer
    return(cpy)

rawDescription: Use binary COPY table FROM with psycopg2


rawDescription: Match beginning and end of string with regex in python


rawDescription: using variables in class functions in another class (python)

description: Using variables in class functions in another class (python)


code: hdist = mttt_pings['hdist'].values

rawDescription: Python: simplifying code by writing it in a more Pandas specific way


code:
def foo(x):
   for i in xrange(10):
      yield x * i
...
for x in foo(5):
   print(x)

rawDescription: What is the best way to translate this recursive python method into Java?


code:
class IfMacro(MultiLineMacro):
  syntax = (
      Group("if", Var(), ":", Var(), name='if_'),
      ZeroOrMore("elif", Var(), ":", Var(), name='elifs'),
      Optional("else", Var(name='elseBody'))
    )

  def handle(self, syntaxtree, if_=None, elifs=None, elseBody=None):
    # Default parameters in case there is no such named item.
    # In this case this can only happen for 'elseBody'.
    return If(
        [(cond, Stmt(body)) for keyword, cond, body in [if_] + elifs],
        None if elseNody is None else Stmt(elseBody)
      )

rawDescription: Pythonic macro syntax

description: Pythonic macro syntax


code:
widths=(4,10,10)
items=(1,"ONE",2)
"".join("%*s" % i for i in zip(widths, items))

rawDescription: Writing/parsing a fixed width file using Python


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

from itertools import product
from string import ascii_uppercase
from matplotlib import patheffects

m, n = 4, 7 # 4 rows, 7 columns
df = pd.DataFrame(np.random.randn(m, n),
                  columns=list(ascii_uppercase[:n]),
                  index=list(ascii_uppercase[-m:]))

ax = plt.imshow(df, interpolation='nearest', cmap='Oranges').axes

_ = ax.set_xticks(np.linspace(0, n-1, n))
_ = ax.set_xticklabels(df.columns)
_ = ax.set_yticks(np.linspace(0, m-1, m))
_ = ax.set_yticklabels(df.index)

ax.grid('off')
ax.xaxis.tick_top()

rawDescription: Create heatmap using pandas TimeSeries

description: Create heatmap using pandas TimeSeries


rawDescription: ForeignKey to a Model field?

description: ForeignKey to a Model field


code:
import re
def matchany(subject):
    match = re.match(
        r"""
        (?=.*\(([^()]*)\))   # Find match between () --> group 1
        (?=.*\{([^{}]*)\})   # Find match between {} --> group 2
        (?=.*!([^!]*)!)      # Find match between !! --> group 3""",
        subject, re.VERBOSE)
    return match.groups() if match else None

rawDescription: apply a regex to retrieve a string

description: Apply a regex to retrieve a string


rawDescription: How do I select from drop down menu with changing id on reload of webpage

description: Select from drop down menu with changing id on reload of webpage


code:
class LatestArticleMixin(object):

    def get_context_data(self, **kwargs):
        context = super(LatestArticleMixin, self).get_context_data(**kwargs)
        try:
            context['latest_article_list'] = Entertainmentblog.objects.order_by('-posted')[:25]
        except:
            pass
        return context

rawDescription: how to use ListView class for two different templates

description: Use ListView class for two different templates


code:
def view2(request, form_class=MyForm, template_name='myapp/page2.html'):
    # app code here
    this_view = 'view2'
    render_to_response(template_name, locals(), RequestContext(request))

rawDescription: Getting current url

description: Getting current url


code: iterable = (x,y)

rawDescription: "MOST-OF" in python

description: "MOST-OF" in python


code: a

rawDescription: How do I extract a sub-array from a numpy 2d array?

description: Extract a sub-array from a numpy 2d array


code:
w = (np.arange(N) - N /2.) / T

# integration
Fys = fft(ys)
with np.errstate(divide="ignore", invalid="ignore"):
    modFys = ifftshift(1./ (2 * np.pi * 1j * w) * fftshift(Fys))

# modFys[0] will hold the result of dividing the DC component of y by 0, so it
# will be nan or inf.  Setting modFys[0] to 0 amounts to choosing a specific
# constant of integration.
modFys[0] = 0

fourier = ifft(modFys).real

rawDescription: numerical integration in Fourier space with numpy.fft

description: Numerical integration in Fourier space with numpy.fft


rawDescription: Appending predicted values and residuals to pandas dataframe


code: avalid = not getattr(f, 'a_invalid', False)

rawDescription: Python way for object method chaining for class instance variables


code:
gettext = lambda s: s
some_text = gettext('Some text')

lazy_translated = ugettext_lazy(text)
untranslated = some_text

rawDescription: Access untranslated content of Django's ugettext_lazy


code:
def __setitem__(self, key, item):
    self.data[key] = item
    if key == "sensor":
        print("Sensor activated!")

rawDescription: what is the dict class used for

description: What is the dict class used for


rawDescription: Extracting a table from web with different hierarchical tags


code: return binSearch(arr, i, lower, idx)

rawDescription: Why is my recursive binary search function not returning anything?


code:
from itertools import combinations

s = {'a', 'b', 'c'}

res = [(set(comb), s.difference(comb)) for comb in combinations(s, 2)]

rawDescription: Calculating combinations of subsets of given size leading up to the set


code:
def decrypt(ciphertext, password):
    salt = ciphertext[0:SALT_SIZE]

    ciphertext_sans_salt = ciphertext[SALT_SIZE:]

    key = generate_key(password, salt, NUMBER_OF_ITERATIONS)

    cipher = AES.new(key, AES.MODE_ECB)

    padded_plaintext = cipher.decrypt(ciphertext_sans_salt)

    plaintext = unpad_text(padded_plaintext)

    return plaintext

rawDescription: Encrypt / decrypt data in python with salt


code:
OBJECT_LIBRARY = {'A': lambda : A(a, b), 'B': lambda : B(b, c)} # assuming a, b, c are defined

OBJECT_LIBRARY['A']()

rawDescription: Python: Dictionary: Based on the key provided return an initialized class object variable


code: fg1 = bg1.apply(frame)

rawDescription: OpenCV Python cv2.BackgroundSubtractor parameters


code:
data = numpy.fromfile(my_file, dtype=numpy.uint8).reshape(-1, N)
streams = [data[:,stream_index == i].ravel() for i in range(k)]

rawDescription: Fast way to read interleaved data?

description: Fast way to read interleaved data


code: print(key, len([item for item in value if item]))

rawDescription: Counting how many values were attributed to a key an a python (3.2) dictionary


code:
arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
    # use a list comprehension to build your array on the fly
    new_array = np.array((array.float(i) for i in line.split(' ')))
    arrays.append(new_array)

rawDescription: Reading file string into an array (In a pythonic way)


code: return dict(points=[point1, point2, ...])

rawDescription: Can I refer to a dictionary's key name with a variable, from within a view

description: Refer to a dictionary's key name with a variable, from within a view


code:
keys = rdd.keys()
identity = lambda x: x

offset = (keys
    .mapPartitions(lambda iter: heapq.nlargest(n, iter))
    .sortBy(identity)
    .zipWithIndex()
    .filter(lambda xi: xi[1] < n)
    .keys()
    .max())

rdd.filter(lambda kv: kv[0] <= offset)

rawDescription: Return RDD of largest N values from another RDD in SPARK


code:
coords = [np.column_stack(where(lbl == k)) for k in labels]
coords

rawDescription: How to group elements of a numpy array with the same value in separate numpy arrays

description: Group elements of a numpy array with the same value in separate numpy arrays


code: re.sub(r",(?=\S)", ", ", "Hello,World! Hello, World!")

rawDescription: "ReplaceWith" & - but only part of it

description: "ReplaceWith" & - but only part of it


code:
def format_math(string):
    return (string.replace("**", "^")).replace("*", "")

rawDescription: integration and differentiation with sympy/pyqt python

description: Integration and differentiation with sympy/pyqt python


code:
class FillList(list):
    def __setitem__(self, index, value):
        try:
            super().__setitem__(index, value)
        except IndexError:
            for _ in range(index-len(self)+1):
                self.append(None)
            super().__setitem__(index, value)

rawDescription: Python list set value at index if index does not exist


rawDescription: add columns where condition is met, but preserve previous value in pandas python

description: Add columns where condition is met, but preserve previous value in pandas python


code:
def file_len(fname):
    i = 0
    with open(fname) as f:
        for i, l in enumerate(f, 1):
            pass
    return i

rawDescription: Container list in Python: standard list vs numpy array


rawDescription: Understanding performance difference

description: Understanding performance difference


code:
a = Small(100)
type(a)
b = Small(1234)
type(b)
c = Big(2)
type(c)

rawDescription: Changing the class type of a class after inserted data


code:
import pexpect

image = "fedora-20.img"
user = "root"
password = "changeme"

# Define the qemu cmd to run
# The important bit is to redirect the serial to stdio
cmd = "qemu-kvm"
cmd += " -m 1024 -serial stdio -net user -net nic"
cmd += " -snapshot -hda %s" % image
cmd += " -watchdog-action poweroff"

# Spawn the qemu process and log to stdout
child = pexpect.spawn(cmd)
child.logfile = sys.stdout

# Now wait for the login
child.expect('(?i)login:')

# And login with the credentials from above
child.sendline(user)
child.expect('(?i)password:')
child.sendline(password)
child.expect('# ')

# Now shutdown the machine and end the process
if child.isalive():
    child.sendline('init 0')
    child.close()

if child.isalive():
    print('Child did not exit gracefully.')
else:
    print('Child exited gracefully.')

rawDescription: automation of processes by python

description: Automation of processes by python


code:
getattr(obj, 'mymod')
# or
obj.__dict__['mymod']
# or
vars(obj)['mymod']

rawDescription: Import object from module of same name using __import__


code: data = data.replace(',', '')

rawDescription: How to remove certain characters from a variable? (Python)

description: Remove certain characters from a variable? (Python)


code:
vals = np.random.randint(0,20, (4,3))
df = pd.DataFrame(np.hstack([vals, vals]), columns=['Time', 'H1', 'N2', 'Time Relative', 'N2', 'Time'] )
df.T.drop_duplicates().T

rawDescription: python pandas remove duplicate columns

description: Python pandas remove duplicate columns


code:
a = 'some words'
b = a.encode('utf-8')
print(b)
c = b.decode('utf-8')
print(c)
isinstance(b, bytes)
isinstance(b, str)
isinstance(c, str)
isinstance(c, bytes)

rawDescription: Py2/3 compatibility for string input to dll used with ctypes


code:
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class Thing(Base):
    __tablename__ = 'thing'

    id = Column(Integer, primary_key=True)
    data = Column(NullComparisons(50))
print(Thing.data != 'hi')

rawDescription: NULL safe inequality comparisons in SQL Alchemy?


code:
import types
types.MethodType(f1, None, C)

rawDescription: What is the difference between a function, an unbound method and a bound method?


code: p = src.popen( ['sh', './timer.sh', 'filename.txt'], stdout=subprocess.PIPE )

rawDescription: Passing a "shell script" as a string to Python subprocess.Popen


code:
import subprocess

driveStr = subprocess.check_output("fsutil fsinfo drives")
driveStr = driveStr.strip().lstrip('Drives: ')
drives = driveStr.split()

rawDescription: Search all drives for a file

description: Search all drives for a file


code:
with open('file.txt') as f:
    rows = [line.strip().split(',') for line in f]
rows
nums = [list(map(int, row)) for row in rows]
nums

rawDescription: Convert list of lists of string to list of lists of int


rawDescription: For Python 3.3, how can I make a list of functions using one lambda statement?


rawDescription: Python decorating functions before call

description: Python decorating functions before call


code: [index for index, item in enumerate(thelist) if item[0] == "332"]

rawDescription: What's the fastest way to locate a list element within a list in python?


code:
# python sort
x = [results]
x.sort(key=len)

rawDescription: Simple Django queryset __icontains search that will find most specific elements first


code:
import sys,new,os
p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('flufl',))
ie = os.path.exists(os.path.join(p,'__init__.py'))
m = not ie and sys.modules.setdefault('flufl',new.module('flufl'))
mp = (m or []) and m.__dict__.setdefault('__path__',[])
(p not in mp) and mp.append(p)

rawDescription: Python package without __init__

description: Python package without __init__


code:
# Dummy data
from random import randint as r

a,b = 97,123

d = [(dict([(chr(r(a,b)),j) for j in range(1000)]),
       ''.join([chr(r(a,b)) for i in range(5)]))
                            for j in range(100)]

# Pickle it
import cPickle as pickle

f = open('store.dat','w')
pickle.dump(d,f)
f.close()

rawDescription: Pickling a list consisting of 'n' 2-tuple values


rawDescription: Linear Regression with 3 input vectors and 4 output vectors?


rawDescription: how to retrieve field value (values are itself string)in given line using regular expression in python

description: Retrieve field value (values are itself string)in given line using regular expression in python


code:
@sockets.route('/stream')
def stream_socket(ws):
    with picamera.PiCamera() as camera:
      camera.start_preview()
      # Camera warm-up time
      time.sleep(2)

      while not ws.closed:
        stream = io.BytesIO()
        camera.capture(stream, 'yuv')
        ws.send(stream.getvalue())
        #perhaps add a time.sleep() here to enforce a constant framerate?

rawDescription: YUV live video streaming using Flask

description: YUV live video streaming using Flask


rawDescription: Pythonic way to test if a row is in an array


code: [x.uint for x in b.cut(p)]

rawDescription: Writing a numpy array to binary file with variable integer precision


code:
def calculate(self, red=None, blue=None, yellow=None):
    if red is None:
        red = self.red
    if blue is None:
        blue = self.blue
    if yellow is None:
        yellow = self.yellow
    return red + blue + yellow

rawDescription: Python: How to override data attributes in method calls?


code: A[mask] = B[mask]

rawDescription: Replacing elements in Numpy 2D array with corresponding elements of another Numpy 2D array depending on a condition


code:
import csv

with open(outputfile, 'w', newlines='') as ofh:
    writer = csv.writer(ofh)

    for row in data:
        row = list(row[:2]) + row[2]
        writer.writerow(row)

rawDescription: Writing a list with nested tuples to a csv file


rawDescription: Python regex - strip out beginning and end and leave middle untouched


code:
state_center_dict = {}
for state in us_states:
    state_center_dict[state] = find_state_center(us_states[state])

position_closest_state = {}  # save known result
tweets_by_state = {}
for tweet in tweets:
    position = tweet_location(tweet)
    min, result_state = 100000, 'CA'

    if position in position_closest_state:
        result_state = position_closest_state[position]
    else:
        for state in us_states:
            distance = geo_distance(position, state_center_dict[state])
            if distance < min:
                min = distance
                result_state = state
                position_closest_state[position] = result_state

rawDescription: Is there a faster way to do this? (python twitter location)


code: cur.execute("SELECT COUNT(*) FROM test WHERE unit_id IN %s", [['0A1']])

rawDescription: How can I prevent extra quotations being inserted into MySQLdb statement from Python?

description: Prevent extra quotations being inserted into MySQLdb statement from Python


rawDescription: Work with tuple of dictionaries

description: Work with tuple of dictionaries


code:
for key, value in di.items():
    for i, e in enumerate(value):
        if e is None: di[key][i]='None'

rawDescription: Replacing items in a dictionary of lists in Python


code: serialize_object(MyStuff(10, "hello world"), XMLStream())

rawDescription: What is the best-maintained generic functions implementation for Python?


rawDescription: Removing the first part of a concatenated string with Python


code:
fcond = threading.Condition()
fargs = set()

def f(x):
    with fcond:
        while x in fargs:
            fcond.wait()
        fargs.add(x)  # this thread has exclusive rights to use `x`

    # do useful stuff with x
    # any other thread trying to call f(x) will
    # block in the .wait above()

    with fcond:
        fargs.remove(x)      # we're done with x
        fcond.notify_all()   # let blocked threads (if any) proceed

rawDescription: Garbage-collect a lock once no threads are asking for it


code: command --no-feature

rawDescription: parsing boolean values with argparse

description: Parsing boolean values with argparse


code: df

rawDescription: Groupby Clause in Pandas

description: Groupby Clause in Pandas


rawDescription: Various queries - MongoDB

description: Various queries - MongoDB


code: a= [6 for v in a]

rawDescription: Pythonic Referenced For Loop

description: Pythonic Referenced For Loop


code:
class TheThread(QtCore.QThread):
    def __init__(self, theQueue, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.theQueue = theQueue

    def run(self):
        task = self.theQueue.get()
        self.sleep(1)
        print(task)
        self.theQueue.task_done()

threads=[]
for i in range(1, 3):
    thread = TheThread(theQueue)
    threads.append(thread)
    thread.start()

for i in range(len(threads)):
    theQueue.put(i)

for t in threads:
    t.wait()

rawDescription: Using While condition inside of Thread's run() method


rawDescription: How do I union a list of lists based on a common string in the lists, Python

description: Union a list of lists based on a common string in the lists, Python


code: br.addheaders = [('Cookie','cookiename=cookie value')]

rawDescription: Adding new cookies with Mechanize Python


code:
def unique_preserve_order(seq, key=None):
    if key is None:
        key = lambda elem: elem
    seen = set()
    seen_add = seen.add
    augmented = ((key(x), x) for x in seq)
    return [x for k, x in augmented if not (k in seen or seen_add(k))]

from pprint import pprint
import operator
yourlist = [(67, u'top-coldestcitiesinamerica'), (66, u'ecofriendlyideastocelebrateindependenceday-phpapp'), (65, u'a-b-c-ca-d-ab-ea-d-c-c'), (64, u'a-b-c-ca-d-ab-ea-d-c-c'), (63, u'alexandre-meybeck-faowhatisclimate-smartagriculture-backgroundopportunitiesandchallenges'), (62, u'ghgemissions'), (61, u'top-coldestcitiesinamerica'), (58, u'infographicthe-stateofdigitaltransformationaltimetergroup'), (57, u'culture'), (55, u'cas-k-ihaveanidea'), (54, u'trendsfor'), (53, u'batteryimpedance'), (52, u'evs-howey-full'), (51, u'bericht'), (49, u'classiccarinsurance'), (47, u'uploaded_file'), (46, u'x_file'), (45, u's-s-main'), (44, u'vehicle-propulsion'), (43, u'x_file')]
pprint(unique_preserve_order(yourlist, operator.itemgetter(1)))

rawDescription: delete duplicates from list of tuples

description: Delete duplicates from list of tuples


code:
import lxml.etree as ET
import lxml.builder as builder
E = builder.E
F = builder.ElementMaker(namespace='http://foo', nsmap={'others':'http://foo'})

x = 2*5
xmlTemplate = ET.tostring(F.root(
    E.personal(
        F.sequence(
            E.feature(name='Michael',
                   age=str(x),
                   dob='15/10/1900')
            ), reference="500.txt")),
                          pretty_print=True)
print(xmlTemplate)

rawDescription: How to build an xml template with variable attributes from scratch

description: Build an xml template with variable attributes from scratch


code:
auc_table <- h2o.getGrid(grid_id = "eeg_demo_gbm_grid", sort_by = "auc", decreasing = TRUE)
print(auc_table)

rawDescription: H2O R api: retrieving optimal model from grid search


code:
def some_view(request):
     form = PatientForm(user=request.user)

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


rawDescription: implementation of graphs in python that have a label

description: Implementation of graphs in python that have a label


code:
import itertools as IT

def neighbor_product(letters, numbers, repeat = 2):
    N = len(numbers)
    numbers = collections.deque(numbers)
    for lets in IT.product(letters, repeat = repeat):
        for i in range(N):
            yield ''.join(IT.chain.from_iterable(zip(lets, IT.cycle(numbers))))
            numbers.rotate(-1)

letters = 'ABCD'
numbers = '123'
for item in neighbor_product(letters, numbers, repeat = 3):
    print(item)

rawDescription: Python make more scalable of a given list products


code:
params = ['convert', '-density 300 -resize 220x205', 'pdf_file', 'thumb.jpg']
subprocess.check_call(params)

rawDescription: Python PDF thumbnail preview generation

description: Python PDF thumbnail preview generation


code:
def random_partition(n,s):
    S = s
    partition = []
    _min = min_max(n,S)
    _max = n-S+1

    total = number_of_partitions(n,S)
    which = random.randrange(1,total+1) # random number

    while n:
        for k in range(_min,_max+1):
            count = P(n,S,k)
            if count >= which:
                count = P(n,S,k-1)
                break

        partition.append(k)
        n -= k
        if n == 0: break
        S -= 1
        which -= count
        _min = min_max(n,S)
        _max = k

    return partition

rawDescription: An algorithm for randomly generating integer partitions of a particular length, in Python?


code:
import numpy as np
fft = np.fft

def autocorrelation(x):
    """
    Compute autocorrelation using FFT
    The idea comes from
    http://dsp.stackexchange.com/a/1923/4363 (Hilmar)
    """
    x = np.asarray(x)
    N = len(x)
    x = x-x.mean()
    s = fft.fft(x, N*2-1)
    result = np.real(fft.ifft(s * np.conjugate(s), N*2-1))
    result = result[:N]
    result /= result[0]
    return result

def AutoCorrelation(x):
    x = np.asarray(x)
    y = x-x.mean()
    result = np.correlate(y, y, mode='full')
    result = result[len(result)//2:]
    result /= result[0]
    return result

def autocorrelate(x):
    fftx = fft.fft(x)
    fftx_mean = np.mean(fftx)
    fftx_std = np.std(fftx)

    ffty = np.conjugate(fftx)
    ffty_mean = np.mean(ffty)
    ffty_std = np.std(ffty)

    result = fft.ifft((fftx - fftx_mean) * (ffty - ffty_mean))
    result = fft.fftshift(result)
    return [i / (fftx_std * ffty_std) for i in result.real]

np.set_printoptions(precision=3, suppress=True)

"""
These tests come from
http://www.maplesoft.com/support/help/Maple/view.aspx?path=Statistics/AutoCorrelation
http://www.maplesoft.com/support/help/Maple/view.aspx?path=updates%2fMaple15%2fcomputation
"""
tests = [
    ([1,2,1,2,1,2,1,2], [1,-0.875,0.75,-0.625,0.5,-0.375,0.25,-0.125]),
    ([1,-1,1,-1], [1, -0.75, 0.5, -0.25]),
    ]

for x, answer in tests:
    x = np.array(x)
    answer = np.array(answer)
    # print(autocorrelate(x))
    print(autocorrelation(x))
    print(AutoCorrelation(x))
    assert np.allclose(AutoCorrelation(x), answer)
    print

"""
Test that autocorrelation() agrees with AutoCorrelation()
"""
for i in range(1000):
    x = np.random.random(np.random.randint(2,100))*100
    assert np.allclose(autocorrelation(x), AutoCorrelation(x))

rawDescription: Statistical Scaling of autocorrelation using numpy.fft


rawDescription: Can we change background color of checkbox text in WxPython?


code:
for host in hostlist:
    pool.apply_async(worker, args = (host,), callback = on_return)

rawDescription: Python multiprocessing pool - iterating over objects methods?


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

df = pd.DataFrame(np.random.poisson(5, size=(100, 5)))

fig, ax = plt.subplots()
#Note showfliers=False is more readable, but requires a recent version iirc
box = df.boxplot(ax=ax, sym='')
ax.margins(y=0)
plt.show()

rawDescription: Matplotlib - How do I set ylim() for a series of plots?


code:
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi()

    def setupUi(self):
        self.setObjectName("MainWindow")
        self.resize(277, 244)
        self.statusbar = QtGui.QStatusBar()
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

    def closeEvent(self,event):
        result = QtGui.QMessageBox.question(self,
                      "Confirm Exit...",
                      "Are you sure you want to exit ?",
                      QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)
        event.ignore()

        if result == QtGui.QMessageBox.Yes:
            event.accept()

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

rawDescription: PyQt's QMainWindow closeEvent is never called


code:
# Comma as separator
damn = '{:,} Dmn'.format(self.damn)
# Locale aware separator
damn = '{:n} Dmn'.format(self.damn)

rawDescription: python locale currency to 0 decimals

description: Python locale currency to 0 decimals


code: sql = "select * from Table where id in (%s)" % (', '.join(str(id) for id in longIdList))

rawDescription: how to select a long list of id's in sql using python

description: Select a long list of id's in sql using python


code: fig = plt.figure(figsize=(3*wcell+wpad, nrows*hcell+hpad))

rawDescription: Creating tables in matplotlib

description: Creating tables in matplotlib


code:
def index(l, s):
    len_s = len(s)
    for pos in range(len(l) - len_s + 1):
        if l[pos:pos + len_s] == s:
            return pos
    return -1

rawDescription: Check if list of strings contains string sequence


code:
def helloSolarSystem(original_function):
    def new_function(*args, **kwargs):
        original_function(*args, **kwargs)   <-- (1)
        print("Hello, solar system!")
    return new_function

rawDescription: Explain how Python decorator works

description: Explain how Python decorator works


code: w.closeEvent = closeEvent

rawDescription: PyQt - Event Binding (calling a function when the QCloseEvent occurs) - Procedural Style


code:
class Node:
    def __init__(self, data=None, prev=None, next=None):
        self.data = data
        self.prev = prev
        self.next = next

    def __repr__(self):
        return '<{}, {}>'.format(self.data, self.next)

rawDescription: How could I make this singly linked list into a doubly linked list?


rawDescription: Take logic operation it self not only the boolean result as a input of function in PYTHON


code:
from mod2 import test #Import mod2, bring test function into current module namespace
test("mod1.py")  #run the test function (defined in mod2)

rawDescription: Some confusion regarding imports in Python


code:
class Namespace(object): pass
n = Namespace()
n.__dict__ = globals().copy()

rawDescription: What is the pythonic way to have conditional shadowing?


code: a = np.random.random([5,5])

rawDescription: Count of specific case per row in matrix


code:
counter = collections.Counter(...)
counter = dict(counter)

rawDescription: Can you make Counter not write-out "Counter"

description: Make Counter not write-out "Counter"


code: re.split(r'([\s]+)', 'hello world\n')

rawDescription: What are the empty strings of my readline() after split


code:
for type_tag in soup.find_all('TYPE', text=re.compile('^\s*(?:EX|XML)', re.I)):
    type_tag.extract()

rawDescription: Python: Regex v. BeautifulSoup to remove from text <TYPE>


rawDescription: Appending '0x' before the hex numbers in a string


code: crypto = Chiper("criptografia", "zenitpolar", "polarzenit")

rawDescription: OO Aproach python

description: OO Aproach python


code:
class Rectangle:
    def __init__(self, length, width):
        self.length = length # no need to mask these by starting the names with _
        self.width = width

    @property # this lets us call this method without parentheses - it'll look like an ordinary attribute, but it's really calling a method
    def area(self):
        return self.length * self.width

    @property
    def perimeter(self):
        return 2*(self.length + self.width) # the original has 2 multiplications and 1 addition, while this has 1 multiplication and 1 addition - negligible, but it's good to see this sort of thing once in a while in case you have to optimize something at some point

rawDescription: Rectangle OOP/classes

description: Rectangle OOP/classes


code: foo = foobar2.clip_lower(0).apply(lambda x: x['var1']+x['var2']-x['var3']-x['var4'], axis=1)

rawDescription: Pandas: Adding conditionally

description: Pandas: Adding conditionally


code:
with open("in3.txt") as f:
    lines = f.readlines()
    with open("out.txt", "w") as f1:
        for x, line in enumerate(lines): # Changed to enumerate as per recommendation
            y = x*10
            f1.write("\n00:01:"+str(y)+"\n")
            f1.write(line)

rawDescription: Copying line by line from one text file to another using Python


code:
from itertools import takewhile, count

# ...
def myfunc():
    return takewhile(lambda x: x is not None, (lookup(i) for i in count(1)))

rawDescription: for(i=0;True;i++) in python?

description: For(i=0;True;i++) in python


rawDescription: Data generation incomplete: Python random


code:
db = SQLAlchemy(metadata=MetaData(naming_convention={
    'pk': 'pk_%(table_name)s',
    'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',
    'ix': 'ix_%(table_name)s_%(column_0_name)s',
    'uq': 'uq_%(table_name)s_%(column_0_name)s',
    'ck': 'ck_%(table_name)s_%(constraint_name)s',
}))

rawDescription: Changing constraint naming conventions in Flask-SQLAlchemy


rawDescription: Python super usage example

description: Python super usage example


code:
read_0a = random.randint(500,1000)
read_1a = a[0] + read_0a - a[1]

rawDescription: How to index and automate processing of list using input csv file

description: Index and automate processing of list using input csv file


code:
x = ('GCI/PyFiles/prova3.py', 'GCI/', \
     'GCI/PyFiles/', 'GCI/Screenshots/', \
     'GCI/prova2.py', 'prova.py')

structure = {}
for fn in x:
    path = fn.split('/')

    tmpd = structure
    for p in path[:-1]:
        try:
            tmpd = tmpd[p]
        except KeyError:
            tmpd = tmpd[p] = {}

    tmpd[path[-1]] = None

rawDescription: Directory tree in a QTreeWidget

description: Directory tree in a QTreeWidget


code:
# ...
class Splatter(object):
    def __init__(self, r):
        self.r = int(r)
        self.surface = pygame.Surface((r*2, r*2))
        self.surface.fill(pygame.Color("red"))
        pygame.draw.circle(self.surface, pygame.Color("black"),
                           (int(self.surface.get_width()/2),
                            int(self.surface.get_height()/2)),
                           self.r)

    def display(self, x, y):
        SCREEN.blit(self.surface, (int(x), int(y)))

SCREEN.fill(SCREEN_COLOR)
s = Splatter(20)
s.display(SCREEN.get_width()/2, SCREEN.get_height()/2)
pygame.display.flip()
# ...

rawDescription: why I'm getting a square instead of a circle in pygame?

description: Why I'm getting a square instead of a circle in pygame


code: abcd

rawDescription: super simple cipher function in python. comparing a list to keys in a dictionary

description: Super simple cipher function in python. comparing a list to keys in a dictionary


code:
FULL_URL_WITH_QUERY_STRINg: request.build_absolute_uri()
FULL_URL: request.build_absolute_uri('?')
ABSOLUTE_ROOT: request.build_absolute_uri('/')[:-1].strip("/")
ABSOLUTE_ROOT_URL: request.build_absolute_uri('/').strip("/")

rawDescription: How to get full url from django request

description: Get full url from django request


code:
for item in parse(source):
    try:
        location = item['device']['vfb']['location']['value']
    except KeyError:
        pass

rawDescription: regular expression for a string format

description: Regular expression for a string format


code:
username, passwd = get_login_cli(username, **kwargs)

print("username = %s" % (username))

rawDescription: Cache user remote credentials for command line tool


code:
from django.db import models
from django.conf.settings import AUTH_USER_MODEL

class Profile(models.Model):
    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

    user = models.OneToOneField(AUTH_USER_MODEL, verbose_name='User',
                                related_name='profile')
    full_name = models.CharField('Full name', max_length=64, blank=False)
    phone = models.CharField('Phone', max_length=64, blank=True)

rawDescription: Django registration redux registration only with email (no password)


code: from projectname.utils import get_shop_id

rawDescription: Django Global function and variable

description: Django Global function and variable


code:
method1(s)
(method1(s) == method2(s)).all()

rawDescription: Creating an indicator for strings of numbers, ignoring a particular one in python pandas


rawDescription: python - representing boolean expressions with lists

description: Python - representing boolean expressions with lists


code:
df['month'] = df.index.month
df['monthly_mean'] = df.groupby('month').m_ta.transform('mean')
df['monthly_std'] = df.groupby('month').m_ta.transform('std')

rawDescription: calculate standard deviation and plot the curving fit using Python 2.7

description: Calculate standard deviation and plot the curving fit using Python 2.7


code: info = LAPACKE_dgtsv(LAPACK_ROW_MAJOR, ...)

rawDescription: Wrapping a LAPACKE function using Cython


code:
def divs_of_squared_fact(n):
    return get_num_divisors((p, 2*e) for p, e in get_factorization_factorial(n))

rawDescription: Find the number of divisors of (N!)^2

description: Find the number of divisors of (N!)^2


rawDescription: Remove all occurrences of several chars from a string


code:
sdiff = np.sign(diff)
zc = np.where(sdiff[:-1] != sdiff[1:])

rawDescription: Can I get first derivative for kernel density estimation in python?

description: Get first derivative for kernel density estimation in python


code:
[fn() for fn in self.pre]
[fn(val) for fn in self.mid]

rawDescription: Python one-liner to call list of functions


code:
for page in parse_ranges('1, 3, 4-7, 9-'):
    if page > 20:
        break

    print(page)

rawDescription: How to represent a dynamic list of ranges?

description: Represent a dynamic list of ranges


code:
d={'A': [1,2,3], 'B': "Hello", 'C': ["this is good"]}
d.keys()
list(d.keys())
list(d.values())
list(d.items())

rawDescription: Python Dictionary Methods behaving diff for 2.7.6 and 3.3 version


code:
for i in [0, 1, 2]:
    j = i + 3
    results.append(lambda i=i, j=j: nodes[i].value() == nodes[j].value())

rawDescription: Deferred evaluation with lambda in Python


code:
import requests

url = 'http://www.ichangtou.com/#company:data_000008.html'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

response = requests.get(url, headers=headers)
print(response.content)

rawDescription: How to use Python requests to fake a browser visit?

description: Use Python requests to fake a browser visit


code: next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('targ_'), globals().items()) if value in v)

rawDescription: Find if value exists in multiple lists

description: Find if value exists in multiple lists


rawDescription: How to Read Reg_Binary type values in string format from Registry in python


code: lb.inverse_transform(label[:, 0])

rawDescription: sklearn LabelBinarizer returns vector when there are 2 classes

description: Sklearn LabelBinarizer returns vector when there are 2 classes


code:
import cp
foo = cp.MyClass(5, 10)
import copy
bar = copy.copy(foo)
bar == foo

rawDescription: how to make copies of Cython objects?

description: Make copies of Cython objects


rawDescription: Python - Iterating lists and dictionaries


code: obj[(slice(1, 3), slice(None, None))]

rawDescription: Implementing fancy indexing in a class

description: Implementing fancy indexing in a class


code:
import pygame
from pygame.locals import *
pygame.init()
Screen = pygame.display.set_mode([1000, 600])
MousePos = pygame.mouse.get_pos()
Contin = True
while Contin:
    MousePos = pygame.mouse.get_pos()
    print(MousePos)
    DoSomething(MousePos)

rawDescription: Python/Pygame mouse position not updating and program losing focus


code:
import urllib
import bs4
url=urllib.urlopen('http://www.tcmb.gov.tr/kurlar/201501/02012015.xml').read().decode('Windows-1252')
soup=bs4.BeautifulSoup(url)
data=soup.get_text(' ')
print(data)

rawDescription: Web Mining with Python

description: Web Mining with Python


code: [list(v[1].values) for v in df.groupby("Loc").sum().iterrows()]

rawDescription: Python Numerical Error Arising in Series of Nested Lists


rawDescription: Averaging over different levels in pandas


code:
walk(d,func=removeEmptyFolders)
from pprint import pprint
pprint(d)

rawDescription: Python: Search for and delete nested lists of dictionaries


code:
found = regex.finditer(strings)
for i in found:
  print(i.group(1) or i.group(3))

rawDescription: Conditioning on Regex

description: Conditioning on Regex


code:
def defang(string):
    return string.decode('utf-8').encode('ascii', 'xmlcharrefreplace')

rawDescription: Some Basic Python Questions

description: Some Basic Python Questions


code:
properties = {}
for field_name, field_def in my_fields.items():
    properties[field_name] = getattr(forms, field_def['name'])(**field_def['attrs'])

rawDescription: Python : convert unicode string to raw object/text


rawDescription: Updating elements in nested list using 'for' won't work in python list


code:
#views.py

def index(request):
    movies = Movie.objects.all() # movies instead of obj
    contacts = get_paginator(request, movies, 10)
    return render(request, "movie/index.html",
                  {'title': title ,'movies':movies,'contacts':contacts})

rawDescription: Django get the foreign key object value

description: Django get the foreign key object value


rawDescription: Python inspect module: keyword only args


code:
@app.route('/message', methods=['GET', 'POST'])
def message():
    cur = db.execute('select id,msg from msg_msg')
    message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
    if request.method == 'POST':

        g.db = connect_db()
        cur = g.db.execute('insert into msg_msg (msg) values (?)',request.form['input_msg'])
        message = [dict(msg_id=row[0], msg_msg=row[1]) for row in cur.fetchall()]
        g.db.close()

    return render_template('message.html' , message = message)

rawDescription: How to use SUBMIT form to save message in Database

description: Use SUBMIT form to save message in Database


code:
def index(request):
    authors = Author.objects.all()
    context={'authors':authors}
    return render(request,'index.html', context)

rawDescription: Display model and its relations

description: Display model and its relations


rawDescription: Pandas: Calculate average for all entries that only differ in two columns


code:
M = []
resultlist = []
resultlist.append(M)
M is resultlist[0]
M.append(1)
resultlist[0]
M

rawDescription: Most Pythonic way to iteratively build up a list?


rawDescription: XPath: Assessing an Error in this Line of Code?


code:
p = player(0,0)
p.move('up') # and so on..

rawDescription: Storing code in a list or dictionary?

description: Storing code in a list or dictionary


code:
def load_signed_request(self, signed_request):
            """Load the user state from a signed_request value"""
            sig, payload = signed_request.split(u'.', 1)
            sig = self.base64_url_decode(sig)
            data = json.loads(self.base64_url_decode(payload))

            expected_sig = hmac.new(self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()

            # allow the signed_request to function for upto 1 day
            if sig == expected_sig and data[u'issued_at'] > (time.time() - 86400):
                    return data.get(u'user_id'), data.get(u'oauth_token')
            else:
                    return None,None

rawDescription: How to redirect the url after logging into Facebook?

description: Redirect the url after logging into Facebook


code:
def film_chart_view(request, is_random=None):
    if is_random:
        ...

rawDescription: Django optional view parameter with HttpResponseRedirect


code:
def select_active(cls):
    return cls.select(lambda obj: not obj.deleted)

select_active(Message).filter(lambda msg: msg.author == current_user)

rawDescription: Writing select functions for customized Pony


code:
class LatestUsers(models.Model):
    latest_users = models.ManyToManyField(User)

rawDescription: Fastest way to retrieve newly registered users' instances in Django web app


code: myDict['key'] = ...

rawDescription: Converting a python dictionary to a JSON - like object


code:
selection = [L for L in lists
             if x1 in L and x2 in L[L.index(x1)+1:]]

rawDescription: Fast way to find lists contains two particular items?


rawDescription: Selecting all objects in the list of objects (in Python)


code: print >> file, line

rawDescription: Read every second line and print to new file


code:
def human_infoz():

    name = raw_input("Enter human name> ")
    address = raw_input("Human Address> ")
    phone = raw_input("Human Phone Number> ")
    email = raw_input("Human Email> ")
    listinfo = [name, address, phone, email]
    return listinfo

go = human_infoz()
namez,add,phone,email = go

rawDescription: Print function attribute

description: Print function attribute


rawDescription: How do I automatically pass arguments to a function on certain objects

description: Automatically pass arguments to a function on certain objects


code:
if filter(lambda x: letter in x, a_lst):
    print('yes', letter)
else:
    print('no', letter)

rawDescription: Checking charcters in a string and outputing a Single message


code:
import matplotlib.pyplot as plt
import matplotlib.delaunay
import matplotlib.tri as tri
import numpy as np
import math

# Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.

# First create the x and y coordinates of the points.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)

angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[...,np.newaxis], n_radii, axis=1)
angles[:,1::2] += math.pi/n_angles

x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()

tt = matplotlib.delaunay.triangulate.Triangulation(x,y)
triang = tri.Triangulation(x, y)

# Plot the triangulation.
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(triang, 'bo-')

plt.plot(tt.circumcenters[:,0],tt.circumcenters[:,1],'r.')
plt.show()

rawDescription: Getting the circumcentres from a delaunay triangulation generated using matplotlib


code:
class NewDataFrame(pandas.DataFrame):
    def sort_clean(self, sort_cols):
        self.sort(sort_cols, inplace=True)
        self.reset_index(inplace=True, drop=True)

rawDescription: attach functions to pandas

description: Attach functions to pandas


code:
H = nx.Graph()
H.add_node('8.8.8.8', longitude=37, latitude=50)
H.node['8.8.8.8']

rawDescription: how do I make a cutomised object as a node for networkx and how do I look it up?

description: Make a cutomised object as a node for networkx and how do I look it up


code:
import nltk

text1 = 'hello he heloo hello hi '
text1 = text1.split(' ')
fdist1 = nltk.FreqDist(text1)
print (fdist1.most_common(50))

rawDescription: To find frequency of every word in text file in python


code:
import numpy as np
a = np.arange(100)

offset_length = [(3,10),(50,3),(60,20),(95,1)]
np.concatenate([a[offset:offset+length] for offset,length in offset_length])

rawDescription: Numpy Array Slicing

description: Numpy Array Slicing


code:
import re
re.sub(r"([aeiou])",r"X\g<1>", "hello")

rawDescription: insert letter before vowel in word

description: Insert letter before vowel in word


code: item.append(d[k].get('v1', ''))

rawDescription: How to convert some values in a dict into a list in a clean style in Python?

description: Convert some values in a dict into a list in a clean style in Python


code:
from one import A, B, C
from two import D, E, F

rawDescription: Treating a Directory as a Single Module?

description: Treating a Directory as a Single Module


code:
lis=[[1,2,1],
     [3,4,1],
     [1,2,2],
     [3,4,2]]
seen=set()
[li for li in lis if tuple(li[:2]) not in seen and not seen.add(tuple(li[:2]))]

rawDescription: Cycling through a list of list, checking and removing?


code:
import datetime
import calendar
d = datetime.datetime(yyyy,mm,dd,hours,minutes,seconds)
calendar.timegm(d.timetuple())

rawDescription: Find the epoch of the most recent midnight


code:
class DefaultOption(dict):

    def __init__(self, config, section, **kv):
        self._config = config
        self._section = section
        dict.__init__(self, **kv)

    def items(self):
        _items = []
        for option in self:
            if not self._config.has_option(self._section, option):
                _items.append((option, self[option]))
            else:
                value_in_config = self._config.get(self._section, option)
                _items.append((option, value_in_config))
        return _items

rawDescription: Python configparser getting and setting without exceptions


code:
for each_div in soup.find_all('div',{'class':'username'}):
    each_div = each_div.replace('''
''',"")
    each_div = each_div.replace("
","")
    f.write(str(each_div) + "\n")

rawDescription: Python How to remove characters from a string inside a list


code: numpy.any(np_array[:, :100] > 1, axis=1)

rawDescription: Numpy argwhere inequality conditions

description: Numpy argwhere inequality conditions


code:
class cache(object):
    def __init__(self, fun):
        self.fun = fun
        self.cache = {}

    def __call__(self, *args, **kwargs):
        key  = str(args) + str(kwargs)
        try:
            return self.cache[key]
        except KeyError:
            self.cache[key] = rval = self.fun(*args, **kwargs)
            return rval
        except TypeError: # incase key isn't a valid key - don't cache
            return self.fun(*args, **kwargs)

rawDescription: Caching in urllib2?

description: Caching in urllib2


code:
from PyQt4 import QtCore

class TestModel(QtCore.QAbstractTableModel):
    """The model associated with tasks table view"""

    def __init__(self, parent=None):
        """Constructor for TestModel"""
        super(TestModel, self).__init__(parent)
        self.__tasks = [['Task 1', 141546123, 80],
                        ['Task 2', 141546123, 80],
                        ['Task 3', 141546123, 80],
                        ['Task 4', 141546123, 80],
                        ['Task 5', 141546123, 80]]
        # self.__tasks = [[]]
        self.__header = ['Task', 'Timestamp', 'Status']
        self.__empty_row_count = 0
        self.__total_row_count = 0  # Max visible rows.

    def updateRows(self, n):
        self.__total_row_count = n
        if n > self.tasksCount():  # If the view has an empty space.
            self.__empty_row_count = n - self.tasksCount()
        else:
            self.__empty_row_count = 0

        self.reset()  # Reset the view, results to call rowCount method.

    def emptyRowCount(self):
        return self.__empty_row_count

    def tasksCount(self):
        if len(self.__tasks) == 1 and self.__tasks[0] == []:
            return 0
        return len(self.__tasks)

    def rowCount(self, parent=None, *args, **kwargs):
        return self.tasksCount() + self.__empty_row_count
        # Data rows + empty rows.

    def columnCount(self, parent=None, *args, **kwargs):
        return len(self.__header) + 1
        # headers + the last stretched column

    def flags(self, index):
        row = index.row()
        if row >= self.tasksCount():  # If it's an empty row.
            return QtCore.Qt.ItemIsEnabled  # Non selectable.

        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def data(self, index, role=QtCore.Qt.DisplayRole):
        row = index.row()
        column = index.column()
        if row < self.tasksCount() and column < len(self.__header):
            if role == QtCore.Qt.DisplayRole:
                return self.__tasks[row][column]

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                if section < len(self.__header):
                    return self.__header[section]

    def addRow(self):

        success = self.__tasks.append(['Task x', 141546123, 80])
        if self.__empty_row_count > 0:
            self.__empty_row_count -= 1
        self.reset()  # Update the view.

        return success

    def delRow(self):
        if self.__tasks:
            self.__tasks = self.__tasks[:-1]
            if self.__empty_row_count == 0:  # If the visible view was full before the deleting.
                if self.__total_row_count - self.tasksCount() == 1:  # If the view didn't remain full.
                    self.__empty_row_count += 1
            else:
                self.__empty_row_count += 1
            self.reset()  # Update the view.
            return True

rawDescription: Fill in QtableView's bottom space with empty rows


code:
def ct_special(relations, n):
    # `relations` is an iterable producing relations.
    # A relation is a sequence, interpreted to mean
    # relation[0] < relation[1] < relation[2] < ...
    # All elements are in range(n).
    # The result is a vector of length n such that
    # result[i] is the ordinal assigned to i, or
    # result[i] is -1 if i didn't appear in the relations.
    succs = [[] for i in xrange(n)]
    npreds = [-1] * n
    nopreds = [-1] * n
    numnopreds = 0

    def add_elt(u):
        if not 0 <= u < n:
            raise ValueError("element %s out of range" % u)
        if npreds[u] < 0:
            npreds[u] = 0

    for r in relations:
        u = r[0]
        add_elt(u)
        for i in range(1, len(r)):
            v = r[i]
            add_elt(v)
            succs[u].append(v)
            npreds[v] += 1
            u = v

    result = [-1] * n
    for u in xrange(n):
        if npreds[u] == 0:
            nopreds[numnopreds] = u
            numnopreds += 1

    ordinal = nopreds_start = 0
    while nopreds_start < numnopreds:
        next_nopreds_start = numnopreds
        for i in xrange(nopreds_start, numnopreds):
            u = nopreds[i]
            result[u] = ordinal
            for v in succs[u]:
                npreds[v] -= 1
                assert npreds[v] >= 0
                if npreds[v] == 0:
                    nopreds[numnopreds] = v
                    numnopreds += 1
        nopreds_start = next_nopreds_start
        ordinal += 1
    if any(count > 0 for count in npreds):
        raise ValueError("elements in cycles")
    return result

rawDescription: More efficient algorithm to compute an integer mapping for a set of relations


code:
with open("data1.txt", "r") as f1, open("data2.txt", "r") as f2:
        lines = set(f1) # efficient 0(1) lookups using a set
        for lined_no, line in enumerate(f2, 1): # single pass over large file
            # print(line_no) # uncomment if you want to see every line number
            if line in lines:
                print(line,line_no)

rawDescription: Match lines in two text files

description: Match lines in two text files


code:
def all_remainders(num, denom):
  value = num
  yield value # we want the original number
  while value >= denom:
    value -= denom
    yield value

rawDescription: How do i get Python to show all possible remainders instead of just the one that occurs with the largest multiple of the number?

description: Get Python to show all possible remainders instead of just the one that occurs with the largest multiple of the number


code: test2({"test":1, "asterisk":2})

rawDescription: Is there any benefits for using * or ** in python?


code:
import numpy as np
import matplotlib.pyplot as plt
phi = 0.5
theta = 1.2
Rphi = np.array([[np.cos(phi), -np.sin(phi), 0.], [np.sin(phi), np.cos(phi), 0.], [0.,0.,1.]])
Rtheta = np.array([[1.,0.,0.], [0., np.cos(theta), -np.sin(theta)], [0., np.sin(theta), np.cos(theta)]])
R = np.dot(Rphi, Rtheta)
Router = 0.06
Rinner = 0.04
Rsaturn = 0.018

#rs0 = np.array([[np.cos(phi), np.sin(phi), 0.] for phi in np.linspace(0., 2*np.pi, 100)])
phivec1 = np.linspace(0., np.pi, 50)
phivec2 = np.linspace(np.pi,2*np.pi, 50)
rs1 = np.array([np.cos(phivec1), np.sin(phivec1), np.zeros_like(phivec1)]).T  # first half arc
rs2 = np.array([np.cos(phivec2), np.sin(phivec2), np.zeros_like(phivec2)]).T  # second half arc
rs0 = np.concatenate((rs1,rs2),axis=0)  # full arc for Saturn
rs1 = np.dot(rs1, R.T)  # rotate
rs2 = np.dot(rs2, R.T)  # rotate

# draw foreground
semiring1 = np.concatenate((Router*rs1[:,:2],Rinner*rs1[::-1,:2]),axis=0)
plt.fill(semiring1[:,0], semiring1[:,1],'blue',edgecolor='none')
# draw Saturn
plt.fill(Rsaturn*rs0[:,0], Rsaturn*rs0[:,1],'yellow')
# draw foreground
semiring2 = np.concatenate((Router*rs2[:,:2],Rinner*rs2[::-1,:2]),axis=0)
plt.fill(semiring2[:,0], semiring2[:,1],'blue',edgecolor='none')
plt.axis('equal')

rawDescription: How to fill between two rings with matplotlib

description: Fill between two rings with matplotlib


code: type(np.float32(1) / np.float32(2))

rawDescription: cython function output slightly different from python function output

description: Cython function output slightly different from python function output


code:
def shiftString(string, number):
    return "".join(map(lambda x: chr(ord(x)+number),string))

rawDescription: Printing alphabets advanced by n in Python


rawDescription: Create arg string from ArgumentParser parsed args in Python


code:
# partition on the first 'rescued', drop the prefix, re-join the rest
text = ''.join(text.partition('rescued')[1:])
# partition on the last 'Finished', drop the last char of the prefix, re-join
bits = text.partition('Finished')
text = ''.join(bits[0][:-1], bits[1], bits[2])

rawDescription: How do I remove all non-standard characters from a file?

description: Remove all non-standard characters from a file


rawDescription: Python Detect if one-to-one onto mapping exists


rawDescription: Editing Indices of Pandas Series

description: Editing Indices of Pandas Series


code: ie1 = None

rawDescription: How to open a New window in Python PAMIE

description: Open a New window in Python PAMIE


code:
@escaped
@property
def users_name(self):
  ...

rawDescription: How to automatically escape properties when they are being set/retrieved?

description: Automatically escape properties when they are being set/retrieved


code:
import itertools

items = Item.objects.all()

for item1, item2 in itertools.combinations(items, 2):
    similarity = SequenceMatcher(None, item1.desc, item2.desc).ratio()
    if similarity > 0.7:
        for item in item1, item2:
            item.possible_duplicate = True
            item.save()

rawDescription: How can I compare each object with each?

description: Compare each object with each


code:
def quicksort(lst):
    if not lst:
        return []
    return (quicksort([x for x in lst[1:] if x <  lst[0]])
            + [lst[0]] +
            quicksort([x for x in lst[1:] if x >= lst[0]]))

rawDescription: Python: How to sort the alphabet in a list without sorted functions?


code:
msg = 'hi there'
prefix = '{:0>5d}'.format(len(msg)) # No b at the front--this is a str
str_message = prefix + msg # still a str
encoded_message = str_message.encode('utf-8') # or whatever encoding

print(encoded_message) # prints: b'00008hi there'

rawDescription: Byte formatting in python 3

description: Byte formatting in python 3


code: converters = [str.strip] + [float] * (len(headers) - 1)

rawDescription: How to import a csv file using python with headers intact, where first column is a non-numerical

description: Import a csv file using python with headers intact, where first column is a non-numerical


code:
# File c.py

from b import somemethod
from a import Klass

somemethod(Klass)

rawDescription: alias for python class in another module

description: Alias for python class in another module


rawDescription: Python regex replace sentence with starting word


rawDescription: Compute number of dates between two string dates and return an integer


code: user.favoriters.all()  # though that is not a good related_name

rawDescription: Django ORM - querying many to many through models?


code:
mydict = dict(zip(range(100), range(100)))
timeit.timeit('pickle.dumps(mydict,0)', 'from __main__ import pickle, mydict', number=10000)
timeit.timeit('pickle.dumps(mydict,1)', 'from __main__ import pickle, mydict', number=10000)
timeit.timeit('pickle.dumps(mydict,2)', 'from __main__ import pickle, mydict', number=10000)

rawDescription: Why does it take longer to dump and load with pickle.HIGHEST_PROTOCOL?


rawDescription: How to pass python list dynamically to another python file

description: Pass python list dynamically to another python file


code:
df
pd.isnull(df.index)

rawDescription: pandas dataframe selecting the nan indexes

description: Pandas dataframe selecting the nan indexes


code:
def is_jpg(filename):
    data = open(filename,'rb').read(11)
    if data[:4] != '\xff\xd8\xff\xe0': return False
    if data[6:] != 'JFIF\0': return False
    return True

rawDescription: Python: Check if uploaded file is jpg

description: Python: Check if uploaded file is jpg


code:
import numpy as np
import math
from decimal import *

a = 58106601358565889
b = np.sqrt(a)
c = math.sqrt(a)
d = Decimal(58106601358565889).sqrt()

print(d)
print(int(d))

print(c)
print(int(c))

print(b)
print(int(b))

rawDescription: Distinguishing large integers from near integers in python


code:
{
    u'menu2': [u'Some data2', u'Foo2', u'Foo3', u'Some data3'],
    u'menu1': [u'Some data1', u'Foo1']
}

rawDescription: Parsing html table with BeautifulSoup to python dictionary


code:
a = object()
b = object()
a is b

rawDescription: Python Function Called with Default Argument Different From No Argument


code:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random

def fun(x, y):
  return x + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 10
xs = [i for i in range(n) for _ in range(n)]
ys = range(n) * n
zs = [fun(x, y) for x,y in zip(xs,ys)]

ax.scatter(xs, ys, zs)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: I want to use matplotlib to make a 3d plot given a z function


code:
import urllib
value = "kindle fire"
urllib.quote_plus(value)

rawDescription: URL call with string keyword substitution


code:
parent_parser = argparse.ArgumentParser(description="Read text files.")
parent_parser.add_argument('filename', help='TXT file', type=file, nargs='+')

rawDescription: Create parser with subcommands in argparse, customize positional argument(s)


code:
import Tkinter as tk

root = tk.Tk()
buttons = [tk.Button(root,text=str(i)) for i in range(6)]
for i,b in enumerate(buttons):
    b.grid(row=i,column=0)

textbox = tk.Text(root)
textbox.grid(row=0,column=1,rowspan=6)

root.mainloop()

rawDescription: Python Tkinter Layout Problems

description: Python Tkinter Layout Problems


code:
from lxml.html.soupparser import parse
xml = parse(open("foo.xml"))
e3 = xml.xpath("//doc[1]//a")
e4 = xml.xpath("//doc[2]//a")
(len(e3))
(len(e4))
(len(xml.xpath("//a")))

rawDescription: BeautifulSoup first element incorrect

description: BeautifulSoup first element incorrect


code:
import tkinter as tk

class Dialog(object):
    def show(self, num_fields):
        self.num_fields = num_fields
        self.root = tk.Tk()
        self.entries = []
        for i in range(num_fields):
            entry = tk.Entry(self.root)
            entry.pack(fill="x")
            self.entries.append(entry)

        ok = tk.Button(self.root, text="OK", command=self.ok)
        ok.pack(side="bottom", anchor="e", pady=(10,0), padx=10)

        # wait for the window to be destroyed, then
        # return the values. If the user clicks the OK button
        # the values will be set; if they cancel the dialog
        # this will return None.
        self.values = None
        self.root.wait_window()
        return self.values

    def ok(self):
        # save all the values, then destroy the window
        self.values = []
        for i in range(self.num_fields):
            self.values.append(self.entries[i].get())

        self.root.destroy()

rawDescription: Trying to produce function for a custom number of tkinter Entry fields.


rawDescription: RPython ord() with non-ascii character

description: RPython ord() with non-ascii character


code:
filter = tuple(filter)

[s for s in to_check if s.startswith(filter)]

rawDescription: Check if the beginning of a string matches something from a list of strings (python)


code:
from itertools import groupby
from operator import itemgetter
{k: list(g) for k, g in groupby(items, itemgetter('a'))}

rawDescription: Pythonic way to group items in a list

description: Pythonic way to group items in a list