This commit is contained in:
Vitor Santos Costa 2016-08-25 01:26:11 -05:00
parent 79791604d9
commit f12349993b
11 changed files with 131 additions and 2746 deletions

View File

@ -5,7 +5,9 @@ main :-
Plt = matplotlib.pyplot, Plt = matplotlib.pyplot,
:= import( Plt ), := import( Plt ),
:= ( := (
Plt.figure(figsize=(10,2.5))
Plt.plot([1,2,3,4]), Plt.plot([1,2,3,4]),
Plt.ylabel(`some numbers`), Plt.ylabel(`some numbers`),
Plt.show() Plt.show()
). ).

View File

@ -1,26 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "MetaKernel YAP 3",
"language": "prolog",
"name": "yap_kernel"
},
"widgets": {
"state": {},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

View File

@ -1,86 +0,0 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"code_folding": [],
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<ipywidgets.widgets.widget_selection.ToggleButtons object at 0x105e24da0>\n",
"No (more) answers\n"
]
}
],
"source": [
":= import(mathplot).\n",
"X := plot([1,2,3])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": " YAP-6.3",
"language": "prolog",
"name": "yap_kernel"
},
"language_info": {
"codemirror_mode": {
"name": "prolog",
"version": 2
},
"file_extension": ".yap",
"help_links": [
{
"text": "MetaKernel Magics",
"url": "https://github.com/calysto/metakernel/blob/master/metakernel/magics/README.md"
}
],
"mimetype": "text/prolog",
"name": "text",
"pygments_lexer": "prolog",
"version": "0.0.1"
},
"latex_envs": {
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 0
},
"nav_menu": {},
"toc": {
"navigate_menu": true,
"number_sections": true,
"sideBar": true,
"threshold": 6,
"toc_cell": false,
"toc_section_display": "block",
"toc_window_display": false
},
"widgets": {
"state": {
"09b21d398da9424d94cf3c8e51054154": {
"views": []
},
"369de2fecba34468a7c9cf64076bac60": {
"views": []
},
"7f758a42f83c469882761606f7f8133e": {
"views": []
},
"c028bb350ed6424eb48a02762907868d": {
"views": []
}
},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@ -1,3 +1,2 @@
"""A Prolog kernel for Jupyter""" from ipykernel._version import version_info, __version__, kernel_protocol_version_info, kernel_protocol_version
from ipykernel.connect import *
__version__ = '0.0.1'

View File

@ -1,6 +1,9 @@
try: import sys
from ipykernel.kernelapp import IPKernelApp
except ImportError:
from IPython.kernel.zmq.kernelapp import IPKernelApp import ipdb; ipdb.set_trace()
from .kernel import YAPKernel
IPKernelApp.launch_instance(kernel_class=YAPKernel)
if __name__ == '__main__':
from yap_kernel import kernelapp as app
app.launch_new_instance()

View File

@ -1,48 +0,0 @@
import base64
import imghdr
import os
#from IPython.
_TEXT_SAVED_IMAGE = "yap_kernel: saved image data to:"
image_setup_cmd = """
display () {
TMPFILE=$(mktemp ${TMPDIR-/tmp}/yap_kernel.XXXXXXXXXX)
cat > $TMPFILE
echo "%s $TMPFILE" >&2
}
""" % _TEXT_SAVED_IMAGE
def display_data_for_image(filename):
with open(filename, 'rb') as f:
image = f.read()
os.unlink(filename)
image_type = imghdr.what(None, image)
if image_type is None:
raise ValueError("Not a valid image: %s" % image)
image_data = base64.b64encode(image).decode('ascii')
content = {
'data': {
'image/' + image_type: image_data
},
'metadata': {}
}
return content
def extract_image_filenames(output):
output_lines = []
image_filenames = []
for line in output.split("\n"):
if line.startswith(_TEXT_SAVED_IMAGE):
filename = line.rstrip().split(": ")[-1]
image_filenames.append(filename)
else:
output_lines.append(line)
output = "\n".join(output_lines)
return image_filenames, output

View File

@ -1,44 +0,0 @@
import json
import os
import sys
try:
from jupyter_client.kernelspec import install_kernel_spec
except ImportError:
from IPython.kernel.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {
"argv": [sys.executable,
"-m", "yap_kernel",
"-f", "{connection_file}"],
"display_name": "yap",
"mimetype": "text/x-prolog",
"language": "prolog",
"name": "yap",
}
def install_my_kernel_spec(user=False):
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
# TODO: Copy resources once they're specified
print('Installing IPython kernel spec')
install_kernel_spec(td, 'yap', user=False, replace=True)
def _is_root():
return True
try:
return os.geteuid() == 0
except AttributeError:
return False # assume not an admin on non-Unix platforms
def main(argv=[]):
user = '--user' in argv or not _is_root()
install_my_kernel_spec(user=user)
if __name__ == '__main__':
main(argv=sys.argv)

View File

@ -1,5 +1,15 @@
:- if( current_prolog_flag(apple, true) ). :- if( current_prolog_flag(apple, true) ).
:- putenv( 'LC_CTYPE', 'en_us:UTF-8'), :- putenv( 'LC_CTYPE', 'en_us:UTF-8').
plot_inline :-
X := self.inline_plotting,
nb_setval(inline, X ),
X = true,
!,
:= (
import( matplotlib ),
matplotlib.use( `nbagg` )
).
:- endif. :- endif.

View File

@ -1,60 +1,81 @@
from distutils.command.install import install #!/usr/bin/env python
from distutils.core import setup # coding: utf-8
from distutils import log
import json # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
# the name of the package
name = 'yap_kernel'
#-----------------------------------------------------------------------------
# Minimal Python version sanity check
#-----------------------------------------------------------------------------
import sys import sys
v = sys.version_info
if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
error = "ERROR: %s requires Python version 2.7 or 3.3 or above." % name
print(error, file=sys.stderr)
sys.exit(1)
PY3 = (sys.version_info[0] >= 3)
#-----------------------------------------------------------------------------
# get on with it
#-----------------------------------------------------------------------------
import os import os
from glob import glob
PY3 = sys.version_info[0] >= 3 from distutils.core import setup
kernel_json = { packages = ["${CMAKE_CURRENT_SOURCE_DIR}"]
"argv": [sys.executable,
"-m", "yap_kernel", version_ns = {}
"-f", "{connection_file}"], setup_args = dict(
"display_name": " YAP-6.3" , name = 'yap_kernel',
"language": "prolog", version = '0.0.1',
"name": "yap_kernel", packages = ["yap_kernel"],
package_dir = {'': '${CMAKE_SOURCE_DIR}/packages/python' },
description = "YAP Kernel for Jupyter",
long_description="A simple YAP kernel for Jupyter/IPython",
url="https://github.com/vscosta/yap-6.3",
author='Vitor Santos Costa, based on the the IPython',
author_email='vsc@dcc.fc.up.pt',
license = 'BSD',
platforms = "Linux, Mac OS X, Windows",
keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'],
classifiers = [
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Prolog',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
if 'develop' in sys.argv or any(a.startswith('bdist') for a in sys.argv):
import setuptools
setuptools_args = {}
install_requires = setuptools_args['install_requires'] = [
'ipython>=4.0.0',
'traitlets>=4.1.0',
'jupyter_client',
'tornado>=4.0',
]
extras_require = setuptools_args['extras_require'] = {
'test:python_version=="2.7"': ['mock', 'nose_warnings_filters'],
} }
if 'setuptools' in sys.modules:
setup_args.update(setuptools_args)
class install_with_kernelspec(install): if __name__ == '__main__':
def run(self): setup(**setup_args)
install.run(self)
from jupyter_client.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
log.info('Installing kernel spec')
try:
install_kernel_spec(td, 'yap_kernel', user=self.user,
replace=True)
except:
install_kernel_spec(td, 'yap_kernel', user=not self.user,
replace=True)
svem_flag = '--single-version-externally-managed'
if svem_flag in sys.argv:
# Die, setuptools, die.
sys.argv.remove(svem_flag)
setup(name='yap_kernel',
version='0.0.1',
package_dir = {'': '${CMAKE_SOURCE_DIR}/packages/python/yap_kernel' },
description='A simple YAP kernel for Jupyter/IPython',
long_description="A simple YAP kernel for Jupyter/IPython, based on MetaKernel",
url="https://github.com/vscosta/yap-6.3",
author='Vitor Santos Costa, based on the metakernel from Douglas Blank',
author_email='vsc@dcc.fc.up.pt',
py_modules=['yap_kernel'],
install_requires=["metakernel","yap"],
cmdclass={'install': install_with_kernelspec},
classifiers = [
'Framework :: IPython',
'License :: OSI Approved :: BSD License',
'Programming Language :: YAP :: 6.3',
'Programming Language :: Python :: 3',
'Topic :: System :: Shells',
]
)

View File

@ -1,25 +1,42 @@
from __future__ import print_function from __future__ import print_function
from metakernel import MetaKernel from ipykernel.ipkernel import IPythonKernel
import sys import sys
import signal import signal
import yap import yap
import yapex
import ipywidgets as widgets import logging
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.debug('often makes a very good meal of %s', 'visiting tourists')
kernel_json = {
"argv": [sys.executable,
"-m", "yap_kernel",
"-f", "{connection_file}"],
"display_name": " YAP-6.3" ,
"language": "prolog",
"name": "yap_kernel",
}
def eprint(*args, **kwargs): def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs) print(*args, file=sys.stderr, **kwargs)
class YAPKernel(IPythonKernel):
class MetaKernelyap(MetaKernel):
implementation = 'MetaKernel YAP' implementation = 'MetaKernel YAP'
implementation_version = '1.0' implementation_version = '1.0'
language = 'text' language = 'text'
language_version = '0.1' language_version = '0.1'
banner = "MetaKernel YAP" banner = "YAP-6.3"
language_info = { language_info = {
'mimetype': 'text/prolog', 'mimetype': 'text/prolog',
'name': 'text', 'name': 'text',
@ -31,14 +48,12 @@ class MetaKernelyap(MetaKernel):
'pygments_lexer': 'prolog', 'pygments_lexer': 'prolog',
'version' : "0.0.1", 'version' : "0.0.1",
'file_extension': '.yap', 'file_extension': '.yap',
'help_links': MetaKernel.help_links,
} }
def __init__(self, **kwargs): def __init__(self, **kwargs):
MetaKernel.__init__(self, **kwargs) super(YAPKernel, self).__init__( **kwargs)
self._start_yap(**kwargs) _start_yap( **kwargs )
self.olines = ""
self.ask = True
def _start_yap(self, **kwargs): def _start_yap(self, **kwargs):
# Signal handlers are inherited by forked processes, and we can't easily # Signal handlers are inherited by forked processes, and we can't easily
@ -51,18 +66,16 @@ class MetaKernelyap(MetaKernel):
self.q = None self.q = None
self.engine.query("load_files(library(python), [])").command() self.engine.query("load_files(library(python), [])").command()
self.engine.query("load_files(library(jupyter), [])").command() self.engine.query("load_files(library(jupyter), [])").command()
banner = "YAP {0} Kernel".format(self.engine.version()) banner = "YAP6-3 Kernel"
self.olines = banner self.olines = banner
finally: finally:
signal.signal(signal.SIGINT, sig) signal.signal(signal.SIGINT, sig)
# Register Yap function to write image data to temporary file
#self.yapwrapper.run_command(image_setup_cmd)
def get_usage(self): def get_usage(self):
return "This is the YAP kernel." return "This is the YAP kernel."
def query_prolog(self, s):
def run_cell(self, s, store_history=False, silent=False, shell_futures=True):
if not self.q: if not self.q:
self.q = self.engine.query(s) self.q = self.engine.query(s)
@ -94,118 +107,3 @@ class MetaKernelyap(MetaKernel):
if self.q: if self.q:
self.q.close() self.q.close()
self.q = None self.q = None
def do_execute_direct(self, code):
if not code.strip():
return ""
lines = code.split("\n")
interrupted = False
self.doReset = True
nlines = ""
try:
for line in lines:
line = line.strip()
if line.startswith('#'):
# wait
print( "comment")
elif line.startswith('%'):
# wait
call_magic( line )
elif line.endswith(';'):
nlines += line.rstrip(';').rstrip()
self.doReset = False
break
elif line.endswith('!'):
nlines += line.rstrip('!').rstrip()
self.ask = False
self.doReset = False
break
else:
line = line.rstrip()
if line:
nlines += line + "\n"
if nlines != self.olines:
self.closeq( )
self.olines = nlines
elif self.doReset:
opt = widgets.ToggleButtons(
description='Query Solutions:',
options=['First', 'Next', 'All'],
)
print( opt )
if opt == 'First':
self.closeq( )
elif opt == 'Next':
self.doReset = False
else:
self.ask = False
self.doReset = False
self.query_prolog( nlines )
while not self.ask and self.q:
self.query_prolog( nlines )
except SyntaxError as err:
print("Syntax Error error: {0}".format(err))
except EOFError:
return
except RuntimeError as err:
print("YAP Execution Error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except KeyboardInterrupt:
return 'stopped by user'
except:
print("Unexpected error:", sys.exc_info()[0])
raise
def do_complete(self, code, cursor_pos):
print(code)
print(cursor_pos)
eprint( code, " -- ", str(cursor_pos ) )
# code = code[:cursor_pos]
# default = {'matches': [], 'cursor_start': 0,
# 'cursor_end': cursor_pos, 'metadata': dict(),
# 'status': 'ok'}
# if not code or code[-1] == ' ':
# return default
# tokens = code.replace(';', ' ').split()
# if not tokens:
# return default
# matches = []
# token = tokens[-1]
# start = cursor_pos - len(token)
# if token[0] == '$':
# # complete variables
# cmd = 'compgen -A arrayvar -A export \
# -A variable %s' % token[1:] # strip leading $
# output = self.bashwrapper.run_command(cmd).rstrip()
# completions = set(output.split())
# # append matches including leading $
# matches.extend(['$'+c for c in completions])
# else:
# # complete functions and builtins
# cmd = 'compgen -cdfa %s' % token
# output = self.bashwrapper.run_command(cmd).rstrip()
# matches.extend(output.split())
# if not matches:
# return default
# matches = [m for m in matches if m.startswith(token)]
# return {'matches': sorted(matches), 'cursor_start': start,
# 'cursor_end': cursor_pos, 'metadata': dict(),
# 'status': 'ok'}
def repr(self, data):
return repr(data)
if __name__ == '__main__':
try:
from ipykernel.kernelapp import IPKernelApp
except ImportError:
from jupyter_client.zmq.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=MetaKernelyap)