repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Pylons/hupper
src/hupper/worker.py
iter_module_paths
def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filename is not None: abs_filename = os.path.abspath(filename) if os.path.isfile(abs_filename): yield abs_filename
python
def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filename is not None: abs_filename = os.path.abspath(filename) if os.path.isfile(abs_filename): yield abs_filename
[ "def", "iter_module_paths", "(", "modules", "=", "None", ")", ":", "modules", "=", "modules", "or", "list", "(", "sys", ".", "modules", ".", "values", "(", ")", ")", "for", "module", "in", "modules", ":", "try", ":", "filename", "=", "module", ".", "__file__", "except", "(", "AttributeError", ",", "ImportError", ")", ":", "# pragma: no cover", "continue", "if", "filename", "is", "not", "None", ":", "abs_filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "abs_filename", ")", ":", "yield", "abs_filename" ]
Yield paths of all imported modules.
[ "Yield", "paths", "of", "all", "imported", "modules", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L97-L108
train
Pylons/hupper
src/hupper/worker.py
WatchSysModules.update_paths
def update_paths(self): """ Check sys.modules for paths to add to our path set.""" new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
python
def update_paths(self): """ Check sys.modules for paths to add to our path set.""" new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
[ "def", "update_paths", "(", "self", ")", ":", "new_paths", "=", "[", "]", "with", "self", ".", "lock", ":", "for", "path", "in", "expand_source_paths", "(", "iter_module_paths", "(", ")", ")", ":", "if", "path", "not", "in", "self", ".", "paths", ":", "self", ".", "paths", ".", "add", "(", "path", ")", "new_paths", ".", "append", "(", "path", ")", "if", "new_paths", ":", "self", ".", "watch_paths", "(", "new_paths", ")" ]
Check sys.modules for paths to add to our path set.
[ "Check", "sys", ".", "modules", "for", "paths", "to", "add", "to", "our", "path", "set", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L39-L48
train
Pylons/hupper
src/hupper/worker.py
WatchSysModules.search_traceback
def search_traceback(self, tb): """ Inspect a traceback for new paths to add to our path set.""" new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
python
def search_traceback(self, tb): """ Inspect a traceback for new paths to add to our path set.""" new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths)
[ "def", "search_traceback", "(", "self", ",", "tb", ")", ":", "new_paths", "=", "[", "]", "with", "self", ".", "lock", ":", "for", "filename", ",", "line", ",", "funcname", ",", "txt", "in", "traceback", ".", "extract_tb", "(", "tb", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "path", "not", "in", "self", ".", "paths", ":", "self", ".", "paths", ".", "add", "(", "path", ")", "new_paths", ".", "append", "(", "path", ")", "if", "new_paths", ":", "self", ".", "watch_paths", "(", "new_paths", ")" ]
Inspect a traceback for new paths to add to our path set.
[ "Inspect", "a", "traceback", "for", "new", "paths", "to", "add", "to", "our", "path", "set", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/worker.py#L50-L60
train
Pylons/hupper
src/hupper/ipc.py
args_from_interpreter_flags
def args_from_interpreter_flags(): """ Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'optimize': 'O', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag, 0) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
python
def args_from_interpreter_flags(): """ Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'optimize': 'O', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag, 0) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args
[ "def", "args_from_interpreter_flags", "(", ")", ":", "flag_opt_map", "=", "{", "'debug'", ":", "'d'", ",", "'dont_write_bytecode'", ":", "'B'", ",", "'no_user_site'", ":", "'s'", ",", "'no_site'", ":", "'S'", ",", "'ignore_environment'", ":", "'E'", ",", "'verbose'", ":", "'v'", ",", "'bytes_warning'", ":", "'b'", ",", "'quiet'", ":", "'q'", ",", "'optimize'", ":", "'O'", ",", "}", "args", "=", "[", "]", "for", "flag", ",", "opt", "in", "flag_opt_map", ".", "items", "(", ")", ":", "v", "=", "getattr", "(", "sys", ".", "flags", ",", "flag", ",", "0", ")", "if", "v", ">", "0", ":", "args", ".", "append", "(", "'-'", "+", "opt", "*", "v", ")", "for", "opt", "in", "sys", ".", "warnoptions", ":", "args", ".", "append", "(", "'-W'", "+", "opt", ")", "return", "args" ]
Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.
[ "Return", "a", "list", "of", "command", "-", "line", "arguments", "reproducing", "the", "current", "settings", "in", "sys", ".", "flags", "and", "sys", ".", "warnoptions", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/ipc.py#L221-L245
train
Pylons/hupper
src/hupper/ipc.py
spawn
def spawn(spec, kwargs, pass_fds=()): """ Invoke a python function in a subprocess. """ r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) process = subprocess.Popen(args, env=env, close_fds=False) to_child = os.fdopen(w, 'wb') to_child.write(pickle.dumps([preparation_data, spec, kwargs])) to_child.close() return process
python
def spawn(spec, kwargs, pass_fds=()): """ Invoke a python function in a subprocess. """ r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) process = subprocess.Popen(args, env=env, close_fds=False) to_child = os.fdopen(w, 'wb') to_child.write(pickle.dumps([preparation_data, spec, kwargs])) to_child.close() return process
[ "def", "spawn", "(", "spec", ",", "kwargs", ",", "pass_fds", "=", "(", ")", ")", ":", "r", ",", "w", "=", "os", ".", "pipe", "(", ")", "for", "fd", "in", "[", "r", "]", "+", "list", "(", "pass_fds", ")", ":", "set_inheritable", "(", "fd", ",", "True", ")", "preparation_data", "=", "get_preparation_data", "(", ")", "r_handle", "=", "get_handle", "(", "r", ")", "args", ",", "env", "=", "get_command_line", "(", "pipe_handle", "=", "r_handle", ")", "process", "=", "subprocess", ".", "Popen", "(", "args", ",", "env", "=", "env", ",", "close_fds", "=", "False", ")", "to_child", "=", "os", ".", "fdopen", "(", "w", ",", "'wb'", ")", "to_child", ".", "write", "(", "pickle", ".", "dumps", "(", "[", "preparation_data", ",", "spec", ",", "kwargs", "]", ")", ")", "to_child", ".", "close", "(", ")", "return", "process" ]
Invoke a python function in a subprocess.
[ "Invoke", "a", "python", "function", "in", "a", "subprocess", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/ipc.py#L287-L306
train
Pylons/hupper
src/hupper/utils.py
get_watchman_sockpath
def get_watchman_sockpath(binpath='watchman'): """ Find the watchman socket or raise.""" path = os.getenv('WATCHMAN_SOCK') if path: return path cmd = [binpath, '--output-encoding=json', 'get-sockname'] result = subprocess.check_output(cmd) result = json.loads(result) return result['sockname']
python
def get_watchman_sockpath(binpath='watchman'): """ Find the watchman socket or raise.""" path = os.getenv('WATCHMAN_SOCK') if path: return path cmd = [binpath, '--output-encoding=json', 'get-sockname'] result = subprocess.check_output(cmd) result = json.loads(result) return result['sockname']
[ "def", "get_watchman_sockpath", "(", "binpath", "=", "'watchman'", ")", ":", "path", "=", "os", ".", "getenv", "(", "'WATCHMAN_SOCK'", ")", "if", "path", ":", "return", "path", "cmd", "=", "[", "binpath", ",", "'--output-encoding=json'", ",", "'get-sockname'", "]", "result", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "result", "=", "json", ".", "loads", "(", "result", ")", "return", "result", "[", "'sockname'", "]" ]
Find the watchman socket or raise.
[ "Find", "the", "watchman", "socket", "or", "raise", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/utils.py#L49-L58
train
Pylons/hupper
src/hupper/reloader.py
start_reloader
def start_reloader( worker_path, reload_interval=1, shutdown_interval=default, verbose=1, logger=None, monitor_factory=None, worker_args=None, worker_kwargs=None, ignore_files=None, ): """ Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog <https://pypi.org/project/watchdog/>`_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore. """ if is_active(): return get_reloader() if logger is None: logger = DefaultLogger(verbose) if monitor_factory is None: monitor_factory = find_default_monitor_factory(logger) if shutdown_interval is default: shutdown_interval = reload_interval reloader = Reloader( worker_path=worker_path, worker_args=worker_args, worker_kwargs=worker_kwargs, reload_interval=reload_interval, shutdown_interval=shutdown_interval, monitor_factory=monitor_factory, logger=logger, ignore_files=ignore_files, ) return reloader.run()
python
def start_reloader( worker_path, reload_interval=1, shutdown_interval=default, verbose=1, logger=None, monitor_factory=None, worker_args=None, worker_kwargs=None, ignore_files=None, ): """ Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog <https://pypi.org/project/watchdog/>`_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore. """ if is_active(): return get_reloader() if logger is None: logger = DefaultLogger(verbose) if monitor_factory is None: monitor_factory = find_default_monitor_factory(logger) if shutdown_interval is default: shutdown_interval = reload_interval reloader = Reloader( worker_path=worker_path, worker_args=worker_args, worker_kwargs=worker_kwargs, reload_interval=reload_interval, shutdown_interval=shutdown_interval, monitor_factory=monitor_factory, logger=logger, ignore_files=ignore_files, ) return reloader.run()
[ "def", "start_reloader", "(", "worker_path", ",", "reload_interval", "=", "1", ",", "shutdown_interval", "=", "default", ",", "verbose", "=", "1", ",", "logger", "=", "None", ",", "monitor_factory", "=", "None", ",", "worker_args", "=", "None", ",", "worker_kwargs", "=", "None", ",", "ignore_files", "=", "None", ",", ")", ":", "if", "is_active", "(", ")", ":", "return", "get_reloader", "(", ")", "if", "logger", "is", "None", ":", "logger", "=", "DefaultLogger", "(", "verbose", ")", "if", "monitor_factory", "is", "None", ":", "monitor_factory", "=", "find_default_monitor_factory", "(", "logger", ")", "if", "shutdown_interval", "is", "default", ":", "shutdown_interval", "=", "reload_interval", "reloader", "=", "Reloader", "(", "worker_path", "=", "worker_path", ",", "worker_args", "=", "worker_args", ",", "worker_kwargs", "=", "worker_kwargs", ",", "reload_interval", "=", "reload_interval", ",", "shutdown_interval", "=", "shutdown_interval", ",", "monitor_factory", "=", "monitor_factory", ",", "logger", "=", "logger", ",", "ignore_files", "=", "ignore_files", ",", ")", "return", "reloader", ".", "run", "(", ")" ]
Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog <https://pypi.org/project/watchdog/>`_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore.
[ "Start", "a", "monitor", "and", "then", "fork", "a", "worker", "process", "which", "starts", "by", "executing", "the", "importable", "function", "at", "worker_path", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L289-L364
train
Pylons/hupper
src/hupper/reloader.py
Reloader.run
def run(self): """ Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted. """ self._capture_signals() self._start_monitor() try: while True: if not self._run_worker(): self._wait_for_changes() time.sleep(self.reload_interval) except KeyboardInterrupt: pass finally: self._stop_monitor() self._restore_signals() sys.exit(1)
python
def run(self): """ Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted. """ self._capture_signals() self._start_monitor() try: while True: if not self._run_worker(): self._wait_for_changes() time.sleep(self.reload_interval) except KeyboardInterrupt: pass finally: self._stop_monitor() self._restore_signals() sys.exit(1)
[ "def", "run", "(", "self", ")", ":", "self", ".", "_capture_signals", "(", ")", "self", ".", "_start_monitor", "(", ")", "try", ":", "while", "True", ":", "if", "not", "self", ".", "_run_worker", "(", ")", ":", "self", ".", "_wait_for_changes", "(", ")", "time", ".", "sleep", "(", "self", ".", "reload_interval", ")", "except", "KeyboardInterrupt", ":", "pass", "finally", ":", "self", ".", "_stop_monitor", "(", ")", "self", ".", "_restore_signals", "(", ")", "sys", ".", "exit", "(", "1", ")" ]
Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted.
[ "Execute", "the", "reloader", "forever", "blocking", "the", "current", "thread", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L102-L121
train
Pylons/hupper
src/hupper/reloader.py
Reloader.run_once
def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals()
python
def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals()
[ "def", "run_once", "(", "self", ")", ":", "self", ".", "_capture_signals", "(", ")", "self", ".", "_start_monitor", "(", ")", "try", ":", "self", ".", "_run_worker", "(", ")", "except", "KeyboardInterrupt", ":", "return", "finally", ":", "self", ".", "_stop_monitor", "(", ")", "self", ".", "_restore_signals", "(", ")" ]
Execute the worker once. This method will return after a file change is detected.
[ "Execute", "the", "worker", "once", "." ]
197173c09e775b66c148468b6299c571e736c381
https://github.com/Pylons/hupper/blob/197173c09e775b66c148468b6299c571e736c381/src/hupper/reloader.py#L123-L138
train
BYU-PCCL/holodeck
holodeck/holodeckclient.py
HolodeckClient.malloc
def malloc(self, key, shape, dtype): """Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block. Args: key (str): The key to identify the block. shape (list of int): The shape of the numpy array to allocate. dtype (type): The numpy data type (e.g. np.float32). Returns: np.ndarray: The numpy array that is positioned on the shared memory. """ if key not in self._memory or self._memory[key].shape != shape or self._memory[key].dtype != dtype: self._memory[key] = Shmem(key, shape, dtype, self._uuid) return self._memory[key].np_array
python
def malloc(self, key, shape, dtype): """Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block. Args: key (str): The key to identify the block. shape (list of int): The shape of the numpy array to allocate. dtype (type): The numpy data type (e.g. np.float32). Returns: np.ndarray: The numpy array that is positioned on the shared memory. """ if key not in self._memory or self._memory[key].shape != shape or self._memory[key].dtype != dtype: self._memory[key] = Shmem(key, shape, dtype, self._uuid) return self._memory[key].np_array
[ "def", "malloc", "(", "self", ",", "key", ",", "shape", ",", "dtype", ")", ":", "if", "key", "not", "in", "self", ".", "_memory", "or", "self", ".", "_memory", "[", "key", "]", ".", "shape", "!=", "shape", "or", "self", ".", "_memory", "[", "key", "]", ".", "dtype", "!=", "dtype", ":", "self", ".", "_memory", "[", "key", "]", "=", "Shmem", "(", "key", ",", "shape", ",", "dtype", ",", "self", ".", "_uuid", ")", "return", "self", ".", "_memory", "[", "key", "]", ".", "np_array" ]
Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block. Args: key (str): The key to identify the block. shape (list of int): The shape of the numpy array to allocate. dtype (type): The numpy data type (e.g. np.float32). Returns: np.ndarray: The numpy array that is positioned on the shared memory.
[ "Allocates", "a", "block", "of", "shared", "memory", "and", "returns", "a", "numpy", "array", "whose", "data", "corresponds", "with", "that", "block", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/holodeckclient.py#L88-L102
train
BYU-PCCL/holodeck
holodeck/packagemanager.py
package_info
def package_info(pkg_name): """Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information """ indent = " " for config, _ in _iter_packages(): if pkg_name == config["name"]: print("Package:", pkg_name) print(indent, "Platform:", config["platform"]) print(indent, "Version:", config["version"]) print(indent, "Path:", config["path"]) print(indent, "Worlds:") for world in config["maps"]: world_info(world["name"], world_config=world, initial_indent=" ")
python
def package_info(pkg_name): """Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information """ indent = " " for config, _ in _iter_packages(): if pkg_name == config["name"]: print("Package:", pkg_name) print(indent, "Platform:", config["platform"]) print(indent, "Version:", config["version"]) print(indent, "Path:", config["path"]) print(indent, "Worlds:") for world in config["maps"]: world_info(world["name"], world_config=world, initial_indent=" ")
[ "def", "package_info", "(", "pkg_name", ")", ":", "indent", "=", "\" \"", "for", "config", ",", "_", "in", "_iter_packages", "(", ")", ":", "if", "pkg_name", "==", "config", "[", "\"name\"", "]", ":", "print", "(", "\"Package:\"", ",", "pkg_name", ")", "print", "(", "indent", ",", "\"Platform:\"", ",", "config", "[", "\"platform\"", "]", ")", "print", "(", "indent", ",", "\"Version:\"", ",", "config", "[", "\"version\"", "]", ")", "print", "(", "indent", ",", "\"Path:\"", ",", "config", "[", "\"path\"", "]", ")", "print", "(", "indent", ",", "\"Worlds:\"", ")", "for", "world", "in", "config", "[", "\"maps\"", "]", ":", "world_info", "(", "world", "[", "\"name\"", "]", ",", "world_config", "=", "world", ",", "initial_indent", "=", "\" \"", ")" ]
Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information
[ "Prints", "the", "information", "of", "a", "package", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L38-L53
train
BYU-PCCL/holodeck
holodeck/packagemanager.py
world_info
def world_info(world_name, world_config=None, initial_indent="", next_indent=" "): """Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output line. Defaults to "". next_indent (str optional): This indent will be applied within each nested line. Defaults to " ". """ if world_config is None: for config, _ in _iter_packages(): for world in config["maps"]: if world["name"] == world_name: world_config = world if world_config is None: raise HolodeckException("Couldn't find world " + world_name) second_indent = initial_indent + next_indent agent_indent = second_indent + next_indent sensor_indent = agent_indent + next_indent print(initial_indent, world_config["name"]) print(second_indent, "Resolution:", world_config["window_width"], "x", world_config["window_height"]) print(second_indent, "Agents:") for agent in world_config["agents"]: print(agent_indent, "Name:", agent["agent_name"]) print(agent_indent, "Type:", agent["agent_type"]) print(agent_indent, "Sensors:") for sensor in agent["sensors"]: print(sensor_indent, sensor)
python
def world_info(world_name, world_config=None, initial_indent="", next_indent=" "): """Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output line. Defaults to "". next_indent (str optional): This indent will be applied within each nested line. Defaults to " ". """ if world_config is None: for config, _ in _iter_packages(): for world in config["maps"]: if world["name"] == world_name: world_config = world if world_config is None: raise HolodeckException("Couldn't find world " + world_name) second_indent = initial_indent + next_indent agent_indent = second_indent + next_indent sensor_indent = agent_indent + next_indent print(initial_indent, world_config["name"]) print(second_indent, "Resolution:", world_config["window_width"], "x", world_config["window_height"]) print(second_indent, "Agents:") for agent in world_config["agents"]: print(agent_indent, "Name:", agent["agent_name"]) print(agent_indent, "Type:", agent["agent_type"]) print(agent_indent, "Sensors:") for sensor in agent["sensors"]: print(sensor_indent, sensor)
[ "def", "world_info", "(", "world_name", ",", "world_config", "=", "None", ",", "initial_indent", "=", "\"\"", ",", "next_indent", "=", "\" \"", ")", ":", "if", "world_config", "is", "None", ":", "for", "config", ",", "_", "in", "_iter_packages", "(", ")", ":", "for", "world", "in", "config", "[", "\"maps\"", "]", ":", "if", "world", "[", "\"name\"", "]", "==", "world_name", ":", "world_config", "=", "world", "if", "world_config", "is", "None", ":", "raise", "HolodeckException", "(", "\"Couldn't find world \"", "+", "world_name", ")", "second_indent", "=", "initial_indent", "+", "next_indent", "agent_indent", "=", "second_indent", "+", "next_indent", "sensor_indent", "=", "agent_indent", "+", "next_indent", "print", "(", "initial_indent", ",", "world_config", "[", "\"name\"", "]", ")", "print", "(", "second_indent", ",", "\"Resolution:\"", ",", "world_config", "[", "\"window_width\"", "]", ",", "\"x\"", ",", "world_config", "[", "\"window_height\"", "]", ")", "print", "(", "second_indent", ",", "\"Agents:\"", ")", "for", "agent", "in", "world_config", "[", "\"agents\"", "]", ":", "print", "(", "agent_indent", ",", "\"Name:\"", ",", "agent", "[", "\"agent_name\"", "]", ")", "print", "(", "agent_indent", ",", "\"Type:\"", ",", "agent", "[", "\"agent_type\"", "]", ")", "print", "(", "agent_indent", ",", "\"Sensors:\"", ")", "for", "sensor", "in", "agent", "[", "\"sensors\"", "]", ":", "print", "(", "sensor_indent", ",", "sensor", ")" ]
Gets and prints the information of a world. Args: world_name (str): the name of the world to retrieve information for world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None. initial_indent (str optional): This indent will apply to each output line. Defaults to "". next_indent (str optional): This indent will be applied within each nested line. Defaults to " ".
[ "Gets", "and", "prints", "the", "information", "of", "a", "world", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L56-L86
train
BYU-PCCL/holodeck
holodeck/packagemanager.py
install
def install(package_name): """Installs a holodeck package. Args: package_name (str): The name of the package to install """ holodeck_path = util.get_holodeck_path() binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) package_url = packages[package_name] print("Installing " + package_name + " at " + holodeck_path) install_path = os.path.join(holodeck_path, "worlds") binary_url = binary_website + util.get_os_key() + "_" + package_url _download_binary(binary_url, install_path) if os.name == "posix": _make_binary_excecutable(package_name, install_path)
python
def install(package_name): """Installs a holodeck package. Args: package_name (str): The name of the package to install """ holodeck_path = util.get_holodeck_path() binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) package_url = packages[package_name] print("Installing " + package_name + " at " + holodeck_path) install_path = os.path.join(holodeck_path, "worlds") binary_url = binary_website + util.get_os_key() + "_" + package_url _download_binary(binary_url, install_path) if os.name == "posix": _make_binary_excecutable(package_name, install_path)
[ "def", "install", "(", "package_name", ")", ":", "holodeck_path", "=", "util", ".", "get_holodeck_path", "(", ")", "binary_website", "=", "\"https://s3.amazonaws.com/holodeckworlds/\"", "if", "package_name", "not", "in", "packages", ":", "raise", "HolodeckException", "(", "\"Unknown package name \"", "+", "package_name", ")", "package_url", "=", "packages", "[", "package_name", "]", "print", "(", "\"Installing \"", "+", "package_name", "+", "\" at \"", "+", "holodeck_path", ")", "install_path", "=", "os", ".", "path", ".", "join", "(", "holodeck_path", ",", "\"worlds\"", ")", "binary_url", "=", "binary_website", "+", "util", ".", "get_os_key", "(", ")", "+", "\"_\"", "+", "package_url", "_download_binary", "(", "binary_url", ",", "install_path", ")", "if", "os", ".", "name", "==", "\"posix\"", ":", "_make_binary_excecutable", "(", "package_name", ",", "install_path", ")" ]
Installs a holodeck package. Args: package_name (str): The name of the package to install
[ "Installs", "a", "holodeck", "package", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L89-L107
train
BYU-PCCL/holodeck
holodeck/packagemanager.py
remove
def remove(package_name): """Removes a holodeck package. Args: package_name (str): the name of the package to remove """ if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) for config, path in _iter_packages(): if config["name"] == package_name: shutil.rmtree(path)
python
def remove(package_name): """Removes a holodeck package. Args: package_name (str): the name of the package to remove """ if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) for config, path in _iter_packages(): if config["name"] == package_name: shutil.rmtree(path)
[ "def", "remove", "(", "package_name", ")", ":", "if", "package_name", "not", "in", "packages", ":", "raise", "HolodeckException", "(", "\"Unknown package name \"", "+", "package_name", ")", "for", "config", ",", "path", "in", "_iter_packages", "(", ")", ":", "if", "config", "[", "\"name\"", "]", "==", "package_name", ":", "shutil", ".", "rmtree", "(", "path", ")" ]
Removes a holodeck package. Args: package_name (str): the name of the package to remove
[ "Removes", "a", "holodeck", "package", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/packagemanager.py#L110-L120
train
BYU-PCCL/holodeck
holodeck/holodeck.py
make
def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False): """Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4. window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512). cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256). verbose (bool): Whether to run in verbose mode. Defaults to False. Returns: HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified world, and other supplied arguments. """ holodeck_worlds = _get_worlds_map() if world_name not in holodeck_worlds: raise HolodeckException("Invalid World Name") param_dict = copy(holodeck_worlds[world_name]) param_dict["start_world"] = True param_dict["uuid"] = str(uuid.uuid4()) param_dict["gl_version"] = gl_version param_dict["verbose"] = verbose if window_res is not None: param_dict["window_width"] = window_res[0] param_dict["window_height"] = window_res[1] if cam_res is not None: param_dict["camera_width"] = cam_res[0] param_dict["camera_height"] = cam_res[1] return HolodeckEnvironment(**param_dict)
python
def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False): """Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4. window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512). cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256). verbose (bool): Whether to run in verbose mode. Defaults to False. Returns: HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified world, and other supplied arguments. """ holodeck_worlds = _get_worlds_map() if world_name not in holodeck_worlds: raise HolodeckException("Invalid World Name") param_dict = copy(holodeck_worlds[world_name]) param_dict["start_world"] = True param_dict["uuid"] = str(uuid.uuid4()) param_dict["gl_version"] = gl_version param_dict["verbose"] = verbose if window_res is not None: param_dict["window_width"] = window_res[0] param_dict["window_height"] = window_res[1] if cam_res is not None: param_dict["camera_width"] = cam_res[0] param_dict["camera_height"] = cam_res[1] return HolodeckEnvironment(**param_dict)
[ "def", "make", "(", "world_name", ",", "gl_version", "=", "GL_VERSION", ".", "OPENGL4", ",", "window_res", "=", "None", ",", "cam_res", "=", "None", ",", "verbose", "=", "False", ")", ":", "holodeck_worlds", "=", "_get_worlds_map", "(", ")", "if", "world_name", "not", "in", "holodeck_worlds", ":", "raise", "HolodeckException", "(", "\"Invalid World Name\"", ")", "param_dict", "=", "copy", "(", "holodeck_worlds", "[", "world_name", "]", ")", "param_dict", "[", "\"start_world\"", "]", "=", "True", "param_dict", "[", "\"uuid\"", "]", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "param_dict", "[", "\"gl_version\"", "]", "=", "gl_version", "param_dict", "[", "\"verbose\"", "]", "=", "verbose", "if", "window_res", "is", "not", "None", ":", "param_dict", "[", "\"window_width\"", "]", "=", "window_res", "[", "0", "]", "param_dict", "[", "\"window_height\"", "]", "=", "window_res", "[", "1", "]", "if", "cam_res", "is", "not", "None", ":", "param_dict", "[", "\"camera_width\"", "]", "=", "cam_res", "[", "0", "]", "param_dict", "[", "\"camera_height\"", "]", "=", "cam_res", "[", "1", "]", "return", "HolodeckEnvironment", "(", "*", "*", "param_dict", ")" ]
Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENGL4. window_res ((int, int), optional): The resolution to load the game window at. Defaults to (512, 512). cam_res ((int, int), optional): The resolution to load the pixel camera sensors at. Defaults to (256, 256). verbose (bool): Whether to run in verbose mode. Defaults to False. Returns: HolodeckEnvironment: A holodeck environment instantiated with all the settings necessary for the specified world, and other supplied arguments.
[ "Creates", "a", "holodeck", "environment", "using", "the", "supplied", "world", "name", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/holodeck.py#L22-L54
train
BYU-PCCL/holodeck
holodeck/shmem.py
Shmem.unlink
def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
python
def unlink(self): """unlinks the shared memory""" if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
[ "def", "unlink", "(", "self", ")", ":", "if", "os", ".", "name", "==", "\"posix\"", ":", "self", ".", "__linux_unlink__", "(", ")", "elif", "os", ".", "name", "==", "\"nt\"", ":", "self", ".", "__windows_unlink__", "(", ")", "else", ":", "raise", "HolodeckException", "(", "\"Currently unsupported os: \"", "+", "os", ".", "name", ")" ]
unlinks the shared memory
[ "unlinks", "the", "shared", "memory" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/shmem.py#L51-L58
train
BYU-PCCL/holodeck
holodeck/command.py
Command.add_number_parameters
def add_number_parameters(self, number): """Add given number parameters to the internal list. Args: number (list of int or list of float): A number or list of numbers to add to the parameters. """ if isinstance(number, list): for x in number: self.add_number_parameters(x) return self._parameters.append("{ \"value\": " + str(number) + " }")
python
def add_number_parameters(self, number): """Add given number parameters to the internal list. Args: number (list of int or list of float): A number or list of numbers to add to the parameters. """ if isinstance(number, list): for x in number: self.add_number_parameters(x) return self._parameters.append("{ \"value\": " + str(number) + " }")
[ "def", "add_number_parameters", "(", "self", ",", "number", ")", ":", "if", "isinstance", "(", "number", ",", "list", ")", ":", "for", "x", "in", "number", ":", "self", ".", "add_number_parameters", "(", "x", ")", "return", "self", ".", "_parameters", ".", "append", "(", "\"{ \\\"value\\\": \"", "+", "str", "(", "number", ")", "+", "\" }\"", ")" ]
Add given number parameters to the internal list. Args: number (list of int or list of float): A number or list of numbers to add to the parameters.
[ "Add", "given", "number", "parameters", "to", "the", "internal", "list", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L49-L59
train
BYU-PCCL/holodeck
holodeck/command.py
Command.add_string_parameters
def add_string_parameters(self, string): """Add given string parameters to the internal list. Args: string (list of str or str): A string or list of strings to add to the parameters. """ if isinstance(string, list): for x in string: self.add_string_parameters(x) return self._parameters.append("{ \"value\": \"" + string + "\" }")
python
def add_string_parameters(self, string): """Add given string parameters to the internal list. Args: string (list of str or str): A string or list of strings to add to the parameters. """ if isinstance(string, list): for x in string: self.add_string_parameters(x) return self._parameters.append("{ \"value\": \"" + string + "\" }")
[ "def", "add_string_parameters", "(", "self", ",", "string", ")", ":", "if", "isinstance", "(", "string", ",", "list", ")", ":", "for", "x", "in", "string", ":", "self", ".", "add_string_parameters", "(", "x", ")", "return", "self", ".", "_parameters", ".", "append", "(", "\"{ \\\"value\\\": \\\"\"", "+", "string", "+", "\"\\\" }\"", ")" ]
Add given string parameters to the internal list. Args: string (list of str or str): A string or list of strings to add to the parameters.
[ "Add", "given", "string", "parameters", "to", "the", "internal", "list", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L61-L71
train
BYU-PCCL/holodeck
holodeck/command.py
SetWeatherCommand.set_type
def set_type(self, weather_type): """Set the weather type. Args: weather_type (str): The weather type. """ weather_type.lower() exists = self.has_type(weather_type) if exists: self.add_string_parameters(weather_type)
python
def set_type(self, weather_type): """Set the weather type. Args: weather_type (str): The weather type. """ weather_type.lower() exists = self.has_type(weather_type) if exists: self.add_string_parameters(weather_type)
[ "def", "set_type", "(", "self", ",", "weather_type", ")", ":", "weather_type", ".", "lower", "(", ")", "exists", "=", "self", ".", "has_type", "(", "weather_type", ")", "if", "exists", ":", "self", ".", "add_string_parameters", "(", "weather_type", ")" ]
Set the weather type. Args: weather_type (str): The weather type.
[ "Set", "the", "weather", "type", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L227-L236
train
BYU-PCCL/holodeck
example.py
uav_example
def uav_example(): """A basic example of how to use the UAV agent.""" env = holodeck.make("UrbanCity") # This changes the control scheme for the uav env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) for i in range(10): env.reset() # This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude. command = np.array([0, 0, 2, 10]) for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] velocity = state[Sensors.VELOCITY_SENSOR]
python
def uav_example(): """A basic example of how to use the UAV agent.""" env = holodeck.make("UrbanCity") # This changes the control scheme for the uav env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) for i in range(10): env.reset() # This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude. command = np.array([0, 0, 2, 10]) for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] velocity = state[Sensors.VELOCITY_SENSOR]
[ "def", "uav_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"UrbanCity\"", ")", "# This changes the control scheme for the uav", "env", ".", "set_control_scheme", "(", "\"uav0\"", ",", "ControlSchemes", ".", "UAV_ROLL_PITCH_YAW_RATE_ALT", ")", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "# This command tells the UAV to not roll or pitch, but to constantly yaw left at 10m altitude.", "command", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "2", ",", "10", "]", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")", "# To access specific sensor data:", "pixels", "=", "state", "[", "Sensors", ".", "PIXEL_CAMERA", "]", "velocity", "=", "state", "[", "Sensors", ".", "VELOCITY_SENSOR", "]" ]
A basic example of how to use the UAV agent.
[ "A", "basic", "example", "of", "how", "to", "use", "the", "UAV", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L10-L27
train
BYU-PCCL/holodeck
example.py
sphere_example
def sphere_example(): """A basic example of how to use the sphere agent.""" env = holodeck.make("MazeWorld") # This command is to constantly rotate to the right command = 2 for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
python
def sphere_example(): """A basic example of how to use the sphere agent.""" env = holodeck.make("MazeWorld") # This command is to constantly rotate to the right command = 2 for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
[ "def", "sphere_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"MazeWorld\"", ")", "# This command is to constantly rotate to the right", "command", "=", "2", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")", "# To access specific sensor data:", "pixels", "=", "state", "[", "Sensors", ".", "PIXEL_CAMERA", "]", "orientation", "=", "state", "[", "Sensors", ".", "ORIENTATION_SENSOR", "]" ]
A basic example of how to use the sphere agent.
[ "A", "basic", "example", "of", "how", "to", "use", "the", "sphere", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L36-L49
train
BYU-PCCL/holodeck
example.py
android_example
def android_example(): """A basic example of how to use the android agent.""" env = holodeck.make("AndroidPlayground") # The Android's command is a 94 length vector representing torques to be applied at each of his joints command = np.ones(94) * 10 for i in range(10): env.reset() for j in range(1000): if j % 50 == 0: command *= -1 state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
python
def android_example(): """A basic example of how to use the android agent.""" env = holodeck.make("AndroidPlayground") # The Android's command is a 94 length vector representing torques to be applied at each of his joints command = np.ones(94) * 10 for i in range(10): env.reset() for j in range(1000): if j % 50 == 0: command *= -1 state, reward, terminal, _ = env.step(command) # To access specific sensor data: pixels = state[Sensors.PIXEL_CAMERA] orientation = state[Sensors.ORIENTATION_SENSOR]
[ "def", "android_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"AndroidPlayground\"", ")", "# The Android's command is a 94 length vector representing torques to be applied at each of his joints", "command", "=", "np", ".", "ones", "(", "94", ")", "*", "10", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "for", "j", "in", "range", "(", "1000", ")", ":", "if", "j", "%", "50", "==", "0", ":", "command", "*=", "-", "1", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")", "# To access specific sensor data:", "pixels", "=", "state", "[", "Sensors", ".", "PIXEL_CAMERA", "]", "orientation", "=", "state", "[", "Sensors", ".", "ORIENTATION_SENSOR", "]" ]
A basic example of how to use the android agent.
[ "A", "basic", "example", "of", "how", "to", "use", "the", "android", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L53-L69
train
BYU-PCCL/holodeck
example.py
multi_agent_example
def multi_agent_example(): """A basic example of using multiple agents""" env = holodeck.make("UrbanCity") cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() # This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked. sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav1", agents.UavAgent, sensors) env.spawn_agent(agent, [1, 1, 5]) env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.set_control_scheme("uav1", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.tick() # Tick the environment once so the second agent spawns before we try to interact with it. env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
python
def multi_agent_example(): """A basic example of using multiple agents""" env = holodeck.make("UrbanCity") cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() # This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked. sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav1", agents.UavAgent, sensors) env.spawn_agent(agent, [1, 1, 5]) env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.set_control_scheme("uav1", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) env.tick() # Tick the environment once so the second agent spawns before we try to interact with it. env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
[ "def", "multi_agent_example", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"UrbanCity\"", ")", "cmd0", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "-", "2", ",", "10", "]", ")", "cmd1", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "5", ",", "10", "]", ")", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "# This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked.", "sensors", "=", "[", "Sensors", ".", "PIXEL_CAMERA", ",", "Sensors", ".", "LOCATION_SENSOR", ",", "Sensors", ".", "VELOCITY_SENSOR", "]", "agent", "=", "AgentDefinition", "(", "\"uav1\"", ",", "agents", ".", "UavAgent", ",", "sensors", ")", "env", ".", "spawn_agent", "(", "agent", ",", "[", "1", ",", "1", ",", "5", "]", ")", "env", ".", "set_control_scheme", "(", "\"uav0\"", ",", "ControlSchemes", ".", "UAV_ROLL_PITCH_YAW_RATE_ALT", ")", "env", ".", "set_control_scheme", "(", "\"uav1\"", ",", "ControlSchemes", ".", "UAV_ROLL_PITCH_YAW_RATE_ALT", ")", "env", ".", "tick", "(", ")", "# Tick the environment once so the second agent spawns before we try to interact with it.", "env", ".", "act", "(", "\"uav0\"", ",", "cmd0", ")", "env", ".", "act", "(", "\"uav1\"", ",", "cmd1", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "states", "=", "env", ".", "tick", "(", ")", "uav0_terminal", "=", "states", "[", "\"uav0\"", "]", "[", "Sensors", ".", "TERMINAL", "]", "uav1_reward", "=", "states", "[", "\"uav1\"", "]", "[", "Sensors", ".", "REWARD", "]" ]
A basic example of using multiple agents
[ "A", "basic", "example", "of", "using", "multiple", "agents" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L73-L96
train
BYU-PCCL/holodeck
example.py
world_command_examples
def world_command_examples(): """A few examples to showcase commands for manipulating the worlds.""" env = holodeck.make("MazeWorld") # This is the unaltered MazeWorld for _ in range(300): _ = env.tick() env.reset() # The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM. env.set_day_time(6) for _ in range(300): _ = env.tick() env.reset() # reset() undoes all alterations to the world # The start_day_cycle command starts rotating the sun to emulate day cycles. # The parameter sets the day length in minutes. env.start_day_cycle(5) for _ in range(1500): _ = env.tick() env.reset() # The set_fog_density changes the density of the fog in the world. 1 is the maximum density. env.set_fog_density(.25) for _ in range(300): _ = env.tick() env.reset() # The set_weather_command changes the weather in the world. The two available options are "rain" and "cloudy". # The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent. # Every world is clear by default. env.set_weather("rain") for _ in range(500): _ = env.tick() env.reset() env.set_weather("cloudy") for _ in range(500): _ = env.tick() env.reset() env.teleport_camera([1000, 1000, 1000], [0, 0, 0]) for _ in range(500): _ = env.tick() env.reset()
python
def world_command_examples(): """A few examples to showcase commands for manipulating the worlds.""" env = holodeck.make("MazeWorld") # This is the unaltered MazeWorld for _ in range(300): _ = env.tick() env.reset() # The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM. env.set_day_time(6) for _ in range(300): _ = env.tick() env.reset() # reset() undoes all alterations to the world # The start_day_cycle command starts rotating the sun to emulate day cycles. # The parameter sets the day length in minutes. env.start_day_cycle(5) for _ in range(1500): _ = env.tick() env.reset() # The set_fog_density changes the density of the fog in the world. 1 is the maximum density. env.set_fog_density(.25) for _ in range(300): _ = env.tick() env.reset() # The set_weather_command changes the weather in the world. The two available options are "rain" and "cloudy". # The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent. # Every world is clear by default. env.set_weather("rain") for _ in range(500): _ = env.tick() env.reset() env.set_weather("cloudy") for _ in range(500): _ = env.tick() env.reset() env.teleport_camera([1000, 1000, 1000], [0, 0, 0]) for _ in range(500): _ = env.tick() env.reset()
[ "def", "world_command_examples", "(", ")", ":", "env", "=", "holodeck", ".", "make", "(", "\"MazeWorld\"", ")", "# This is the unaltered MazeWorld", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# The set_day_time_command sets the hour between 0 and 23 (military time). This example sets it to 6 AM.", "env", ".", "set_day_time", "(", "6", ")", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# reset() undoes all alterations to the world", "# The start_day_cycle command starts rotating the sun to emulate day cycles.", "# The parameter sets the day length in minutes.", "env", ".", "start_day_cycle", "(", "5", ")", "for", "_", "in", "range", "(", "1500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# The set_fog_density changes the density of the fog in the world. 1 is the maximum density.", "env", ".", "set_fog_density", "(", ".25", ")", "for", "_", "in", "range", "(", "300", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "# The set_weather_command changes the weather in the world. The two available options are \"rain\" and \"cloudy\".", "# The rainfall particle system is attached to the agent, so the rain particles will only be found around each agent.", "# Every world is clear by default.", "env", ".", "set_weather", "(", "\"rain\"", ")", "for", "_", "in", "range", "(", "500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "env", ".", "set_weather", "(", "\"cloudy\"", ")", "for", "_", "in", "range", "(", "500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")", "env", ".", "teleport_camera", "(", "[", "1000", ",", "1000", ",", "1000", "]", ",", "[", "0", ",", "0", ",", "0", "]", ")", "for", "_", "in", "range", "(", "500", ")", ":", "_", "=", "env", ".", "tick", "(", ")", "env", ".", "reset", "(", ")" ]
A few examples to showcase commands for manipulating the worlds.
[ "A", "few", "examples", "to", "showcase", "commands", "for", "manipulating", "the", "worlds", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L99-L143
train
BYU-PCCL/holodeck
example.py
editor_example
def editor_example(): """This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine. Most people that use holodeck will not need this. """ sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav0", agents.UavAgent, sensors) env = HolodeckEnvironment(agent, start_world=False) env.agents["uav0"].set_control_scheme(1) command = [0, 0, 10, 50] for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command)
python
def editor_example(): """This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine. Most people that use holodeck will not need this. """ sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR] agent = AgentDefinition("uav0", agents.UavAgent, sensors) env = HolodeckEnvironment(agent, start_world=False) env.agents["uav0"].set_control_scheme(1) command = [0, 0, 10, 50] for i in range(10): env.reset() for _ in range(1000): state, reward, terminal, _ = env.step(command)
[ "def", "editor_example", "(", ")", ":", "sensors", "=", "[", "Sensors", ".", "PIXEL_CAMERA", ",", "Sensors", ".", "LOCATION_SENSOR", ",", "Sensors", ".", "VELOCITY_SENSOR", "]", "agent", "=", "AgentDefinition", "(", "\"uav0\"", ",", "agents", ".", "UavAgent", ",", "sensors", ")", "env", "=", "HolodeckEnvironment", "(", "agent", ",", "start_world", "=", "False", ")", "env", ".", "agents", "[", "\"uav0\"", "]", ".", "set_control_scheme", "(", "1", ")", "command", "=", "[", "0", ",", "0", ",", "10", ",", "50", "]", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "state", ",", "reward", ",", "terminal", ",", "_", "=", "env", ".", "step", "(", "command", ")" ]
This editor example shows how to interact with holodeck worlds while they are being built in the Unreal Engine. Most people that use holodeck will not need this.
[ "This", "editor", "example", "shows", "how", "to", "interact", "with", "holodeck", "worlds", "while", "they", "are", "being", "built", "in", "the", "Unreal", "Engine", ".", "Most", "people", "that", "use", "holodeck", "will", "not", "need", "this", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L146-L159
train
BYU-PCCL/holodeck
example.py
editor_multi_agent_example
def editor_multi_agent_example(): """This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary. """ agent_definitions = [ AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR]), AgentDefinition("uav1", agents.UavAgent, [Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]) ] env = HolodeckEnvironment(agent_definitions, start_world=False) cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
python
def editor_multi_agent_example(): """This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary. """ agent_definitions = [ AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR]), AgentDefinition("uav1", agents.UavAgent, [Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]) ] env = HolodeckEnvironment(agent_definitions, start_world=False) cmd0 = np.array([0, 0, -2, 10]) cmd1 = np.array([0, 0, 5, 10]) for i in range(10): env.reset() env.act("uav0", cmd0) env.act("uav1", cmd1) for _ in range(1000): states = env.tick() uav0_terminal = states["uav0"][Sensors.TERMINAL] uav1_reward = states["uav1"][Sensors.REWARD]
[ "def", "editor_multi_agent_example", "(", ")", ":", "agent_definitions", "=", "[", "AgentDefinition", "(", "\"uav0\"", ",", "agents", ".", "UavAgent", ",", "[", "Sensors", ".", "PIXEL_CAMERA", ",", "Sensors", ".", "LOCATION_SENSOR", "]", ")", ",", "AgentDefinition", "(", "\"uav1\"", ",", "agents", ".", "UavAgent", ",", "[", "Sensors", ".", "LOCATION_SENSOR", ",", "Sensors", ".", "VELOCITY_SENSOR", "]", ")", "]", "env", "=", "HolodeckEnvironment", "(", "agent_definitions", ",", "start_world", "=", "False", ")", "cmd0", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "-", "2", ",", "10", "]", ")", "cmd1", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "5", ",", "10", "]", ")", "for", "i", "in", "range", "(", "10", ")", ":", "env", ".", "reset", "(", ")", "env", ".", "act", "(", "\"uav0\"", ",", "cmd0", ")", "env", ".", "act", "(", "\"uav1\"", ",", "cmd1", ")", "for", "_", "in", "range", "(", "1000", ")", ":", "states", "=", "env", ".", "tick", "(", ")", "uav0_terminal", "=", "states", "[", "\"uav0\"", "]", "[", "Sensors", ".", "TERMINAL", "]", "uav1_reward", "=", "states", "[", "\"uav1\"", "]", "[", "Sensors", ".", "REWARD", "]" ]
This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary.
[ "This", "editor", "example", "shows", "how", "to", "interact", "with", "holodeck", "worlds", "that", "have", "multiple", "agents", ".", "This", "is", "specifically", "for", "when", "working", "with", "UE4", "directly", "and", "not", "a", "prebuilt", "binary", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/example.py#L162-L183
train
BYU-PCCL/holodeck
holodeck/util.py
get_holodeck_path
def get_holodeck_path(): """Gets the path of the holodeck environment Returns: (str): path to the current holodeck environment """ if "HOLODECKPATH" in os.environ and os.environ["HOLODECKPATH"] != "": return os.environ["HOLODECKPATH"] if os.name == "posix": return os.path.expanduser("~/.local/share/holodeck") elif os.name == "nt": return os.path.expanduser("~\\AppData\\Local\\holodeck") else: raise NotImplementedError("holodeck is only supported for Linux and Windows")
python
def get_holodeck_path(): """Gets the path of the holodeck environment Returns: (str): path to the current holodeck environment """ if "HOLODECKPATH" in os.environ and os.environ["HOLODECKPATH"] != "": return os.environ["HOLODECKPATH"] if os.name == "posix": return os.path.expanduser("~/.local/share/holodeck") elif os.name == "nt": return os.path.expanduser("~\\AppData\\Local\\holodeck") else: raise NotImplementedError("holodeck is only supported for Linux and Windows")
[ "def", "get_holodeck_path", "(", ")", ":", "if", "\"HOLODECKPATH\"", "in", "os", ".", "environ", "and", "os", ".", "environ", "[", "\"HOLODECKPATH\"", "]", "!=", "\"\"", ":", "return", "os", ".", "environ", "[", "\"HOLODECKPATH\"", "]", "if", "os", ".", "name", "==", "\"posix\"", ":", "return", "os", ".", "path", ".", "expanduser", "(", "\"~/.local/share/holodeck\"", ")", "elif", "os", ".", "name", "==", "\"nt\"", ":", "return", "os", ".", "path", ".", "expanduser", "(", "\"~\\\\AppData\\\\Local\\\\holodeck\"", ")", "else", ":", "raise", "NotImplementedError", "(", "\"holodeck is only supported for Linux and Windows\"", ")" ]
Gets the path of the holodeck environment Returns: (str): path to the current holodeck environment
[ "Gets", "the", "path", "of", "the", "holodeck", "environment" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/util.py#L11-L24
train
BYU-PCCL/holodeck
holodeck/util.py
convert_unicode
def convert_unicode(value): """Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string """ if isinstance(value, dict): return {convert_unicode(key): convert_unicode(value) for key, value in value.iteritems()} elif isinstance(value, list): return [convert_unicode(item) for item in value] elif isinstance(value, unicode): return value.encode('utf-8') else: return value
python
def convert_unicode(value): """Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string """ if isinstance(value, dict): return {convert_unicode(key): convert_unicode(value) for key, value in value.iteritems()} elif isinstance(value, list): return [convert_unicode(item) for item in value] elif isinstance(value, unicode): return value.encode('utf-8') else: return value
[ "def", "convert_unicode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "{", "convert_unicode", "(", "key", ")", ":", "convert_unicode", "(", "value", ")", "for", "key", ",", "value", "in", "value", ".", "iteritems", "(", ")", "}", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "convert_unicode", "(", "item", ")", "for", "item", "in", "value", "]", "elif", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "value", ".", "encode", "(", "'utf-8'", ")", "else", ":", "return", "value" ]
Resolves python 2 issue with json loading in unicode instead of string Args: value (str): Unicode value to be converted Returns: (str): converted string
[ "Resolves", "python", "2", "issue", "with", "json", "loading", "in", "unicode", "instead", "of", "string" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/util.py#L27-L45
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.info
def info(self): """Returns a string with specific information about the environment. This information includes which agents are in the environment and which sensors they have. Returns: str: The information in a string format. """ result = list() result.append("Agents:\n") for agent in self._all_agents: result.append("\tName: ") result.append(agent.name) result.append("\n\tType: ") result.append(type(agent).__name__) result.append("\n\t") result.append("Sensors:\n") for sensor in self._sensor_map[agent.name].keys(): result.append("\t\t") result.append(Sensors.name(sensor)) result.append("\n") return "".join(result)
python
def info(self): """Returns a string with specific information about the environment. This information includes which agents are in the environment and which sensors they have. Returns: str: The information in a string format. """ result = list() result.append("Agents:\n") for agent in self._all_agents: result.append("\tName: ") result.append(agent.name) result.append("\n\tType: ") result.append(type(agent).__name__) result.append("\n\t") result.append("Sensors:\n") for sensor in self._sensor_map[agent.name].keys(): result.append("\t\t") result.append(Sensors.name(sensor)) result.append("\n") return "".join(result)
[ "def", "info", "(", "self", ")", ":", "result", "=", "list", "(", ")", "result", ".", "append", "(", "\"Agents:\\n\"", ")", "for", "agent", "in", "self", ".", "_all_agents", ":", "result", ".", "append", "(", "\"\\tName: \"", ")", "result", ".", "append", "(", "agent", ".", "name", ")", "result", ".", "append", "(", "\"\\n\\tType: \"", ")", "result", ".", "append", "(", "type", "(", "agent", ")", ".", "__name__", ")", "result", ".", "append", "(", "\"\\n\\t\"", ")", "result", ".", "append", "(", "\"Sensors:\\n\"", ")", "for", "sensor", "in", "self", ".", "_sensor_map", "[", "agent", ".", "name", "]", ".", "keys", "(", ")", ":", "result", ".", "append", "(", "\"\\t\\t\"", ")", "result", ".", "append", "(", "Sensors", ".", "name", "(", "sensor", ")", ")", "result", ".", "append", "(", "\"\\n\"", ")", "return", "\"\"", ".", "join", "(", "result", ")" ]
Returns a string with specific information about the environment. This information includes which agents are in the environment and which sensors they have. Returns: str: The information in a string format.
[ "Returns", "a", "string", "with", "specific", "information", "about", "the", "environment", ".", "This", "information", "includes", "which", "agents", "are", "in", "the", "environment", "and", "which", "sensors", "they", "have", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L142-L162
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.reset
def reset(self): """Resets the environment, and returns the state. If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from agent name to state. Returns: tuple or dict: For single agent environment, returns the same as `step`. For multi-agent environment, returns the same as `tick`. """ self._reset_ptr[0] = True self._commands.clear() for _ in range(self._pre_start_steps + 1): self.tick() return self._default_state_fn()
python
def reset(self): """Resets the environment, and returns the state. If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from agent name to state. Returns: tuple or dict: For single agent environment, returns the same as `step`. For multi-agent environment, returns the same as `tick`. """ self._reset_ptr[0] = True self._commands.clear() for _ in range(self._pre_start_steps + 1): self.tick() return self._default_state_fn()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_reset_ptr", "[", "0", "]", "=", "True", "self", ".", "_commands", ".", "clear", "(", ")", "for", "_", "in", "range", "(", "self", ".", "_pre_start_steps", "+", "1", ")", ":", "self", ".", "tick", "(", ")", "return", "self", ".", "_default_state_fn", "(", ")" ]
Resets the environment, and returns the state. If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from agent name to state. Returns: tuple or dict: For single agent environment, returns the same as `step`. For multi-agent environment, returns the same as `tick`.
[ "Resets", "the", "environment", "and", "returns", "the", "state", ".", "If", "it", "is", "a", "single", "agent", "environment", "it", "returns", "that", "state", "for", "that", "agent", ".", "Otherwise", "it", "returns", "a", "dict", "from", "agent", "name", "to", "state", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L164-L179
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.step
def step(self, action): """Supplies an action to the main agent and tells the environment to tick once. Primary mode of interaction for single agent environments. Args: action (np.ndarray): An action for the main agent to carry out on the next tick. Returns: tuple: The (state, reward, terminal, info) tuple for the agent. State is a dictionary from sensor enum (see :obj:`holodeck.sensors.Sensors`) to np.ndarray. Reward is the float reward returned by the environment. Terminal is the bool terminal signal returned by the environment. Info is any additional info, depending on the world. Defaults to None. """ self._agent.act(action) self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_single_state()
python
def step(self, action): """Supplies an action to the main agent and tells the environment to tick once. Primary mode of interaction for single agent environments. Args: action (np.ndarray): An action for the main agent to carry out on the next tick. Returns: tuple: The (state, reward, terminal, info) tuple for the agent. State is a dictionary from sensor enum (see :obj:`holodeck.sensors.Sensors`) to np.ndarray. Reward is the float reward returned by the environment. Terminal is the bool terminal signal returned by the environment. Info is any additional info, depending on the world. Defaults to None. """ self._agent.act(action) self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_single_state()
[ "def", "step", "(", "self", ",", "action", ")", ":", "self", ".", "_agent", ".", "act", "(", "action", ")", "self", ".", "_handle_command_buffer", "(", ")", "self", ".", "_client", ".", "release", "(", ")", "self", ".", "_client", ".", "acquire", "(", ")", "return", "self", ".", "_get_single_state", "(", ")" ]
Supplies an action to the main agent and tells the environment to tick once. Primary mode of interaction for single agent environments. Args: action (np.ndarray): An action for the main agent to carry out on the next tick. Returns: tuple: The (state, reward, terminal, info) tuple for the agent. State is a dictionary from sensor enum (see :obj:`holodeck.sensors.Sensors`) to np.ndarray. Reward is the float reward returned by the environment. Terminal is the bool terminal signal returned by the environment. Info is any additional info, depending on the world. Defaults to None.
[ "Supplies", "an", "action", "to", "the", "main", "agent", "and", "tells", "the", "environment", "to", "tick", "once", ".", "Primary", "mode", "of", "interaction", "for", "single", "agent", "environments", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L181-L202
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.teleport
def teleport(self, agent_name, location=None, rotation=None): """Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't teleported, but may still be rotated. Defaults to None. rotation (np.ndarray or list): A new rotation target for the agent. If no rotation is given, it isn't rotated, but may still be teleported. Defaults to None. """ self.agents[agent_name].teleport(location * 100, rotation) # * 100 to convert m to cm self.tick()
python
def teleport(self, agent_name, location=None, rotation=None): """Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't teleported, but may still be rotated. Defaults to None. rotation (np.ndarray or list): A new rotation target for the agent. If no rotation is given, it isn't rotated, but may still be teleported. Defaults to None. """ self.agents[agent_name].teleport(location * 100, rotation) # * 100 to convert m to cm self.tick()
[ "def", "teleport", "(", "self", ",", "agent_name", ",", "location", "=", "None", ",", "rotation", "=", "None", ")", ":", "self", ".", "agents", "[", "agent_name", "]", ".", "teleport", "(", "location", "*", "100", ",", "rotation", ")", "# * 100 to convert m to cm", "self", ".", "tick", "(", ")" ]
Teleports the target agent to any given location, and applies a specific rotation. Args: agent_name (str): The name of the agent to teleport. location (np.ndarray or list): XYZ coordinates (in meters) for the agent to be teleported to. If no location is given, it isn't teleported, but may still be rotated. Defaults to None. rotation (np.ndarray or list): A new rotation target for the agent. If no rotation is given, it isn't rotated, but may still be teleported. Defaults to None.
[ "Teleports", "the", "target", "agent", "to", "any", "given", "location", "and", "applies", "a", "specific", "rotation", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L204-L215
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.tick
def tick(self): """Ticks the environment once. Normally used for multi-agent environments. Returns: dict: A dictionary from agent name to its full state. The full state is another dictionary from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information for each sensor. The sensors always include the reward and terminal sensors. """ self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_full_state()
python
def tick(self): """Ticks the environment once. Normally used for multi-agent environments. Returns: dict: A dictionary from agent name to its full state. The full state is another dictionary from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information for each sensor. The sensors always include the reward and terminal sensors. """ self._handle_command_buffer() self._client.release() self._client.acquire() return self._get_full_state()
[ "def", "tick", "(", "self", ")", ":", "self", ".", "_handle_command_buffer", "(", ")", "self", ".", "_client", ".", "release", "(", ")", "self", ".", "_client", ".", "acquire", "(", ")", "return", "self", ".", "_get_full_state", "(", ")" ]
Ticks the environment once. Normally used for multi-agent environments. Returns: dict: A dictionary from agent name to its full state. The full state is another dictionary from :obj:`holodeck.sensors.Sensors` enum to np.ndarray, containing the sensors information for each sensor. The sensors always include the reward and terminal sensors.
[ "Ticks", "the", "environment", "once", ".", "Normally", "used", "for", "multi", "-", "agent", "environments", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L229-L240
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.add_state_sensors
def add_state_sensors(self, agent_name, sensors): """Adds a sensor to a particular agent. This only works if the world you are running also includes that particular sensor on the agent. Args: agent_name (str): The name of the agent to add the sensor to. sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to add to the agent. Should be objects that inherit from :obj:`HolodeckSensor`. """ if isinstance(sensors, list): for sensor in sensors: self.add_state_sensors(agent_name, sensor) else: if agent_name not in self._sensor_map: self._sensor_map[agent_name] = dict() self._sensor_map[agent_name][sensors] = self._client.malloc(agent_name + "_" + Sensors.name(sensors), Sensors.shape(sensors), Sensors.dtype(sensors))
python
def add_state_sensors(self, agent_name, sensors): """Adds a sensor to a particular agent. This only works if the world you are running also includes that particular sensor on the agent. Args: agent_name (str): The name of the agent to add the sensor to. sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to add to the agent. Should be objects that inherit from :obj:`HolodeckSensor`. """ if isinstance(sensors, list): for sensor in sensors: self.add_state_sensors(agent_name, sensor) else: if agent_name not in self._sensor_map: self._sensor_map[agent_name] = dict() self._sensor_map[agent_name][sensors] = self._client.malloc(agent_name + "_" + Sensors.name(sensors), Sensors.shape(sensors), Sensors.dtype(sensors))
[ "def", "add_state_sensors", "(", "self", ",", "agent_name", ",", "sensors", ")", ":", "if", "isinstance", "(", "sensors", ",", "list", ")", ":", "for", "sensor", "in", "sensors", ":", "self", ".", "add_state_sensors", "(", "agent_name", ",", "sensor", ")", "else", ":", "if", "agent_name", "not", "in", "self", ".", "_sensor_map", ":", "self", ".", "_sensor_map", "[", "agent_name", "]", "=", "dict", "(", ")", "self", ".", "_sensor_map", "[", "agent_name", "]", "[", "sensors", "]", "=", "self", ".", "_client", ".", "malloc", "(", "agent_name", "+", "\"_\"", "+", "Sensors", ".", "name", "(", "sensors", ")", ",", "Sensors", ".", "shape", "(", "sensors", ")", ",", "Sensors", ".", "dtype", "(", "sensors", ")", ")" ]
Adds a sensor to a particular agent. This only works if the world you are running also includes that particular sensor on the agent. Args: agent_name (str): The name of the agent to add the sensor to. sensors (:obj:`HolodeckSensor` or list of :obj:`HolodeckSensor`): Sensors to add to the agent. Should be objects that inherit from :obj:`HolodeckSensor`.
[ "Adds", "a", "sensor", "to", "a", "particular", "agent", ".", "This", "only", "works", "if", "the", "world", "you", "are", "running", "also", "includes", "that", "particular", "sensor", "on", "the", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L242-L260
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.spawn_agent
def spawn_agent(self, agent_definition, location): """Queues a spawn agent command. It will be applied when `tick` or `step` is called next. The agent won't be able to be used until the next frame. Args: agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn. location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters). """ self._should_write_to_command_buffer = True self._add_agents(agent_definition) command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type) self._commands.add_command(command_to_send)
python
def spawn_agent(self, agent_definition, location): """Queues a spawn agent command. It will be applied when `tick` or `step` is called next. The agent won't be able to be used until the next frame. Args: agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn. location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters). """ self._should_write_to_command_buffer = True self._add_agents(agent_definition) command_to_send = SpawnAgentCommand(location, agent_definition.name, agent_definition.type) self._commands.add_command(command_to_send)
[ "def", "spawn_agent", "(", "self", ",", "agent_definition", ",", "location", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "self", ".", "_add_agents", "(", "agent_definition", ")", "command_to_send", "=", "SpawnAgentCommand", "(", "location", ",", "agent_definition", ".", "name", ",", "agent_definition", ".", "type", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queues a spawn agent command. It will be applied when `tick` or `step` is called next. The agent won't be able to be used until the next frame. Args: agent_definition (:obj:`AgentDefinition`): The definition of the agent to spawn. location (np.ndarray or list): The position to spawn the agent in the world, in XYZ coordinates (in meters).
[ "Queues", "a", "spawn", "agent", "command", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "The", "agent", "won", "t", "be", "able", "to", "be", "used", "until", "the", "next", "frame", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L262-L273
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.set_fog_density
def set_fog_density(self, density): """Queue up a change fog density command. It will be applied when `tick` or `step` is called next. By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the world, it will be automatically created with the given density. Args: density (float): The new density value, between 0 and 1. The command will not be sent if the given density is invalid. """ if density < 0 or density > 1: raise HolodeckException("Fog density should be between 0 and 1") self._should_write_to_command_buffer = True command_to_send = ChangeFogDensityCommand(density) self._commands.add_command(command_to_send)
python
def set_fog_density(self, density): """Queue up a change fog density command. It will be applied when `tick` or `step` is called next. By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the world, it will be automatically created with the given density. Args: density (float): The new density value, between 0 and 1. The command will not be sent if the given density is invalid. """ if density < 0 or density > 1: raise HolodeckException("Fog density should be between 0 and 1") self._should_write_to_command_buffer = True command_to_send = ChangeFogDensityCommand(density) self._commands.add_command(command_to_send)
[ "def", "set_fog_density", "(", "self", ",", "density", ")", ":", "if", "density", "<", "0", "or", "density", ">", "1", ":", "raise", "HolodeckException", "(", "\"Fog density should be between 0 and 1\"", ")", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "ChangeFogDensityCommand", "(", "density", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a change fog density command. It will be applied when `tick` or `step` is called next. By the next tick, the exponential height fog in the world will have the new density. If there is no fog in the world, it will be automatically created with the given density. Args: density (float): The new density value, between 0 and 1. The command will not be sent if the given density is invalid.
[ "Queue", "up", "a", "change", "fog", "density", "command", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "By", "the", "next", "tick", "the", "exponential", "height", "fog", "in", "the", "world", "will", "have", "the", "new", "density", ".", "If", "there", "is", "no", "fog", "in", "the", "world", "it", "will", "be", "automatically", "created", "with", "the", "given", "density", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L275-L289
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.set_day_time
def set_day_time(self, hour): """Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive. """ self._should_write_to_command_buffer = True command_to_send = DayTimeCommand(hour % 24) self._commands.add_command(command_to_send)
python
def set_day_time(self, hour): """Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive. """ self._should_write_to_command_buffer = True command_to_send = DayTimeCommand(hour % 24) self._commands.add_command(command_to_send)
[ "def", "set_day_time", "(", "self", ",", "hour", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayTimeCommand", "(", "hour", "%", "24", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive.
[ "Queue", "up", "a", "change", "day", "time", "command", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "By", "the", "next", "tick", "the", "lighting", "and", "the", "skysphere", "will", "be", "updated", "with", "the", "new", "hour", ".", "If", "there", "is", "no", "skysphere", "or", "directional", "light", "in", "the", "world", "the", "command", "will", "not", "function", "properly", "but", "will", "not", "cause", "a", "crash", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L291-L301
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.start_day_cycle
def start_day_cycle(self, day_length): """Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next. The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a day will be roughly equivalent to the number of minutes given. Args: day_length (int): The number of minutes each day will be. """ if day_length <= 0: raise HolodeckException("The given day length should be between above 0!") self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(True) command_to_send.set_day_length(day_length) self._commands.add_command(command_to_send)
python
def start_day_cycle(self, day_length): """Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next. The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a day will be roughly equivalent to the number of minutes given. Args: day_length (int): The number of minutes each day will be. """ if day_length <= 0: raise HolodeckException("The given day length should be between above 0!") self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(True) command_to_send.set_day_length(day_length) self._commands.add_command(command_to_send)
[ "def", "start_day_cycle", "(", "self", ",", "day_length", ")", ":", "if", "day_length", "<=", "0", ":", "raise", "HolodeckException", "(", "\"The given day length should be between above 0!\"", ")", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayCycleCommand", "(", "True", ")", "command_to_send", ".", "set_day_length", "(", "day_length", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a day cycle command to start the day cycle. It will be applied when `tick` or `step` is called next. The sky sphere will now update each tick with an updated sun angle as it moves about the sky. The length of a day will be roughly equivalent to the number of minutes given. Args: day_length (int): The number of minutes each day will be.
[ "Queue", "up", "a", "day", "cycle", "command", "to", "start", "the", "day", "cycle", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "The", "sky", "sphere", "will", "now", "update", "each", "tick", "with", "an", "updated", "sun", "angle", "as", "it", "moves", "about", "the", "sky", ".", "The", "length", "of", "a", "day", "will", "be", "roughly", "equivalent", "to", "the", "number", "of", "minutes", "given", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L303-L317
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.stop_day_cycle
def stop_day_cycle(self): """Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next. By the next tick, day cycle will stop where it is. """ self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(False) self._commands.add_command(command_to_send)
python
def stop_day_cycle(self): """Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next. By the next tick, day cycle will stop where it is. """ self._should_write_to_command_buffer = True command_to_send = DayCycleCommand(False) self._commands.add_command(command_to_send)
[ "def", "stop_day_cycle", "(", "self", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayCycleCommand", "(", "False", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a day cycle command to stop the day cycle. It will be applied when `tick` or `step` is called next. By the next tick, day cycle will stop where it is.
[ "Queue", "up", "a", "day", "cycle", "command", "to", "stop", "the", "day", "cycle", ".", "It", "will", "be", "applied", "when", "tick", "or", "step", "is", "called", "next", ".", "By", "the", "next", "tick", "day", "cycle", "will", "stop", "where", "it", "is", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L319-L325
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.teleport_camera
def teleport_camera(self, location, rotation): """Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated """ self._should_write_to_command_buffer = True command_to_send = TeleportCameraCommand(location, rotation) self._commands.add_command(command_to_send)
python
def teleport_camera(self, location, rotation): """Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated """ self._should_write_to_command_buffer = True command_to_send = TeleportCameraCommand(location, rotation) self._commands.add_command(command_to_send)
[ "def", "teleport_camera", "(", "self", ",", "location", ",", "rotation", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "TeleportCameraCommand", "(", "location", ",", "rotation", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ")" ]
Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated
[ "Queue", "up", "a", "teleport", "camera", "command", "to", "stop", "the", "day", "cycle", ".", "By", "the", "next", "tick", "the", "camera", "s", "location", "and", "rotation", "will", "be", "updated" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L327-L333
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment.set_control_scheme
def set_control_scheme(self, agent_name, control_scheme): """Set the control scheme for a specific agent. Args: agent_name (str): The name of the agent to set the control scheme for. control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`) """ if agent_name not in self.agents: print("No such agent %s" % agent_name) else: self.agents[agent_name].set_control_scheme(control_scheme)
python
def set_control_scheme(self, agent_name, control_scheme): """Set the control scheme for a specific agent. Args: agent_name (str): The name of the agent to set the control scheme for. control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`) """ if agent_name not in self.agents: print("No such agent %s" % agent_name) else: self.agents[agent_name].set_control_scheme(control_scheme)
[ "def", "set_control_scheme", "(", "self", ",", "agent_name", ",", "control_scheme", ")", ":", "if", "agent_name", "not", "in", "self", ".", "agents", ":", "print", "(", "\"No such agent %s\"", "%", "agent_name", ")", "else", ":", "self", ".", "agents", "[", "agent_name", "]", ".", "set_control_scheme", "(", "control_scheme", ")" ]
Set the control scheme for a specific agent. Args: agent_name (str): The name of the agent to set the control scheme for. control_scheme (int): A control scheme value (see :obj:`holodeck.agents.ControlSchemes`)
[ "Set", "the", "control", "scheme", "for", "a", "specific", "agent", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L357-L367
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment._handle_command_buffer
def _handle_command_buffer(self): """Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then clears the contents of the self._commands list""" if self._should_write_to_command_buffer: self._write_to_command_buffer(self._commands.to_json()) self._should_write_to_command_buffer = False self._commands.clear()
python
def _handle_command_buffer(self): """Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then clears the contents of the self._commands list""" if self._should_write_to_command_buffer: self._write_to_command_buffer(self._commands.to_json()) self._should_write_to_command_buffer = False self._commands.clear()
[ "def", "_handle_command_buffer", "(", "self", ")", ":", "if", "self", ".", "_should_write_to_command_buffer", ":", "self", ".", "_write_to_command_buffer", "(", "self", ".", "_commands", ".", "to_json", "(", ")", ")", "self", ".", "_should_write_to_command_buffer", "=", "False", "self", ".", "_commands", ".", "clear", "(", ")" ]
Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then clears the contents of the self._commands list
[ "Checks", "if", "we", "should", "write", "to", "the", "command", "buffer", "writes", "all", "of", "the", "queued", "commands", "to", "the", "buffer", "and", "then", "clears", "the", "contents", "of", "the", "self", ".", "_commands", "list" ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L423-L429
train
BYU-PCCL/holodeck
holodeck/environments.py
HolodeckEnvironment._write_to_command_buffer
def _write_to_command_buffer(self, to_write): """Write input to the command buffer. Reformat input string to the correct format. Args: to_write (str): The string to write to the command buffer. """ # TODO(mitch): Handle the edge case of writing too much data to the buffer. np.copyto(self._command_bool_ptr, True) to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of the file. input_bytes = str.encode(to_write) for index, val in enumerate(input_bytes): self._command_buffer_ptr[index] = val
python
def _write_to_command_buffer(self, to_write): """Write input to the command buffer. Reformat input string to the correct format. Args: to_write (str): The string to write to the command buffer. """ # TODO(mitch): Handle the edge case of writing too much data to the buffer. np.copyto(self._command_bool_ptr, True) to_write += '0' # The gason JSON parser in holodeck expects a 0 at the end of the file. input_bytes = str.encode(to_write) for index, val in enumerate(input_bytes): self._command_buffer_ptr[index] = val
[ "def", "_write_to_command_buffer", "(", "self", ",", "to_write", ")", ":", "# TODO(mitch): Handle the edge case of writing too much data to the buffer.", "np", ".", "copyto", "(", "self", ".", "_command_bool_ptr", ",", "True", ")", "to_write", "+=", "'0'", "# The gason JSON parser in holodeck expects a 0 at the end of the file.", "input_bytes", "=", "str", ".", "encode", "(", "to_write", ")", "for", "index", ",", "val", "in", "enumerate", "(", "input_bytes", ")", ":", "self", ".", "_command_buffer_ptr", "[", "index", "]", "=", "val" ]
Write input to the command buffer. Reformat input string to the correct format. Args: to_write (str): The string to write to the command buffer.
[ "Write", "input", "to", "the", "command", "buffer", ".", "Reformat", "input", "string", "to", "the", "correct", "format", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L453-L464
train
BYU-PCCL/holodeck
holodeck/agents.py
HolodeckAgent.teleport
def teleport(self, location=None, rotation=None): """Teleports the agent to a specific location, with a specific rotation. Args: location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters. If None, keeps the current location. Defaults to None. rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent. If None, keeps the current rotation. Defaults to None. Returns: None """ val = 0 if location is not None: val += 1 np.copyto(self._teleport_buffer, location) if rotation is not None: np.copyto(self._rotation_buffer, rotation) val += 2 self._teleport_bool_buffer[0] = val
python
def teleport(self, location=None, rotation=None): """Teleports the agent to a specific location, with a specific rotation. Args: location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters. If None, keeps the current location. Defaults to None. rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent. If None, keeps the current rotation. Defaults to None. Returns: None """ val = 0 if location is not None: val += 1 np.copyto(self._teleport_buffer, location) if rotation is not None: np.copyto(self._rotation_buffer, rotation) val += 2 self._teleport_bool_buffer[0] = val
[ "def", "teleport", "(", "self", ",", "location", "=", "None", ",", "rotation", "=", "None", ")", ":", "val", "=", "0", "if", "location", "is", "not", "None", ":", "val", "+=", "1", "np", ".", "copyto", "(", "self", ".", "_teleport_buffer", ",", "location", ")", "if", "rotation", "is", "not", "None", ":", "np", ".", "copyto", "(", "self", ".", "_rotation_buffer", ",", "rotation", ")", "val", "+=", "2", "self", ".", "_teleport_bool_buffer", "[", "0", "]", "=", "val" ]
Teleports the agent to a specific location, with a specific rotation. Args: location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters. If None, keeps the current location. Defaults to None. rotation (np.ndarray, optional): An array with three elements specifying the target rotation of the agent. If None, keeps the current rotation. Defaults to None. Returns: None
[ "Teleports", "the", "agent", "to", "a", "specific", "location", "with", "a", "specific", "rotation", "." ]
01acd4013f5acbd9f61fbc9caaafe19975e8b121
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/agents.py#L79-L98
train
browniebroke/deezer-python
deezer/client.py
Client.url
def url(self, request=""): """Build the url with the appended request if provided.""" if request.startswith("/"): request = request[1:] return "{}://{}/{}".format(self.scheme, self.host, request)
python
def url(self, request=""): """Build the url with the appended request if provided.""" if request.startswith("/"): request = request[1:] return "{}://{}/{}".format(self.scheme, self.host, request)
[ "def", "url", "(", "self", ",", "request", "=", "\"\"", ")", ":", "if", "request", ".", "startswith", "(", "\"/\"", ")", ":", "request", "=", "request", "[", "1", ":", "]", "return", "\"{}://{}/{}\"", ".", "format", "(", "self", ".", "scheme", ",", "self", ".", "host", ",", "request", ")" ]
Build the url with the appended request if provided.
[ "Build", "the", "url", "with", "the", "appended", "request", "if", "provided", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L95-L99
train
browniebroke/deezer-python
deezer/client.py
Client.object_url
def object_url(self, object_t, object_id=None, relation=None, **kwargs): """ Helper method to build the url to query to access the object passed as parameter :raises TypeError: if the object type is invalid """ if object_t not in self.objects_types: raise TypeError("{} is not a valid type".format(object_t)) request_items = ( str(item) for item in [object_t, object_id, relation] if item is not None ) request = "/".join(request_items) base_url = self.url(request) if self.access_token is not None: kwargs["access_token"] = str(self.access_token) if kwargs: for key, value in kwargs.items(): if not isinstance(value, str): kwargs[key] = str(value) # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7) sorted_kwargs = SortedDict.from_dict(kwargs) result = "{}?{}".format(base_url, urlencode(sorted_kwargs)) else: result = base_url return result
python
def object_url(self, object_t, object_id=None, relation=None, **kwargs): """ Helper method to build the url to query to access the object passed as parameter :raises TypeError: if the object type is invalid """ if object_t not in self.objects_types: raise TypeError("{} is not a valid type".format(object_t)) request_items = ( str(item) for item in [object_t, object_id, relation] if item is not None ) request = "/".join(request_items) base_url = self.url(request) if self.access_token is not None: kwargs["access_token"] = str(self.access_token) if kwargs: for key, value in kwargs.items(): if not isinstance(value, str): kwargs[key] = str(value) # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7) sorted_kwargs = SortedDict.from_dict(kwargs) result = "{}?{}".format(base_url, urlencode(sorted_kwargs)) else: result = base_url return result
[ "def", "object_url", "(", "self", ",", "object_t", ",", "object_id", "=", "None", ",", "relation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "object_t", "not", "in", "self", ".", "objects_types", ":", "raise", "TypeError", "(", "\"{} is not a valid type\"", ".", "format", "(", "object_t", ")", ")", "request_items", "=", "(", "str", "(", "item", ")", "for", "item", "in", "[", "object_t", ",", "object_id", ",", "relation", "]", "if", "item", "is", "not", "None", ")", "request", "=", "\"/\"", ".", "join", "(", "request_items", ")", "base_url", "=", "self", ".", "url", "(", "request", ")", "if", "self", ".", "access_token", "is", "not", "None", ":", "kwargs", "[", "\"access_token\"", "]", "=", "str", "(", "self", ".", "access_token", ")", "if", "kwargs", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "kwargs", "[", "key", "]", "=", "str", "(", "value", ")", "# kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7)", "sorted_kwargs", "=", "SortedDict", ".", "from_dict", "(", "kwargs", ")", "result", "=", "\"{}?{}\"", ".", "format", "(", "base_url", ",", "urlencode", "(", "sorted_kwargs", ")", ")", "else", ":", "result", "=", "base_url", "return", "result" ]
Helper method to build the url to query to access the object passed as parameter :raises TypeError: if the object type is invalid
[ "Helper", "method", "to", "build", "the", "url", "to", "query", "to", "access", "the", "object", "passed", "as", "parameter" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L101-L126
train
browniebroke/deezer-python
deezer/client.py
Client.get_album
def get_album(self, object_id, relation=None, **kwargs): """ Get the album with the provided id :returns: an :class:`~deezer.resources.Album` object """ return self.get_object("album", object_id, relation=relation, **kwargs)
python
def get_album(self, object_id, relation=None, **kwargs): """ Get the album with the provided id :returns: an :class:`~deezer.resources.Album` object """ return self.get_object("album", object_id, relation=relation, **kwargs)
[ "def", "get_album", "(", "self", ",", "object_id", ",", "relation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_object", "(", "\"album\"", ",", "object_id", ",", "relation", "=", "relation", ",", "*", "*", "kwargs", ")" ]
Get the album with the provided id :returns: an :class:`~deezer.resources.Album` object
[ "Get", "the", "album", "with", "the", "provided", "id" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L150-L156
train
browniebroke/deezer-python
deezer/client.py
Client.get_artist
def get_artist(self, object_id, relation=None, **kwargs): """ Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object """ return self.get_object("artist", object_id, relation=relation, **kwargs)
python
def get_artist(self, object_id, relation=None, **kwargs): """ Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object """ return self.get_object("artist", object_id, relation=relation, **kwargs)
[ "def", "get_artist", "(", "self", ",", "object_id", ",", "relation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_object", "(", "\"artist\"", ",", "object_id", ",", "relation", "=", "relation", ",", "*", "*", "kwargs", ")" ]
Get the artist with the provided id :returns: an :class:`~deezer.resources.Artist` object
[ "Get", "the", "artist", "with", "the", "provided", "id" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L158-L164
train
browniebroke/deezer-python
deezer/client.py
Client.search
def search(self, query, relation=None, index=0, limit=25, **kwargs): """ Search track, album, artist or user :returns: a list of :class:`~deezer.resources.Resource` objects. """ return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
python
def search(self, query, relation=None, index=0, limit=25, **kwargs): """ Search track, album, artist or user :returns: a list of :class:`~deezer.resources.Resource` objects. """ return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
[ "def", "search", "(", "self", ",", "query", ",", "relation", "=", "None", ",", "index", "=", "0", ",", "limit", "=", "25", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_object", "(", "\"search\"", ",", "relation", "=", "relation", ",", "q", "=", "query", ",", "index", "=", "index", ",", "limit", "=", "limit", ",", "*", "*", "kwargs", ")" ]
Search track, album, artist or user :returns: a list of :class:`~deezer.resources.Resource` objects.
[ "Search", "track", "album", "artist", "or", "user" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L236-L244
train
browniebroke/deezer-python
deezer/client.py
Client.advanced_search
def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs): """ Advanced search of track, album or artist. See `Search section of Deezer API <https://developers.deezer.com/api/search>`_ for search terms. :returns: a list of :class:`~deezer.resources.Resource` objects. >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}) >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}, ... relation="track") """ assert isinstance(terms, dict), "terms must be a dict" # terms are sorted (for consistent tests between Python < 3.7 and >= 3.7) query = " ".join(sorted(['{}:"{}"'.format(k, v) for (k, v) in terms.items()])) return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
python
def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs): """ Advanced search of track, album or artist. See `Search section of Deezer API <https://developers.deezer.com/api/search>`_ for search terms. :returns: a list of :class:`~deezer.resources.Resource` objects. >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}) >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}, ... relation="track") """ assert isinstance(terms, dict), "terms must be a dict" # terms are sorted (for consistent tests between Python < 3.7 and >= 3.7) query = " ".join(sorted(['{}:"{}"'.format(k, v) for (k, v) in terms.items()])) return self.get_object( "search", relation=relation, q=query, index=index, limit=limit, **kwargs )
[ "def", "advanced_search", "(", "self", ",", "terms", ",", "relation", "=", "None", ",", "index", "=", "0", ",", "limit", "=", "25", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "terms", ",", "dict", ")", ",", "\"terms must be a dict\"", "# terms are sorted (for consistent tests between Python < 3.7 and >= 3.7)", "query", "=", "\" \"", ".", "join", "(", "sorted", "(", "[", "'{}:\"{}\"'", ".", "format", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "terms", ".", "items", "(", ")", "]", ")", ")", "return", "self", ".", "get_object", "(", "\"search\"", ",", "relation", "=", "relation", ",", "q", "=", "query", ",", "index", "=", "index", ",", "limit", "=", "limit", ",", "*", "*", "kwargs", ")" ]
Advanced search of track, album or artist. See `Search section of Deezer API <https://developers.deezer.com/api/search>`_ for search terms. :returns: a list of :class:`~deezer.resources.Resource` objects. >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}) >>> client.advanced_search({"artist": "Daft Punk", "album": "Homework"}, ... relation="track")
[ "Advanced", "search", "of", "track", "album", "or", "artist", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/client.py#L246-L264
train
browniebroke/deezer-python
deezer/resources.py
Resource.asdict
def asdict(self): """ Convert resource to dictionary """ result = {} for key in self._fields: value = getattr(self, key) if isinstance(value, list): value = [i.asdict() if isinstance(i, Resource) else i for i in value] if isinstance(value, Resource): value = value.asdict() result[key] = value return result
python
def asdict(self): """ Convert resource to dictionary """ result = {} for key in self._fields: value = getattr(self, key) if isinstance(value, list): value = [i.asdict() if isinstance(i, Resource) else i for i in value] if isinstance(value, Resource): value = value.asdict() result[key] = value return result
[ "def", "asdict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "key", "in", "self", ".", "_fields", ":", "value", "=", "getattr", "(", "self", ",", "key", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "i", ".", "asdict", "(", ")", "if", "isinstance", "(", "i", ",", "Resource", ")", "else", "i", "for", "i", "in", "value", "]", "if", "isinstance", "(", "value", ",", "Resource", ")", ":", "value", "=", "value", ".", "asdict", "(", ")", "result", "[", "key", "]", "=", "value", "return", "result" ]
Convert resource to dictionary
[ "Convert", "resource", "to", "dictionary" ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/resources.py#L28-L40
train
browniebroke/deezer-python
deezer/resources.py
Resource.get_relation
def get_relation(self, relation, **kwargs): """ Generic method to load the relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 return self.client.get_object(self.type, self.id, relation, self, **kwargs)
python
def get_relation(self, relation, **kwargs): """ Generic method to load the relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 return self.client.get_object(self.type, self.id, relation, self, **kwargs)
[ "def", "get_relation", "(", "self", ",", "relation", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=E1101", "return", "self", ".", "client", ".", "get_object", "(", "self", ".", "type", ",", "self", ".", "id", ",", "relation", ",", "self", ",", "*", "*", "kwargs", ")" ]
Generic method to load the relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects.
[ "Generic", "method", "to", "load", "the", "relation", "from", "any", "resource", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/resources.py#L42-L52
train
browniebroke/deezer-python
deezer/resources.py
Resource.iter_relation
def iter_relation(self, relation, **kwargs): """ Generic method to iterate relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 index = 0 while 1: items = self.get_relation(relation, index=index, **kwargs) for item in items: yield (item) if len(items) == 0: break index += len(items)
python
def iter_relation(self, relation, **kwargs): """ Generic method to iterate relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects. """ # pylint: disable=E1101 index = 0 while 1: items = self.get_relation(relation, index=index, **kwargs) for item in items: yield (item) if len(items) == 0: break index += len(items)
[ "def", "iter_relation", "(", "self", ",", "relation", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=E1101", "index", "=", "0", "while", "1", ":", "items", "=", "self", ".", "get_relation", "(", "relation", ",", "index", "=", "index", ",", "*", "*", "kwargs", ")", "for", "item", "in", "items", ":", "yield", "(", "item", ")", "if", "len", "(", "items", ")", "==", "0", ":", "break", "index", "+=", "len", "(", "items", ")" ]
Generic method to iterate relation from any resource. Query the client with the object's known parameters and try to retrieve the provided relation type. This is not meant to be used directly by a client, it's more a helper method for the child objects.
[ "Generic", "method", "to", "iterate", "relation", "from", "any", "resource", "." ]
fb869c3617045b22e7124e4b783ec1a68d283ac3
https://github.com/browniebroke/deezer-python/blob/fb869c3617045b22e7124e4b783ec1a68d283ac3/deezer/resources.py#L54-L72
train
lambdamusic/Ontospy
ontospy/ontodocs/viz/viz_sigmajs.py
run
def run(graph, save_on_github=False, main_entity=None): """ 2016-11-30 """ try: ontology = graph.all_ontologies[0] uri = ontology.uri except: ontology = None uri = ";".join([s for s in graph.sources]) # ontotemplate = open("template.html", "r") ontotemplate = open(ONTODOCS_VIZ_TEMPLATES + "sigmajs.html", "r") t = Template(ontotemplate.read()) dict_graph = build_class_json(graph.classes) JSON_DATA_CLASSES = json.dumps(dict_graph) if False: c_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_classes) p_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_properties) s_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_skos) c_total = len(graph.classes) p_total = len(graph.all_properties) s_total = len(graph.all_skos_concepts) # hack to make sure that we have a default top level object JSON_DATA_CLASSES = json.dumps({'children' : c_mylist, 'name' : 'owl:Thing', 'id' : "None" }) JSON_DATA_PROPERTIES = json.dumps({'children' : p_mylist, 'name' : 'Properties', 'id' : "None" }) JSON_DATA_CONCEPTS = json.dumps({'children' : s_mylist, 'name' : 'Concepts', 'id' : "None" }) c = Context({ "ontology": ontology, "main_uri" : uri, "STATIC_PATH": ONTODOCS_VIZ_STATIC, "classes": graph.classes, "classes_TOPLAYER": len(graph.toplayer_classes), "properties": graph.all_properties, "properties_TOPLAYER": len(graph.toplayer_properties), "skosConcepts": graph.all_skos_concepts, "skosConcepts_TOPLAYER": len(graph.toplayer_skos), # "TOTAL_CLASSES": c_total, # "TOTAL_PROPERTIES": p_total, # "TOTAL_CONCEPTS": s_total, 'JSON_DATA_CLASSES' : JSON_DATA_CLASSES, # 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES, # 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS, }) rnd = t.render(c) return safe_str(rnd)
python
def run(graph, save_on_github=False, main_entity=None): """ 2016-11-30 """ try: ontology = graph.all_ontologies[0] uri = ontology.uri except: ontology = None uri = ";".join([s for s in graph.sources]) # ontotemplate = open("template.html", "r") ontotemplate = open(ONTODOCS_VIZ_TEMPLATES + "sigmajs.html", "r") t = Template(ontotemplate.read()) dict_graph = build_class_json(graph.classes) JSON_DATA_CLASSES = json.dumps(dict_graph) if False: c_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_classes) p_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_properties) s_mylist = build_D3treeStandard(0, 99, 1, graph.toplayer_skos) c_total = len(graph.classes) p_total = len(graph.all_properties) s_total = len(graph.all_skos_concepts) # hack to make sure that we have a default top level object JSON_DATA_CLASSES = json.dumps({'children' : c_mylist, 'name' : 'owl:Thing', 'id' : "None" }) JSON_DATA_PROPERTIES = json.dumps({'children' : p_mylist, 'name' : 'Properties', 'id' : "None" }) JSON_DATA_CONCEPTS = json.dumps({'children' : s_mylist, 'name' : 'Concepts', 'id' : "None" }) c = Context({ "ontology": ontology, "main_uri" : uri, "STATIC_PATH": ONTODOCS_VIZ_STATIC, "classes": graph.classes, "classes_TOPLAYER": len(graph.toplayer_classes), "properties": graph.all_properties, "properties_TOPLAYER": len(graph.toplayer_properties), "skosConcepts": graph.all_skos_concepts, "skosConcepts_TOPLAYER": len(graph.toplayer_skos), # "TOTAL_CLASSES": c_total, # "TOTAL_PROPERTIES": p_total, # "TOTAL_CONCEPTS": s_total, 'JSON_DATA_CLASSES' : JSON_DATA_CLASSES, # 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES, # 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS, }) rnd = t.render(c) return safe_str(rnd)
[ "def", "run", "(", "graph", ",", "save_on_github", "=", "False", ",", "main_entity", "=", "None", ")", ":", "try", ":", "ontology", "=", "graph", ".", "all_ontologies", "[", "0", "]", "uri", "=", "ontology", ".", "uri", "except", ":", "ontology", "=", "None", "uri", "=", "\";\"", ".", "join", "(", "[", "s", "for", "s", "in", "graph", ".", "sources", "]", ")", "# ontotemplate = open(\"template.html\", \"r\")", "ontotemplate", "=", "open", "(", "ONTODOCS_VIZ_TEMPLATES", "+", "\"sigmajs.html\"", ",", "\"r\"", ")", "t", "=", "Template", "(", "ontotemplate", ".", "read", "(", ")", ")", "dict_graph", "=", "build_class_json", "(", "graph", ".", "classes", ")", "JSON_DATA_CLASSES", "=", "json", ".", "dumps", "(", "dict_graph", ")", "if", "False", ":", "c_mylist", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "graph", ".", "toplayer_classes", ")", "p_mylist", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "graph", ".", "toplayer_properties", ")", "s_mylist", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "graph", ".", "toplayer_skos", ")", "c_total", "=", "len", "(", "graph", ".", "classes", ")", "p_total", "=", "len", "(", "graph", ".", "all_properties", ")", "s_total", "=", "len", "(", "graph", ".", "all_skos_concepts", ")", "# hack to make sure that we have a default top level object", "JSON_DATA_CLASSES", "=", "json", ".", "dumps", "(", "{", "'children'", ":", "c_mylist", ",", "'name'", ":", "'owl:Thing'", ",", "'id'", ":", "\"None\"", "}", ")", "JSON_DATA_PROPERTIES", "=", "json", ".", "dumps", "(", "{", "'children'", ":", "p_mylist", ",", "'name'", ":", "'Properties'", ",", "'id'", ":", "\"None\"", "}", ")", "JSON_DATA_CONCEPTS", "=", "json", ".", "dumps", "(", "{", "'children'", ":", "s_mylist", ",", "'name'", ":", "'Concepts'", ",", "'id'", ":", "\"None\"", "}", ")", "c", "=", "Context", "(", "{", "\"ontology\"", ":", "ontology", ",", "\"main_uri\"", ":", "uri", ",", "\"STATIC_PATH\"", ":", "ONTODOCS_VIZ_STATIC", ",", "\"classes\"", ":", "graph", ".", "classes", ",", "\"classes_TOPLAYER\"", ":", "len", "(", "graph", ".", "toplayer_classes", ")", ",", "\"properties\"", ":", "graph", ".", "all_properties", ",", "\"properties_TOPLAYER\"", ":", "len", "(", "graph", ".", "toplayer_properties", ")", ",", "\"skosConcepts\"", ":", "graph", ".", "all_skos_concepts", ",", "\"skosConcepts_TOPLAYER\"", ":", "len", "(", "graph", ".", "toplayer_skos", ")", ",", "# \"TOTAL_CLASSES\": c_total,", "# \"TOTAL_PROPERTIES\": p_total,", "# \"TOTAL_CONCEPTS\": s_total,", "'JSON_DATA_CLASSES'", ":", "JSON_DATA_CLASSES", ",", "# 'JSON_DATA_PROPERTIES' : JSON_DATA_PROPERTIES,", "# 'JSON_DATA_CONCEPTS' : JSON_DATA_CONCEPTS,", "}", ")", "rnd", "=", "t", ".", "render", "(", "c", ")", "return", "safe_str", "(", "rnd", ")" ]
2016-11-30
[ "2016", "-", "11", "-", "30" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz/viz_sigmajs.py#L149-L204
train
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader._debugGraph
def _debugGraph(self): """internal util to print out contents of graph""" print("Len of graph: ", len(self.rdflib_graph)) for x, y, z in self.rdflib_graph: print(x, y, z)
python
def _debugGraph(self): """internal util to print out contents of graph""" print("Len of graph: ", len(self.rdflib_graph)) for x, y, z in self.rdflib_graph: print(x, y, z)
[ "def", "_debugGraph", "(", "self", ")", ":", "print", "(", "\"Len of graph: \"", ",", "len", "(", "self", ".", "rdflib_graph", ")", ")", "for", "x", ",", "y", ",", "z", "in", "self", ".", "rdflib_graph", ":", "print", "(", "x", ",", "y", ",", "z", ")" ]
internal util to print out contents of graph
[ "internal", "util", "to", "print", "out", "contents", "of", "graph" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L61-L65
train
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader.load_uri
def load_uri(self, uri): """ Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/issues/436). Also it deals with the RDFA error message which seems to stick into a graph even if the parse operation fails. NOTE the final merge operation can be improved as graph-set operations involving blank nodes could case collisions (https://rdflib.readthedocs.io/en/stable/merging.html) :param uri: single RDF source location :return: None (sets self.rdflib_graph and self.sources_valid) """ # if self.verbose: printDebug("----------") if self.verbose: printDebug("Reading: <%s>" % uri, fg="green") success = False sorted_fmt_opts = try_sort_fmt_opts(self.rdf_format_opts, uri) for f in sorted_fmt_opts: if self.verbose: printDebug(".. trying rdf serialization: <%s>" % f) try: if f == 'json-ld': if self.verbose: printDebug( "Detected JSONLD - loading data into rdflib.ConjunctiveGraph()", fg='green') temp_graph = rdflib.ConjunctiveGraph() else: temp_graph = rdflib.Graph() temp_graph.parse(uri, format=f) if self.verbose: printDebug("..... success!", bold=True) success = True self.sources_valid += [uri] # ok, so merge self.rdflib_graph = self.rdflib_graph + temp_graph break except: temp = None if self.verbose: printDebug("..... failed") # self._debugGraph() if not success == True: self.loading_failed(sorted_fmt_opts, uri=uri) self.sources_invalid += [uri]
python
def load_uri(self, uri): """ Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/issues/436). Also it deals with the RDFA error message which seems to stick into a graph even if the parse operation fails. NOTE the final merge operation can be improved as graph-set operations involving blank nodes could case collisions (https://rdflib.readthedocs.io/en/stable/merging.html) :param uri: single RDF source location :return: None (sets self.rdflib_graph and self.sources_valid) """ # if self.verbose: printDebug("----------") if self.verbose: printDebug("Reading: <%s>" % uri, fg="green") success = False sorted_fmt_opts = try_sort_fmt_opts(self.rdf_format_opts, uri) for f in sorted_fmt_opts: if self.verbose: printDebug(".. trying rdf serialization: <%s>" % f) try: if f == 'json-ld': if self.verbose: printDebug( "Detected JSONLD - loading data into rdflib.ConjunctiveGraph()", fg='green') temp_graph = rdflib.ConjunctiveGraph() else: temp_graph = rdflib.Graph() temp_graph.parse(uri, format=f) if self.verbose: printDebug("..... success!", bold=True) success = True self.sources_valid += [uri] # ok, so merge self.rdflib_graph = self.rdflib_graph + temp_graph break except: temp = None if self.verbose: printDebug("..... failed") # self._debugGraph() if not success == True: self.loading_failed(sorted_fmt_opts, uri=uri) self.sources_invalid += [uri]
[ "def", "load_uri", "(", "self", ",", "uri", ")", ":", "# if self.verbose: printDebug(\"----------\")", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"Reading: <%s>\"", "%", "uri", ",", "fg", "=", "\"green\"", ")", "success", "=", "False", "sorted_fmt_opts", "=", "try_sort_fmt_opts", "(", "self", ".", "rdf_format_opts", ",", "uri", ")", "for", "f", "in", "sorted_fmt_opts", ":", "if", "self", ".", "verbose", ":", "printDebug", "(", "\".. trying rdf serialization: <%s>\"", "%", "f", ")", "try", ":", "if", "f", "==", "'json-ld'", ":", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"Detected JSONLD - loading data into rdflib.ConjunctiveGraph()\"", ",", "fg", "=", "'green'", ")", "temp_graph", "=", "rdflib", ".", "ConjunctiveGraph", "(", ")", "else", ":", "temp_graph", "=", "rdflib", ".", "Graph", "(", ")", "temp_graph", ".", "parse", "(", "uri", ",", "format", "=", "f", ")", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"..... success!\"", ",", "bold", "=", "True", ")", "success", "=", "True", "self", ".", "sources_valid", "+=", "[", "uri", "]", "# ok, so merge", "self", ".", "rdflib_graph", "=", "self", ".", "rdflib_graph", "+", "temp_graph", "break", "except", ":", "temp", "=", "None", "if", "self", ".", "verbose", ":", "printDebug", "(", "\"..... failed\"", ")", "# self._debugGraph()", "if", "not", "success", "==", "True", ":", "self", ".", "loading_failed", "(", "sorted_fmt_opts", ",", "uri", "=", "uri", ")", "self", ".", "sources_invalid", "+=", "[", "uri", "]" ]
Load a single resource into the graph for this object. Approach: try loading into a temporary graph first, if that succeeds merge it into the main graph. This allows to deal with the JSONLD loading issues which can solved only by using a ConjunctiveGraph (https://github.com/RDFLib/rdflib/issues/436). Also it deals with the RDFA error message which seems to stick into a graph even if the parse operation fails. NOTE the final merge operation can be improved as graph-set operations involving blank nodes could case collisions (https://rdflib.readthedocs.io/en/stable/merging.html) :param uri: single RDF source location :return: None (sets self.rdflib_graph and self.sources_valid)
[ "Load", "a", "single", "resource", "into", "the", "graph", "for", "this", "object", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L114-L158
train
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader.print_summary
def print_summary(self): """ print out stats about loading operation """ if self.sources_valid: printDebug( "----------\nLoaded %d triples.\n----------" % len( self.rdflib_graph), fg='white') printDebug( "RDF sources loaded successfully: %d of %d." % (len(self.sources_valid), len(self.sources_valid) + len(self.sources_invalid)), fg='green') for s in self.sources_valid: printDebug("..... '" + s + "'", fg='white') printDebug("----------", fg='white') else: printDebug("Sorry - no valid RDF was found", fg='red') if self.sources_invalid: printDebug( "----------\nRDF sources failed to load: %d.\n----------" % (len(self.sources_invalid)), fg='red') for s in self.sources_invalid: printDebug("-> " + s, fg="red")
python
def print_summary(self): """ print out stats about loading operation """ if self.sources_valid: printDebug( "----------\nLoaded %d triples.\n----------" % len( self.rdflib_graph), fg='white') printDebug( "RDF sources loaded successfully: %d of %d." % (len(self.sources_valid), len(self.sources_valid) + len(self.sources_invalid)), fg='green') for s in self.sources_valid: printDebug("..... '" + s + "'", fg='white') printDebug("----------", fg='white') else: printDebug("Sorry - no valid RDF was found", fg='red') if self.sources_invalid: printDebug( "----------\nRDF sources failed to load: %d.\n----------" % (len(self.sources_invalid)), fg='red') for s in self.sources_invalid: printDebug("-> " + s, fg="red")
[ "def", "print_summary", "(", "self", ")", ":", "if", "self", ".", "sources_valid", ":", "printDebug", "(", "\"----------\\nLoaded %d triples.\\n----------\"", "%", "len", "(", "self", ".", "rdflib_graph", ")", ",", "fg", "=", "'white'", ")", "printDebug", "(", "\"RDF sources loaded successfully: %d of %d.\"", "%", "(", "len", "(", "self", ".", "sources_valid", ")", ",", "len", "(", "self", ".", "sources_valid", ")", "+", "len", "(", "self", ".", "sources_invalid", ")", ")", ",", "fg", "=", "'green'", ")", "for", "s", "in", "self", ".", "sources_valid", ":", "printDebug", "(", "\"..... '\"", "+", "s", "+", "\"'\"", ",", "fg", "=", "'white'", ")", "printDebug", "(", "\"----------\"", ",", "fg", "=", "'white'", ")", "else", ":", "printDebug", "(", "\"Sorry - no valid RDF was found\"", ",", "fg", "=", "'red'", ")", "if", "self", ".", "sources_invalid", ":", "printDebug", "(", "\"----------\\nRDF sources failed to load: %d.\\n----------\"", "%", "(", "len", "(", "self", ".", "sources_invalid", ")", ")", ",", "fg", "=", "'red'", ")", "for", "s", "in", "self", ".", "sources_invalid", ":", "printDebug", "(", "\"-> \"", "+", "s", ",", "fg", "=", "\"red\"", ")" ]
print out stats about loading operation
[ "print", "out", "stats", "about", "loading", "operation" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L225-L251
train
lambdamusic/Ontospy
ontospy/core/rdf_loader.py
RDFLoader.loading_failed
def loading_failed(self, rdf_format_opts, uri=""): """default message if we need to abort loading""" if uri: uri = " <%s>" % str(uri) printDebug( "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)" % (uri, str(rdf_format_opts)), "red") printDebug( "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\n<http://www.ivan-herman.net/Misc/2008/owlrl/>" ) return
python
def loading_failed(self, rdf_format_opts, uri=""): """default message if we need to abort loading""" if uri: uri = " <%s>" % str(uri) printDebug( "----------\nFatal error parsing graph%s\n(using RDF serializations: %s)" % (uri, str(rdf_format_opts)), "red") printDebug( "----------\nTIP: You can try one of the following RDF validation services\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\n<http://www.ivan-herman.net/Misc/2008/owlrl/>" ) return
[ "def", "loading_failed", "(", "self", ",", "rdf_format_opts", ",", "uri", "=", "\"\"", ")", ":", "if", "uri", ":", "uri", "=", "\" <%s>\"", "%", "str", "(", "uri", ")", "printDebug", "(", "\"----------\\nFatal error parsing graph%s\\n(using RDF serializations: %s)\"", "%", "(", "uri", ",", "str", "(", "rdf_format_opts", ")", ")", ",", "\"red\"", ")", "printDebug", "(", "\"----------\\nTIP: You can try one of the following RDF validation services\\n<http://mowl-power.cs.man.ac.uk:8080/validator/validate>\\n<http://www.ivan-herman.net/Misc/2008/owlrl/>\"", ")", "return" ]
default message if we need to abort loading
[ "default", "message", "if", "we", "need", "to", "abort", "loading" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/rdf_loader.py#L253-L264
train
lambdamusic/Ontospy
ontospy/core/entities.py
RDF_Entity._build_qname
def _build_qname(self, uri=None, namespaces=None): """ extracts a qualified name for a uri """ if not uri: uri = self.uri if not namespaces: namespaces = self.namespaces return uri2niceString(uri, namespaces)
python
def _build_qname(self, uri=None, namespaces=None): """ extracts a qualified name for a uri """ if not uri: uri = self.uri if not namespaces: namespaces = self.namespaces return uri2niceString(uri, namespaces)
[ "def", "_build_qname", "(", "self", ",", "uri", "=", "None", ",", "namespaces", "=", "None", ")", ":", "if", "not", "uri", ":", "uri", "=", "self", ".", "uri", "if", "not", "namespaces", ":", "namespaces", "=", "self", ".", "namespaces", "return", "uri2niceString", "(", "uri", ",", "namespaces", ")" ]
extracts a qualified name for a uri
[ "extracts", "a", "qualified", "name", "for", "a", "uri" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/entities.py#L93-L99
train
lambdamusic/Ontospy
ontospy/core/entities.py
RDF_Entity.ancestors
def ancestors(self, cl=None, noduplicates=True): """ returns all ancestors in the taxonomy """ if not cl: cl = self if cl.parents(): bag = [] for x in cl.parents(): if x.uri != cl.uri: # avoid circular relationships bag += [x] + self.ancestors(x, noduplicates) else: bag += [x] # finally: if noduplicates: return remove_duplicates(bag) else: return bag else: return []
python
def ancestors(self, cl=None, noduplicates=True): """ returns all ancestors in the taxonomy """ if not cl: cl = self if cl.parents(): bag = [] for x in cl.parents(): if x.uri != cl.uri: # avoid circular relationships bag += [x] + self.ancestors(x, noduplicates) else: bag += [x] # finally: if noduplicates: return remove_duplicates(bag) else: return bag else: return []
[ "def", "ancestors", "(", "self", ",", "cl", "=", "None", ",", "noduplicates", "=", "True", ")", ":", "if", "not", "cl", ":", "cl", "=", "self", "if", "cl", ".", "parents", "(", ")", ":", "bag", "=", "[", "]", "for", "x", "in", "cl", ".", "parents", "(", ")", ":", "if", "x", ".", "uri", "!=", "cl", ".", "uri", ":", "# avoid circular relationships", "bag", "+=", "[", "x", "]", "+", "self", ".", "ancestors", "(", "x", ",", "noduplicates", ")", "else", ":", "bag", "+=", "[", "x", "]", "# finally:", "if", "noduplicates", ":", "return", "remove_duplicates", "(", "bag", ")", "else", ":", "return", "bag", "else", ":", "return", "[", "]" ]
returns all ancestors in the taxonomy
[ "returns", "all", "ancestors", "in", "the", "taxonomy" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/entities.py#L114-L131
train
lambdamusic/Ontospy
ontospy/core/entities.py
RDF_Entity.descendants
def descendants(self, cl=None, noduplicates=True): """ returns all descendants in the taxonomy """ if not cl: cl = self if cl.children(): bag = [] for x in cl.children(): if x.uri != cl.uri: # avoid circular relationships bag += [x] + self.descendants(x, noduplicates) else: bag += [x] # finally: if noduplicates: return remove_duplicates(bag) else: return bag else: return []
python
def descendants(self, cl=None, noduplicates=True): """ returns all descendants in the taxonomy """ if not cl: cl = self if cl.children(): bag = [] for x in cl.children(): if x.uri != cl.uri: # avoid circular relationships bag += [x] + self.descendants(x, noduplicates) else: bag += [x] # finally: if noduplicates: return remove_duplicates(bag) else: return bag else: return []
[ "def", "descendants", "(", "self", ",", "cl", "=", "None", ",", "noduplicates", "=", "True", ")", ":", "if", "not", "cl", ":", "cl", "=", "self", "if", "cl", ".", "children", "(", ")", ":", "bag", "=", "[", "]", "for", "x", "in", "cl", ".", "children", "(", ")", ":", "if", "x", ".", "uri", "!=", "cl", ".", "uri", ":", "# avoid circular relationships", "bag", "+=", "[", "x", "]", "+", "self", ".", "descendants", "(", "x", ",", "noduplicates", ")", "else", ":", "bag", "+=", "[", "x", "]", "# finally:", "if", "noduplicates", ":", "return", "remove_duplicates", "(", "bag", ")", "else", ":", "return", "bag", "else", ":", "return", "[", "]" ]
returns all descendants in the taxonomy
[ "returns", "all", "descendants", "in", "the", "taxonomy" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/entities.py#L133-L150
train
lambdamusic/Ontospy
ontospy/core/entities.py
Ontology.annotations
def annotations(self, qname=True): """ wrapper that returns all triples for an onto. By default resources URIs are transformed into qnames """ if qname: return sorted([(uri2niceString(x, self.namespaces) ), (uri2niceString(y, self.namespaces)), z] for x, y, z in self.triples) else: return sorted(self.triples)
python
def annotations(self, qname=True): """ wrapper that returns all triples for an onto. By default resources URIs are transformed into qnames """ if qname: return sorted([(uri2niceString(x, self.namespaces) ), (uri2niceString(y, self.namespaces)), z] for x, y, z in self.triples) else: return sorted(self.triples)
[ "def", "annotations", "(", "self", ",", "qname", "=", "True", ")", ":", "if", "qname", ":", "return", "sorted", "(", "[", "(", "uri2niceString", "(", "x", ",", "self", ".", "namespaces", ")", ")", ",", "(", "uri2niceString", "(", "y", ",", "self", ".", "namespaces", ")", ")", ",", "z", "]", "for", "x", ",", "y", ",", "z", "in", "self", ".", "triples", ")", "else", ":", "return", "sorted", "(", "self", ".", "triples", ")" ]
wrapper that returns all triples for an onto. By default resources URIs are transformed into qnames
[ "wrapper", "that", "returns", "all", "triples", "for", "an", "onto", ".", "By", "default", "resources", "URIs", "are", "transformed", "into", "qnames" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/entities.py#L243-L253
train
lambdamusic/Ontospy
ontospy/core/entities.py
OntoClass.printStats
def printStats(self): """ shortcut to pull out useful info for interactive use """ printDebug("----------------") printDebug("Parents......: %d" % len(self.parents())) printDebug("Children.....: %d" % len(self.children())) printDebug("Ancestors....: %d" % len(self.ancestors())) printDebug("Descendants..: %d" % len(self.descendants())) printDebug("Domain of....: %d" % len(self.domain_of)) printDebug("Range of.....: %d" % len(self.range_of)) printDebug("Instances....: %d" % self.count()) printDebug("----------------")
python
def printStats(self): """ shortcut to pull out useful info for interactive use """ printDebug("----------------") printDebug("Parents......: %d" % len(self.parents())) printDebug("Children.....: %d" % len(self.children())) printDebug("Ancestors....: %d" % len(self.ancestors())) printDebug("Descendants..: %d" % len(self.descendants())) printDebug("Domain of....: %d" % len(self.domain_of)) printDebug("Range of.....: %d" % len(self.range_of)) printDebug("Instances....: %d" % self.count()) printDebug("----------------")
[ "def", "printStats", "(", "self", ")", ":", "printDebug", "(", "\"----------------\"", ")", "printDebug", "(", "\"Parents......: %d\"", "%", "len", "(", "self", ".", "parents", "(", ")", ")", ")", "printDebug", "(", "\"Children.....: %d\"", "%", "len", "(", "self", ".", "children", "(", ")", ")", ")", "printDebug", "(", "\"Ancestors....: %d\"", "%", "len", "(", "self", ".", "ancestors", "(", ")", ")", ")", "printDebug", "(", "\"Descendants..: %d\"", "%", "len", "(", "self", ".", "descendants", "(", ")", ")", ")", "printDebug", "(", "\"Domain of....: %d\"", "%", "len", "(", "self", ".", "domain_of", ")", ")", "printDebug", "(", "\"Range of.....: %d\"", "%", "len", "(", "self", ".", "range_of", ")", ")", "printDebug", "(", "\"Instances....: %d\"", "%", "self", ".", "count", "(", ")", ")", "printDebug", "(", "\"----------------\"", ")" ]
shortcut to pull out useful info for interactive use
[ "shortcut", "to", "pull", "out", "useful", "info", "for", "interactive", "use" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/entities.py#L325-L335
train
lambdamusic/Ontospy
ontospy/core/ontospy.py
Ontospy.load_sparql
def load_sparql(self, sparql_endpoint, verbose=False, hide_base_schemas=True, hide_implicit_types=True, hide_implicit_preds=True, credentials=None): """ Set up a SPARQLStore backend as a virtual ontospy graph Note: we're using a 'SPARQLUpdateStore' backend instead of 'SPARQLStore' cause otherwise authentication fails (https://github.com/RDFLib/rdflib/issues/755) @TODO this error seems to be fixed in upcoming rdflib versions https://github.com/RDFLib/rdflib/pull/744 """ try: # graph = rdflib.Graph('SPARQLStore') # graph = rdflib.ConjunctiveGraph('SPARQLStore') graph = rdflib.ConjunctiveGraph('SPARQLUpdateStore') if credentials and type(credentials) == tuple: # https://github.com/RDFLib/rdflib/issues/343 graph.store.setCredentials(credentials[0], credentials[1]) # graph.store.setHTTPAuth('BASIC') # graph.store.setHTTPAuth('DIGEST') graph.open(sparql_endpoint) self.rdflib_graph = graph self.sparql_endpoint = sparql_endpoint self.sources = [sparql_endpoint] self.sparqlHelper = SparqlHelper(self.rdflib_graph, self.sparql_endpoint) self.namespaces = sorted(self.rdflib_graph.namespaces()) except: printDebug("Error trying to connect to Endpoint.") raise
python
def load_sparql(self, sparql_endpoint, verbose=False, hide_base_schemas=True, hide_implicit_types=True, hide_implicit_preds=True, credentials=None): """ Set up a SPARQLStore backend as a virtual ontospy graph Note: we're using a 'SPARQLUpdateStore' backend instead of 'SPARQLStore' cause otherwise authentication fails (https://github.com/RDFLib/rdflib/issues/755) @TODO this error seems to be fixed in upcoming rdflib versions https://github.com/RDFLib/rdflib/pull/744 """ try: # graph = rdflib.Graph('SPARQLStore') # graph = rdflib.ConjunctiveGraph('SPARQLStore') graph = rdflib.ConjunctiveGraph('SPARQLUpdateStore') if credentials and type(credentials) == tuple: # https://github.com/RDFLib/rdflib/issues/343 graph.store.setCredentials(credentials[0], credentials[1]) # graph.store.setHTTPAuth('BASIC') # graph.store.setHTTPAuth('DIGEST') graph.open(sparql_endpoint) self.rdflib_graph = graph self.sparql_endpoint = sparql_endpoint self.sources = [sparql_endpoint] self.sparqlHelper = SparqlHelper(self.rdflib_graph, self.sparql_endpoint) self.namespaces = sorted(self.rdflib_graph.namespaces()) except: printDebug("Error trying to connect to Endpoint.") raise
[ "def", "load_sparql", "(", "self", ",", "sparql_endpoint", ",", "verbose", "=", "False", ",", "hide_base_schemas", "=", "True", ",", "hide_implicit_types", "=", "True", ",", "hide_implicit_preds", "=", "True", ",", "credentials", "=", "None", ")", ":", "try", ":", "# graph = rdflib.Graph('SPARQLStore')", "# graph = rdflib.ConjunctiveGraph('SPARQLStore')", "graph", "=", "rdflib", ".", "ConjunctiveGraph", "(", "'SPARQLUpdateStore'", ")", "if", "credentials", "and", "type", "(", "credentials", ")", "==", "tuple", ":", "# https://github.com/RDFLib/rdflib/issues/343", "graph", ".", "store", ".", "setCredentials", "(", "credentials", "[", "0", "]", ",", "credentials", "[", "1", "]", ")", "# graph.store.setHTTPAuth('BASIC') # graph.store.setHTTPAuth('DIGEST')", "graph", ".", "open", "(", "sparql_endpoint", ")", "self", ".", "rdflib_graph", "=", "graph", "self", ".", "sparql_endpoint", "=", "sparql_endpoint", "self", ".", "sources", "=", "[", "sparql_endpoint", "]", "self", ".", "sparqlHelper", "=", "SparqlHelper", "(", "self", ".", "rdflib_graph", ",", "self", ".", "sparql_endpoint", ")", "self", ".", "namespaces", "=", "sorted", "(", "self", ".", "rdflib_graph", ".", "namespaces", "(", ")", ")", "except", ":", "printDebug", "(", "\"Error trying to connect to Endpoint.\"", ")", "raise" ]
Set up a SPARQLStore backend as a virtual ontospy graph Note: we're using a 'SPARQLUpdateStore' backend instead of 'SPARQLStore' cause otherwise authentication fails (https://github.com/RDFLib/rdflib/issues/755) @TODO this error seems to be fixed in upcoming rdflib versions https://github.com/RDFLib/rdflib/pull/744
[ "Set", "up", "a", "SPARQLStore", "backend", "as", "a", "virtual", "ontospy", "graph" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L144-L177
train
lambdamusic/Ontospy
ontospy/core/ontospy.py
Ontospy.build_all
def build_all(self, verbose=False, hide_base_schemas=True, hide_implicit_types=True, hide_implicit_preds=True): """ Extract all ontology entities from an RDF graph and construct Python representations of them. """ if verbose: printDebug("Scanning entities...", "green") printDebug("----------", "comment") self.build_ontologies() if verbose: printDebug("Ontologies.........: %d" % len(self.all_ontologies), "comment") self.build_classes(hide_base_schemas, hide_implicit_types) if verbose: printDebug("Classes............: %d" % len(self.all_classes), "comment") self.build_properties(hide_implicit_preds) if verbose: printDebug("Properties.........: %d" % len(self.all_properties), "comment") if verbose: printDebug("..annotation.......: %d" % len(self.all_properties_annotation), "comment") if verbose: printDebug("..datatype.........: %d" % len(self.all_properties_datatype), "comment") if verbose: printDebug("..object...........: %d" % len(self.all_properties_object), "comment") self.build_skos_concepts() if verbose: printDebug("Concepts (SKOS)....: %d" % len(self.all_skos_concepts), "comment") self.build_shapes() if verbose: printDebug("Shapes (SHACL).....: %d" % len(self.all_shapes), "comment") # self.__computeTopLayer() self.__computeInferredProperties() if verbose: printDebug("----------", "comment")
python
def build_all(self, verbose=False, hide_base_schemas=True, hide_implicit_types=True, hide_implicit_preds=True): """ Extract all ontology entities from an RDF graph and construct Python representations of them. """ if verbose: printDebug("Scanning entities...", "green") printDebug("----------", "comment") self.build_ontologies() if verbose: printDebug("Ontologies.........: %d" % len(self.all_ontologies), "comment") self.build_classes(hide_base_schemas, hide_implicit_types) if verbose: printDebug("Classes............: %d" % len(self.all_classes), "comment") self.build_properties(hide_implicit_preds) if verbose: printDebug("Properties.........: %d" % len(self.all_properties), "comment") if verbose: printDebug("..annotation.......: %d" % len(self.all_properties_annotation), "comment") if verbose: printDebug("..datatype.........: %d" % len(self.all_properties_datatype), "comment") if verbose: printDebug("..object...........: %d" % len(self.all_properties_object), "comment") self.build_skos_concepts() if verbose: printDebug("Concepts (SKOS)....: %d" % len(self.all_skos_concepts), "comment") self.build_shapes() if verbose: printDebug("Shapes (SHACL).....: %d" % len(self.all_shapes), "comment") # self.__computeTopLayer() self.__computeInferredProperties() if verbose: printDebug("----------", "comment")
[ "def", "build_all", "(", "self", ",", "verbose", "=", "False", ",", "hide_base_schemas", "=", "True", ",", "hide_implicit_types", "=", "True", ",", "hide_implicit_preds", "=", "True", ")", ":", "if", "verbose", ":", "printDebug", "(", "\"Scanning entities...\"", ",", "\"green\"", ")", "printDebug", "(", "\"----------\"", ",", "\"comment\"", ")", "self", ".", "build_ontologies", "(", ")", "if", "verbose", ":", "printDebug", "(", "\"Ontologies.........: %d\"", "%", "len", "(", "self", ".", "all_ontologies", ")", ",", "\"comment\"", ")", "self", ".", "build_classes", "(", "hide_base_schemas", ",", "hide_implicit_types", ")", "if", "verbose", ":", "printDebug", "(", "\"Classes............: %d\"", "%", "len", "(", "self", ".", "all_classes", ")", ",", "\"comment\"", ")", "self", ".", "build_properties", "(", "hide_implicit_preds", ")", "if", "verbose", ":", "printDebug", "(", "\"Properties.........: %d\"", "%", "len", "(", "self", ".", "all_properties", ")", ",", "\"comment\"", ")", "if", "verbose", ":", "printDebug", "(", "\"..annotation.......: %d\"", "%", "len", "(", "self", ".", "all_properties_annotation", ")", ",", "\"comment\"", ")", "if", "verbose", ":", "printDebug", "(", "\"..datatype.........: %d\"", "%", "len", "(", "self", ".", "all_properties_datatype", ")", ",", "\"comment\"", ")", "if", "verbose", ":", "printDebug", "(", "\"..object...........: %d\"", "%", "len", "(", "self", ".", "all_properties_object", ")", ",", "\"comment\"", ")", "self", ".", "build_skos_concepts", "(", ")", "if", "verbose", ":", "printDebug", "(", "\"Concepts (SKOS)....: %d\"", "%", "len", "(", "self", ".", "all_skos_concepts", ")", ",", "\"comment\"", ")", "self", ".", "build_shapes", "(", ")", "if", "verbose", ":", "printDebug", "(", "\"Shapes (SHACL).....: %d\"", "%", "len", "(", "self", ".", "all_shapes", ")", ",", "\"comment\"", ")", "# self.__computeTopLayer()", "self", ".", "__computeInferredProperties", "(", ")", "if", "verbose", ":", "printDebug", "(", "\"----------\"", ",", "\"comment\"", ")" ]
Extract all ontology entities from an RDF graph and construct Python representations of them.
[ "Extract", "all", "ontology", "entities", "from", "an", "RDF", "graph", "and", "construct", "Python", "representations", "of", "them", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L185-L228
train
lambdamusic/Ontospy
ontospy/core/ontospy.py
Ontospy.build_ontologies
def build_ontologies(self, exclude_BNodes=False, return_string=False): """ Extract ontology instances info from the graph, then creates python objects for them. Note: often ontology info is nested in structures like this: [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ] Hence there is some logic to deal with these edge cases. """ out = [] qres = self.sparqlHelper.getOntology() if qres: # NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..) for candidate in qres: if isBlankNode(candidate[0]): if exclude_BNodes: continue else: checkDC_ID = [x for x in self.rdflib_graph.objects( candidate[0], rdflib.namespace.DC.identifier)] if checkDC_ID: out += [Ontology(checkDC_ID[0], namespaces=self.namespaces), ] else: vannprop = rdflib.URIRef( "http://purl.org/vocab/vann/preferredNamespaceUri") vannpref = rdflib.URIRef( "http://purl.org/vocab/vann/preferredNamespacePrefix") checkDC_ID = [x for x in self.rdflib_graph.objects( candidate[0], vannprop)] if checkDC_ID: checkDC_prefix = [ x for x in self.rdflib_graph.objects(candidate[0], vannpref)] if checkDC_prefix: out += [Ontology(checkDC_ID[0], namespaces=self.namespaces, prefPrefix=checkDC_prefix[0])] else: out += [Ontology(checkDC_ID[0], namespaces=self.namespaces)] else: out += [Ontology(candidate[0], namespaces=self.namespaces)] else: pass # printDebug("No owl:Ontologies found") # finally... add all annotations/triples self.all_ontologies = out for onto in self.all_ontologies: onto.triples = self.sparqlHelper.entityTriples(onto.uri) onto._buildGraph()
python
def build_ontologies(self, exclude_BNodes=False, return_string=False): """ Extract ontology instances info from the graph, then creates python objects for them. Note: often ontology info is nested in structures like this: [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ] Hence there is some logic to deal with these edge cases. """ out = [] qres = self.sparqlHelper.getOntology() if qres: # NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..) for candidate in qres: if isBlankNode(candidate[0]): if exclude_BNodes: continue else: checkDC_ID = [x for x in self.rdflib_graph.objects( candidate[0], rdflib.namespace.DC.identifier)] if checkDC_ID: out += [Ontology(checkDC_ID[0], namespaces=self.namespaces), ] else: vannprop = rdflib.URIRef( "http://purl.org/vocab/vann/preferredNamespaceUri") vannpref = rdflib.URIRef( "http://purl.org/vocab/vann/preferredNamespacePrefix") checkDC_ID = [x for x in self.rdflib_graph.objects( candidate[0], vannprop)] if checkDC_ID: checkDC_prefix = [ x for x in self.rdflib_graph.objects(candidate[0], vannpref)] if checkDC_prefix: out += [Ontology(checkDC_ID[0], namespaces=self.namespaces, prefPrefix=checkDC_prefix[0])] else: out += [Ontology(checkDC_ID[0], namespaces=self.namespaces)] else: out += [Ontology(candidate[0], namespaces=self.namespaces)] else: pass # printDebug("No owl:Ontologies found") # finally... add all annotations/triples self.all_ontologies = out for onto in self.all_ontologies: onto.triples = self.sparqlHelper.entityTriples(onto.uri) onto._buildGraph()
[ "def", "build_ontologies", "(", "self", ",", "exclude_BNodes", "=", "False", ",", "return_string", "=", "False", ")", ":", "out", "=", "[", "]", "qres", "=", "self", ".", "sparqlHelper", ".", "getOntology", "(", ")", "if", "qres", ":", "# NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..)", "for", "candidate", "in", "qres", ":", "if", "isBlankNode", "(", "candidate", "[", "0", "]", ")", ":", "if", "exclude_BNodes", ":", "continue", "else", ":", "checkDC_ID", "=", "[", "x", "for", "x", "in", "self", ".", "rdflib_graph", ".", "objects", "(", "candidate", "[", "0", "]", ",", "rdflib", ".", "namespace", ".", "DC", ".", "identifier", ")", "]", "if", "checkDC_ID", ":", "out", "+=", "[", "Ontology", "(", "checkDC_ID", "[", "0", "]", ",", "namespaces", "=", "self", ".", "namespaces", ")", ",", "]", "else", ":", "vannprop", "=", "rdflib", ".", "URIRef", "(", "\"http://purl.org/vocab/vann/preferredNamespaceUri\"", ")", "vannpref", "=", "rdflib", ".", "URIRef", "(", "\"http://purl.org/vocab/vann/preferredNamespacePrefix\"", ")", "checkDC_ID", "=", "[", "x", "for", "x", "in", "self", ".", "rdflib_graph", ".", "objects", "(", "candidate", "[", "0", "]", ",", "vannprop", ")", "]", "if", "checkDC_ID", ":", "checkDC_prefix", "=", "[", "x", "for", "x", "in", "self", ".", "rdflib_graph", ".", "objects", "(", "candidate", "[", "0", "]", ",", "vannpref", ")", "]", "if", "checkDC_prefix", ":", "out", "+=", "[", "Ontology", "(", "checkDC_ID", "[", "0", "]", ",", "namespaces", "=", "self", ".", "namespaces", ",", "prefPrefix", "=", "checkDC_prefix", "[", "0", "]", ")", "]", "else", ":", "out", "+=", "[", "Ontology", "(", "checkDC_ID", "[", "0", "]", ",", "namespaces", "=", "self", ".", "namespaces", ")", "]", "else", ":", "out", "+=", "[", "Ontology", "(", "candidate", "[", "0", "]", ",", "namespaces", "=", "self", ".", "namespaces", ")", "]", "else", ":", "pass", "# printDebug(\"No owl:Ontologies found\")", "# finally... add all annotations/triples", "self", ".", "all_ontologies", "=", "out", "for", "onto", "in", "self", ".", "all_ontologies", ":", "onto", ".", "triples", "=", "self", ".", "sparqlHelper", ".", "entityTriples", "(", "onto", ".", "uri", ")", "onto", ".", "_buildGraph", "(", ")" ]
Extract ontology instances info from the graph, then creates python objects for them. Note: often ontology info is nested in structures like this: [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ] Hence there is some logic to deal with these edge cases.
[ "Extract", "ontology", "instances", "info", "from", "the", "graph", "then", "creates", "python", "objects", "for", "them", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L230-L286
train
lambdamusic/Ontospy
ontospy/core/ontospy.py
Ontospy.build_entity_from_uri
def build_entity_from_uri(self, uri, ontospyClass=None): """ Extract RDF statements having a URI as subject, then instantiate the RDF_Entity Python object so that it can be queried further. Passing <ontospyClass> allows to instantiate a user-defined RDF_Entity subclass. NOTE: the entity is not attached to any index. In future version we may create an index for these (individuals?) keeping into account that any existing model entity could be (re)created this way. """ if not ontospyClass: ontospyClass = RDF_Entity elif not issubclass(ontospyClass, RDF_Entity): click.secho("Error: <%s> is not a subclass of ontospy.RDF_Entity" % str(ontospyClass)) return None else: pass qres = self.sparqlHelper.entityTriples(uri) if qres: entity = ontospyClass(rdflib.URIRef(uri), None, self.namespaces) entity.triples = qres entity._buildGraph() # force construction of mini graph # try to add class info test = entity.getValuesForProperty(rdflib.RDF.type) if test: entity.rdftype = test entity.rdftype_qname = [entity._build_qname(x) for x in test] return entity else: return None
python
def build_entity_from_uri(self, uri, ontospyClass=None): """ Extract RDF statements having a URI as subject, then instantiate the RDF_Entity Python object so that it can be queried further. Passing <ontospyClass> allows to instantiate a user-defined RDF_Entity subclass. NOTE: the entity is not attached to any index. In future version we may create an index for these (individuals?) keeping into account that any existing model entity could be (re)created this way. """ if not ontospyClass: ontospyClass = RDF_Entity elif not issubclass(ontospyClass, RDF_Entity): click.secho("Error: <%s> is not a subclass of ontospy.RDF_Entity" % str(ontospyClass)) return None else: pass qres = self.sparqlHelper.entityTriples(uri) if qres: entity = ontospyClass(rdflib.URIRef(uri), None, self.namespaces) entity.triples = qres entity._buildGraph() # force construction of mini graph # try to add class info test = entity.getValuesForProperty(rdflib.RDF.type) if test: entity.rdftype = test entity.rdftype_qname = [entity._build_qname(x) for x in test] return entity else: return None
[ "def", "build_entity_from_uri", "(", "self", ",", "uri", ",", "ontospyClass", "=", "None", ")", ":", "if", "not", "ontospyClass", ":", "ontospyClass", "=", "RDF_Entity", "elif", "not", "issubclass", "(", "ontospyClass", ",", "RDF_Entity", ")", ":", "click", ".", "secho", "(", "\"Error: <%s> is not a subclass of ontospy.RDF_Entity\"", "%", "str", "(", "ontospyClass", ")", ")", "return", "None", "else", ":", "pass", "qres", "=", "self", ".", "sparqlHelper", ".", "entityTriples", "(", "uri", ")", "if", "qres", ":", "entity", "=", "ontospyClass", "(", "rdflib", ".", "URIRef", "(", "uri", ")", ",", "None", ",", "self", ".", "namespaces", ")", "entity", ".", "triples", "=", "qres", "entity", ".", "_buildGraph", "(", ")", "# force construction of mini graph", "# try to add class info", "test", "=", "entity", ".", "getValuesForProperty", "(", "rdflib", ".", "RDF", ".", "type", ")", "if", "test", ":", "entity", ".", "rdftype", "=", "test", "entity", ".", "rdftype_qname", "=", "[", "entity", ".", "_build_qname", "(", "x", ")", "for", "x", "in", "test", "]", "return", "entity", "else", ":", "return", "None" ]
Extract RDF statements having a URI as subject, then instantiate the RDF_Entity Python object so that it can be queried further. Passing <ontospyClass> allows to instantiate a user-defined RDF_Entity subclass. NOTE: the entity is not attached to any index. In future version we may create an index for these (individuals?) keeping into account that any existing model entity could be (re)created this way.
[ "Extract", "RDF", "statements", "having", "a", "URI", "as", "subject", "then", "instantiate", "the", "RDF_Entity", "Python", "object", "so", "that", "it", "can", "be", "queried", "further", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L561-L588
train
lambdamusic/Ontospy
ontospy/core/ontospy.py
Ontospy.printClassTree
def printClassTree(self, element=None, showids=False, labels=False, showtype=False): """ Print nicely into stdout the class tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12-- """ TYPE_MARGIN = 11 # length for owl:class etc.. if not element: # first time for x in self.toplayer_classes: printGenericTree(x, 0, showids, labels, showtype, TYPE_MARGIN) else: printGenericTree(element, 0, showids, labels, showtype, TYPE_MARGIN)
python
def printClassTree(self, element=None, showids=False, labels=False, showtype=False): """ Print nicely into stdout the class tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12-- """ TYPE_MARGIN = 11 # length for owl:class etc.. if not element: # first time for x in self.toplayer_classes: printGenericTree(x, 0, showids, labels, showtype, TYPE_MARGIN) else: printGenericTree(element, 0, showids, labels, showtype, TYPE_MARGIN)
[ "def", "printClassTree", "(", "self", ",", "element", "=", "None", ",", "showids", "=", "False", ",", "labels", "=", "False", ",", "showtype", "=", "False", ")", ":", "TYPE_MARGIN", "=", "11", "# length for owl:class etc..", "if", "not", "element", ":", "# first time", "for", "x", "in", "self", ".", "toplayer_classes", ":", "printGenericTree", "(", "x", ",", "0", ",", "showids", ",", "labels", ",", "showtype", ",", "TYPE_MARGIN", ")", "else", ":", "printGenericTree", "(", "element", ",", "0", ",", "showids", ",", "labels", ",", "showtype", ",", "TYPE_MARGIN", ")" ]
Print nicely into stdout the class tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12--
[ "Print", "nicely", "into", "stdout", "the", "class", "tree", "of", "an", "ontology" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L1073-L1089
train
lambdamusic/Ontospy
ontospy/core/ontospy.py
Ontospy.printPropertyTree
def printPropertyTree(self, element=None, showids=False, labels=False, showtype=False): """ Print nicely into stdout the property tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12-- """ TYPE_MARGIN = 18 # length for owl:AnnotationProperty etc.. if not element: # first time for x in self.toplayer_properties: printGenericTree(x, 0, showids, labels, showtype, TYPE_MARGIN) else: printGenericTree(element, 0, showids, labels, showtype, TYPE_MARGIN)
python
def printPropertyTree(self, element=None, showids=False, labels=False, showtype=False): """ Print nicely into stdout the property tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12-- """ TYPE_MARGIN = 18 # length for owl:AnnotationProperty etc.. if not element: # first time for x in self.toplayer_properties: printGenericTree(x, 0, showids, labels, showtype, TYPE_MARGIN) else: printGenericTree(element, 0, showids, labels, showtype, TYPE_MARGIN)
[ "def", "printPropertyTree", "(", "self", ",", "element", "=", "None", ",", "showids", "=", "False", ",", "labels", "=", "False", ",", "showtype", "=", "False", ")", ":", "TYPE_MARGIN", "=", "18", "# length for owl:AnnotationProperty etc..", "if", "not", "element", ":", "# first time", "for", "x", "in", "self", ".", "toplayer_properties", ":", "printGenericTree", "(", "x", ",", "0", ",", "showids", ",", "labels", ",", "showtype", ",", "TYPE_MARGIN", ")", "else", ":", "printGenericTree", "(", "element", ",", "0", ",", "showids", ",", "labels", ",", "showtype", ",", "TYPE_MARGIN", ")" ]
Print nicely into stdout the property tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12--
[ "Print", "nicely", "into", "stdout", "the", "property", "tree", "of", "an", "ontology" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L1091-L1107
train
lambdamusic/Ontospy
ontospy/extras/hacks/sketch.py
Sketch.add
def add(self, text="", default_continuousAdd=True): """add some turtle text""" if not text and default_continuousAdd: self.continuousAdd() else: pprefix = "" for x,y in self.rdflib_graph.namespaces(): pprefix += "@prefix %s: <%s> . \n" % (x, y) # add final . if missing if text and (not text.strip().endswith(".")): text += " ." # smart replacements text = text.replace(" sub ", " rdfs:subClassOf ") text = text.replace(" class ", " owl:Class ") # finally self.rdflib_graph.parse(data=pprefix+text, format="turtle")
python
def add(self, text="", default_continuousAdd=True): """add some turtle text""" if not text and default_continuousAdd: self.continuousAdd() else: pprefix = "" for x,y in self.rdflib_graph.namespaces(): pprefix += "@prefix %s: <%s> . \n" % (x, y) # add final . if missing if text and (not text.strip().endswith(".")): text += " ." # smart replacements text = text.replace(" sub ", " rdfs:subClassOf ") text = text.replace(" class ", " owl:Class ") # finally self.rdflib_graph.parse(data=pprefix+text, format="turtle")
[ "def", "add", "(", "self", ",", "text", "=", "\"\"", ",", "default_continuousAdd", "=", "True", ")", ":", "if", "not", "text", "and", "default_continuousAdd", ":", "self", ".", "continuousAdd", "(", ")", "else", ":", "pprefix", "=", "\"\"", "for", "x", ",", "y", "in", "self", ".", "rdflib_graph", ".", "namespaces", "(", ")", ":", "pprefix", "+=", "\"@prefix %s: <%s> . \\n\"", "%", "(", "x", ",", "y", ")", "# add final . if missing", "if", "text", "and", "(", "not", "text", ".", "strip", "(", ")", ".", "endswith", "(", "\".\"", ")", ")", ":", "text", "+=", "\" .\"", "# smart replacements", "text", "=", "text", ".", "replace", "(", "\" sub \"", ",", "\" rdfs:subClassOf \"", ")", "text", "=", "text", ".", "replace", "(", "\" class \"", ",", "\" owl:Class \"", ")", "# finally", "self", ".", "rdflib_graph", ".", "parse", "(", "data", "=", "pprefix", "+", "text", ",", "format", "=", "\"turtle\"", ")" ]
add some turtle text
[ "add", "some", "turtle", "text" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/sketch.py#L79-L94
train
lambdamusic/Ontospy
ontospy/extras/hacks/sketch.py
Sketch.rdf_source
def rdf_source(self, aformat="turtle"): """ Serialize graph using the format required """ if aformat and aformat not in self.SUPPORTED_FORMATS: return "Sorry. Allowed formats are %s" % str(self.SUPPORTED_FORMATS) if aformat == "dot": return self.__serializedDot() else: # use stardard rdf serializations return self.rdflib_graph.serialize(format=aformat)
python
def rdf_source(self, aformat="turtle"): """ Serialize graph using the format required """ if aformat and aformat not in self.SUPPORTED_FORMATS: return "Sorry. Allowed formats are %s" % str(self.SUPPORTED_FORMATS) if aformat == "dot": return self.__serializedDot() else: # use stardard rdf serializations return self.rdflib_graph.serialize(format=aformat)
[ "def", "rdf_source", "(", "self", ",", "aformat", "=", "\"turtle\"", ")", ":", "if", "aformat", "and", "aformat", "not", "in", "self", ".", "SUPPORTED_FORMATS", ":", "return", "\"Sorry. Allowed formats are %s\"", "%", "str", "(", "self", ".", "SUPPORTED_FORMATS", ")", "if", "aformat", "==", "\"dot\"", ":", "return", "self", ".", "__serializedDot", "(", ")", "else", ":", "# use stardard rdf serializations", "return", "self", ".", "rdflib_graph", ".", "serialize", "(", "format", "=", "aformat", ")" ]
Serialize graph using the format required
[ "Serialize", "graph", "using", "the", "format", "required" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/sketch.py#L122-L132
train
lambdamusic/Ontospy
ontospy/extras/hacks/sketch.py
Sketch.omnigraffle
def omnigraffle(self): """ tries to open an export directly in omnigraffle """ temp = self.rdf_source("dot") try: # try to put in the user/tmp folder from os.path import expanduser home = expanduser("~") filename = home + "/tmp/turtle_sketch.dot" f = open(filename, "w") except: filename = "turtle_sketch.dot" f = open(filename, "w") f.write(temp) f.close() try: os.system("open " + filename) except: os.system("start " + filename)
python
def omnigraffle(self): """ tries to open an export directly in omnigraffle """ temp = self.rdf_source("dot") try: # try to put in the user/tmp folder from os.path import expanduser home = expanduser("~") filename = home + "/tmp/turtle_sketch.dot" f = open(filename, "w") except: filename = "turtle_sketch.dot" f = open(filename, "w") f.write(temp) f.close() try: os.system("open " + filename) except: os.system("start " + filename)
[ "def", "omnigraffle", "(", "self", ")", ":", "temp", "=", "self", ".", "rdf_source", "(", "\"dot\"", ")", "try", ":", "# try to put in the user/tmp folder", "from", "os", ".", "path", "import", "expanduser", "home", "=", "expanduser", "(", "\"~\"", ")", "filename", "=", "home", "+", "\"/tmp/turtle_sketch.dot\"", "f", "=", "open", "(", "filename", ",", "\"w\"", ")", "except", ":", "filename", "=", "\"turtle_sketch.dot\"", "f", "=", "open", "(", "filename", ",", "\"w\"", ")", "f", ".", "write", "(", "temp", ")", "f", ".", "close", "(", ")", "try", ":", "os", ".", "system", "(", "\"open \"", "+", "filename", ")", "except", ":", "os", ".", "system", "(", "\"start \"", "+", "filename", ")" ]
tries to open an export directly in omnigraffle
[ "tries", "to", "open", "an", "export", "directly", "in", "omnigraffle" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/sketch.py#L149-L166
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
main
def main(): """ standalone line script """ print("Ontospy " + VERSION) Shell()._clear_screen() print(Style.BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style.RESET_ALL) # manager.get_or_create_home_repo() Shell().cmdloop() raise SystemExit(1)
python
def main(): """ standalone line script """ print("Ontospy " + VERSION) Shell()._clear_screen() print(Style.BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style.RESET_ALL) # manager.get_or_create_home_repo() Shell().cmdloop() raise SystemExit(1)
[ "def", "main", "(", ")", ":", "print", "(", "\"Ontospy \"", "+", "VERSION", ")", "Shell", "(", ")", ".", "_clear_screen", "(", ")", "print", "(", "Style", ".", "BRIGHT", "+", "\"** Ontospy Interactive Ontology Browser \"", "+", "VERSION", "+", "\" **\"", "+", "Style", ".", "RESET_ALL", ")", "# manager.get_or_create_home_repo()", "Shell", "(", ")", ".", "cmdloop", "(", ")", "raise", "SystemExit", "(", "1", ")" ]
standalone line script
[ "standalone", "line", "script" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1319-L1328
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._print
def _print(self, ms, style="TIP"): """ abstraction for managing color printing """ styles1 = {'IMPORTANT': Style.BRIGHT, 'TIP': Style.DIM, 'URI': Style.BRIGHT, 'TEXT': Fore.GREEN, 'MAGENTA': Fore.MAGENTA, 'BLUE': Fore.BLUE, 'GREEN': Fore.GREEN, 'RED': Fore.RED, 'DEFAULT': Style.DIM, } try: print(styles1[style] + ms + Style.RESET_ALL) except: print(styles1['DEFAULT'] + ms + Style.RESET_ALL)
python
def _print(self, ms, style="TIP"): """ abstraction for managing color printing """ styles1 = {'IMPORTANT': Style.BRIGHT, 'TIP': Style.DIM, 'URI': Style.BRIGHT, 'TEXT': Fore.GREEN, 'MAGENTA': Fore.MAGENTA, 'BLUE': Fore.BLUE, 'GREEN': Fore.GREEN, 'RED': Fore.RED, 'DEFAULT': Style.DIM, } try: print(styles1[style] + ms + Style.RESET_ALL) except: print(styles1['DEFAULT'] + ms + Style.RESET_ALL)
[ "def", "_print", "(", "self", ",", "ms", ",", "style", "=", "\"TIP\"", ")", ":", "styles1", "=", "{", "'IMPORTANT'", ":", "Style", ".", "BRIGHT", ",", "'TIP'", ":", "Style", ".", "DIM", ",", "'URI'", ":", "Style", ".", "BRIGHT", ",", "'TEXT'", ":", "Fore", ".", "GREEN", ",", "'MAGENTA'", ":", "Fore", ".", "MAGENTA", ",", "'BLUE'", ":", "Fore", ".", "BLUE", ",", "'GREEN'", ":", "Fore", ".", "GREEN", ",", "'RED'", ":", "Fore", ".", "RED", ",", "'DEFAULT'", ":", "Style", ".", "DIM", ",", "}", "try", ":", "print", "(", "styles1", "[", "style", "]", "+", "ms", "+", "Style", ".", "RESET_ALL", ")", "except", ":", "print", "(", "styles1", "[", "'DEFAULT'", "]", "+", "ms", "+", "Style", ".", "RESET_ALL", ")" ]
abstraction for managing color printing
[ "abstraction", "for", "managing", "color", "printing" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L157-L172
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._printM
def _printM(self, messages): """print a list of strings - for the mom used only by stats printout""" if len(messages) == 2: print(Style.BRIGHT + messages[0] + Style.RESET_ALL + Fore.BLUE + messages[1] + Style.RESET_ALL) else: print("Not implemented")
python
def _printM(self, messages): """print a list of strings - for the mom used only by stats printout""" if len(messages) == 2: print(Style.BRIGHT + messages[0] + Style.RESET_ALL + Fore.BLUE + messages[1] + Style.RESET_ALL) else: print("Not implemented")
[ "def", "_printM", "(", "self", ",", "messages", ")", ":", "if", "len", "(", "messages", ")", "==", "2", ":", "print", "(", "Style", ".", "BRIGHT", "+", "messages", "[", "0", "]", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "BLUE", "+", "messages", "[", "1", "]", "+", "Style", ".", "RESET_ALL", ")", "else", ":", "print", "(", "\"Not implemented\"", ")" ]
print a list of strings - for the mom used only by stats printout
[ "print", "a", "list", "of", "strings", "-", "for", "the", "mom", "used", "only", "by", "stats", "printout" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L174-L180
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._printDescription
def _printDescription(self, hrlinetop=True): """generic method to print out a description""" if hrlinetop: self._print("----------------") NOTFOUND = "[not found]" if self.currentEntity: obj = self.currentEntity['object'] label = obj.bestLabel() or NOTFOUND description = obj.bestDescription() or NOTFOUND print(Style.BRIGHT + "OBJECT TYPE: " + Style.RESET_ALL + Fore.BLACK + uri2niceString(obj.rdftype) + Style.RESET_ALL) print(Style.BRIGHT + "URI : " + Style.RESET_ALL + Fore.GREEN + "<" + unicode(obj.uri) + ">" + Style.RESET_ALL) print(Style.BRIGHT + "TITLE : " + Style.RESET_ALL + Fore.BLACK + label + Style.RESET_ALL) print(Style.BRIGHT + "DESCRIPTION: " + Style.RESET_ALL + Fore.BLACK + description + Style.RESET_ALL) else: self._clear_screen() self._print("Graph: <" + self.current['fullpath'] + ">", 'TIP') self._print("----------------", "TIP") self._printStats(self.current['graph']) for obj in self.current['graph'].all_ontologies: print(Style.BRIGHT + "Ontology URI: " + Style.RESET_ALL + Fore.RED + "<%s>" % str(obj.uri) + Style.RESET_ALL) # self._print("==> Ontology URI: <%s>" % str(obj.uri), "IMPORTANT") # self._print("----------------", "TIP") label = obj.bestLabel() or NOTFOUND description = obj.bestDescription() or NOTFOUND print(Style.BRIGHT + "Title : " + Style.RESET_ALL + Fore.BLACK + label + Style.RESET_ALL) print(Style.BRIGHT + "Description : " + Style.RESET_ALL + Fore.BLACK + description + Style.RESET_ALL) self._print("----------------", "TIP")
python
def _printDescription(self, hrlinetop=True): """generic method to print out a description""" if hrlinetop: self._print("----------------") NOTFOUND = "[not found]" if self.currentEntity: obj = self.currentEntity['object'] label = obj.bestLabel() or NOTFOUND description = obj.bestDescription() or NOTFOUND print(Style.BRIGHT + "OBJECT TYPE: " + Style.RESET_ALL + Fore.BLACK + uri2niceString(obj.rdftype) + Style.RESET_ALL) print(Style.BRIGHT + "URI : " + Style.RESET_ALL + Fore.GREEN + "<" + unicode(obj.uri) + ">" + Style.RESET_ALL) print(Style.BRIGHT + "TITLE : " + Style.RESET_ALL + Fore.BLACK + label + Style.RESET_ALL) print(Style.BRIGHT + "DESCRIPTION: " + Style.RESET_ALL + Fore.BLACK + description + Style.RESET_ALL) else: self._clear_screen() self._print("Graph: <" + self.current['fullpath'] + ">", 'TIP') self._print("----------------", "TIP") self._printStats(self.current['graph']) for obj in self.current['graph'].all_ontologies: print(Style.BRIGHT + "Ontology URI: " + Style.RESET_ALL + Fore.RED + "<%s>" % str(obj.uri) + Style.RESET_ALL) # self._print("==> Ontology URI: <%s>" % str(obj.uri), "IMPORTANT") # self._print("----------------", "TIP") label = obj.bestLabel() or NOTFOUND description = obj.bestDescription() or NOTFOUND print(Style.BRIGHT + "Title : " + Style.RESET_ALL + Fore.BLACK + label + Style.RESET_ALL) print(Style.BRIGHT + "Description : " + Style.RESET_ALL + Fore.BLACK + description + Style.RESET_ALL) self._print("----------------", "TIP")
[ "def", "_printDescription", "(", "self", ",", "hrlinetop", "=", "True", ")", ":", "if", "hrlinetop", ":", "self", ".", "_print", "(", "\"----------------\"", ")", "NOTFOUND", "=", "\"[not found]\"", "if", "self", ".", "currentEntity", ":", "obj", "=", "self", ".", "currentEntity", "[", "'object'", "]", "label", "=", "obj", ".", "bestLabel", "(", ")", "or", "NOTFOUND", "description", "=", "obj", ".", "bestDescription", "(", ")", "or", "NOTFOUND", "print", "(", "Style", ".", "BRIGHT", "+", "\"OBJECT TYPE: \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "BLACK", "+", "uri2niceString", "(", "obj", ".", "rdftype", ")", "+", "Style", ".", "RESET_ALL", ")", "print", "(", "Style", ".", "BRIGHT", "+", "\"URI : \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "GREEN", "+", "\"<\"", "+", "unicode", "(", "obj", ".", "uri", ")", "+", "\">\"", "+", "Style", ".", "RESET_ALL", ")", "print", "(", "Style", ".", "BRIGHT", "+", "\"TITLE : \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "BLACK", "+", "label", "+", "Style", ".", "RESET_ALL", ")", "print", "(", "Style", ".", "BRIGHT", "+", "\"DESCRIPTION: \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "BLACK", "+", "description", "+", "Style", ".", "RESET_ALL", ")", "else", ":", "self", ".", "_clear_screen", "(", ")", "self", ".", "_print", "(", "\"Graph: <\"", "+", "self", ".", "current", "[", "'fullpath'", "]", "+", "\">\"", ",", "'TIP'", ")", "self", ".", "_print", "(", "\"----------------\"", ",", "\"TIP\"", ")", "self", ".", "_printStats", "(", "self", ".", "current", "[", "'graph'", "]", ")", "for", "obj", "in", "self", ".", "current", "[", "'graph'", "]", ".", "all_ontologies", ":", "print", "(", "Style", ".", "BRIGHT", "+", "\"Ontology URI: \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "RED", "+", "\"<%s>\"", "%", "str", "(", "obj", ".", "uri", ")", "+", "Style", ".", "RESET_ALL", ")", "# self._print(\"==> Ontology URI: <%s>\" % str(obj.uri), \"IMPORTANT\")", "# self._print(\"----------------\", \"TIP\")", "label", "=", "obj", ".", "bestLabel", "(", ")", "or", "NOTFOUND", "description", "=", "obj", ".", "bestDescription", "(", ")", "or", "NOTFOUND", "print", "(", "Style", ".", "BRIGHT", "+", "\"Title : \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "BLACK", "+", "label", "+", "Style", ".", "RESET_ALL", ")", "print", "(", "Style", ".", "BRIGHT", "+", "\"Description : \"", "+", "Style", ".", "RESET_ALL", "+", "Fore", ".", "BLACK", "+", "description", "+", "Style", ".", "RESET_ALL", ")", "self", ".", "_print", "(", "\"----------------\"", ",", "\"TIP\"", ")" ]
generic method to print out a description
[ "generic", "method", "to", "print", "out", "a", "description" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L240-L274
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._next_ontology
def _next_ontology(self): """Dynamically retrieves the next ontology in the list""" currentfile = self.current['file'] try: idx = self.all_ontologies.index(currentfile) return self.all_ontologies[idx+1] except: return self.all_ontologies[0]
python
def _next_ontology(self): """Dynamically retrieves the next ontology in the list""" currentfile = self.current['file'] try: idx = self.all_ontologies.index(currentfile) return self.all_ontologies[idx+1] except: return self.all_ontologies[0]
[ "def", "_next_ontology", "(", "self", ")", ":", "currentfile", "=", "self", ".", "current", "[", "'file'", "]", "try", ":", "idx", "=", "self", ".", "all_ontologies", ".", "index", "(", "currentfile", ")", "return", "self", ".", "all_ontologies", "[", "idx", "+", "1", "]", "except", ":", "return", "self", ".", "all_ontologies", "[", "0", "]" ]
Dynamically retrieves the next ontology in the list
[ "Dynamically", "retrieves", "the", "next", "ontology", "in", "the", "list" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L519-L526
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._load_ontology
def _load_ontology(self, filename, preview_mode=False): """ Loads an ontology Unless preview_mode=True, it is always loaded from the local repository note: if the ontology does not have a cached version, it is created preview_mode: used to pass a URI/path to be inspected without saving it locally """ if not preview_mode: fullpath = self.LOCAL_MODELS + filename g = manager.get_pickled_ontology(filename) if not g: g = manager.do_pickle_ontology(filename) else: fullpath = filename filename = os.path.basename(os.path.normpath(fullpath)) g = Ontospy(fullpath, verbose=True) self.current = {'file': filename, 'fullpath': fullpath, 'graph': g} self.currentEntity = None self._print_entity_intro(g)
python
def _load_ontology(self, filename, preview_mode=False): """ Loads an ontology Unless preview_mode=True, it is always loaded from the local repository note: if the ontology does not have a cached version, it is created preview_mode: used to pass a URI/path to be inspected without saving it locally """ if not preview_mode: fullpath = self.LOCAL_MODELS + filename g = manager.get_pickled_ontology(filename) if not g: g = manager.do_pickle_ontology(filename) else: fullpath = filename filename = os.path.basename(os.path.normpath(fullpath)) g = Ontospy(fullpath, verbose=True) self.current = {'file': filename, 'fullpath': fullpath, 'graph': g} self.currentEntity = None self._print_entity_intro(g)
[ "def", "_load_ontology", "(", "self", ",", "filename", ",", "preview_mode", "=", "False", ")", ":", "if", "not", "preview_mode", ":", "fullpath", "=", "self", ".", "LOCAL_MODELS", "+", "filename", "g", "=", "manager", ".", "get_pickled_ontology", "(", "filename", ")", "if", "not", "g", ":", "g", "=", "manager", ".", "do_pickle_ontology", "(", "filename", ")", "else", ":", "fullpath", "=", "filename", "filename", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "normpath", "(", "fullpath", ")", ")", "g", "=", "Ontospy", "(", "fullpath", ",", "verbose", "=", "True", ")", "self", ".", "current", "=", "{", "'file'", ":", "filename", ",", "'fullpath'", ":", "fullpath", ",", "'graph'", ":", "g", "}", "self", ".", "currentEntity", "=", "None", "self", ".", "_print_entity_intro", "(", "g", ")" ]
Loads an ontology Unless preview_mode=True, it is always loaded from the local repository note: if the ontology does not have a cached version, it is created preview_mode: used to pass a URI/path to be inspected without saving it locally
[ "Loads", "an", "ontology" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L531-L551
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._select_property
def _select_property(self, line): """try to match a property and load it""" g = self.current['graph'] if not line: out = g.all_properties using_pattern = False else: using_pattern = True if line.isdigit(): line = int(line) out = g.get_property(line) if out: if type(out) == type([]): choice = self._selectFromList(out, using_pattern, "property") if choice: self.currentEntity = {'name': choice.locale or choice.uri, 'object': choice, 'type': 'property'} else: self.currentEntity = {'name': out.locale or out.uri, 'object': out, 'type': 'property'} # ..finally: if self.currentEntity: self._print_entity_intro(entity=self.currentEntity) else: print("not found")
python
def _select_property(self, line): """try to match a property and load it""" g = self.current['graph'] if not line: out = g.all_properties using_pattern = False else: using_pattern = True if line.isdigit(): line = int(line) out = g.get_property(line) if out: if type(out) == type([]): choice = self._selectFromList(out, using_pattern, "property") if choice: self.currentEntity = {'name': choice.locale or choice.uri, 'object': choice, 'type': 'property'} else: self.currentEntity = {'name': out.locale or out.uri, 'object': out, 'type': 'property'} # ..finally: if self.currentEntity: self._print_entity_intro(entity=self.currentEntity) else: print("not found")
[ "def", "_select_property", "(", "self", ",", "line", ")", ":", "g", "=", "self", ".", "current", "[", "'graph'", "]", "if", "not", "line", ":", "out", "=", "g", ".", "all_properties", "using_pattern", "=", "False", "else", ":", "using_pattern", "=", "True", "if", "line", ".", "isdigit", "(", ")", ":", "line", "=", "int", "(", "line", ")", "out", "=", "g", ".", "get_property", "(", "line", ")", "if", "out", ":", "if", "type", "(", "out", ")", "==", "type", "(", "[", "]", ")", ":", "choice", "=", "self", ".", "_selectFromList", "(", "out", ",", "using_pattern", ",", "\"property\"", ")", "if", "choice", ":", "self", ".", "currentEntity", "=", "{", "'name'", ":", "choice", ".", "locale", "or", "choice", ".", "uri", ",", "'object'", ":", "choice", ",", "'type'", ":", "'property'", "}", "else", ":", "self", ".", "currentEntity", "=", "{", "'name'", ":", "out", ".", "locale", "or", "out", ".", "uri", ",", "'object'", ":", "out", ",", "'type'", ":", "'property'", "}", "# ..finally:", "if", "self", ".", "currentEntity", ":", "self", ".", "_print_entity_intro", "(", "entity", "=", "self", ".", "currentEntity", ")", "else", ":", "print", "(", "\"not found\"", ")" ]
try to match a property and load it
[ "try", "to", "match", "a", "property", "and", "load", "it" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L597-L623
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell._select_concept
def _select_concept(self, line): """try to match a class and load it""" g = self.current['graph'] if not line: out = g.all_skos_concepts using_pattern = False else: using_pattern = True if line.isdigit(): line = int(line) out = g.get_skos(line) if out: if type(out) == type([]): choice = self._selectFromList(out, using_pattern, "concept") if choice: self.currentEntity = {'name': choice.locale or choice.uri, 'object': choice, 'type': 'concept'} else: self.currentEntity = {'name': out.locale or out.uri, 'object': out, 'type': 'concept'} # ..finally: if self.currentEntity: self._print_entity_intro(entity=self.currentEntity) else: print("not found")
python
def _select_concept(self, line): """try to match a class and load it""" g = self.current['graph'] if not line: out = g.all_skos_concepts using_pattern = False else: using_pattern = True if line.isdigit(): line = int(line) out = g.get_skos(line) if out: if type(out) == type([]): choice = self._selectFromList(out, using_pattern, "concept") if choice: self.currentEntity = {'name': choice.locale or choice.uri, 'object': choice, 'type': 'concept'} else: self.currentEntity = {'name': out.locale or out.uri, 'object': out, 'type': 'concept'} # ..finally: if self.currentEntity: self._print_entity_intro(entity=self.currentEntity) else: print("not found")
[ "def", "_select_concept", "(", "self", ",", "line", ")", ":", "g", "=", "self", ".", "current", "[", "'graph'", "]", "if", "not", "line", ":", "out", "=", "g", ".", "all_skos_concepts", "using_pattern", "=", "False", "else", ":", "using_pattern", "=", "True", "if", "line", ".", "isdigit", "(", ")", ":", "line", "=", "int", "(", "line", ")", "out", "=", "g", ".", "get_skos", "(", "line", ")", "if", "out", ":", "if", "type", "(", "out", ")", "==", "type", "(", "[", "]", ")", ":", "choice", "=", "self", ".", "_selectFromList", "(", "out", ",", "using_pattern", ",", "\"concept\"", ")", "if", "choice", ":", "self", ".", "currentEntity", "=", "{", "'name'", ":", "choice", ".", "locale", "or", "choice", ".", "uri", ",", "'object'", ":", "choice", ",", "'type'", ":", "'concept'", "}", "else", ":", "self", ".", "currentEntity", "=", "{", "'name'", ":", "out", ".", "locale", "or", "out", ".", "uri", ",", "'object'", ":", "out", ",", "'type'", ":", "'concept'", "}", "# ..finally:", "if", "self", ".", "currentEntity", ":", "self", ".", "_print_entity_intro", "(", "entity", "=", "self", ".", "currentEntity", ")", "else", ":", "print", "(", "\"not found\"", ")" ]
try to match a class and load it
[ "try", "to", "match", "a", "class", "and", "load", "it" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L625-L650
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.do_visualize
def do_visualize(self, line): """Visualize an ontology - ie wrapper for export command""" if not self.current: self._help_noontology() return line = line.split() try: # from ..viz.builder import action_visualize from ..ontodocs.builder import action_visualize except: self._print("This command requires the ontodocs package: `pip install ontodocs`") return import webbrowser url = action_visualize(args=self.current['file'], fromshell=True) if url: webbrowser.open(url) return
python
def do_visualize(self, line): """Visualize an ontology - ie wrapper for export command""" if not self.current: self._help_noontology() return line = line.split() try: # from ..viz.builder import action_visualize from ..ontodocs.builder import action_visualize except: self._print("This command requires the ontodocs package: `pip install ontodocs`") return import webbrowser url = action_visualize(args=self.current['file'], fromshell=True) if url: webbrowser.open(url) return
[ "def", "do_visualize", "(", "self", ",", "line", ")", ":", "if", "not", "self", ".", "current", ":", "self", ".", "_help_noontology", "(", ")", "return", "line", "=", "line", ".", "split", "(", ")", "try", ":", "# from ..viz.builder import action_visualize", "from", ".", ".", "ontodocs", ".", "builder", "import", "action_visualize", "except", ":", "self", ".", "_print", "(", "\"This command requires the ontodocs package: `pip install ontodocs`\"", ")", "return", "import", "webbrowser", "url", "=", "action_visualize", "(", "args", "=", "self", ".", "current", "[", "'file'", "]", ",", "fromshell", "=", "True", ")", "if", "url", ":", "webbrowser", ".", "open", "(", "url", ")", "return" ]
Visualize an ontology - ie wrapper for export command
[ "Visualize", "an", "ontology", "-", "ie", "wrapper", "for", "export", "command" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L964-L984
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.do_import
def do_import(self, line): """Import an ontology""" line = line.split() if line and line[0] == "starter-pack": actions.action_bootstrap() elif line and line[0] == "uri": self._print( "------------------\nEnter a valid graph URI: (e.g. http://www.w3.org/2009/08/skos-reference/skos.rdf)") var = input() if var: if var.startswith("http"): try: actions.action_import(var) except: self._print( "OPS... An Unknown Error Occurred - Aborting installation of <%s>" % var) else: self._print("Not valid. TIP: URIs should start with 'http://'") elif line and line[0] == "file": self._print( "------------------\nEnter a full file path: (e.g. '/Users/mike/Desktop/journals.ttl')") var = input() if var: try: actions.action_import(var) except: self._print( "OPS... An Unknown Error Occurred - Aborting installation of <%s>" % var) elif line and line[0] == "repo": actions.action_webimport() else: self.help_import() self.all_ontologies = manager.get_localontologies() return
python
def do_import(self, line): """Import an ontology""" line = line.split() if line and line[0] == "starter-pack": actions.action_bootstrap() elif line and line[0] == "uri": self._print( "------------------\nEnter a valid graph URI: (e.g. http://www.w3.org/2009/08/skos-reference/skos.rdf)") var = input() if var: if var.startswith("http"): try: actions.action_import(var) except: self._print( "OPS... An Unknown Error Occurred - Aborting installation of <%s>" % var) else: self._print("Not valid. TIP: URIs should start with 'http://'") elif line and line[0] == "file": self._print( "------------------\nEnter a full file path: (e.g. '/Users/mike/Desktop/journals.ttl')") var = input() if var: try: actions.action_import(var) except: self._print( "OPS... An Unknown Error Occurred - Aborting installation of <%s>" % var) elif line and line[0] == "repo": actions.action_webimport() else: self.help_import() self.all_ontologies = manager.get_localontologies() return
[ "def", "do_import", "(", "self", ",", "line", ")", ":", "line", "=", "line", ".", "split", "(", ")", "if", "line", "and", "line", "[", "0", "]", "==", "\"starter-pack\"", ":", "actions", ".", "action_bootstrap", "(", ")", "elif", "line", "and", "line", "[", "0", "]", "==", "\"uri\"", ":", "self", ".", "_print", "(", "\"------------------\\nEnter a valid graph URI: (e.g. http://www.w3.org/2009/08/skos-reference/skos.rdf)\"", ")", "var", "=", "input", "(", ")", "if", "var", ":", "if", "var", ".", "startswith", "(", "\"http\"", ")", ":", "try", ":", "actions", ".", "action_import", "(", "var", ")", "except", ":", "self", ".", "_print", "(", "\"OPS... An Unknown Error Occurred - Aborting installation of <%s>\"", "%", "var", ")", "else", ":", "self", ".", "_print", "(", "\"Not valid. TIP: URIs should start with 'http://'\"", ")", "elif", "line", "and", "line", "[", "0", "]", "==", "\"file\"", ":", "self", ".", "_print", "(", "\"------------------\\nEnter a full file path: (e.g. '/Users/mike/Desktop/journals.ttl')\"", ")", "var", "=", "input", "(", ")", "if", "var", ":", "try", ":", "actions", ".", "action_import", "(", "var", ")", "except", ":", "self", ".", "_print", "(", "\"OPS... An Unknown Error Occurred - Aborting installation of <%s>\"", "%", "var", ")", "elif", "line", "and", "line", "[", "0", "]", "==", "\"repo\"", ":", "actions", ".", "action_webimport", "(", ")", "else", ":", "self", ".", "help_import", "(", ")", "self", ".", "all_ontologies", "=", "manager", ".", "get_localontologies", "(", ")", "return" ]
Import an ontology
[ "Import", "an", "ontology" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L986-L1026
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.do_file
def do_file(self, line): """PErform some file operation""" opts = self.FILE_OPTS if not self.all_ontologies: self._help_nofiles() return line = line.split() if not line or line[0] not in opts: self.help_file() return if line[0] == "rename": self._rename_file() elif line[0] == "delete": self._delete_file() else: return
python
def do_file(self, line): """PErform some file operation""" opts = self.FILE_OPTS if not self.all_ontologies: self._help_nofiles() return line = line.split() if not line or line[0] not in opts: self.help_file() return if line[0] == "rename": self._rename_file() elif line[0] == "delete": self._delete_file() else: return
[ "def", "do_file", "(", "self", ",", "line", ")", ":", "opts", "=", "self", ".", "FILE_OPTS", "if", "not", "self", ".", "all_ontologies", ":", "self", ".", "_help_nofiles", "(", ")", "return", "line", "=", "line", ".", "split", "(", ")", "if", "not", "line", "or", "line", "[", "0", "]", "not", "in", "opts", ":", "self", ".", "help_file", "(", ")", "return", "if", "line", "[", "0", "]", "==", "\"rename\"", ":", "self", ".", "_rename_file", "(", ")", "elif", "line", "[", "0", "]", "==", "\"delete\"", ":", "self", ".", "_delete_file", "(", ")", "else", ":", "return" ]
PErform some file operation
[ "PErform", "some", "file", "operation" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1028-L1047
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.do_serialize
def do_serialize(self, line): """Serialize an entity into an RDF flavour""" opts = self.SERIALIZE_OPTS if not self.current: self._help_noontology() return line = line.split() g = self.current['graph'] if not line: line = ['turtle'] if line[0] not in opts: self.help_serialize() return elif self.currentEntity: self.currentEntity['object'].printSerialize(line[0]) else: self._print(g.rdf_source(format=line[0]))
python
def do_serialize(self, line): """Serialize an entity into an RDF flavour""" opts = self.SERIALIZE_OPTS if not self.current: self._help_noontology() return line = line.split() g = self.current['graph'] if not line: line = ['turtle'] if line[0] not in opts: self.help_serialize() return elif self.currentEntity: self.currentEntity['object'].printSerialize(line[0]) else: self._print(g.rdf_source(format=line[0]))
[ "def", "do_serialize", "(", "self", ",", "line", ")", ":", "opts", "=", "self", ".", "SERIALIZE_OPTS", "if", "not", "self", ".", "current", ":", "self", ".", "_help_noontology", "(", ")", "return", "line", "=", "line", ".", "split", "(", ")", "g", "=", "self", ".", "current", "[", "'graph'", "]", "if", "not", "line", ":", "line", "=", "[", "'turtle'", "]", "if", "line", "[", "0", "]", "not", "in", "opts", ":", "self", ".", "help_serialize", "(", ")", "return", "elif", "self", ".", "currentEntity", ":", "self", ".", "currentEntity", "[", "'object'", "]", ".", "printSerialize", "(", "line", "[", "0", "]", ")", "else", ":", "self", ".", "_print", "(", "g", ".", "rdf_source", "(", "format", "=", "line", "[", "0", "]", ")", ")" ]
Serialize an entity into an RDF flavour
[ "Serialize", "an", "entity", "into", "an", "RDF", "flavour" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1049-L1071
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.do_back
def do_back(self, line): "Go back one step. From entity => ontology; from ontology => ontospy top level." if self.currentEntity: self.currentEntity = None self.prompt = _get_prompt(self.current['file']) else: self.current = None self.prompt = _get_prompt()
python
def do_back(self, line): "Go back one step. From entity => ontology; from ontology => ontospy top level." if self.currentEntity: self.currentEntity = None self.prompt = _get_prompt(self.current['file']) else: self.current = None self.prompt = _get_prompt()
[ "def", "do_back", "(", "self", ",", "line", ")", ":", "if", "self", ".", "currentEntity", ":", "self", ".", "currentEntity", "=", "None", "self", ".", "prompt", "=", "_get_prompt", "(", "self", ".", "current", "[", "'file'", "]", ")", "else", ":", "self", ".", "current", "=", "None", "self", ".", "prompt", "=", "_get_prompt", "(", ")" ]
Go back one step. From entity => ontology; from ontology => ontospy top level.
[ "Go", "back", "one", "step", ".", "From", "entity", "=", ">", "ontology", ";", "from", "ontology", "=", ">", "ontospy", "top", "level", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1100-L1107
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.do_zen
def do_zen(self, line): """Inspiring quotes for the working ontologist""" _quote = random.choice(QUOTES) # print(_quote['source']) print(Style.DIM + unicode(_quote['text'])) print(Style.BRIGHT + unicode(_quote['source']) + Style.RESET_ALL)
python
def do_zen(self, line): """Inspiring quotes for the working ontologist""" _quote = random.choice(QUOTES) # print(_quote['source']) print(Style.DIM + unicode(_quote['text'])) print(Style.BRIGHT + unicode(_quote['source']) + Style.RESET_ALL)
[ "def", "do_zen", "(", "self", ",", "line", ")", ":", "_quote", "=", "random", ".", "choice", "(", "QUOTES", ")", "# print(_quote['source'])", "print", "(", "Style", ".", "DIM", "+", "unicode", "(", "_quote", "[", "'text'", "]", ")", ")", "print", "(", "Style", ".", "BRIGHT", "+", "unicode", "(", "_quote", "[", "'source'", "]", ")", "+", "Style", ".", "RESET_ALL", ")" ]
Inspiring quotes for the working ontologist
[ "Inspiring", "quotes", "for", "the", "working", "ontologist" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1114-L1119
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.complete_get
def complete_get(self, text, line, begidx, endidx): """completion for find command""" options = self.GET_OPTS if not text: completions = options else: completions = [f for f in options if f.startswith(text) ] return completions
python
def complete_get(self, text, line, begidx, endidx): """completion for find command""" options = self.GET_OPTS if not text: completions = options else: completions = [f for f in options if f.startswith(text) ] return completions
[ "def", "complete_get", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "options", "=", "self", ".", "GET_OPTS", "if", "not", "text", ":", "completions", "=", "options", "else", ":", "completions", "=", "[", "f", "for", "f", "in", "options", "if", "f", ".", "startswith", "(", "text", ")", "]", "return", "completions" ]
completion for find command
[ "completion", "for", "find", "command" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1234-L1246
train
lambdamusic/Ontospy
ontospy/extras/shell_lib.py
Shell.complete_info
def complete_info(self, text, line, begidx, endidx): """completion for info command""" opts = self.INFO_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(text) ] return completions
python
def complete_info(self, text, line, begidx, endidx): """completion for info command""" opts = self.INFO_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(text) ] return completions
[ "def", "complete_info", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "opts", "=", "self", ".", "INFO_OPTS", "if", "not", "text", ":", "completions", "=", "opts", "else", ":", "completions", "=", "[", "f", "for", "f", "in", "opts", "if", "f", ".", "startswith", "(", "text", ")", "]", "return", "completions" ]
completion for info command
[ "completion", "for", "info", "command" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/shell_lib.py#L1248-L1260
train
lambdamusic/Ontospy
ontospy/ontodocs/utils.py
build_D3treeStandard
def build_D3treeStandard(old, MAX_DEPTH, level=1, toplayer=None): """ For d3s examples all we need is a json with name, children and size .. eg { "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", "children": [ {"name": "AgglomerativeCluster", "size": 3938}, {"name": "CommunityStructure", "size": 3812}, {"name": "HierarchicalCluster", "size": 6714}, {"name": "MergeEdge", "size": 743} ] }, etc... """ out = [] if not old: old = toplayer for x in old: d = {} # print "*" * level, x.label d['qname'] = x.qname d['name'] = x.bestLabel(quotes=False).replace("_", " ") d['objid'] = x.id if x.children() and level < MAX_DEPTH: d['size'] = len(x.children()) + 5 # fake size d['realsize'] = len(x.children()) # real size d['children'] = build_D3treeStandard(x.children(), MAX_DEPTH, level + 1) else: d['size'] = 1 # default size d['realsize'] = 0 # default size out += [d] return out
python
def build_D3treeStandard(old, MAX_DEPTH, level=1, toplayer=None): """ For d3s examples all we need is a json with name, children and size .. eg { "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", "children": [ {"name": "AgglomerativeCluster", "size": 3938}, {"name": "CommunityStructure", "size": 3812}, {"name": "HierarchicalCluster", "size": 6714}, {"name": "MergeEdge", "size": 743} ] }, etc... """ out = [] if not old: old = toplayer for x in old: d = {} # print "*" * level, x.label d['qname'] = x.qname d['name'] = x.bestLabel(quotes=False).replace("_", " ") d['objid'] = x.id if x.children() and level < MAX_DEPTH: d['size'] = len(x.children()) + 5 # fake size d['realsize'] = len(x.children()) # real size d['children'] = build_D3treeStandard(x.children(), MAX_DEPTH, level + 1) else: d['size'] = 1 # default size d['realsize'] = 0 # default size out += [d] return out
[ "def", "build_D3treeStandard", "(", "old", ",", "MAX_DEPTH", ",", "level", "=", "1", ",", "toplayer", "=", "None", ")", ":", "out", "=", "[", "]", "if", "not", "old", ":", "old", "=", "toplayer", "for", "x", "in", "old", ":", "d", "=", "{", "}", "# print \"*\" * level, x.label", "d", "[", "'qname'", "]", "=", "x", ".", "qname", "d", "[", "'name'", "]", "=", "x", ".", "bestLabel", "(", "quotes", "=", "False", ")", ".", "replace", "(", "\"_\"", ",", "\" \"", ")", "d", "[", "'objid'", "]", "=", "x", ".", "id", "if", "x", ".", "children", "(", ")", "and", "level", "<", "MAX_DEPTH", ":", "d", "[", "'size'", "]", "=", "len", "(", "x", ".", "children", "(", ")", ")", "+", "5", "# fake size", "d", "[", "'realsize'", "]", "=", "len", "(", "x", ".", "children", "(", ")", ")", "# real size", "d", "[", "'children'", "]", "=", "build_D3treeStandard", "(", "x", ".", "children", "(", ")", ",", "MAX_DEPTH", ",", "level", "+", "1", ")", "else", ":", "d", "[", "'size'", "]", "=", "1", "# default size", "d", "[", "'realsize'", "]", "=", "0", "# default size", "out", "+=", "[", "d", "]", "return", "out" ]
For d3s examples all we need is a json with name, children and size .. eg { "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", "children": [ {"name": "AgglomerativeCluster", "size": 3938}, {"name": "CommunityStructure", "size": 3812}, {"name": "HierarchicalCluster", "size": 6714}, {"name": "MergeEdge", "size": 743} ] }, etc...
[ "For", "d3s", "examples", "all", "we", "need", "is", "a", "json", "with", "name", "children", "and", "size", "..", "eg" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/utils.py#L11-L51
train
lambdamusic/Ontospy
ontospy/ontodocs/utils.py
build_D3bubbleChart
def build_D3bubbleChart(old, MAX_DEPTH, level=1, toplayer=None): """ Similar to standar d3, but nodes with children need to be duplicated otherwise they are not depicted explicitly but just color coded "name": "all", "children": [ {"name": "Biological Science", "size": 9000}, {"name": "Biological Science", "children": [ {"name": "Biological techniques", "size": 6939}, {"name": "Cell biology", "size": 4166}, {"name": "Drug discovery X", "size": 3620, "children": [ {"name": "Biochemistry X", "size": 4585}, {"name": "Biochemistry X", "size": 4585 }, ]}, {"name": "Drug discovery Y", "size": 3620, "children": [ {"name": "Biochemistry Y", "size": 4585}, {"name": "Biochemistry Y", "size": 4585 }, ]}, {"name": "Drug discovery A", "size": 3620, "children": [ {"name": "Biochemistry A", "size": 4585}, ]}, {"name": "Drug discovery B", "size": 3620, }, ]}, etc... """ out = [] if not old: old = toplayer for x in old: d = {} # print "*" * level, x.label d['qname'] = x.qname d['name'] = x.bestLabel(quotes=False).replace("_", " ") d['objid'] = x.id if x.children() and level < MAX_DEPTH: duplicate_row = {} duplicate_row['qname'] = x.qname duplicate_row['name'] = x.bestLabel(quotes=False).replace("_", " ") duplicate_row['objid'] = x.id duplicate_row['size'] = len(x.children()) + 5 # fake size duplicate_row['realsize'] = len(x.children()) # real size out += [duplicate_row] d['children'] = build_D3bubbleChart(x.children(), MAX_DEPTH, level + 1) else: d['size'] = 1 # default size d['realsize'] = 0 # default size out += [d] return out
python
def build_D3bubbleChart(old, MAX_DEPTH, level=1, toplayer=None): """ Similar to standar d3, but nodes with children need to be duplicated otherwise they are not depicted explicitly but just color coded "name": "all", "children": [ {"name": "Biological Science", "size": 9000}, {"name": "Biological Science", "children": [ {"name": "Biological techniques", "size": 6939}, {"name": "Cell biology", "size": 4166}, {"name": "Drug discovery X", "size": 3620, "children": [ {"name": "Biochemistry X", "size": 4585}, {"name": "Biochemistry X", "size": 4585 }, ]}, {"name": "Drug discovery Y", "size": 3620, "children": [ {"name": "Biochemistry Y", "size": 4585}, {"name": "Biochemistry Y", "size": 4585 }, ]}, {"name": "Drug discovery A", "size": 3620, "children": [ {"name": "Biochemistry A", "size": 4585}, ]}, {"name": "Drug discovery B", "size": 3620, }, ]}, etc... """ out = [] if not old: old = toplayer for x in old: d = {} # print "*" * level, x.label d['qname'] = x.qname d['name'] = x.bestLabel(quotes=False).replace("_", " ") d['objid'] = x.id if x.children() and level < MAX_DEPTH: duplicate_row = {} duplicate_row['qname'] = x.qname duplicate_row['name'] = x.bestLabel(quotes=False).replace("_", " ") duplicate_row['objid'] = x.id duplicate_row['size'] = len(x.children()) + 5 # fake size duplicate_row['realsize'] = len(x.children()) # real size out += [duplicate_row] d['children'] = build_D3bubbleChart(x.children(), MAX_DEPTH, level + 1) else: d['size'] = 1 # default size d['realsize'] = 0 # default size out += [d] return out
[ "def", "build_D3bubbleChart", "(", "old", ",", "MAX_DEPTH", ",", "level", "=", "1", ",", "toplayer", "=", "None", ")", ":", "out", "=", "[", "]", "if", "not", "old", ":", "old", "=", "toplayer", "for", "x", "in", "old", ":", "d", "=", "{", "}", "# print \"*\" * level, x.label", "d", "[", "'qname'", "]", "=", "x", ".", "qname", "d", "[", "'name'", "]", "=", "x", ".", "bestLabel", "(", "quotes", "=", "False", ")", ".", "replace", "(", "\"_\"", ",", "\" \"", ")", "d", "[", "'objid'", "]", "=", "x", ".", "id", "if", "x", ".", "children", "(", ")", "and", "level", "<", "MAX_DEPTH", ":", "duplicate_row", "=", "{", "}", "duplicate_row", "[", "'qname'", "]", "=", "x", ".", "qname", "duplicate_row", "[", "'name'", "]", "=", "x", ".", "bestLabel", "(", "quotes", "=", "False", ")", ".", "replace", "(", "\"_\"", ",", "\" \"", ")", "duplicate_row", "[", "'objid'", "]", "=", "x", ".", "id", "duplicate_row", "[", "'size'", "]", "=", "len", "(", "x", ".", "children", "(", ")", ")", "+", "5", "# fake size", "duplicate_row", "[", "'realsize'", "]", "=", "len", "(", "x", ".", "children", "(", ")", ")", "# real size", "out", "+=", "[", "duplicate_row", "]", "d", "[", "'children'", "]", "=", "build_D3bubbleChart", "(", "x", ".", "children", "(", ")", ",", "MAX_DEPTH", ",", "level", "+", "1", ")", "else", ":", "d", "[", "'size'", "]", "=", "1", "# default size", "d", "[", "'realsize'", "]", "=", "0", "# default size", "out", "+=", "[", "d", "]", "return", "out" ]
Similar to standar d3, but nodes with children need to be duplicated otherwise they are not depicted explicitly but just color coded "name": "all", "children": [ {"name": "Biological Science", "size": 9000}, {"name": "Biological Science", "children": [ {"name": "Biological techniques", "size": 6939}, {"name": "Cell biology", "size": 4166}, {"name": "Drug discovery X", "size": 3620, "children": [ {"name": "Biochemistry X", "size": 4585}, {"name": "Biochemistry X", "size": 4585 }, ]}, {"name": "Drug discovery Y", "size": 3620, "children": [ {"name": "Biochemistry Y", "size": 4585}, {"name": "Biochemistry Y", "size": 4585 }, ]}, {"name": "Drug discovery A", "size": 3620, "children": [ {"name": "Biochemistry A", "size": 4585}, ]}, {"name": "Drug discovery B", "size": 3620, }, ]}, etc...
[ "Similar", "to", "standar", "d3", "but", "nodes", "with", "children", "need", "to", "be", "duplicated", "otherwise", "they", "are", "not", "depicted", "explicitly", "but", "just", "color", "coded" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/utils.py#L63-L113
train
lambdamusic/Ontospy
ontospy/ontodocs/viz_factory.py
VizFactory.infer_best_title
def infer_best_title(self): """Selects something usable as a title for an ontospy graph""" if self.ontospy_graph.all_ontologies: return self.ontospy_graph.all_ontologies[0].uri elif self.ontospy_graph.sources: return self.ontospy_graph.sources[0] else: return "Untitled"
python
def infer_best_title(self): """Selects something usable as a title for an ontospy graph""" if self.ontospy_graph.all_ontologies: return self.ontospy_graph.all_ontologies[0].uri elif self.ontospy_graph.sources: return self.ontospy_graph.sources[0] else: return "Untitled"
[ "def", "infer_best_title", "(", "self", ")", ":", "if", "self", ".", "ontospy_graph", ".", "all_ontologies", ":", "return", "self", ".", "ontospy_graph", ".", "all_ontologies", "[", "0", "]", ".", "uri", "elif", "self", ".", "ontospy_graph", ".", "sources", ":", "return", "self", ".", "ontospy_graph", ".", "sources", "[", "0", "]", "else", ":", "return", "\"Untitled\"" ]
Selects something usable as a title for an ontospy graph
[ "Selects", "something", "usable", "as", "a", "title", "for", "an", "ontospy", "graph" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz_factory.py#L73-L80
train
lambdamusic/Ontospy
ontospy/ontodocs/viz_factory.py
VizFactory.build
def build(self, output_path=""): """method that should be inherited by all vis classes""" self.output_path = self.checkOutputPath(output_path) self._buildStaticFiles() self.final_url = self._buildTemplates() printDebug("Done.", "comment") printDebug("=> %s" % (self.final_url), "comment") return self.final_url
python
def build(self, output_path=""): """method that should be inherited by all vis classes""" self.output_path = self.checkOutputPath(output_path) self._buildStaticFiles() self.final_url = self._buildTemplates() printDebug("Done.", "comment") printDebug("=> %s" % (self.final_url), "comment") return self.final_url
[ "def", "build", "(", "self", ",", "output_path", "=", "\"\"", ")", ":", "self", ".", "output_path", "=", "self", ".", "checkOutputPath", "(", "output_path", ")", "self", ".", "_buildStaticFiles", "(", ")", "self", ".", "final_url", "=", "self", ".", "_buildTemplates", "(", ")", "printDebug", "(", "\"Done.\"", ",", "\"comment\"", ")", "printDebug", "(", "\"=> %s\"", "%", "(", "self", ".", "final_url", ")", ",", "\"comment\"", ")", "return", "self", ".", "final_url" ]
method that should be inherited by all vis classes
[ "method", "that", "should", "be", "inherited", "by", "all", "vis", "classes" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz_factory.py#L82-L90
train
lambdamusic/Ontospy
ontospy/ontodocs/viz_factory.py
VizFactory._buildTemplates
def _buildTemplates(self): """ do all the things necessary to build the viz should be adapted to work for single-file viz, or multi-files etc. :param output_path: :return: """ # in this case we only have one contents = self._renderTemplate(self.template_name, extraContext=None) # the main url used for opening viz f = self.main_file_name main_url = self._save2File(contents, f, self.output_path) return main_url
python
def _buildTemplates(self): """ do all the things necessary to build the viz should be adapted to work for single-file viz, or multi-files etc. :param output_path: :return: """ # in this case we only have one contents = self._renderTemplate(self.template_name, extraContext=None) # the main url used for opening viz f = self.main_file_name main_url = self._save2File(contents, f, self.output_path) return main_url
[ "def", "_buildTemplates", "(", "self", ")", ":", "# in this case we only have one", "contents", "=", "self", ".", "_renderTemplate", "(", "self", ".", "template_name", ",", "extraContext", "=", "None", ")", "# the main url used for opening viz", "f", "=", "self", ".", "main_file_name", "main_url", "=", "self", ".", "_save2File", "(", "contents", ",", "f", ",", "self", ".", "output_path", ")", "return", "main_url" ]
do all the things necessary to build the viz should be adapted to work for single-file viz, or multi-files etc. :param output_path: :return:
[ "do", "all", "the", "things", "necessary", "to", "build", "the", "viz", "should", "be", "adapted", "to", "work", "for", "single", "-", "file", "viz", "or", "multi", "-", "files", "etc", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz_factory.py#L92-L105
train
lambdamusic/Ontospy
ontospy/ontodocs/viz_factory.py
VizFactory._build_basic_context
def _build_basic_context(self): """ Return a standard dict used in django as a template context """ # printDebug(str(self.ontospy_graph.toplayer_classes)) topclasses = self.ontospy_graph.toplayer_classes[:] if len(topclasses) < 3: # massage the toplayer! for topclass in self.ontospy_graph.toplayer_classes: for child in topclass.children(): if child not in topclasses: topclasses.append(child) if not self.static_url: self.static_url = "static/" # default context_data = { "STATIC_URL": self.static_url, "ontodocs_version": VERSION, "ontospy_graph": self.ontospy_graph, "topclasses": topclasses, "docs_title": self.title, "namespaces": self.ontospy_graph.namespaces, "stats": self.ontospy_graph.stats(), "sources": self.ontospy_graph.sources, "ontologies": self.ontospy_graph.all_ontologies, "classes": self.ontospy_graph.all_classes, "properties": self.ontospy_graph.all_properties, "objproperties": self.ontospy_graph.all_properties_object, "dataproperties": self.ontospy_graph.all_properties_datatype, "annotationproperties": self.ontospy_graph.all_properties_annotation, "skosConcepts": self.ontospy_graph.all_skos_concepts, "instances": [] } return context_data
python
def _build_basic_context(self): """ Return a standard dict used in django as a template context """ # printDebug(str(self.ontospy_graph.toplayer_classes)) topclasses = self.ontospy_graph.toplayer_classes[:] if len(topclasses) < 3: # massage the toplayer! for topclass in self.ontospy_graph.toplayer_classes: for child in topclass.children(): if child not in topclasses: topclasses.append(child) if not self.static_url: self.static_url = "static/" # default context_data = { "STATIC_URL": self.static_url, "ontodocs_version": VERSION, "ontospy_graph": self.ontospy_graph, "topclasses": topclasses, "docs_title": self.title, "namespaces": self.ontospy_graph.namespaces, "stats": self.ontospy_graph.stats(), "sources": self.ontospy_graph.sources, "ontologies": self.ontospy_graph.all_ontologies, "classes": self.ontospy_graph.all_classes, "properties": self.ontospy_graph.all_properties, "objproperties": self.ontospy_graph.all_properties_object, "dataproperties": self.ontospy_graph.all_properties_datatype, "annotationproperties": self.ontospy_graph.all_properties_annotation, "skosConcepts": self.ontospy_graph.all_skos_concepts, "instances": [] } return context_data
[ "def", "_build_basic_context", "(", "self", ")", ":", "# printDebug(str(self.ontospy_graph.toplayer_classes))", "topclasses", "=", "self", ".", "ontospy_graph", ".", "toplayer_classes", "[", ":", "]", "if", "len", "(", "topclasses", ")", "<", "3", ":", "# massage the toplayer!", "for", "topclass", "in", "self", ".", "ontospy_graph", ".", "toplayer_classes", ":", "for", "child", "in", "topclass", ".", "children", "(", ")", ":", "if", "child", "not", "in", "topclasses", ":", "topclasses", ".", "append", "(", "child", ")", "if", "not", "self", ".", "static_url", ":", "self", ".", "static_url", "=", "\"static/\"", "# default", "context_data", "=", "{", "\"STATIC_URL\"", ":", "self", ".", "static_url", ",", "\"ontodocs_version\"", ":", "VERSION", ",", "\"ontospy_graph\"", ":", "self", ".", "ontospy_graph", ",", "\"topclasses\"", ":", "topclasses", ",", "\"docs_title\"", ":", "self", ".", "title", ",", "\"namespaces\"", ":", "self", ".", "ontospy_graph", ".", "namespaces", ",", "\"stats\"", ":", "self", ".", "ontospy_graph", ".", "stats", "(", ")", ",", "\"sources\"", ":", "self", ".", "ontospy_graph", ".", "sources", ",", "\"ontologies\"", ":", "self", ".", "ontospy_graph", ".", "all_ontologies", ",", "\"classes\"", ":", "self", ".", "ontospy_graph", ".", "all_classes", ",", "\"properties\"", ":", "self", ".", "ontospy_graph", ".", "all_properties", ",", "\"objproperties\"", ":", "self", ".", "ontospy_graph", ".", "all_properties_object", ",", "\"dataproperties\"", ":", "self", ".", "ontospy_graph", ".", "all_properties_datatype", ",", "\"annotationproperties\"", ":", "self", ".", "ontospy_graph", ".", "all_properties_annotation", ",", "\"skosConcepts\"", ":", "self", ".", "ontospy_graph", ".", "all_skos_concepts", ",", "\"instances\"", ":", "[", "]", "}", "return", "context_data" ]
Return a standard dict used in django as a template context
[ "Return", "a", "standard", "dict", "used", "in", "django", "as", "a", "template", "context" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz_factory.py#L161-L195
train
lambdamusic/Ontospy
ontospy/ontodocs/viz_factory.py
VizFactory.checkOutputPath
def checkOutputPath(self, output_path): """ Create or clean up output path """ if not output_path: # output_path = self.output_path_DEFAULT output_path = os.path.join(self.output_path_DEFAULT, slugify(unicode(self.title))) if os.path.exists(output_path): shutil.rmtree(output_path) os.makedirs(output_path) return output_path
python
def checkOutputPath(self, output_path): """ Create or clean up output path """ if not output_path: # output_path = self.output_path_DEFAULT output_path = os.path.join(self.output_path_DEFAULT, slugify(unicode(self.title))) if os.path.exists(output_path): shutil.rmtree(output_path) os.makedirs(output_path) return output_path
[ "def", "checkOutputPath", "(", "self", ",", "output_path", ")", ":", "if", "not", "output_path", ":", "# output_path = self.output_path_DEFAULT", "output_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_path_DEFAULT", ",", "slugify", "(", "unicode", "(", "self", ".", "title", ")", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "output_path", ")", ":", "shutil", ".", "rmtree", "(", "output_path", ")", "os", ".", "makedirs", "(", "output_path", ")", "return", "output_path" ]
Create or clean up output path
[ "Create", "or", "clean", "up", "output", "path" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz_factory.py#L205-L216
train
lambdamusic/Ontospy
ontospy/ontodocs/viz_factory.py
VizFactory.highlight_code
def highlight_code(self, ontospy_entity): """ produce an html version of Turtle code with syntax highlighted using Pygments CSS """ try: pygments_code = highlight(ontospy_entity.rdf_source(), TurtleLexer(), HtmlFormatter()) pygments_code_css = HtmlFormatter().get_style_defs('.highlight') return { "pygments_code": pygments_code, "pygments_code_css": pygments_code_css } except Exception as e: printDebug("Error: Pygmentize Failed", "red") return {}
python
def highlight_code(self, ontospy_entity): """ produce an html version of Turtle code with syntax highlighted using Pygments CSS """ try: pygments_code = highlight(ontospy_entity.rdf_source(), TurtleLexer(), HtmlFormatter()) pygments_code_css = HtmlFormatter().get_style_defs('.highlight') return { "pygments_code": pygments_code, "pygments_code_css": pygments_code_css } except Exception as e: printDebug("Error: Pygmentize Failed", "red") return {}
[ "def", "highlight_code", "(", "self", ",", "ontospy_entity", ")", ":", "try", ":", "pygments_code", "=", "highlight", "(", "ontospy_entity", ".", "rdf_source", "(", ")", ",", "TurtleLexer", "(", ")", ",", "HtmlFormatter", "(", ")", ")", "pygments_code_css", "=", "HtmlFormatter", "(", ")", ".", "get_style_defs", "(", "'.highlight'", ")", "return", "{", "\"pygments_code\"", ":", "pygments_code", ",", "\"pygments_code_css\"", ":", "pygments_code_css", "}", "except", "Exception", "as", "e", ":", "printDebug", "(", "\"Error: Pygmentize Failed\"", ",", "\"red\"", ")", "return", "{", "}" ]
produce an html version of Turtle code with syntax highlighted using Pygments CSS
[ "produce", "an", "html", "version", "of", "Turtle", "code", "with", "syntax", "highlighted", "using", "Pygments", "CSS" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/ontodocs/viz_factory.py#L218-L233
train
lambdamusic/Ontospy
ontospy/extras/sparqlpy.py
SparqlEndpoint.query
def query(self, q, format="", convert=True): """ Generic SELECT query structure. 'q' is the main body of the query. The results passed out are not converted yet: see the 'format' method Results could be iterated using the idiom: for l in obj : do_something_with_line(l) If convert is False, we return the collection of rdflib instances """ lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()] lines.extend(q.split("\n")) query = "\n".join(lines) if self.verbose: print(query, "\n\n") return self.__doQuery(query, format, convert)
python
def query(self, q, format="", convert=True): """ Generic SELECT query structure. 'q' is the main body of the query. The results passed out are not converted yet: see the 'format' method Results could be iterated using the idiom: for l in obj : do_something_with_line(l) If convert is False, we return the collection of rdflib instances """ lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()] lines.extend(q.split("\n")) query = "\n".join(lines) if self.verbose: print(query, "\n\n") return self.__doQuery(query, format, convert)
[ "def", "query", "(", "self", ",", "q", ",", "format", "=", "\"\"", ",", "convert", "=", "True", ")", ":", "lines", "=", "[", "\"PREFIX %s: <%s>\"", "%", "(", "k", ",", "r", ")", "for", "k", ",", "r", "in", "self", ".", "prefixes", ".", "iteritems", "(", ")", "]", "lines", ".", "extend", "(", "q", ".", "split", "(", "\"\\n\"", ")", ")", "query", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "if", "self", ".", "verbose", ":", "print", "(", "query", ",", "\"\\n\\n\"", ")", "return", "self", ".", "__doQuery", "(", "query", ",", "format", ",", "convert", ")" ]
Generic SELECT query structure. 'q' is the main body of the query. The results passed out are not converted yet: see the 'format' method Results could be iterated using the idiom: for l in obj : do_something_with_line(l) If convert is False, we return the collection of rdflib instances
[ "Generic", "SELECT", "query", "structure", ".", "q", "is", "the", "main", "body", "of", "the", "query", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/sparqlpy.py#L103-L121
train
lambdamusic/Ontospy
ontospy/extras/sparqlpy.py
SparqlEndpoint.describe
def describe(self, uri, format="", convert=True): """ A simple DESCRIBE query with no 'where' arguments. 'uri' is the resource you want to describe. TODO: there are some errors with describe queries, due to the results being sent back For the moment we're not using them much.. needs to be tested more. """ lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()] if uri.startswith("http://"): lines.extend(["DESCRIBE <%s>" % uri]) else: # it's a shortened uri lines.extend(["DESCRIBE %s" % uri]) query = "\n".join(lines) if self.verbose: print(query, "\n\n") return self.__doQuery(query, format, convert)
python
def describe(self, uri, format="", convert=True): """ A simple DESCRIBE query with no 'where' arguments. 'uri' is the resource you want to describe. TODO: there are some errors with describe queries, due to the results being sent back For the moment we're not using them much.. needs to be tested more. """ lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()] if uri.startswith("http://"): lines.extend(["DESCRIBE <%s>" % uri]) else: # it's a shortened uri lines.extend(["DESCRIBE %s" % uri]) query = "\n".join(lines) if self.verbose: print(query, "\n\n") return self.__doQuery(query, format, convert)
[ "def", "describe", "(", "self", ",", "uri", ",", "format", "=", "\"\"", ",", "convert", "=", "True", ")", ":", "lines", "=", "[", "\"PREFIX %s: <%s>\"", "%", "(", "k", ",", "r", ")", "for", "k", ",", "r", "in", "self", ".", "prefixes", ".", "iteritems", "(", ")", "]", "if", "uri", ".", "startswith", "(", "\"http://\"", ")", ":", "lines", ".", "extend", "(", "[", "\"DESCRIBE <%s>\"", "%", "uri", "]", ")", "else", ":", "# it's a shortened uri", "lines", ".", "extend", "(", "[", "\"DESCRIBE %s\"", "%", "uri", "]", ")", "query", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "if", "self", ".", "verbose", ":", "print", "(", "query", ",", "\"\\n\\n\"", ")", "return", "self", ".", "__doQuery", "(", "query", ",", "format", ",", "convert", ")" ]
A simple DESCRIBE query with no 'where' arguments. 'uri' is the resource you want to describe. TODO: there are some errors with describe queries, due to the results being sent back For the moment we're not using them much.. needs to be tested more.
[ "A", "simple", "DESCRIBE", "query", "with", "no", "where", "arguments", ".", "uri", "is", "the", "resource", "you", "want", "to", "describe", "." ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/sparqlpy.py#L125-L144
train
lambdamusic/Ontospy
ontospy/extras/sparqlpy.py
SparqlEndpoint.__doQuery
def __doQuery(self, query, format, convert): """ Inner method that does the actual query """ self.__getFormat(format) self.sparql.setQuery(query) if convert: results = self.sparql.query().convert() else: results = self.sparql.query() return results
python
def __doQuery(self, query, format, convert): """ Inner method that does the actual query """ self.__getFormat(format) self.sparql.setQuery(query) if convert: results = self.sparql.query().convert() else: results = self.sparql.query() return results
[ "def", "__doQuery", "(", "self", ",", "query", ",", "format", ",", "convert", ")", ":", "self", ".", "__getFormat", "(", "format", ")", "self", ".", "sparql", ".", "setQuery", "(", "query", ")", "if", "convert", ":", "results", "=", "self", ".", "sparql", ".", "query", "(", ")", ".", "convert", "(", ")", "else", ":", "results", "=", "self", ".", "sparql", ".", "query", "(", ")", "return", "results" ]
Inner method that does the actual query
[ "Inner", "method", "that", "does", "the", "actual", "query" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/sparqlpy.py#L212-L223
train
lambdamusic/Ontospy
ontospy/extras/hacks/turtle-cli.py
get_default_preds
def get_default_preds(): """dynamically build autocomplete options based on an external file""" g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False) classes = [(x.qname, x.bestDescription()) for x in g.all_classes] properties = [(x.qname, x.bestDescription()) for x in g.all_properties] commands = [('exit', 'exits the terminal'), ('show', 'show current buffer')] return rdfschema + owlschema + classes + properties + commands
python
def get_default_preds(): """dynamically build autocomplete options based on an external file""" g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False) classes = [(x.qname, x.bestDescription()) for x in g.all_classes] properties = [(x.qname, x.bestDescription()) for x in g.all_properties] commands = [('exit', 'exits the terminal'), ('show', 'show current buffer')] return rdfschema + owlschema + classes + properties + commands
[ "def", "get_default_preds", "(", ")", ":", "g", "=", "ontospy", ".", "Ontospy", "(", "rdfsschema", ",", "text", "=", "True", ",", "verbose", "=", "False", ",", "hide_base_schemas", "=", "False", ")", "classes", "=", "[", "(", "x", ".", "qname", ",", "x", ".", "bestDescription", "(", ")", ")", "for", "x", "in", "g", ".", "all_classes", "]", "properties", "=", "[", "(", "x", ".", "qname", ",", "x", ".", "bestDescription", "(", ")", ")", "for", "x", "in", "g", ".", "all_properties", "]", "commands", "=", "[", "(", "'exit'", ",", "'exits the terminal'", ")", ",", "(", "'show'", ",", "'show current buffer'", ")", "]", "return", "rdfschema", "+", "owlschema", "+", "classes", "+", "properties", "+", "commands" ]
dynamically build autocomplete options based on an external file
[ "dynamically", "build", "autocomplete", "options", "based", "on", "an", "external", "file" ]
eb46cb13792b2b87f21babdf976996318eec7571
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/turtle-cli.py#L42-L48
train