Merge 192.168.1.79:github/yap-6.3

This commit is contained in:
Vítor Santos Costa
2018-03-26 11:03:08 +01:00
119 changed files with 47950 additions and 1288 deletions

193
packages/python/python.h Normal file
View File

@@ -0,0 +1,193 @@
//@{
/** @brief Prolog to Python library
*
*
* Please look at python.pl for more information, and to real.pl and real.c
* for related work.
*/
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE // python does its own thing
#endif
#include <Python.h>
#include <SWI-Prolog.h>
#ifdef HAVE_STAT
#undef HAVE_STATa
#endif
#include <assert.h>
#include <string.h>
#define EXTRA_MESSSAGES 1
#ifndef PYTHON_H
#define PYTHON_H 1
PyObject *find_obj(PyObject *ob, term_t lhs, bool eval);
#if DEBUG_MEMORY
#define DebugPrintf(s, op) fprintf(stderr, "%s:%d: " s, __FILE__, __LINE__, op)
#else
#define DebugPrintf(s, op)
#endif
/**
* @brief A module is store as an objet plus a list of paths.
*/
#define PY_MAX_MODLEN 16
typedef struct s_mod_t {
PyObject *mod;
int length;
YAP_Term names[PY_MAX_MODLEN];
} Py_mod;
extern X_API YAP_Term pythonToYAP(PyObject *pVal);
extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o);
typedef YAP_Arity arity_t;
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A, ATOM_self;
extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
FUNCTOR_float1, FUNCTOR_int1, FUNCTOR_iter1, FUNCTOR_iter2, FUNCTOR_long1,
FUNCTOR_len1, FUNCTOR_curly1, FUNCTOR_ord1, FUNCTOR_range1, FUNCTOR_range2,
FUNCTOR_range3, FUNCTOR_sum1, FUNCTOR_pointer1, FUNCTOR_complex2,
FUNCTOR_plus2, FUNCTOR_sub2, FUNCTOR_mul2, FUNCTOR_div2, FUNCTOR_hat2,
FUNCTOR_colon2, FUNCTOR_comma2, FUNCTOR_equal2, FUNCTOR_sqbrackets2,
FUNCTOR_dot2;
extern X_API PyObject *py_Main;
extern X_API PyObject *py_Builtin;
extern X_API PyObject *py_Yapex;
extern X_API PyObject *py_Local;
extern X_API PyObject *py_Global;
extern X_API PyObject *py_Context;
extern PyObject *py_F2P;
extern PyObject *py_Sys;
extern PyObject *py_ModDict;
extern bool python_in_python;
extern bool python_release_GIL(term_t state);
extern term_t python_acquire_GIL(void);
static inline Py_ssize_t get_p_int(PyObject *o, Py_ssize_t def) {
if (o == NULL)
return def;
if (PyLong_Check(o)) {
return PyLong_AsLong(o);
#if PY_MAJOR_VERSION < 3
} else if (PyInt_Check(o)) {
return PyInt_AsLong(o);
#endif
}
return def;
}
static inline foreign_t address_to_term(PyObject *pVal, term_t t) {
term_t to = PL_new_term_ref(), t1 = PL_new_term_ref();
PL_put_pointer(t1, (void *)pVal);
PL_cons_functor(to, FUNCTOR_pointer1, t1);
Py_INCREF(pVal);
foreign_t rc = PL_unify(t, to);
PL_reset_term_refs(to);
return rc;
}
static inline int proper_ascii_string(const char *s) {
unsigned char c;
while ((c = *s++)) {
if (c > 127)
return FALSE;
}
return TRUE;
}
static inline PyObject *atom_to_python_string(term_t t) {
// Yap_DebugPlWrite(YAP_GetFromSlot(t)); fprintf(stderr, " here I
// am\n");
char *s = NULL;
if (!PL_get_atom_chars(t, &s))
return NULL;
/* return __main__,s */
#if PY_MAJOR_VERSION < 3
if (proper_ascii_string(s)) {
return PyString_FromStringAndSize(s, strlen(s));
} else
#endif
{
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
// fprintf(stderr, "%s\n", s);
return pobj;
}
}
#define CHECK_CALL(rc, t, call) \
PyErr_Clear();\
rc = call; \
if (rc == NULL || PyErr_Occurred()) {\
YE(t,__LINE__,__FILE__,__FUNCTION__);\
PyErr_Print(); PyErr_Clear();\
}
#define CHECKNULL(t,rc) (rc != NULL ? rc : YE(t,__LINE__,__FILE__,__FUNCTION__) )
#define AOK(rc, err) { if (!rc) YEM( #rc ,__LINE__,__FILE__,__FUNCTION__); }
extern PyObject *YE(term_t t, int line, const char *file, const char *code);
extern void YEM( const char *ex, int line, const char *file, const char *code);
extern void pyErrorHandler__(int line, const char *file, const char *code);
#define pyErrorHandler() \
{ \
if (PyErr_Occurred()) { \
pyErrorHandler__(__LINE__, __FILE__, __FUNCTION__); \
} \
}
#define pyErrorAndReturn(x, y) \
{ \
if (PyErr_Occurred()) { \
pyErrorHandler__(__LINE__, __FILE__, __FUNCTION__); \
return (x); \
} else { \
return (x); \
} \
}
// #define pyErrorAndReturn( x, y ) return x
extern PyObject *compound_to_pyeval(term_t t, PyObject *context);
extern PyObject *compound_to_pytree(term_t t, PyObject *context);
extern PyObject *term_to_python(term_t t, bool eval, PyObject *contextxs);
extern PyObject *term_to_nametuple(const char *s, int arity, term_t t);
extern foreign_t python_to_term(PyObject *pVal, term_t t);
extern bool python_assign(term_t t, PyObject *exp, PyObject *context);
extern foreign_t assign_to_symbol(term_t t, PyObject *e);
extern bool python_asign(term_t t, PyObject *exp, PyObject *context);
extern foreign_t python_builtin(term_t out);
extern int lookupPyModule(Py_mod *q);
extern PyObject *lookupPySymbol(const char *s, PyObject *q, PyObject **d);
extern install_t install_pypreds(void);
extern install_t install_pl2pl(void);
X_API extern bool init_python(void);
extern bool do_init_python(void);
extern PyObject PyInit_yap(void);
extern PyObject *PythonLookup(const char *s, PyObject *o);
extern PyObject *PythonLookupSpecial(const char *s);
#endif

View File

@@ -70,7 +70,7 @@ endif()
DEPENDS ${PYTHON_SOURCES}
)
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --ignore-installed .
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed .
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${YAP_INSTALL_DLLDIR} )

View File

