Skip to content

Instantly share code, notes, and snippets.

@douglas-larocca
Created July 20, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglas-larocca/082c6ce52a2218a4d508 to your computer and use it in GitHub Desktop.
Save douglas-larocca/082c6ce52a2218a4d508 to your computer and use it in GitHub Desktop.
import os
import fnmatch
import re
import json
import sys
import subprocess
import inspect
from datetime import datetime
import operator as op
from IPython.display import *
from IPython.core.magics import DisplayMagics
from pprint import PrettyPrinter
try:
from jsbeautifier import Beautifier
jsb = Beautifier()
except ImportError:
pass
ipython = get_ipython()
# extensions
# ===
#ipython.extension_manager.load_extension('[extension]')
# fsutils
# ===
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
# usability
# ===
def iframe(source):
import uuid
filename = '{uuid}.html'.format(uuid=uuid.uuid4())
with open(filename, 'w') as f:
f.write(source)
frame_source = '<iframe src="{}" width=100% height=800 frameborder=0></iframe>'.format(filename)
display(HTML(frame_source))
# now we define a cleanup function that will wait
# long enough for the iframe to load, then remove the
# file; put this in a function so we can run it as
# a subprocess in order not to block
def cleanup(filename):
import time, os
time.sleep(5)
os.remove(filename)
import multiprocessing
proc = multiprocessing.Process(target=cleanup, args=(filename,))
proc.start()
def recall(obj):
src = inspect.getsource(obj)
ipython.set_next_input(src, replace=True)
class CellInject:
def __init__(self, *args, **kwargs):
pass
def __call__(self, cell, extrajs=''):
if not isinstance(cell, str):
cell = json.dumps(cell)
if not cell.startswith('"'):
cell = json.dumps(cell)
cell = '''
var cell = IPython.notebook.get_selected_cell();
var content = {0};
{extrajs}
cell.code_mirror.setValue(content);
'''.format(cell, extrajs=extrajs)
DisplayMagics().javascript('', cell)
class Edit(CellInject):
def __init__(self, *args, **kwargs):
self.conf = self.startup_module('ipython_notebook_config')
def startup_module(self, name):
path = '{}/startup/{}.py'.format(ipython.profile_dir.location, name)
if os.path.isfile(path):
return path
else:
print(path)
raise ImportError()
def __call__(self, filename=None):
if filename:
if not isinstance(filename, str):
try:
filename = inspect.getsourcefile(filename)
except:
print("Can't get source for object.")
return
with open(filename, 'r') as f:
content = json.dumps(f.read())
else:
# calling ed() will assume we want a temp file
filename = 'tmp{0}.py'.format(datetime.now().strftime('%s'))
content = json.dumps('# temp file '+filename)
js = r'''content = "#%%file {}\n"+content;'''.format(filename)
super().__call__(content, extrajs=js)
def nbconf(self, module=None):
if module:
return self(self.startup_module(module))
else:
return self(self.conf)
class WordWrap(CellInject):
def __init__(self, chars=None, **kwargs):
self._wrap = None
self._chars = chars or 80
def __call__(self, text):
self._text = text
super().__call__(self.wrap)
@property
def wrap(self):
if self._wrap is not None:
return self._wrap
self._wrap = ''
linelen = 0
for word in self._text.replace('\n',' ').split(' '):
cur = word + ' '
curlen = len(cur)
if curlen + linelen >= self._chars:
self._wrap += '\n' + cur
linelen = curlen
else:
self._wrap += cur
linelen += curlen
return self._wrap
class Cell(CellInject):
def __init__(self, *args, **kwargs):
pass
def __call__(self, text, **kwargs):
extrajs=''
if not kwargs.get('literal'):
if isinstance(text, str):
if kwargs.get('js'):
try:
text = jsb.beautify(text)
extrajs = r'''content = "%%javascript\n"+content;'''
except NameError:
pass
elif any(x > 79 for x in map(len, text.splitlines())):
text = PrettyPrinter().pformat(text)
else:
text = PrettyPrinter().pformat(text)
super().__call__(text, extrajs=extrajs)
ed = Edit()
wrap = WordWrap()
cell = Cell()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment