<commit_before>#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Copyright 2011-2018, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from io import StringIO
import json
import os
from subprocess import call
from shlex import split as shlex_split
from shutil import rmtree
from sys import argv
from tempfile import mkdtemp

from ipykernel.kernelapp import launch_new_instance
from ipykernel.kernelbase import Kernel
from jupyter_client.kernelspec import KernelSpecManager
from neo4j.exceptions import ServiceUnavailable, CypherError
from traitlets.config import Config

from py2neo.internal.addressing import get_connection_data
from py2neo.database import Graph
from py2neo.meta import __version__ as py2neo_version


ESCAPE = "!"

KERNEL_NAME = "cypher"

BANNER = """\
Py2neo {py2neo_version} Interactive Cypher
Type '!help' for more information.
""".format(py2neo_version=py2neo_version)


def table_to_text_plain(table):
    s = StringIO()
    table.write(file=s, header=True)
    return s.getvalue()


def table_to_text_html(table):
    s = StringIO()
    table.write_html(file=s, header=True)
    return s.getvalue()


class CypherKernel(Kernel):

    implementation = 'py2neo.cypher'
    implementation_version = py2neo_version
    language_info = {
        "name": "cypher",
        "version": "Neo4j/3.4",
        "pygments_lexer": "py2neo.cypher",
        "file_extension": ".cypher",
    }
    banner = BANNER.strip()
    help_links = []

    def __init__(self, **kwargs):
        Kernel.__init__(self, **kwargs)
        self._server = {}
        self._graph = None

    @property
    def graph(self):
        if self._graph is None:
            if not self._server:
                raise NoServerConfigured()
            self._graph = Graph(**self._server)
        return self._graph

    def display(self, data):
        self.send_response(self.iopub_socket, "display_data", content={"data": data})

    def display_server_info(self, silent, **_):
        if silent:
            return
        try:
            product = self.graph.database.product
        except NoServerConfigured:
            self.display({
                "text/plain": "No server configured",
            })
        else:
            self.display({
                "text/plain": "Server  | {}\nProduct | {}".format(self._server["uri"], product)
            })

    def error(self, name, value, traceback=None):
        error_content = {
            "execution_count": self.execution_count,
            "ename": name,
            "evalue": value,
            "traceback": [name + ": " + value] + (traceback or []),
        }
        self.send_response(self.iopub_socket, "error", error_content)
        return dict(error_content, status="error")

    def _execute_server_command(self, *args, **kwargs):
        """ !server <uri>
        """
        if len(args[1:]) > 1:
            return self.error("Too many arguments", self._execute_server_command.__doc__)
        if not args[1:]:
            self.display_server_info(**kwargs)
            return
        self._server = get_connection_data(args[1])
        self._graph = None
        self.display_server_info(**kwargs)

    commands = {
        "server": _execute_server_command,
    }
<commit_msg>A bit of help<commit_after>#!/usr/bin/env python
# -*- encoding: utf-8 -*-

# Copyright 2011-2018, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from io import StringIO
import json
import os
from subprocess import call
from shlex import split as shlex_split
from shutil import rmtree
from sys import argv
from tempfile import mkdtemp

from ipykernel.kernelapp import launch_new_instance
from ipykernel.kernelbase import Kernel
from jupyter_client.kernelspec import KernelSpecManager
from neo4j.exceptions import ServiceUnavailable, CypherError
from traitlets.config import Config

from py2neo.internal.addressing import get_connection_data
from py2neo.database import Graph
from py2neo.meta import __version__ as py2neo_version


ESCAPE = "!"

KERNEL_NAME = "cypher"

BANNER = """\
Py2neo {py2neo_version} Interactive Cypher
Use `!server bolt://user:password@host:port` to configure a server.
Type `!help` for more information or Ctrl+D to exit the console.
""".format(py2neo_version=py2neo_version)


def table_to_text_plain(table):
    s = StringIO()
    table.write(file=s, header=True)
    return s.getvalue()


def table_to_text_html(table):
    s = StringIO()
    table.write_html(file=s, header=True)
    return s.getvalue()


class CypherKernel(Kernel):

    implementation = 'py2neo.cypher'
    implementation_version = py2neo_version
    language_info = {
        "name": "cypher",
        "version": "Neo4j/3.4",
        "pygments_lexer": "py2neo.cypher",
        "file_extension": ".cypher",
    }
    banner = BANNER.strip()
    help_links = []

    def __init__(self, **kwargs):
        Kernel.__init__(self, **kwargs)
        self._server = {}
        self._graph = None

    @property
    def graph(self):
        if self._graph is None:
            if not self._server:
                raise NoServerConfigured()
            self._graph = Graph(**self._server)
        return self._graph

    def display(self, data):
        self.send_response(self.iopub_socket, "display_data", content={"data": data})

    def display_server_info(self, silent, **_):
        if silent:
            return
        try:
            product = self.graph.database.product
        except NoServerConfigured:
            self.display({
                "text/plain": "No server configured",
            })
        else:
            self.display({
                "text/plain": "Server  | {}\nProduct | {}".format(self._server["uri"], product)
            })

    def error(self, name, value, traceback=None):
        error_content = {
            "execution_count": self.execution_count,
            "ename": name,
            "evalue": value,
            "traceback": [name + ": " + value] + (traceback or []),
        }
        self.send_response(self.iopub_socket, "error", error_content)
        return dict(error_content, status="error")

    def _execute_help_command(self, *args, **kwargs):
        """ !help
        """
        lines = []
        for command in self.commands:
            lines.append("!" + command)
        self.display({
            "text/plain": "\n".join(lines),
        })

    def _execute_server_command(self, *args, **kwargs):
        """ !server <uri>
        """
        if len(args[1:]) > 1:
            return self.error("Too many arguments", self._execute_server_command.__doc__)
        if not args[1:]:
            self.display_server_info(**kwargs)
            return
        self._server = get_connection_data(args[1])
        self._graph = None
        self.display_server_info(**kwargs)

    commands = {
        "help": _execute_help_command,
        "server": _execute_server_command,
    }

{'fraction_non_alphanumeric': 0.10650437428680107, 'fraction_numerical': 0.008114618993280082, 'mean_word_length': 2.763358778625954, 'pattern_counts': {'":': 28, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1970017', 'n_tokens_mistral': 2365, 'n_tokens_neox': 2274, 'n_words': 637}