@@ -0,0 +1,93 @@
<center>
![The YAP Logo](docs/icons/yap_128x128x32.png)
</center>
NOTE: this version of YAP is still experimental, documentation may be out of date.
## Introduction
This document provides User information on version 6.3.4 of
YAP (<em>Yet Another Prolog</em>). The YAP Prolog System is a
high-performance Prolog compiler developed at Universidade do
Porto. YAP supports stream Input/Output, sockets, modules,
exceptions, Prolog debugger, C-interface, dynamic code, internal
database, DCGs, saved states, co-routining, arrays, threads.
We explicitly allow both commercial and non-commercial use of YAP.
YAP is based on the David H. D. Warren's WAM (Warren Abstract Machine),
with several optimizations for better performance. YAP follows the
Edinburgh tradition, and was originally designed to be largely
compatible with DEC-10 Prolog, Quintus Prolog, and especially with
C-Prolog. More recently, we have worked on being compatible with SICStus Prolog and with SWI-Prolog.
YAP implements most of the ISO-Prolog standard. We are striving at
full compatibility, and the manual describes what is still
missing.
The document is intended neither as an introduction to Prolog nor to the
implementation aspects of the compiler. A good introduction to
programming in Prolog is the book @cite TheArtOfProlog , by
L. Sterling and E. Shapiro, published by "The MIT Press, Cambridge
MA". Other references should include the classical @cite ProgrammingInProlog , by W.F. Clocksin and C.S. Mellish, published by
Springer-Verlag.
YAP 6.3.4 has been built with the gcc and clang compilers on Linux and OSX machines. We expect to recover support for WIN32 machines and
Android next.
We are happy to include in YAP several excellent packages developed
under separate licenses. Our thanks to the authors for their kind
authorization to include these packages.
The overall copyright and permission notice for YAP4.3 can be found in
the Artistic file in this directory. YAP follows the Perl Artistic
license, and it is thus non-copylefted freeware. Some components of YAP have been obtained from SWI Prolog and ciao, and have
different licenses.
If you have a question about this software, desire to add code, found a
bug, want to request a feature, or wonder how to get further assistance,
please send e-mail to <yap-users AT lists.sourceforge.net>. To
subscribe to the mailing list, visit the page
<https://lists.sourceforge.net/lists/listinfo/yap-users>.
On-line documentation is available for [YAP](http://www.dcc.fp.pt/~vsc/yap/)
The packages are, in alphabetical order:
+ The CHR package developed by Tom Schrijvers,
Christian Holzbaur, and Jan Wielemaker.
+ The CLP(BN) package and Horus toolkit developed by Tiago Gomes, and Vítor Santos Costa.
+ The CLP(R) package developed by Leslie De Koninck, Bart Demoen, Tom
Schrijvers, and Jan Wielemaker, based on the CLP(Q,R) implementation
by Christian Holzbaur.
+ The CPLint package developed by Fabrizio Riguzzi's research
laboratory at the [University of Ferrara](http://www.ing.unife.it/Docenti/FabrizioRiguzzi/)
+ The CUDA interface package developed by Carlos Martínez, Jorge
Buenabad, Inês Dutra and Vítor Santos Costa.
+ The [GECODE](http://www.gecode.org) interface package developed by Denys Duchier and Vítor Santos Costa.
+ The [JPL](http://www.swi-prolog.org/packages/jpl/) (Java-Prolog Library) package developed by .
The minisat SAT solver interface developed by Michael Codish,
Vitaly Lagoon, and Peter J. Stuckey.
+ The MYDDAS relational data-base interface developed at the
Universidade do Porto by Tiago Soares, Michel Ferreira, and Ricardo Rocha.
+ The [PRISM](http://rjida.meijo-u.ac.jp/prism/) logic-based
programming system for statistical modeling developed at the Sato
Research Laboratory, TITECH, Japan.
+ The ProbLog 1 system developed by the [ProbLog](https://dtai.cs.kuleuven.be/problog) team in the
DTAI group of KULeuven.
+ The [R](http://stoics.org.uk/~nicos/sware/packs/real/) interface package developed by Nicos Angelopoulos,
Vítor Santos Costa, João Azevedo, Jan Wielemaker, and Rui Camacho.

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,33 @@
import imp
import os
import ctypes
import glob
import os.path
import platform
import sys
global yap_lib_path
yap_lib_path = "/home/vsc/anaconda3/conda-bld/yap4py_1522052049872/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placeho/lib"
if platform.system() == 'Windows':
def load( dll ):
dll = glob.glob(os.path.join(yap_lib_path,dll))[0]
dll = os.path.abspath(dll)
ctypes.WinDLL(dll)
elif platform.system() == 'Darwin':
def load( dll ):
dll = glob.glob(os.path.join(os.path.dirname(__file__),dll))[0]
dll = os.path.abspath(dll)
ctypes.CDLL(dll)
print('loaded ',dll)
# try:
# load( '_yap*.so' )
# except:
# load( '_yap*.dylib' )
else:
def load( dll ):
dll = glob.glob(os.path.join(os.path.dirname(__file__),dll))[0]
dll = os.path.abspath(dll)
ctypes.CDLL(dll)
#load('_yap*.so')

View File

@@ -67,7 +67,6 @@ class Query:
return self
def __next__(self):
print(self)
if not self.q:
raise StopIteration()
if self.q.next():
@@ -144,39 +143,41 @@ class YAPShell:
# if not isinstance(eq[0],str):
# print( "Error: Variable Name matches a Python Symbol")
# return
self.do_ask = True
engine = self.engine
bindings = []
g = python_query(self, query)
if not self.q:
try:
engine = self.engine
bindings = []
loop = False
g = python_query(self, query)
self.q = Query( engine, g )
for bind in self.q:
bindings += [bind]
if self.do_ask:
print(bindings)
bindings = []
for bind in self.q:
bindings += [bind]
if loop:
continue
if not self.q.port == "exit":
break
s = input("more(;), all(*), no(\\n), python(#) ?").lstrip()
else:
s = ";"
if s.startswith(';') or s.startswith('y'):
continue
elif s.startswith('#'):
try:
exec(s.lstrip('#'))
except:
raise
elif s.startswith('*') or s.startswith('a'):
self.do_ask = False
continue
else:
break
if self.q:
self.os = query
if bindings:
return True,bindings
print("No (more) answers")
return False, None
if s.startswith(';') or s.startswith('y'):
continue
elif s.startswith('#'):
try:
exec(s.lstrip('#'))
except:
raise
elif s.startswith('*') or s.startswith('a'):
loop = True
continue
else:
break
if self.q:
self.os = query
if bindings:
return True,bindings
print("No (more) answers")
return False, None
except Exception as e:
print("Exception")
print(dir(e))
return False, None
def live(self, engine, **kwargs):
loop = True

BIN
packages/python/yap_.tgz Normal file

Binary file not shown.

View File

@@ -0,0 +1,25 @@
define("codemirror/lib/codemirror" ]
pecs/yap_kernel/prolog"
],
function(CodeMirror){
var onload =
function(CodeMirror){
console.log("I am being loaded");
editor = CodeMirror.fromTextArea(document.getElementById("code"), {
parserfile: "kernelspecs/yap_kernel/prolog.js"
lineNumbers: true,
mode: "text/x-prolog"
});
return {onload:onload}
}
}
);

View File

@@ -0,0 +1,16 @@
"""Entry point for launching an YAP kernel.
This is separate from the yap_kernel package so we can avoid doing imports until
after removing the cwd from sys.path.
"""
import sys
if __name__ == '__main__':
# Remove the CWD from sys.path while we load stuff.
# This is added back by InteractiveShellApp.init_path()
if sys.path[0] == '':
del sys.path[0]
from yap_kernel import kernelapp as app
app.launch_new_instance()

View File

@@ -1,5 +1,6 @@
set (PYTHON_SOURCES
backcall.py
yap_kernel_launcher.py
docs/conf.py
yap_kernel/codeutil.py
@@ -463,7 +464,7 @@ yap.tgz ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/kernel.js ${CMAKE_CURRE
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
COMMAND ${PYTHON_EXECUTABLE} -m pip install --ignore-installed --no-deps .
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed --no-deps .
COMMAND ${PYTHON_EXECUTABLE} -m yap_kernel.kernelspec
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")

View File

@@ -8,7 +8,7 @@ include yap_kernel/resources/kernel.json
# Documentation
graft
# graft
# Patterns to exclude from any directory
global-exclude *~
global-exclude *.pyc

View File

@@ -0,0 +1,4 @@
if __name__ == '__main__':
import yap_kernel.kernelapp
yap_kernel.kernelapp.launch_new_instance()

View File

@@ -0,0 +1,5 @@
version_info = (4, 4, 1)
__version__ = '.'.join(map(str, version_info))
kernel_protocol_version_info = (5, 0)
kernel_protocol_version = '%s.%s' % kernel_protocol_version_info

View File

@@ -0,0 +1,109 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 18:17:15 2014
@author: takluyver
"""
import sys
PY3 = (sys.version_info[0] >= 3)
try:
from inspect import signature, Parameter # Python >= 3.3
except ImportError:
from ._signatures import signature, Parameter
if PY3:
from functools import wraps
else:
from functools import wraps as _wraps
def wraps(f):
def dec(func):
_wraps(f)(func)
func.__wrapped__ = f
return func
return dec
def callback_prototype(prototype):
"""Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
which can be used to prepare third party callbacks.
"""
protosig = signature(prototype)
positional, keyword = [], []
for name, param in protosig.parameters.items():
if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
raise TypeError("*args/**kwargs not supported in prototypes")
if (param.default is not Parameter.empty) \
or (param.kind == Parameter.KEYWORD_ONLY):
keyword.append(name)
else:
positional.append(name)
kwargs = dict.fromkeys(keyword)
def adapt(callback):
"""Introspect and prepare a third party callback."""
sig = signature(callback)
try:
# XXX: callback can have extra optional parameters - OK?
sig.bind(*positional, **kwargs)
return callback
except TypeError:
pass
# Match up arguments
unmatched_pos = positional[:]
unmatched_kw = kwargs.copy()
unrecognised = []
# TODO: unrecognised parameters with default values - OK?
for name, param in sig.parameters.items():
# print(name, param.kind) #DBG
if param.kind == Parameter.POSITIONAL_ONLY:
if len(unmatched_pos) > 0:
unmatched_pos.pop(0)
else:
unrecognised.append(name)
elif param.kind == Parameter.POSITIONAL_OR_KEYWORD:
if (param.default is not Parameter.empty) and (name in unmatched_kw):
unmatched_kw.pop(name)
elif len(unmatched_pos) > 0:
unmatched_pos.pop(0)
else:
unrecognised.append(name)
elif param.kind == Parameter.VAR_POSITIONAL:
unmatched_pos = []
elif param.kind == Parameter.KEYWORD_ONLY:
if name in unmatched_kw:
unmatched_kw.pop(name)
else:
unrecognised.append(name)
else: # VAR_KEYWORD
unmatched_kw = {}
# print(unmatched_pos, unmatched_kw, unrecognised) #DBG
if unrecognised:
raise TypeError("Function {!r} had unmatched arguments: {}".format(callback, unrecognised))
n_positional = len(positional) - len(unmatched_pos)
@wraps(callback)
def adapted(*args, **kwargs):
"""Wrapper for third party callbacks that discards excess arguments"""
# print(args, kwargs)
args = args[:n_positional]
for name in unmatched_kw:
# XXX: Could name not be in kwargs?
kwargs.pop(name)
# print(args, kwargs, unmatched_pos, cut_positional, unmatched_kw)
return callback(*args, **kwargs)
return adapted
prototype.adapt = adapt
return prototype

View File

@@ -0,0 +1,209 @@
# -*- coding: utf-8 -*-
"""YAP Stuff for Main IPython class."""
#-----------------------------------------------------------------------------
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
from __future__ import absolute_import, print_function
import __future__
import abc
import ast
import atexit
import functools
import os
import re
import runpy
import signal
import sys
import tempfile
import traceback
import types
import subprocess
import warnings
import yap
from io import open as io_open
from pickleshare import PickleShareDB
from traitlets.config.configurable import SingletonConfigurable
from IPython.core import oinspect
from IPython.core import magic
from IPython.core import page
from IPython.core import prefilter
from IPython.core import shadowns
from IPython.core import ultratb
from IPython.core import interactiveshell
from IPython.core.alias import Alias, AliasManager
from IPython.core.autocall import ExitAutocall
from IPython.core.builtin_trap import BuiltinTrap
from IPython.core.events import EventManager, available_events
from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
from IPython.core.debugger import Pdb
from IPython.core.display_trap import DisplayTrap
from IPython.core.displayhook import DisplayHook
from IPython.core.displaypub import DisplayPublisher
from IPython.core.error import InputRejected, UsageError
from IPython.core.extensions import ExtensionManager
from IPython.core.formatters import DisplayFormatter
from IPython.core.history import HistoryManager
from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
from IPython.core.logger import Logger
from IPython.core.macro import Macro
from IPython.core.payload import PayloadManager
from IPython.core.prefilter import PrefilterManager
from IPython.core.profiledir import ProfileDir
from IPython.core.usage import default_banner
from IPython.core.interactiveshell import InteractiveShellABC, InteractiveShell, ExecutionResult
from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
from IPython.utils import PyColorize
from IPython.utils import io
from IPython.utils import py3compat
from IPython.utils import openpy
from IPython.utils.decorators import undoc
from IPython.utils.io import ask_yes_no
from IPython.utils.ipstruct import Struct
from IPython.paths import get_ipython_dir
from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
from IPython.utils.process import system, getoutput
from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
with_metaclass, iteritems)
from IPython.utils.strdispatch import StrDispatch
from IPython.utils.syspathcontext import prepended_to_syspath
from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
from IPython.utils.tempdir import TemporaryDirectory
from traitlets import (
Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
observe, default,
)
from warnings import warn
from logging import error
class YAPInteractiveShell:
"""An enhanced, interactive shell for YAP."""
def __init__(self, kernel):
self.yapeng = yap.YAPEngine()
self.q = None
self.shell = kernel.shell
self.shell.run_cell = self.run_cell
def closeq(self):
if self.q:
self.q.close()
self.q = None
def run_cell(self, s, store_history=True, silent=False, shell_futures=True):
"""Run a complete IPython cell.
Parameters
----------
raw_cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored in IPython's
history. For user code calling back into IPython's machinery, this
should be set to False.
silent : bool
If True, avoid side-effects, such as implicit displayhooks and
and logging. silent=True forces store_history=False.
shell_futures : bool
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
Returns
-------
result : :class:`ExecutionResult`
"""
result = ExecutionResult()
if (not s) or s.isspace():
self.shell.last_execution_succeeded = True
return result
if store_history:
result.execution_count = self.shell.execution_count
def error_before_exec(value):
result.error_before_exec = value
self.shell.last_execution_succeeded = False
return result
if not self.q:
try:
self.q = self.yapeng.query(s)
except SyntaxError:
return error_before_exec( sys.exc_info()[1])
cell = s # cell has to exist so it can be stored/logged
# Store raw and processed history
# if not silent:
# self.shell..logger.log(cell, s)
has_raised = False
try:
#f = io.StringIO()
# with redirect_stdout(f):
run = self.q.next()
# print('{0}'.format(f.getvalue()))
# Execute the user code
if run:
myvs = self.q.namedVarsCopy()
if myvs:
i = 0
for peq in myvs:
name = peq[0]
bind = peq[1]
if bind.isVar():
var = yap.YAPAtom('$VAR')
f = yap.YAPFunctor(var, 1)
bind.unify(yap.YAPApplTerm(f, (name)))
else:
i = bind.numberVars(i, True)
print(name.text() + " = " + bind.text())
else:
print("yes")
if self.q.deterministic():
self.closeq()
else:
print("No (more) answers")
self.closeq()
except:
result.error_in_exec = sys.exc_info()[1]
# self.showtraceback()
has_raised = True
self.closeq()
self.shell.last_execution_succeeded = not has_raised
result.result = self.shell.last_execution_succeeded
print( self.q )
# Reset this so later displayed values do not modify the
# ExecutionResult
# self.displayhook.exec_result = None
#self.events.trigger('post_execute')
#if not silent:
# self.events.trigger('post_run_cell')
if store_history:
# Write output to the database. Does nothing unless
# history output logging is enabled.
# self.history_manager.store_output(self.execution_count)
# Each cell is a *single* input, regardless of how many lines it has
self.shell.execution_count += 1
return result

View File

@@ -0,0 +1,18 @@
:- use_module(library(python)).
:- if( current_prolog_flag(apple, true) ).
:- 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.

View File

@@ -0,0 +1,488 @@
"""An Application for launching a kernel"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import atexit
import os
import sys
import signal
import traceback
import logging
from tornado import ioloop
import zmq
from zmq.eventloop import ioloop as zmq_ioloop
from zmq.eventloop.zmqstream import ZMQStream
from ipykernel.zmqshell import ZMQInteractiveShell
from IPython.core.application import (
BaseIPythonApplication, base_flags, base_aliases, catch_config_error
)
from IPython.core.profiledir import ProfileDir
from IPython.core.shellapp import (
InteractiveShellApp, shell_flags, shell_aliases
)
from IPython.utils import io
from ipython_genutils.path import filefind, ensure_dir_exists
from traitlets import (
Any, Instance, Dict, Unicode, Integer, Bool, DottedObjectName, Type, default
)
from ipython_genutils.importstring import import_item
from jupyter_core.paths import jupyter_runtime_dir
from jupyter_client import write_connection_file
from jupyter_client.connect import ConnectionFileMixin
# local imports
from ipykernel.iostream import IOPubThread
from ipykernel.heartbeat import Heartbeat
from .yap_kernel import YAPKernel
from ipykernel.parentpoller import ParentPollerUnix, ParentPollerWindows
from jupyter_client.session import (
Session, session_flags, session_aliases,
)
#-----------------------------------------------------------------------------
# Flags and Aliases
#-----------------------------------------------------------------------------
kernel_aliases = dict(base_aliases)
kernel_aliases.update({
'ip' : 'YAPKernelApp.ip',
'hb' : 'YAPKernelApp.hb_port',
'shell' : 'YAPKernelApp.shell_port',
'iopub' : 'YAPKernelApp.iopub_port',
'stdin' : 'YAPKernelApp.stdin_port',
'control' : 'YAPKernelApp.control_port',
'f' : 'YAPKernelApp.connection_file',
'transport': 'YAPKernelApp.transport',
})
kernel_flags = dict(base_flags)
kernel_flags.update({
'no-stdout' : (
{'YAPKernelApp' : {'no_stdout' : True}},
"redirect stdout to the null device"),
'no-stderr' : (
{'YAPKernelApp' : {'no_stderr' : True}},
"redirect stderr to the null device"),
'pylab' : (
{'YAPKernelApp' : {'pylab' : 'auto'}},
"""Pre-load matplotlib and numpy for interactive use with
the default matplotlib backend."""),
})
# inherit flags&aliases for any IPython shell apps
kernel_aliases.update(shell_aliases)
kernel_flags.update(shell_flags)
# inherit flags&aliases for Sessions
kernel_aliases.update(session_aliases)
kernel_flags.update(session_flags)
_ctrl_c_message = """\
NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
To exit, you will have to explicitly quit this process, by either sending
"quit" from a client, or using Ctrl-\\ in UNIX-like environments.
To read more about this, see https://github.com/ipython/ipython/issues/2049
"""
#-----------------------------------------------------------------------------
# Application class for starting an IPython Kernel
#-----------------------------------------------------------------------------
class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
ConnectionFileMixin):
name='YAP-kernel'
aliases = Dict(kernel_aliases)
flags = Dict(kernel_flags)
classes = [YAPKernel, ZMQInteractiveShell, ProfileDir, Session]
# the kernel class, as an importstring
kernel_class = Type('yap_kernel.yap_kernel.YAPKernel',
klass='ipykernel.kernelbase.Kernel',
help="""The Kernel subclass to be used.
This should allow easy re-use of the YAPKernelApp entry point
to configure and launch kernels other than IPython's own.
""").tag(config=True)
kernel = Any()
poller = Any() # don't restrict this even though current pollers are all Threads
heartbeat = Instance(Heartbeat, allow_none=True)
ports = Dict()
subcommands = {
'install': (
'yap_kernel.kernelspec.InstallYAPKernelSpecApp',
'Install the YAP kernel'
),
}
# connection info:
connection_dir = Unicode()
@default('connection_dir')
def _default_connection_dir(self):
return jupyter_runtime_dir()
@property
def abs_connection_file(self):
if os.path.basename(self.connection_file) == self.connection_file:
return os.path.join(self.connection_dir, self.connection_file)
else:
return self.connection_file
# streams, etc.
no_stdout = Bool(False, help="redirect stdout to the null device").tag(config=True)
no_stderr = Bool(False, help="redirect stderr to the null device").tag(config=True)
outstream_class = DottedObjectName('ipykernel.iostream.OutStream',
help="The importstring for the OutStream factory").tag(config=True)
displayhook_class = DottedObjectName('ipykernel.displayhook.ZMQDisplayHook',
help="The importstring for the DisplayHook factory").tag(config=True)
# polling
parent_handle = Integer(int(os.environ.get('JPY_PARENT_PID') or 0),
help="""kill this process if its parent dies. On Windows, the argument
specifies the HANDLE of the parent process, otherwise it is simply boolean.
""").tag(config=True)
interrupt = Integer(int(os.environ.get('JPY_INTERRUPT_EVENT') or 0),
help="""ONLY USED ON WINDOWS
Interrupt this process when the parent is signaled.
""").tag(config=True)
def init_crash_handler(self):
sys.excepthook = self.excepthook
def excepthook(self, etype, evalue, tb):
# write uncaught traceback to 'real' stderr, not zmq-forwarder
traceback.print_exception(etype, evalue, tb, file=sys.__stderr__)
def init_poller(self):
if sys.platform == 'win32':
if self.interrupt or self.parent_handle:
self.poller = ParentPollerWindows(self.interrupt, self.parent_handle)
elif self.parent_handle:
self.poller = ParentPollerUnix()
def _bind_socket(self, s, port):
iface = '%s://%s' % (self.transport, self.ip)
if self.transport == 'tcp':
if port <= 0:
port = s.bind_to_random_port(iface)
else:
s.bind("tcp://%s:%i" % (self.ip, port))
elif self.transport == 'ipc':
if port <= 0:
port = 1
path = "%s-%i" % (self.ip, port)
while os.path.exists(path):
port = port + 1
path = "%s-%i" % (self.ip, port)
else:
path = "%s-%i" % (self.ip, port)
s.bind("ipc://%s" % path)
return port
def write_connection_file(self):
"""write connection info to JSON file"""
cf = self.abs_connection_file
self.log.debug("Writing connection file: %s", cf)
write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport,
shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port,
iopub_port=self.iopub_port, control_port=self.control_port)
def cleanup_connection_file(self):
cf = self.abs_connection_file
self.log.debug("Cleaning up connection file: %s", cf)
try:
os.remove(cf)
except (IOError, OSError):
pass
self.cleanup_ipc_files()
def init_connection_file(self):
if not self.connection_file:
self.connection_file = "kernel-%s.json"%os.getpid()
try:
self.connection_file = filefind(self.connection_file, ['.',self.connection_dir])
except IOError:
self.log.debug("Connection file not found: %s", self.connection_file)
# This means I own it, and I'll create it in this directory:
ensure_dir_exists(os.path.dirname(self.abs_connection_file), 0o700)
# Also, I will clean it up:
atexit.register(self.cleanup_connection_file)
return
try:
self.load_connection_file()
except Exception:
self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
self.exit(1)
def init_sockets(self):
# Create a context, a session, and the kernel sockets.
self.log.info("Starting the kernel at pid: %i", os.getpid())
context = zmq.Context.instance()
# Uncomment this to try closing the context.
# atexit.register(context.term)
self.shell_socket = context.socket(zmq.ROUTER)
self.shell_socket.linger = 1000
self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port)
self.stdin_socket = context.socket(zmq.ROUTER)
self.stdin_socket.linger = 1000
self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port)
self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port)
self.control_socket = context.socket(zmq.ROUTER)
self.control_socket.linger = 1000
self.control_port = self._bind_socket(self.control_socket, self.control_port)
self.log.debug("control ROUTER Channel on port: %i" % self.control_port)
self.init_iopub(context)
def init_iopub(self, context):
self.iopub_socket = context.socket(zmq.PUB)
self.iopub_socket.linger = 1000
self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port)
self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port)
self.configure_tornado_logger()
self.iopub_thread = IOPubThread(self.iopub_socket, pipe=True)
self.iopub_thread.start()
# backward-compat: wrap iopub socket API in background thread
self.iopub_socket = self.iopub_thread.background_socket
def init_heartbeat(self):
"""start the heart beating"""
# heartbeat doesn't share context, because it mustn't be blocked
# by the GIL, which is accessed by libzmq when freeing zero-copy messages
hb_ctx = zmq.Context()
self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port))
self.hb_port = self.heartbeat.port
self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port)
self.heartbeat.start()
def log_connection_info(self):
"""display connection info, and store ports"""
basename = os.path.basename(self.connection_file)
if basename == self.connection_file or \
os.path.dirname(self.connection_file) == self.connection_dir:
# use shortname
tail = basename
else:
tail = self.connection_file
lines = [
"To connect another client to this kernel, use:",
" --existing %s" % tail,
]
# log connection info
# info-level, so often not shown.
# frontends should use the %connect_info magic
# to see the connection info
for line in lines:
self.log.info(line)
# also raw print to the terminal if no parent_handle (`ipython kernel`)
# unless log-level is CRITICAL (--quiet)
if not self.parent_handle and self.log_level < logging.CRITICAL:
io.rprint(_ctrl_c_message)
for line in lines:
io.rprint(line)
self.ports = dict(shell=self.shell_port, iopub=self.iopub_port,
stdin=self.stdin_port, hb=self.hb_port,
control=self.control_port)
def init_blackhole(self):
"""redirects stdout/stderr to devnull if necessary"""
if self.no_stdout or self.no_stderr:
blackhole = open(os.devnull, 'w')
if self.no_stdout:
sys.stdout = sys.__stdout__ = blackhole
if self.no_stderr:
sys.stderr = sys.__stderr__ = blackhole
def init_io(self):
"""Redirect input streams and set a display hook."""
if self.outstream_class:
outstream_factory = import_item(str(self.outstream_class))
sys.stdout = outstream_factory(self.session, self.iopub_thread, u'stdout')
sys.stderr = outstream_factory(self.session, self.iopub_thread, u'stderr')
if self.displayhook_class:
displayhook_factory = import_item(str(self.displayhook_class))
self.displayhook = displayhook_factory(self.session, self.iopub_socket)
sys.displayhook = self.displayhook
self.patch_io()
def patch_io(self):
"""Patch important libraries that can't handle sys.stdout forwarding"""
try:
import faulthandler
except ImportError:
pass
else:
# Warning: this is a monkeypatch of `faulthandler.enable`, watch for possible
# updates to the upstream API and update accordingly (up-to-date as of Python 3.5):
# https://docs.python.org/3/library/faulthandler.html#faulthandler.enable
# change default file to __stderr__ from forwarded stderr
faulthandler_enable = faulthandler.enable
def enable(file=sys.__stderr__, all_threads=True, **kwargs):
return faulthandler_enable(file=file, all_threads=all_threads, **kwargs)
faulthandler.enable = enable
if hasattr(faulthandler, 'register'):
faulthandler_register = faulthandler.register
def register(signum, file=sys.__stderr__, all_threads=True, chain=False, **kwargs):
return faulthandler_register(signum, file=file, all_threads=all_threads,
chain=chain, **kwargs)
faulthandler.register = register
def init_signal(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
def init_kernel(self):
"""Create the Kernel object itself"""
shell_stream = ZMQStream(self.shell_socket)
control_stream = ZMQStream(self.control_socket)
kernel_factory = self.kernel_class.instance
kernel = kernel_factory(parent=self, session=self.session,
shell_streams=[shell_stream, control_stream],
iopub_thread=self.iopub_thread,
iopub_socket=self.iopub_socket,
stdin_socket=self.stdin_socket,
log=self.log,
profile_dir=self.profile_dir,
user_ns=self.user_ns,
)
kernel.record_ports({
name + '_port': port for name, port in self.ports.items()
})
self.kernel = kernel
# Allow the displayhook to get the execution count
self.displayhook.get_execution_count = lambda: kernel.execution_count
def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
# Register inline backend as default
# this is higher priority than matplotlibrc,
# but lower priority than anything else (mpl.use() for instance).
# This only affects matplotlib >= 1.5
if not os.environ.get('MPLBACKEND'):
os.environ['MPLBACKEND'] = 'module://ipykernel.pylab.backend_inline'
# Provide a wrapper for :meth:`YAPInteractiveShellApp.init_gui_pylab`
# to ensure that any exception is printed straight to stderr.
# Normally _showtraceback associates the reply with an execution,
# which means frontends will never draw it, as this exception
# is not associated with any execute request.
shell = self.shell
_showtraceback = shell._showtraceback
try:
# replace error-sending traceback with stderr
def print_tb(etype, evalue, stb):
print ("GUI event loop or pylab initialization failed",
file=sys.stderr)
print (shell.InteractiveTB.stb2text(stb), file=sys.stderr)
shell._showtraceback = print_tb
InteractiveShellApp.init_gui_pylab(self)
finally:
shell._showtraceback = _showtraceback
def init_shell(self):
self.shell = getattr(self.kernel, 'shell', None)
if self.shell:
self.shell.configurables.append(self)
def init_extensions(self):
super(YAPKernelApp, self).init_extensions()
# BEGIN HARDCODED WIDGETS HACK
# Ensure ipywidgets extension is loaded if available
extension_man = self.shell.extension_manager
if 'ipywidgets' not in extension_man.loaded:
try:
extension_man.load_extension('ipywidgets')
except ImportError as e:
self.log.debug('ipywidgets package not installed. Widgets will not be available.')
# END HARDCODED WIDGETS HACK
def configure_tornado_logger(self):
""" Configure the tornado logging.Logger.
Must set up the tornado logger or else tornado will call
basicConfig for the root logger which makes the root logger
go to the real sys.stderr instead of the capture streams.
This function mimics the setup of logging.basicConfig.
"""
logger = logging.getLogger('tornado')
handler = logging.StreamHandler()
formatter = logging.Formatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
logger.addHandler(handler)
@catch_config_error
def initialize(self, argv=None):
super(YAPKernelApp, self).initialize(argv)
if self.subapp is not None:
return
# register zmq IOLoop with tornado
zmq_ioloop.install()
self.init_blackhole()
self.init_connection_file()
self.init_poller()
self.init_sockets()
self.init_heartbeat()
# writing/displaying connection info must be *after* init_sockets/heartbeat
self.write_connection_file()
# Log connection info after writing connection file, so that the connection
# file is definitely available at the time someone reads the log.
self.log_connection_info()
self.init_io()
self.init_signal()
self.init_kernel()
# shell init steps
self.init_path()
self.init_shell()
if self.shell:
self.init_gui_pylab()
self.init_extensions()
self.init_code()
# flush stdout/stderr, so that anything written to these streams during
# initialization do not get associated with the first execution request
sys.stdout.flush()
sys.stderr.flush()
def start(self):
if self.subapp is not None:
return self.subapp.start()
if self.poller is not None:
self.poller.start()
self.kernel.start()
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
pass
launch_new_instance = YAPKernelApp.launch_instance
def main():
"""Run an YAPKernel as an application"""
app = YAPKernelApp.instance()
app.initialize()
app.start()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,490 @@
"""An Application for launching a kernel"""
# Copyright (c) YAP Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import atexit
import os
import sys
import signal
import traceback
import logging
from tornado import ioloop
import zmq
from zmq.eventloop import ioloop as zmq_ioloop
from zmq.eventloop.zmqstream import ZMQStream
from IPython.core.application import (
BaseIPythonApplication, base_flags, base_aliases, catch_config_error
)
from IPython.core.profiledir import ProfileDir
from IPython.core.shellapp import (
InteractiveShellApp, shell_flags, shell_aliases
)
from IPython.utils import io
from ipython_genutils.path import filefind, ensure_dir_exists
from traitlets import (
Any, Instance, Dict, Unicode, Integer, Bool, DottedObjectName, Type, default
)
from ipython_genutils.importstring import import_item
from jupyter_core.paths import jupyter_runtime_dir
from jupyter_client import write_connection_file
from jupyter_client.connect import ConnectionFileMixin
# local imports
from ipykernel.iostream import IOPubThread
from ipykernel.heartbeat import Heartbeat
from .yap_kernel import YAPKernel
from ipykernel.parentpoller import ParentPollerUnix, ParentPollerWindows
from jupyter_client.session import (
Session, session_flags, session_aliases,
)
from ipykernel.zmqshell import ZMQInteractiveShell
#-----------------------------------------------------------------------------
# Flags and Aliases
#-----------------------------------------------------------------------------
kernel_aliases = dict(base_aliases)
kernel_aliases.update({
'ip' : 'YAPKernelApp.ip',
'hb' : 'YAPKernelApp.hb_port',
'shell' : 'YAPKernelApp.shell_port',
'iopub' : 'YAPKernelApp.iopub_port',
'stdin' : 'YAPKernelApp.stdin_port',
'control' : 'YAPKernelApp.control_port',
'f' : 'YAPKernelApp.connection_file',
'transport': 'YAPKernelApp.transport',
})
kernel_flags = dict(base_flags)
kernel_flags.update({
'no-stdout' : (
{'YAPKernelApp' : {'no_stdout' : True}},
"redirect stdout to the null device"),
'no-stderr' : (
{'YAPKernelApp' : {'no_stderr' : True}},
"redirect stderr to the null device"),
'pylab' : (
{'YAPKernelApp' : {'pylab' : 'auto'}},
"""Pre-load matplotlib and numpy for interactive use with
the default matplotlib backend."""),
})
# inherit flags&aliases for any IPython shell apps
kernel_aliases.update(shell_aliases)
kernel_flags.update(shell_flags)
# inherit flags&aliases for Sessions
kernel_aliases.update(session_aliases)
kernel_flags.update(session_flags)
_ctrl_c_message = """\
NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
To exit, you will have to explicitly quit this process, by either sending
"quit" from a client, or using Ctrl-\\ in UNIX-like environments.
To read more about this, see https://github.com/ipython/ipython/issues/2049
"""
#-----------------------------------------------------------------------------
# Application class for starting an YAP Kernel
#-----------------------------------------------------------------------------
class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
ConnectionFileMixin):
name='YAP-kernel'
aliases = Dict(kernel_aliases)
flags = Dict(kernel_flags)
classes = [YAPKernel, ZMQInteractiveShell, ProfileDir, Session]
# the kernel class, as an importstring
kernel_class = Type('yap_kernel.yap_kernel.YAPKernel',
klass='ipykernel.kernelbase.Kernel',
help="""The Kernel subclass to be used.
This should allow easy re-use of the YAPKernelApp entry point
to configure and launch kernels other than YAP's own.
""").tag(config=True)
kernel = Any()
poller = Any() # don't restrict this even though current pollers are all Threads
heartbeat = Instance(Heartbeat, allow_none=True)
ports = Dict()
subcommands = {
'install': (
'yap_kernel.kernelspec.InstallYAPKernelSpecApp',
'Install the YAP kernel'
),
}
# connection info:
connection_dir = Unicode()
@default('connection_dir')
def _default_connection_dir(self):
return jupyter_runtime_dir()
@property
def abs_connection_file(self):
if os.path.basename(self.connection_file) == self.connection_file:
return os.path.join(self.connection_dir, self.connection_file)
else:
return self.connection_file
# streams, etc.
no_stdout = Bool(False, help="redirect stdout to the null device").tag(config=True)
no_stderr = Bool(False, help="redirect stderr to the null device").tag(config=True)
outstream_class = DottedObjectName('ipykernel.iostream.OutStream',
help="The importstring for the OutStream factory").tag(config=True)
displayhook_class = DottedObjectName('ipykernel.displayhook.ZMQDisplayHook',
help="The importstring for the DisplayHook factory").tag(config=True)
# polling
parent_handle = Integer(int(os.environ.get('JPY_PARENT_PID') or 0),
help="""kill this process if its parent dies. On Windows, the argument
specifies the HANDLE of the parent process, otherwise it is simply boolean.
""").tag(config=True)
interrupt = Integer(int(os.environ.get('JPY_INTERRUPT_EVENT') or 0),
help="""ONLY USED ON WINDOWS
Interrupt this process when the parent is signaled.
""").tag(config=True)
def init_crash_handler(self):
sys.excepthook = self.excepthook
def excepthook(self, etype, evalue, tb):
# write uncaught traceback to 'real' stderr, not zmq-forwarder
traceback.print_exception(etype, evalue, tb, file=sys.__stderr__)
def init_poller(self):
if sys.platform == 'win32':
if self.interrupt or self.parent_handle:
self.poller = ParentPollerWindows(self.interrupt, self.parent_handle)
elif self.parent_handle:
self.poller = ParentPollerUnix()
def _bind_socket(self, s, port):
iface = '%s://%s' % (self.transport, self.ip)
if self.transport == 'tcp':
if port <= 0:
port = s.bind_to_random_port(iface)
else:
s.bind("tcp://%s:%i" % (self.ip, port))
elif self.transport == 'ipc':
if port <= 0:
port = 1
path = "%s-%i" % (self.ip, port)
while os.path.exists(path):
port = port + 1
path = "%s-%i" % (self.ip, port)
else:
path = "%s-%i" % (self.ip, port)
s.bind("ipc://%s" % path)
return port
def write_connection_file(self):
"""write connection info to JSON file"""
cf = self.abs_connection_file
self.log.debug("Writing connection file: %s", cf)
write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport,
shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port,
iopub_port=self.iopub_port, control_port=self.control_port)
def cleanup_connection_file(self):
cf = self.abs_connection_file
self.log.debug("Cleaning up connection file: %s", cf)
try:
os.remove(cf)
except (IOError, OSError):
pass
self.cleanup_ipc_files()
def init_connection_file(self):
if not self.connection_file:
self.connection_file = "kernel-%s.json"%os.getpid()
try:
self.connection_file = filefind(self.connection_file, ['.', self.connection_dir])
except IOError:
self.log.debug("Connection file not found: %s", self.connection_file)
# This means I own it, and I'll create it in this directory:
ensure_dir_exists(os.path.dirname(self.abs_connection_file), 0o700)
# Also, I will clean it up:
atexit.register(self.cleanup_connection_file)
return
try:
self.load_connection_file()
except Exception:
self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
self.exit(1)
def init_sockets(self):
# Create a context, a session, and the kernel sockets.
self.log.info("Starting the kernel at pid: %i", os.getpid())
context = zmq.Context.instance()
# Uncomment this to try closing the context.
# atexit.register(context.term)
self.shell_socket = context.socket(zmq.ROUTER)
self.shell_socket.linger = 1000
self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port)
self.stdin_socket = context.socket(zmq.ROUTER)
self.stdin_socket.linger = 1000
self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port)
self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port)
self.control_socket = context.socket(zmq.ROUTER)
self.control_socket.linger = 1000
self.control_port = self._bind_socket(self.control_socket, self.control_port)
self.log.debug("control ROUTER Channel on port: %i" % self.control_port)
self.init_iopub(context)
def init_iopub(self, context):
self.iopub_socket = context.socket(zmq.PUB)
self.iopub_socket.linger = 1000
self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port)
self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port)
self.configure_tornado_logger()
self.iopub_thread = IOPubThread(self.iopub_socket, pipe=True)
self.iopub_thread.start()
# backward-compat: wrap iopub socket API in background thread
self.iopub_socket = self.iopub_thread.background_socket
def init_heartbeat(self):
"""start the heart beating"""
# heartbeat doesn't share context, because it mustn't be blocked
# by the GIL, which is accessed by libzmq when freeing zero-copy messages
hb_ctx = zmq.Context()
self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port))
self.hb_port = self.heartbeat.port
self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port)
self.heartbeat.start()
def log_connection_info(self):
"""display connection info, and store ports"""
basename = os.path.basename(self.connection_file)
if basename == self.connection_file or \
os.path.dirname(self.connection_file) == self.connection_dir:
# use shortname
tail = basename
else:
tail = self.connection_file
lines = [
"To connect another client to this kernel, use:",
" --existing %s" % tail,
]
# log connection info
# info-level, so often not shown.
# frontends should use the %connect_info magic
# to see the connection info
for line in lines:
self.log.info(line)
# also raw print to the terminal if no parent_handle (`ipython kernel`)
# unless log-level is CRITICAL (--quiet)
if not self.parent_handle and self.log_level < logging.CRITICAL:
io.rprint(_ctrl_c_message)
for line in lines:
io.rprint(line)
self.ports = dict(shell=self.shell_port, iopub=self.iopub_port,
stdin=self.stdin_port, hb=self.hb_port,
control=self.control_port)
def init_blackhole(self):
"""redirects stdout/stderr to devnull if necessary"""
if self.no_stdout or self.no_stderr:
blackhole = open(os.devnull, 'w')
if self.no_stdout:
sys.stdout = sys.__stdout__ = blackhole
if self.no_stderr:
sys.stderr = sys.__stderr__ = blackhole
def init_io(self):
"""Redirect input streams and set a display hook."""
if self.outstream_class:
outstream_factory = import_item(str(self.outstream_class))
sys.stdout = outstream_factory(self.session, self.iopub_thread, u'stdout')
sys.stderr = outstream_factory(self.session, self.iopub_thread, u'stderr')
if self.displayhook_class:
displayhook_factory = import_item(str(self.displayhook_class))
self.displayhook = displayhook_factory(self.session, self.iopub_socket)
sys.displayhook = self.displayhook
self.patch_io()
def patch_io(self):
"""Patch important libraries that can't handle sys.stdout forwarding"""
try:
import faulthandler
except ImportError:
pass
else:
# Warning: this is a monkeypatch of `faulthandler.enable`, watch for possible
# updates to the upstream API and update accordingly (up-to-date as of Python 3.5):
# https://docs.python.org/3/library/faulthandler.html#faulthandler.enable
# change default file to __stderr__ from forwarded stderr
faulthandler_enable = faulthandler.enable
def enable(file=sys.__stderr__, all_threads=True, **kwargs):
return faulthandler_enable(file=file, all_threads=all_threads, **kwargs)
faulthandler.enable = enable
if hasattr(faulthandler, 'register'):
faulthandler_register = faulthandler.register
def register(signum, file=sys.__stderr__, all_threads=True, chain=False, **kwargs):
return faulthandler_register(signum, file=file, all_threads=all_threads,
chain=chain, **kwargs)
faulthandler.register = register
def init_signal(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
def init_kernel(self):
"""Create the Kernel object itself"""
shell_stream = ZMQStream(self.shell_socket)
control_stream = ZMQStream(self.control_socket)
kernel_factory = self.kernel_class.instance
kernel = kernel_factory(parent=self, session=self.session,
shell_streams=[shell_stream, control_stream],
iopub_thread=self.iopub_thread,
iopub_socket=self.iopub_socket,
stdin_socket=self.stdin_socket,
log=self.log,
profile_dir=self.profile_dir,
user_ns=self.user_ns,
)
kernel.record_ports({
name + '_port': port for name, port in self.ports.items()
})
self.kernel = kernel
# Allow the displayhook to get the execution count
self.displayhook.get_execution_count = lambda: kernel.execution_count
def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
# Register inline backend as default
# this is higher priority than matplotlibrc,
# but lower priority than anything else (mpl.use() for instance).
# This only affects matplotlib >= 1.5
if not os.environ.get('MPLBACKEND'):
os.environ['MPLBACKEND'] = 'module://ipykernel.pylab.backend_inline'
# Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
# to ensure that any exception is printed straight to stderr.
# Normally _showtraceback associates the reply with an execution,
# which means frontends will never draw it, as this exception
# is not associated with any execute request.
shell = self.shell
_showtraceback = shell._showtraceback
try:
# replace error-sending traceback with stderr
def print_tb(etype, evalue, stb):
print ("GUI event loop or pylab initialization failed",
file=sys.stderr)
print (shell.InteractiveTB.stb2text(stb), file=sys.stderr)
shell._showtraceback = print_tb
InteractiveShellApp.init_gui_pylab(self)
finally:
shell._showtraceback = _showtraceback
def init_shell(self):
self.shell = getattr(self.kernel, 'shell', None)
if self.shell:
self.shell.configurables.append(self)
def init_extensions(self):
super(YAPKernelApp, self).init_extensions()
# BEGIN HARDCODED WIDGETS HACK
# Ensure ipywidgets extension is loaded if available
extension_man = self.shell.extension_manager
if 'ipywidgets' not in extension_man.loaded:
try:
extension_man.load_extension('ipywidgets')
except ImportError as e:
self.log.debug('ipywidgets package not installed. Widgets will not be available.')
# END HARDCODED WIDGETS HACK
def configure_tornado_logger(self):
""" Configure the tornado logging.Logger.
Must set up the tornado logger or else tornado will call
basicConfig for the root logger which makes the root logger
go to the real sys.stderr instead of the capture streams.
This function mimics the setup of logging.basicConfig.
"""
logger = logging.getLogger('tornado')
handler = logging.StreamHandler()
formatter = logging.Formatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
logger.addHandler(handler)
@catch_config_error
def initialize(self, argv=None):
super(YAPKernelApp, self).initialize(argv)
if self.subapp is not None:
return
# register zmq IOLoop with tornado
zmq_ioloop.install()
self.init_blackhole()
self.init_connection_file()
self.init_poller()
self.init_sockets()
self.init_heartbeat()
# writing/displaying connection info must be *after* init_sockets/heartbeat
self.write_connection_file()
# Log connection info after writing connection file, so that the connection
# file is definitely available at the time someone reads the log.
self.log_connection_info()
self.init_io()
self.init_signal()
self.init_kernel()
# shell init steps
self.init_path()
self.init_shell()
if self.shell:
self.init_gui_pylab()
self.init_extensions()
self.init_code()
# flush stdout/stderr, so that anything written to these streams during
# initialization do not get associated with the first execution request
sys.stdout.flush()
sys.stderr.flush()
def start(self):
if self.subapp is not None:
return self.subapp.start()
if self.poller is not None:
self.poller.start()
self.kernel.start()
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
pass
launch_new_instance = YAPKernelApp.launch_instance
def main():
"""Run an IPKernel as an application"""
app = YAPKernelApp.instance()
app.initialize()
app.start()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,82 @@
#!/usr/bin/env python
# coding: utf-8
# 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
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
from glob import glob
from distutils.core import setup
packages = ["${CMAKE_CURRENT_SOURCE_DIR}"]
version_ns = {}
setup_args = dict(
name = 'yap_kernel',
version = '0.0.1',
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'],
data_files=[('share/Yap/js', ['${CMAKE_SOURCE_DIR}/misc/editors/prolog.js'])],
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)
if __name__ == '__main__':
setup(**setup_args)

View File

@@ -0,0 +1,109 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 18:17:15 2014
@author: takluyver
"""
import sys
PY3 = (sys.version_info[0] >= 3)
try:
from inspect import signature, Parameter # Python >= 3.3
except ImportError:
from ._signatures import signature, Parameter
if PY3:
from functools import wraps
else:
from functools import wraps as _wraps
def wraps(f):
def dec(func):
_wraps(f)(func)
func.__wrapped__ = f
return func
return dec
def callback_prototype(prototype):
"""Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
which can be used to prepare third party callbacks.
"""
protosig = signature(prototype)
positional, keyword = [], []
for name, param in protosig.parameters.items():
if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
raise TypeError("*args/**kwargs not supported in prototypes")
if (param.default is not Parameter.empty) \
or (param.kind == Parameter.KEYWORD_ONLY):
keyword.append(name)
else:
positional.append(name)
kwargs = dict.fromkeys(keyword)
def adapt(callback):
"""Introspect and prepare a third party callback."""
sig = signature(callback)
try:
# XXX: callback can have extra optional parameters - OK?
sig.bind(*positional, **kwargs)
return callback
except TypeError:
pass
# Match up arguments
unmatched_pos = positional[:]
unmatched_kw = kwargs.copy()
unrecognised = []
# TODO: unrecognised parameters with default values - OK?
for name, param in sig.parameters.items():
# print(name, param.kind) #DBG
if param.kind == Parameter.POSITIONAL_ONLY:
if len(unmatched_pos) > 0:
unmatched_pos.pop(0)
else:
unrecognised.append(name)
elif param.kind == Parameter.POSITIONAL_OR_KEYWORD:
if (param.default is not Parameter.empty) and (name in unmatched_kw):
unmatched_kw.pop(name)
elif len(unmatched_pos) > 0:
unmatched_pos.pop(0)
else:
unrecognised.append(name)
elif param.kind == Parameter.VAR_POSITIONAL:
unmatched_pos = []
elif param.kind == Parameter.KEYWORD_ONLY:
if name in unmatched_kw:
unmatched_kw.pop(name)
else:
unrecognised.append(name)
else: # VAR_KEYWORD
unmatched_kw = {}
# print(unmatched_pos, unmatched_kw, unrecognised) #DBG
if unrecognised:
raise TypeError("Function {!r} had unmatched arguments: {}".format(callback, unrecognised))
n_positional = len(positional) - len(unmatched_pos)
@wraps(callback)
def adapted(*args, **kwargs):
"""Wrapper for third party callbacks that discards excess arguments"""
# print(args, kwargs)
args = args[:n_positional]
for name in unmatched_kw:
# XXX: Could name not be in kwargs?
kwargs.pop(name)
# print(args, kwargs, unmatched_pos, cut_positional, unmatched_kw)
return callback(*args, **kwargs)
return adapted
prototype.adapt = adapt
return prototype

View File

@@ -13,7 +13,7 @@ events and the arguments which will be passed to them.
This API is experimental in yap_ipython 2.0, and may be revised in future versions.
"""
from backcall import callback_prototype
from yap_ipython.core.backcall import callback_prototype
class EventManager(object):

View File

@@ -1,4 +1,4 @@
from backcall import callback_prototype
from yap_ipython.core.backcall import callback_prototype
import unittest
from unittest.mock import Mock
import nose.tools as nt

View File

@@ -0,0 +1,258 @@
/**
* @file jupyter.yap
*
* @brief allow interaction between Jupyter and YAP.
*
* @long The code in here:
* - establishes communication between Prolog and Python Streams
* - inputs Prolog code and queries
* - supports completion of Prolog programs.
* -
*/
%% :- module( jupyter,
%% [jupyter_query/3,
%% errors/2,
%% ready/2,
%% completion/2,
%% ]
%% ).
:- reexport(library(yapi)).
:- use_module(library(lists)).
:- use_module(library(maplist)).
:- use_module(library(python)).
:- python_import(sys).
jupyter_query(Self, Cell, Line ) :-
setup_call_cleanup(
enter_cell(Self),
jupyter_cell(Self, Cell, Line),
exit_cell(Self)
).
jupyter_cell(_Self, Cell, _) :-
jupyter_consult(Cell),
fail.
jupyter_cell( _Self, _, Line ) :-
blank( Line ),
!.
jupyter_cell( _Self, _, [] ) :- !.
jupyter_cell( Self, _, Line ) :-
python_query( Self, Line ).
jupyter_consult(Text) :-
blank( Text ),
!.
jupyter_consult(Cell) :-
open_mem_read_stream( Cell, Stream),
load_files(user:'jupyter cell',[stream(Stream)]).
%should load_files close?
blank(Text) :-
atom_codes(Text, L),
maplist( blankc, L).
blankc(' ').
blankc('\n').
blankc('\t').
enter_cell(_Self) :-
%open('//python/input', read, _Input, []),
open('//python/sys.stdout', append, _Output, []),
open('//python/sys.stdout', append, _Error, []),
%set_prolog_flag(user_input, _Input),
set_prolog_flag(user_output, _Output),
set_prolog_flag(user_error, _Error).
exit_cell(_Self) :-
%close( user_input),
close( user_output),
close( user_error).
completions(S, Self) :-
open_mem_read_stream(S, St),
scan_to_list(St, Tokens),
close(St),
reverse(Tokens, RTokens),
strip_final_tokens(RTokens, MyTokens),
setof( Completion, complete(MyTokens, Completion), Cs),
Self.matches := Cs.
strip_final_tokens(['EOT'|Ts], Ts) :- !.
strip_final_tokens( Ts, Ts ).
complete([E,l,C,l,A|More],
isconsult(A),
%B = l,
library(C,Lib),
%D=l,
E=atom(Prefix),
\+ arg( Rest ),
check_library( Prefix, Lib, C).
complete([E,l,C,l,-,'['|More],
isconsult(A),
%B = l,
library(C,Lib),
%D=l,
E=atom(Prefix),
\+ arg( Rest ),
check_library( Prefix, Lib, C).
complete([C,l,A|More],
isconsult(A),
%B = l,
C=atom(Prefix),
\+ arg( Rest ),
file_or_library( Prefix, C).
complete([C,l,-,'['|More],
isconsult(A),
%B = l,
C=atom(Prefix),
\+ arg( Rest ),
file_or_library( Prefix, C).
complete( [atom(F)|Rest], C) :-
\+ arg( Rest ),
predicate( F, Pred, Arity ),
cont( Arity, F, Pred, C).
isconsult( atom(use_module) ).
isconsult( atom(ensure_loaded) ).
isconsult( atom(compile) ).
isconsult( atom(consult) ).
isconsult( atom(reconsult) ).
isconsult( atom(load_files) ).
isconsult( '[' ).
arg([']'|_]).
arg([l|_]).
file_or_library(F,C) :-
libsym(C0),
atom_cooncat(F,C,C0).
file_or_library(F,C) :-
check_file(F,C).
check_file(F0,C) :-
atom_concat('\'',F,F0),
!,
absolute_file_name( F, FF, [access(none)] ),
atom_concat( FF, '*' , Pat),
absolute_file_name( Pat, C0, [glob(true)] ),
atom_concat(Pat,C00,C0),
atom_conct(C00,'\'',C).
check_file(F0,C) :-
atom_concat( F0, '*' , Pat),
absolute_file_name( Pat, C0, [glob(true)] ),
atom_concat(Pat,C,C0).
check_library( Lib, F, C) :-
atom_concat( F, '*' , Pat),
LibF =.. [Lib(Pat)],
absolute_file_name( LibF, Lib, [glob(true)] ),
file_directory_name( Lib, Name),
( atom_concat(C, '.yap', Name) -> true ;
atom_concat(C, '.ypp', Name) -> true ;
atom_concat(C, '.prolog', Name) -> true
).
predicate(N,P,A) :-
system_predicate(P0/A),
atom_concat(N,P,P0).
predicate(N,P,A) :-
current_predicate(P0/A),
atom_concat(N,P,P0).
cont(0, F, P, P0) :-
atom_concat( F, P, P0 ).
cont( _, F, P, PB ):-
atom_concat( [F, P, '('], PB ).
ready(_Self, Line ) :-
blank( Line ),
!.
ready(Self, Line ) :-
errors( Self, Line ),
\+ syntax_error(_,_).
errors( Self, Text ) :-
setup_call_cleanup(
open_events( Self, Text, Stream),
clauses(Self, Stream),
close_events( Self )
).
clauses(Self, Stream) :-
repeat,
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
command( Self, Cl ),
Cl == end_of_file,
!.
command(_, end_of_file) :- !.
command( _Self, ( :- op(Prio,Assoc,Name) ) ) :-
addop(Prio,Assoc,Name).
command( _Self, ( :- module(Name, Exports) )) :-
retract( active_module( M0 ) ),
atom_concat( '__m0_', Name, M ),
assert( active_module(M) ),
assert( undo( active_module(M0) ) ),
maplist( addop2(M), Exports).
addop(Prio,Assoc,Name) :-
(
current_op(OPrio, SimilarAssoc, Name),
op(Prio, Assoc, Name),
matched_op(Assoc, SimilarAssoc)
->
assertz( undo(op( OPrio, Assoc, Name ) ) )
;
assertz( undo(op( 0, Assoc, Name ) ) )
).
addop2(M, op(Prio, Assoc, Name)) :-
addop( Prio, Assoc, M:Name ).
matched_op(A, B) :-
optype( A, T),
optype( B, T).
optype(fx,pre).
optype(fy,pre).
optype(xfx,in).
optype(xfy,in).
optype(yfx,in).
optype(yfy,in).
optype(xf,pos).
optype(yf,pos).
:- dynamic user:portray_message/2.
:- multifile user:portray_message/2.
:- dynamic syntax_error/4, undo/1.
open_events(Self, Text, Stream) :-
Self.errors := [],
open_mem_read_stream( Text, Stream ),
assert((user:portray_message(_Severity, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
assert( syntax_error(Cause,LN,CharPos,Details) )
)).
close_events( _Self ) :-
retract( undo(G) ),
call(G),
fail.
close_events( Self ) :-
retract( syntax_error( C, L, N, A )),
Self.errors := [t(C,L,N,A)] + Self.errors,
fail.
close_events( _ ).

View File

@@ -0,0 +1,161 @@
"""prompt-toolkit utilities
Everything in this module is a private API,
not to be used outside yap_ipython.
"""
# Copyright (c) yap_ipython Development Team.
# Distributed under the terms of the Modified BSD License.
import unicodedata
from wcwidth import wcwidth
from yap_ipython.core.completer import (
provisionalcompleter, cursor_to_position,
_deduplicate_completions)
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.layout.lexers import Lexer
from prompt_toolkit.layout.lexers import PygmentsLexer
import pygments.lexers as pygments_lexers
_completion_sentinel = object()
def _elide(string, *, min_elide=30):
"""
If a string is long enough, and has at least 2 dots,
replace the middle part with ellipses.
If three consecutive dots, or two consecutive dots are encountered these are
replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode
equivalents
"""
string = string.replace('...','\N{HORIZONTAL ELLIPSIS}')
string = string.replace('..','\N{TWO DOT LEADER}')
if len(string) < min_elide:
return string
parts = string.split('.')
if len(parts) <= 3:
return string
return '{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}'.format(parts[0], parts[1][0], parts[-2][-1], parts[-1])
def _adjust_completion_text_based_on_context(text, body, offset):
if text.endswith('=') and len(body) > offset and body[offset] is '=':
return text[:-1]
else:
return text
class IPythonPTCompleter(Completer):
"""Adaptor to provide yap_ipython completions to prompt_toolkit"""
def __init__(self, ipy_completer=None, shell=None, patch_stdout=None):
if shell is None and ipy_completer is None:
raise TypeError("Please pass shell=an InteractiveShell instance.")
self._ipy_completer = ipy_completer
self.shell = shell
if patch_stdout is None:
raise TypeError("Please pass patch_stdout")
self.patch_stdout = patch_stdout
@property
def ipy_completer(self):
if self._ipy_completer:
return self._ipy_completer
else:
return self.shell.Completer
def get_completions(self, document, complete_event):
if not document.current_line.strip():
return
# Some bits of our completion system may print stuff (e.g. if a module
# is imported). This context manager ensures that doesn't interfere with
# the prompt.
with self.patch_stdout(), provisionalcompleter():
body = document.text
cursor_row = document.cursor_position_row
cursor_col = document.cursor_position_col
cursor_position = document.cursor_position
offset = cursor_to_position(body, cursor_row, cursor_col)
yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
@staticmethod
def _get_completions(body, offset, cursor_position, ipyc):
"""
Private equivalent of get_completions() use only for unit_testing.
"""
debug = getattr(ipyc, 'debug', False)
completions = _deduplicate_completions(
body, ipyc.completions(body, offset))
for c in completions:
if not c.text:
# Guard against completion machinery giving us an empty string.
continue
text = unicodedata.normalize('NFC', c.text)
# When the first character of the completion has a zero length,
# then it's probably a decomposed unicode character. E.g. caused by
# the "\dot" completion. Try to compose again with the previous
# character.
if wcwidth(text[0]) == 0:
if cursor_position + c.start > 0:
char_before = body[c.start - 1]
fixed_text = unicodedata.normalize(
'NFC', char_before + text)
# Yield the modified completion instead, if this worked.
if wcwidth(text[0:1]) == 1:
yield Completion(fixed_text, start_position=c.start - offset - 1)
continue
# TODO: Use Jedi to determine meta_text
# (Jedi currently has a bug that results in incorrect information.)
# meta_text = ''
# yield Completion(m, start_position=start_pos,
# display_meta=meta_text)
display_text = c.text
adjusted_text = _adjust_completion_text_based_on_context(c.text, body, offset)
if c.type == 'function':
yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text+'()'), display_meta=c.type+c.signature)
else:
yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text), display_meta=c.type)
class IPythonPTLexer(Lexer):
"""
Wrapper around PythonLexer and BashLexer.
"""
def __init__(self):
l = pygments_lexers
self.python_lexer = PygmentsLexer(l.Python3Lexer)
self.shell_lexer = PygmentsLexer(l.BashLexer)
self.magic_lexers = {
'HTML': PygmentsLexer(l.HtmlLexer),
'html': PygmentsLexer(l.HtmlLexer),
'javascript': PygmentsLexer(l.JavascriptLexer),
'js': PygmentsLexer(l.JavascriptLexer),
'perl': PygmentsLexer(l.PerlLexer),
'ruby': PygmentsLexer(l.RubyLexer),
'latex': PygmentsLexer(l.TexLexer),
'prolog': PygmentsLexer(l.PrologLexer),
}
def lex_document(self, cli, document):
text = document.text.lstrip()
lexer = self.python_lexer
if text.startswith('!') or text.startswith('%%bash'):
lexer = self.shell_lexer
elif text.startswith('%%'):
for magic, l in self.magic_lexers.items():
if text.startswith('%%' + magic):
lexer = l
break
return lexer.lex_document(cli, document)

View File

@@ -562,7 +562,7 @@ class YAPRun:
self.os = None
sys.stderr.writeln('Done, with', self.bindings)
return True,self.bindings
if self.bindings:
if found:
sys.stderr.write('Done, with', self.bindings, '\n')
else:
self.query.close()
@@ -571,8 +571,9 @@ class YAPRun:
sys.stderr.write('Fail\n')
return True,{}
except Exception as e:
sys.stderr.write('Exception after', self.bindings, '\n')
has_raised = True
self.result.result = False
return False,{}
def _yrun_cell(self, raw_cell, store_history=True, silent=False,

View File

@@ -0,0 +1,21 @@
Metadata-Version: 1.1
Name: yap-kernel
Version: 6.3.4.dev0
Summary: YAP Kernel for Jupyter
Home-page: http://ipython.org
Author: YAP Development Team
Author-email: YAP-dev@scipy.org
License: BSD
Description-Content-Type: UNKNOWN
Description: UNKNOWN
Keywords: Interactive,Interpreter,Shell,Web
Platform: Linux
Platform: Mac OS X
Platform: Windows
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Prolog
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3

View File

@@ -0,0 +1,271 @@
MANIFEST.in
README.md
setup.cfg
setup.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel_launcher.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/core/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/core/yap_kernel/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/core/yap_kernel/getipython.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/__main__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/config.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/consoleapp.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/display.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/frontend.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/html.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/nbconvert.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/nbformat.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/parallel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/paths.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/qt.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/yapi.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/core/getipython.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/core/interactiveshell.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/core/oinspect.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/core/pylabtools.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/core/release.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/core/shellapp.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/autoreload.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/cythonmagic.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/rmagic.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/storemagic.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/sympyprinting.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/tests/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/tests/test_autoreload.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/extensions/tests/test_storemagic.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/mathjax.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/qt_for_kernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/qt_loaders.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/decorators/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/decorators/_decorators.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/external/decorators/_numpy_testing_noseclasses.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/__main__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/adapter.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/channels.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/channelsabc.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/client.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/clientabc.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/connect.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/kernelspec.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/kernelspecapp.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/launcher.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/manager.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/managerabc.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/multikernelmanager.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/restarter.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/kernel/threaded.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/backgroundjobs.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/clipboard.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/deepreload.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/demo.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/display.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/editorhooks.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/guisupport.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhook.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhookglut.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhookgtk.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhookgtk3.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhookpyglet.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhookqt4.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/inputhookwx.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/kernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/latextools.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/lexers.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/pretty.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/security.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_backgroundjobs.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_clipboard.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_deepreload.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_display.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_editorhooks.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_imports.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_latextools.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_lexers.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_pretty.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/lib/tests/test_security.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/sphinxext/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/sphinxext/custom_doctests.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/sphinxext/ipython_console_highlighting.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/sphinxext/ipython_directive.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/console.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/debugger.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/embed.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/interactiveshell.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/ipapp.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/magics.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/prompts.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/ptshell.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/ptutils.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/shortcuts.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/glut.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/gtk.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/gtk3.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/osx.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/pyglet.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/qt.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/tk.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/pt_inputhooks/wx.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/tests/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/tests/test_embed.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/tests/test_help.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/terminal/tests/test_interactivshell.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/__main__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/decorators.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/globalipapp.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/iptest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/iptestcontroller.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/ipunittest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/skipdoctest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/tools.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/dtexample.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/ipdoctest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/iptest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/setup.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/show_refs.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/simple.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/simplevars.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/test_ipdoctest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/plugin/test_refs.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/tests/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/tests/test_decorators.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/tests/test_ipunittest.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/testing/tests/test_tools.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/PyColorize.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/_process_cli.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/_process_common.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/_process_posix.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/_process_win32.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/_process_win32_controller.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/_sysinfo.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/capture.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/colorable.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/coloransi.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/contexts.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/daemonize.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/data.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/decorators.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/dir2.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/encoding.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/eventful.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/frame.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/generics.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/importstring.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/io.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/ipstruct.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/jsonutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/localinterfaces.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/log.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/module_paths.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/openpy.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/path.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/pickleutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/process.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/py3compat.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/sentinel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/shimmodule.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/signatures.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/strdispatch.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/sysinfo.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/syspathcontext.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tempdir.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/terminal.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/text.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/timing.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tokenize2.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tokenutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/traitlets.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tz.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/ulinecache.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/version.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/wildcard.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_capture.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_decorators.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_dir2.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_imports.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_importstring.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_io.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_module_paths.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_openpy.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_path.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_process.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_pycolorize.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_shimmodule.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_sysinfo.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_tempdir.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_text.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_tokenutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_ipython/utils/tests/test_wildcard.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/__main__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/_eventloop_macos.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/_version.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/codeutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/connect.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/datapub.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/displayhook.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/embed.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/eventloops.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/heartbeat.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/iostream.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/ipkernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/jsonutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/kernelapp.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/kernelbase.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/kernelspec.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/log.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/parentpoller.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/pickleutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/serialize.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/zmqshell.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel.egg-info/PKG-INFO
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel.egg-info/SOURCES.txt
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel.egg-info/dependency_links.txt
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel.egg-info/requires.txt
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel.egg-info/top_level.txt
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/comm/comm.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/comm/manager.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/gui/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/gui/gtk3embed.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/gui/gtkembed.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/blocking.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/channels.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/client.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/ipkernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/manager.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/socket.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/tests/test_kernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/inprocess/tests/test_kernelmanager.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/pylab/backend_inline.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/pylab/config.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/resources/logo-32x32.png
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/resources/logo-64x64.png
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/__init__.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/_asyncio.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_connect.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_embed_kernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_eventloop.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_io.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_jsonutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_kernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_kernelspec.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_message_spec.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_pickleutil.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_serialize.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_start_kernel.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/test_zmq_shell.py
/home/vsc/github/yap-6.3/packages/python/yap_kernel/yap_kernel/tests/utils.py
yap_kernel/resources/kernel.js
yap_kernel/resources/logo-32x32.png
yap_kernel/resources/logo-64x64.png

View File

@@ -0,0 +1,7 @@
[test]
nose_warnings_filters
nose-timer
[test:python_version=="2.7"]
mock

View File

@@ -0,0 +1,4 @@
core
yap_ipython
yap_kernel
yap_kernel_launcher

View File

@@ -0,0 +1,417 @@
from __future__ import print_function
import signal
import yap
import io
import getpass
import sys
import traceback
from IPython.core import release
from ipython_genutils.py3compat import builtin_mod, PY3, unicode_type, safe_unicode
from IPython.utils.tokenutil import token_at_cursor, line_at_cursor
from traitlets import Instance, Type, Any, List
from ipykernel.comm import CommManager
from ipykernel.kernelbase import Kernel as KernelBase
from ipykernel.zmqshell import ZMQInteractiveShell
from .interactiveshell import YAPInteractiveShell
from IPython.core.interactiveshell import InteractiveShellABC, InteractiveShell
from contextlib import redirect_stdout
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):
print(*args, file=sys.stderr, **kwargs)
class YAPKernel(KernelBase):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
allow_none=True)
shell_class = Type(ZMQInteractiveShell )
user_ns = Instance(dict, args=None, allow_none=True)
def _user_ns_changed(self, name, old, new):
if self.shell is not None:
self.shell.user_ns = new
self.shell.init_user_ns()
# A reference to the Python builtin 'raw_input' function.
# (i.e., __builtin__.raw_input for Python 2.7, builtins.input for Python 3)
_sys_raw_input = Any()
_sys_eval_input = Any()
implementation = 'YAP Kernel'
implementation_version = '1.0'
language = 'text'
language_version = '6.3'
banner = "YAP-6.3"
language_info = {
'mimetype': 'text/prolog',
'name': 'text',
# ------ If different from 'language':
'codemirror_mode': {
"version": 2,
"name": "prolog"
},
'pygments_lexer': 'prolog',
'version': "0.0.1",
'file_extension': '.yap',
}
#-------------------------------------------------------------------------
# Things related to history management
#-------------------------------------------------------------------------
def __init__(self, **kwargs):
# sp = super(YAPKernel, self)
super(YAPKernel, self).__init__(**kwargs)
# Initialize the InteractiveShell subclass
self.shell = self.shell_class.instance(parent=self,
profile_dir = self.profile_dir,
user_ns = self.user_ns,
kernel = self,
)
self.shell.displayhook.session = self.session
self.shell.displayhook.pub_socket = self.iopub_socket
self.shell.displayhook.topic = self._topic('execute_result')
self.shell.display_pub.session = self.session
self.shell.display_pub.pub_socket = self.iopub_socket
self.comm_manager = CommManager(parent=self, kernel=self)
# self.shell._last_traceback = None
self.shell.configurables.append(self.comm_manager)
comm_msg_types = [ 'comm_open', 'comm_msg', 'comm_close' ]
for msg_type in comm_msg_types:
self.shell_handlers[msg_type] = getattr(self.comm_manager, msg_type)
self.yap_shell = YAPInteractiveShell( self )
def get_usage(self):
return "This is the YAP kernel."
help_links = List([
{
'text': "Python",
'url': "http://docs.python.org/%i.%i" % sys.version_info[:2],
},
{
'text': "YAP",
'url': "http://YAP.org/documentation.html",
},
{
'text': "NumPy",
'url': "http://docs.scipy.org/doc/numpy/reference/",
},
{
'text': "SciPy",
'url': "http://docs.scipy.org/doc/scipy/reference/",
},
{
'text': "Matplotlib",
'url': "http://matplotlib.org/contents.html",
},
{
'text': "SymPy",
'url': "http://docs.sympy.org/latest/index.html",
},
{
'text': "pandas",
'url': "http://pandas.pydata.org/pandas-docs/stable/",
},
]).tag(config=True)
# Kernel info fields
implementation = 'YAP'
implementation_version = release.version
language_info = {
'name': 'python',
'version': sys.version.split()[0],
'mimetype': 'text/x-python',
'codemirror_mode': {
'name': 'prolog',
'version': sys.version_info[0]
},
'pygments_lexer': 'prolog',
'nbconvert_exporter': 'python',
'file_extension': '.yap'
}
@property
def banner(self):
return self.shell.banner
def start(self):
self.shell.exit_now = False
super(YAPKernel, self).start()
def set_parent(self, ident, parent):
"""Overridden from parent to tell the display hook and output streams
about the parent message.
"""
super(YAPKernel, self).set_parent(ident, parent)
self.shell.set_parent(parent)
def init_metadata(self, parent):
"""Initialize metadata.
Run at the beginning of each execution request.
"""
md = super(YAPKernel, self).init_metadata(parent)
# FIXME: remove deprecated ipyparallel-specific code
# This is required for ipyparallel < 5.0
md.update({
'dependencies_met' : True,
'engine' : self.ident,
})
return md
def finish_metadata(self, parent, metadata, reply_content):
"""Finish populating metadata.
Run after completing an execution request.
"""
# FIXME: remove deprecated ipyparallel-specific code
# This is required by ipyparallel < 5.0
metadata['status'] = reply_content['status']
if reply_content['status'] == 'error' and reply_content['ename'] == 'UnmetDependency':
metadata['dependencies_met'] = False
return metadata
def _forward_input(self, allow_stdin=False):
"""Forward raw_input and getpass to the current frontend.
via input_request
"""
self._allow_stdin = allow_stdin
if PY3:
self._sys_raw_input = builtin_mod.input
builtin_mod.input = self.raw_input
else:
self._sys_raw_input = builtin_mod.raw_input
self._sys_eval_input = builtin_mod.input
builtin_mod.raw_input = self.raw_input
builtin_mod.input = lambda prompt='': eval(self.raw_input(prompt))
self._save_getpass = getpass.getpass
getpass.getpass = self.getpass
def _restore_input(self):
"""Restore raw_input, getpass"""
if PY3:
builtin_mod.input = self._sys_raw_input
else:
builtin_mod.raw_input = self._sys_raw_input
builtin_mod.input = self._sys_eval_input
getpass.getpass = self._save_getpass
@property
def execution_count(self):
return self.shell.execution_count
@execution_count.setter
def execution_count(self, value):
# Ignore the incrememnting done by KernelBase, in favour of our shell's
# execution counter.
pass
def do_execute(self, code, silent, store_history=True,
user_expressions=None, allow_stdin=False):
shell = self.shell # we'll need this a lot here
self._forward_input(allow_stdin)
reply_content = {}
try:
res = shell.run_cell(code, store_history=store_history, silent=silent)
finally:
self._restore_input()
if res.error_before_exec is not None:
err = res.error_before_exec
else:
err = res.error_in_exec
if res.success:
reply_content[u'status'] = u'ok'
elif isinstance(err, KeyboardInterrupt):
reply_content[u'status'] = u'aborted'
else:
reply_content[u'status'] = u'error'
reply_content.update({
# u'traceback': shell._last_traceback or [],
u'ename': unicode_type(type(err).__name__),
u'evalue': safe_unicode(err),
})
# FIXME: deprecate piece for ipyparallel:
e_info = dict(engine_uuid=self.ident, engine_id=self.int_id,
method='execute')
reply_content['engine_info'] = e_info
# Return the execution counter so clients can display prompts
reply_content['execution_count'] = shell.execution_count - 1
if 'traceback' in reply_content:
self.log.info("Exception in execute request:\n%s", '\n'.join(reply_content['traceback']))
# At this point, we can tell whether the main code execution succeeded
# or not. If it did, we proceed to evaluate user_expressions
if reply_content['status'] == 'ok':
reply_content[u'user_expressions'] = \
shell.user_expressions(user_expressions or {})
else:
# If there was an error, don't even try to compute expressions
reply_content[u'user_expressions'] = {}
# Payloads should be retrieved regardless of outcome, so we can both
# recover partial output (that could have been generated early in a
# block, before an error) and always clear the payload system.
reply_content[u'payload'] = shell.payload_manager.read_payload()
# Be aggressive about clearing the payload because we don't want
# it to sit in memory until the next execute_request comes in.
shell.payload_manager.clear_payload()
return reply_content
def do_complete(self, code, cursor_pos):
# FIXME: YAP completers currently assume single line,
# but completion messages give multi-line context
# For now, extract line from cell, based on cursor_pos:
if cursor_pos is None:
cursor_pos = len(code)
line, offset = line_at_cursor(code, cursor_pos)
line_cursor = cursor_pos - offset
txt, matches = self.shell.complete('', line, line_cursor)
return {'matches' : matches,
'cursor_end' : cursor_pos,
'cursor_start' : cursor_pos - len(txt),
'metadata' : {},
'status' : 'ok'}
def do_inspect(self, code, cursor_pos, detail_level=0):
name = token_at_cursor(code, cursor_pos)
info = self.shell.object_inspect(name)
reply_content = {'status' : 'ok'}
reply_content['data'] = data = {}
reply_content['metadata'] = {}
reply_content['found'] = info['found']
if info['found']:
info_text = self.shell.object_inspect_text(
name,
detail_level=detail_level,
)
data['text/plain'] = info_text
return reply_content
def do_history(self, hist_access_type, output, raw, session=0, start=0,
stop=None, n=None, pattern=None, unique=False):
if hist_access_type == 'tail':
hist = self.shell.history_manager.get_tail(n, raw=raw, output=output,
include_latest=True)
elif hist_access_type == 'range':
hist = self.shell.history_manager.get_range(session, start, stop,
raw=raw, output=output)
elif hist_access_type == 'search':
hist = self.shell.history_manager.search(
pattern, raw=raw, output=output, n=n, unique=unique)
else:
hist = []
return {
'status': 'ok',
'history' : list(hist),
}
def do_shutdown(self, restart):
self.shell.exit_now = True
return dict(status='ok', restart=restart)
def do_is_complete(self, code):
status, indent_spaces = self.shell.input_transformer_manager.check_complete(code)
r = {'status': status}
if status == 'incomplete':
r['indent'] = ' ' * indent_spaces
return r
def do_apply(self, content, bufs, msg_id, reply_metadata):
from .serialize import serialize_object, unpack_apply_message
shell = self.shell
try:
working = shell.user_ns
prefix = "_"+str(msg_id).replace("-","")+"_"
f,args,kwargs = unpack_apply_message(bufs, working, copy=False)
fname = getattr(f, '__name__', 'f')
fname = prefix+"f"
argname = prefix+"args"
kwargname = prefix+"kwargs"
resultname = prefix+"result"
ns = { fname : f, argname : args, kwargname : kwargs , resultname : None }
# print ns
working.update(ns)
code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname)
try:
exec(code, shell.user_global_ns, shell.user_ns)
result = working.get(resultname)
finally:
for key in ns:
working.pop(key)
result_buf = serialize_object(result,
buffer_threshold=self.session.buffer_threshold,
item_threshold=self.session.item_threshold,
)
except BaseException as e:
# invoke YAP traceback formatting
shell.showtraceback()
reply_content = {
u'traceback': shell._last_traceback or [],
u'ename': unicode_type(type(e).__name__),
u'evalue': safe_unicode(e),
}
# FIXME: deprecate piece for ipyparallel:
e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='apply')
reply_content['engine_info'] = e_info
self.send_response(self.iopub_socket, u'error', reply_content,
ident=self._topic('error'))
self.log.info("Exception in apply request:\n%s", '\n'.join(reply_content['traceback']))
result_buf = []
reply_content['status'] = 'error'
else:
reply_content = {'status' : 'ok'}
return reply_content, result_buf
def do_clear(self):
self.shell.reset(False)
return dict(status='ok')

View File

@@ -0,0 +1,10 @@
Metadata-Version: 1.0
Name: yapex
Version: 0.1
Summary: UNKNOWN
Home-page: UNKNOWN
Author: UNKNOWN
Author-email: UNKNOWN
License: UNKNOWN
Description: UNKNOWN
Platform: UNKNOWN

View File

@@ -0,0 +1,11 @@
setup.py
/Users/vsc/Yap/yap-6.3/packages/python/yapex.py
/Users/vsc/Yap/yap-6.3/packages/python/yapex.egg-info/PKG-INFO
/Users/vsc/Yap/yap-6.3/packages/python/yapex.egg-info/SOURCES.txt
/Users/vsc/Yap/yap-6.3/packages/python/yapex.egg-info/dependency_links.txt
/Users/vsc/Yap/yap-6.3/packages/python/yapex.egg-info/top_level.txt
/Users/vsc/github/yap-6.3/packages/python/yapex.py
/Users/vsc/github/yap-6.3/packages/python/yapex.egg-info/PKG-INFO
/Users/vsc/github/yap-6.3/packages/python/yapex.egg-info/SOURCES.txt
/Users/vsc/github/yap-6.3/packages/python/yapex.egg-info/dependency_links.txt
/Users/vsc/github/yap-6.3/packages/python/yapex.egg-info/top_level.txt

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1 @@
yapex

101
packages/python/yapex.py Normal file
View File

@@ -0,0 +1,101 @@
import yap
import sys
# debugging support.
import pdb
def query_prolog(engine, s):
def answer(q):
try:
return q.next()
except Exception as e:
print(e.args[1])
return False
#
#construct a query from a one-line string
# q is opaque to Python
q = engine.query(s)
# vs is the list of variables
# you can print it out, the left-side is the variable name,
# the right side wraps a handle to a variable
vs = q.namedVars()
# atom match either symbols, or if no symbol exists, sttrings, In this case
# variable names should match strings
for eq in vs:
if not isinstance(eq[0],str):
print( "Error: Variable Name matches a Python Symbol")
return
ask = True
# launch the query
while answer(q):
# this new vs should contain bindings to vars
vs= q.namedVars()
#numbervars
i=0
# iteratw
for eq in vs:
name = eq[0]
# this is tricky, we're going to bind the variables in the term so thay we can
# output X=Y. The Python way is to use dictionares.
#Instead, we use the T function to tranform the Python term back to Prolog
binding = yap.T(eq[1])
if binding.isVar():
binding.unify(name)
else:
i = binding.numberVars(i, True)
print(name + " = " + binding.text())
#ok, that was Prolog code
print("yes")
# deterministic = one solution
if q.deterministic():
# done
q.close()
return
if ask:
s = input("more(;), all(*), no(\\n), python(#) ?").lstrip()
if s.startswith(';') or s.startswith('y'):
continue
elif s.startswith('#'):
try:
exec(s.lstrip('#'))
except:
raise
elif s.startswith('*') or s.startswith('a'):
ask = False
continue
else:
break
print("No (more) answers")
q.close()
return
def live():
engine = yap.YAPEngine()
loop = True
pdb.set_trace()
while loop:
try:
s = input("?- ")
if not s:
loop = False
query_prolog(engine, s)
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:
print("Unexpected error:", sys.exc_info()[0])
raise
engine.close()
#
# initialize engine
# engine = yap.YAPEngine();
# engine = yap.YAPEngine(yap.YAPParams());
#live()