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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
datascopeanalytics/traces | traces/timeseries.py | TimeSeries.to_bool | def to_bool(self, invert=False):
"""Return the truth value of each element."""
if invert:
def function(x, y):
return False if x else True
else:
def function(x, y):
return True if x else False
return self.operation(None, function) | python | def to_bool(self, invert=False):
"""Return the truth value of each element."""
if invert:
def function(x, y):
return False if x else True
else:
def function(x, y):
return True if x else False
return self.operation(None, function) | [
"def",
"to_bool",
"(",
"self",
",",
"invert",
"=",
"False",
")",
":",
"if",
"invert",
":",
"def",
"function",
"(",
"x",
",",
"y",
")",
":",
"return",
"False",
"if",
"x",
"else",
"True",
"else",
":",
"def",
"function",
"(",
"x",
",",
"y",
")",
"... | Return the truth value of each element. | [
"Return",
"the",
"truth",
"value",
"of",
"each",
"element",
"."
] | 420611151a05fea88a07bc5200fefffdc37cc95b | https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L830-L838 | train | 205,100 |
datascopeanalytics/traces | examples/helloworld.py | read_all | def read_all(pattern='data/lightbulb-*.csv'):
"""Read all of the CSVs in a directory matching the filename pattern
as TimeSeries.
"""
result = []
for filename in glob.iglob(pattern):
print('reading', filename, file=sys.stderr)
ts = traces.TimeSeries.from_csv(
filename,
time_column=0,
time_transform=parse_iso_datetime,
value_column=1,
value_transform=int,
default=0,
)
ts.compact()
result.append(ts)
return result | python | def read_all(pattern='data/lightbulb-*.csv'):
"""Read all of the CSVs in a directory matching the filename pattern
as TimeSeries.
"""
result = []
for filename in glob.iglob(pattern):
print('reading', filename, file=sys.stderr)
ts = traces.TimeSeries.from_csv(
filename,
time_column=0,
time_transform=parse_iso_datetime,
value_column=1,
value_transform=int,
default=0,
)
ts.compact()
result.append(ts)
return result | [
"def",
"read_all",
"(",
"pattern",
"=",
"'data/lightbulb-*.csv'",
")",
":",
"result",
"=",
"[",
"]",
"for",
"filename",
"in",
"glob",
".",
"iglob",
"(",
"pattern",
")",
":",
"print",
"(",
"'reading'",
",",
"filename",
",",
"file",
"=",
"sys",
".",
"std... | Read all of the CSVs in a directory matching the filename pattern
as TimeSeries. | [
"Read",
"all",
"of",
"the",
"CSVs",
"in",
"a",
"directory",
"matching",
"the",
"filename",
"pattern",
"as",
"TimeSeries",
"."
] | 420611151a05fea88a07bc5200fefffdc37cc95b | https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/examples/helloworld.py#L16-L34 | train | 205,101 |
datascopeanalytics/traces | setup.py | read_dependencies | def read_dependencies(filename):
"""Read in the dependencies from the virtualenv requirements file.
"""
dependencies = []
filepath = os.path.join('requirements', filename)
with open(filepath, 'r') as stream:
for line in stream:
package = line.strip().split('#')[0].strip()
if package and package.split(' ')[0] != '-r':
dependencies.append(package)
return dependencies | python | def read_dependencies(filename):
"""Read in the dependencies from the virtualenv requirements file.
"""
dependencies = []
filepath = os.path.join('requirements', filename)
with open(filepath, 'r') as stream:
for line in stream:
package = line.strip().split('#')[0].strip()
if package and package.split(' ')[0] != '-r':
dependencies.append(package)
return dependencies | [
"def",
"read_dependencies",
"(",
"filename",
")",
":",
"dependencies",
"=",
"[",
"]",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'requirements'",
",",
"filename",
")",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"stream",
":",
"... | Read in the dependencies from the virtualenv requirements file. | [
"Read",
"in",
"the",
"dependencies",
"from",
"the",
"virtualenv",
"requirements",
"file",
"."
] | 420611151a05fea88a07bc5200fefffdc37cc95b | https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/setup.py#L34-L45 | train | 205,102 |
pyblish/pyblish-qml | pyblish_qml/ipc/service.py | Service.process | def process(self, plugin, instance=None, action=None):
"""Given JSON objects from client, perform actual processing
Arguments:
plugin (dict): JSON representation of plug-in to process
instance (dict, optional): JSON representation of Instance to
be processed.
action (str, optional): Id of action to process
"""
plugin_obj = self.__plugins[plugin["id"]]
instance_obj = (self.__instances[instance["id"]]
if instance is not None else None)
result = pyblish.plugin.process(
plugin=plugin_obj,
context=self._context,
instance=instance_obj,
action=action)
return formatting.format_result(result) | python | def process(self, plugin, instance=None, action=None):
"""Given JSON objects from client, perform actual processing
Arguments:
plugin (dict): JSON representation of plug-in to process
instance (dict, optional): JSON representation of Instance to
be processed.
action (str, optional): Id of action to process
"""
plugin_obj = self.__plugins[plugin["id"]]
instance_obj = (self.__instances[instance["id"]]
if instance is not None else None)
result = pyblish.plugin.process(
plugin=plugin_obj,
context=self._context,
instance=instance_obj,
action=action)
return formatting.format_result(result) | [
"def",
"process",
"(",
"self",
",",
"plugin",
",",
"instance",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"plugin_obj",
"=",
"self",
".",
"__plugins",
"[",
"plugin",
"[",
"\"id\"",
"]",
"]",
"instance_obj",
"=",
"(",
"self",
".",
"__instances",... | Given JSON objects from client, perform actual processing
Arguments:
plugin (dict): JSON representation of plug-in to process
instance (dict, optional): JSON representation of Instance to
be processed.
action (str, optional): Id of action to process | [
"Given",
"JSON",
"objects",
"from",
"client",
"perform",
"actual",
"processing"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/service.py#L74-L95 | train | 205,103 |
pyblish/pyblish-qml | pyblish_qml/ipc/service.py | Service._dispatch | def _dispatch(self, method, params):
"""Customise exception handling"""
self._count += 1
func = getattr(self, method)
try:
return func(*params)
except Exception as e:
traceback.print_exc()
raise e | python | def _dispatch(self, method, params):
"""Customise exception handling"""
self._count += 1
func = getattr(self, method)
try:
return func(*params)
except Exception as e:
traceback.print_exc()
raise e | [
"def",
"_dispatch",
"(",
"self",
",",
"method",
",",
"params",
")",
":",
"self",
".",
"_count",
"+=",
"1",
"func",
"=",
"getattr",
"(",
"self",
",",
"method",
")",
"try",
":",
"return",
"func",
"(",
"*",
"params",
")",
"except",
"Exception",
"as",
... | Customise exception handling | [
"Customise",
"exception",
"handling"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/service.py#L109-L118 | train | 205,104 |
pyblish/pyblish-qml | pyblish_qml/ipc/service.py | Service.emit | def emit(self, signal, kwargs):
"""Trigger registered callbacks
This method is triggered remotely and run locally.
The keywords "instance" and "plugin" are implicitly
converted to their corresponding Pyblish objects.
"""
if "context" in kwargs:
kwargs["context"] = self._context
if "instance" in kwargs:
kwargs["instance"] = self.__instances[kwargs["instance"]]
if "plugin" in kwargs:
kwargs["plugin"] = self.__plugins[kwargs["plugin"]]
pyblish.api.emit(signal, **kwargs) | python | def emit(self, signal, kwargs):
"""Trigger registered callbacks
This method is triggered remotely and run locally.
The keywords "instance" and "plugin" are implicitly
converted to their corresponding Pyblish objects.
"""
if "context" in kwargs:
kwargs["context"] = self._context
if "instance" in kwargs:
kwargs["instance"] = self.__instances[kwargs["instance"]]
if "plugin" in kwargs:
kwargs["plugin"] = self.__plugins[kwargs["plugin"]]
pyblish.api.emit(signal, **kwargs) | [
"def",
"emit",
"(",
"self",
",",
"signal",
",",
"kwargs",
")",
":",
"if",
"\"context\"",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"context\"",
"]",
"=",
"self",
".",
"_context",
"if",
"\"instance\"",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"instance\"",
"]",
... | Trigger registered callbacks
This method is triggered remotely and run locally.
The keywords "instance" and "plugin" are implicitly
converted to their corresponding Pyblish objects. | [
"Trigger",
"registered",
"callbacks"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/service.py#L120-L138 | train | 205,105 |
pyblish/pyblish-qml | pyblish_qml/vendor/jsonschema/validators.py | RefResolver.resolve_fragment | def resolve_fragment(self, document, fragment):
"""
Resolve a ``fragment`` within the referenced ``document``.
:argument document: the referrant document
:argument str fragment: a URI fragment to resolve within it
"""
fragment = fragment.lstrip(u"/")
parts = unquote(fragment).split(u"/") if fragment else []
for part in parts:
part = part.replace(u"~1", u"/").replace(u"~0", u"~")
if isinstance(document, Sequence):
# Array indexes should be turned into integers
try:
part = int(part)
except ValueError:
pass
try:
document = document[part]
except (TypeError, LookupError):
raise RefResolutionError(
"Unresolvable JSON pointer: %r" % fragment
)
return document | python | def resolve_fragment(self, document, fragment):
"""
Resolve a ``fragment`` within the referenced ``document``.
:argument document: the referrant document
:argument str fragment: a URI fragment to resolve within it
"""
fragment = fragment.lstrip(u"/")
parts = unquote(fragment).split(u"/") if fragment else []
for part in parts:
part = part.replace(u"~1", u"/").replace(u"~0", u"~")
if isinstance(document, Sequence):
# Array indexes should be turned into integers
try:
part = int(part)
except ValueError:
pass
try:
document = document[part]
except (TypeError, LookupError):
raise RefResolutionError(
"Unresolvable JSON pointer: %r" % fragment
)
return document | [
"def",
"resolve_fragment",
"(",
"self",
",",
"document",
",",
"fragment",
")",
":",
"fragment",
"=",
"fragment",
".",
"lstrip",
"(",
"u\"/\"",
")",
"parts",
"=",
"unquote",
"(",
"fragment",
")",
".",
"split",
"(",
"u\"/\"",
")",
"if",
"fragment",
"else",... | Resolve a ``fragment`` within the referenced ``document``.
:argument document: the referrant document
:argument str fragment: a URI fragment to resolve within it | [
"Resolve",
"a",
"fragment",
"within",
"the",
"referenced",
"document",
"."
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/jsonschema/validators.py#L301-L329 | train | 205,106 |
pyblish/pyblish-qml | pyblish_qml/compat.py | generate_safemode_windows | def generate_safemode_windows():
"""Produce batch file to run QML in safe-mode
Usage:
$ python -c "import compat;compat.generate_safemode_windows()"
$ run.bat
"""
try:
import pyblish
import pyblish_qml
import PyQt5
except ImportError:
return sys.stderr.write(
"Run this in a terminal with access to "
"the Pyblish libraries and PyQt5.\n")
template = r"""@echo off
:: Clear all environment variables
@echo off
if exist ".\backup_env.bat" del ".\backup_env.bat"
for /f "tokens=1* delims==" %%a in ('set') do (
echo set %%a=%%b>> .\backup_env.bat
set %%a=
)
:: Set only the bare essentials
set PATH={PyQt5}
set PATH=%PATH%;{python}
set PYTHONPATH={pyblish}
set PYTHONPATH=%PYTHONPATH%;{pyblish_qml}
set PYTHONPATH=%PYTHONPATH%;{PyQt5}
set SystemRoot=C:\Windows
:: Run Pyblish
python -m pyblish_qml
:: Restore environment
backup_env.bat
"""
values = {}
for lib in (pyblish, pyblish_qml, PyQt5):
values[lib.__name__] = os.path.dirname(os.path.dirname(lib.__file__))
values["python"] = os.path.dirname(sys.executable)
with open("run.bat", "w") as f:
print("Writing %s" % template.format(**values))
f.write(template.format(**values)) | python | def generate_safemode_windows():
"""Produce batch file to run QML in safe-mode
Usage:
$ python -c "import compat;compat.generate_safemode_windows()"
$ run.bat
"""
try:
import pyblish
import pyblish_qml
import PyQt5
except ImportError:
return sys.stderr.write(
"Run this in a terminal with access to "
"the Pyblish libraries and PyQt5.\n")
template = r"""@echo off
:: Clear all environment variables
@echo off
if exist ".\backup_env.bat" del ".\backup_env.bat"
for /f "tokens=1* delims==" %%a in ('set') do (
echo set %%a=%%b>> .\backup_env.bat
set %%a=
)
:: Set only the bare essentials
set PATH={PyQt5}
set PATH=%PATH%;{python}
set PYTHONPATH={pyblish}
set PYTHONPATH=%PYTHONPATH%;{pyblish_qml}
set PYTHONPATH=%PYTHONPATH%;{PyQt5}
set SystemRoot=C:\Windows
:: Run Pyblish
python -m pyblish_qml
:: Restore environment
backup_env.bat
"""
values = {}
for lib in (pyblish, pyblish_qml, PyQt5):
values[lib.__name__] = os.path.dirname(os.path.dirname(lib.__file__))
values["python"] = os.path.dirname(sys.executable)
with open("run.bat", "w") as f:
print("Writing %s" % template.format(**values))
f.write(template.format(**values)) | [
"def",
"generate_safemode_windows",
"(",
")",
":",
"try",
":",
"import",
"pyblish",
"import",
"pyblish_qml",
"import",
"PyQt5",
"except",
"ImportError",
":",
"return",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Run this in a terminal with access to \"",
"\"the Pyblis... | Produce batch file to run QML in safe-mode
Usage:
$ python -c "import compat;compat.generate_safemode_windows()"
$ run.bat | [
"Produce",
"batch",
"file",
"to",
"run",
"QML",
"in",
"safe",
"-",
"mode"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/compat.py#L151-L208 | train | 205,107 |
pyblish/pyblish-qml | pyblish_qml/ipc/server.py | find_python | def find_python():
"""Search for Python automatically"""
python = (
_state.get("pythonExecutable") or
# Support for multiple executables.
next((
exe for exe in
os.getenv("PYBLISH_QML_PYTHON_EXECUTABLE", "").split(os.pathsep)
if os.path.isfile(exe)), None
) or
# Search PATH for executables.
which("python") or
which("python3")
)
if not python or not os.path.isfile(python):
raise ValueError("Could not locate Python executable.")
return python | python | def find_python():
"""Search for Python automatically"""
python = (
_state.get("pythonExecutable") or
# Support for multiple executables.
next((
exe for exe in
os.getenv("PYBLISH_QML_PYTHON_EXECUTABLE", "").split(os.pathsep)
if os.path.isfile(exe)), None
) or
# Search PATH for executables.
which("python") or
which("python3")
)
if not python or not os.path.isfile(python):
raise ValueError("Could not locate Python executable.")
return python | [
"def",
"find_python",
"(",
")",
":",
"python",
"=",
"(",
"_state",
".",
"get",
"(",
"\"pythonExecutable\"",
")",
"or",
"# Support for multiple executables.",
"next",
"(",
"(",
"exe",
"for",
"exe",
"in",
"os",
".",
"getenv",
"(",
"\"PYBLISH_QML_PYTHON_EXECUTABLE\... | Search for Python automatically | [
"Search",
"for",
"Python",
"automatically"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/server.py#L336-L356 | train | 205,108 |
pyblish/pyblish-qml | pyblish_qml/ipc/server.py | find_pyqt5 | def find_pyqt5(python):
"""Search for PyQt5 automatically"""
pyqt5 = (
_state.get("pyqt5") or
os.getenv("PYBLISH_QML_PYQT5")
)
# If not registered, ask Python for it explicitly
# This avoids having to expose PyQt5 on PYTHONPATH
# where it may otherwise get picked up by bystanders
# such as Python 2.
if not pyqt5:
try:
path = subprocess.check_output([
python, "-c",
"import PyQt5, sys;"
"sys.stdout.write(PyQt5.__file__)"
# Normally, the output is bytes.
], universal_newlines=True)
pyqt5 = os.path.dirname(os.path.dirname(path))
except subprocess.CalledProcessError:
pass
return pyqt5 | python | def find_pyqt5(python):
"""Search for PyQt5 automatically"""
pyqt5 = (
_state.get("pyqt5") or
os.getenv("PYBLISH_QML_PYQT5")
)
# If not registered, ask Python for it explicitly
# This avoids having to expose PyQt5 on PYTHONPATH
# where it may otherwise get picked up by bystanders
# such as Python 2.
if not pyqt5:
try:
path = subprocess.check_output([
python, "-c",
"import PyQt5, sys;"
"sys.stdout.write(PyQt5.__file__)"
# Normally, the output is bytes.
], universal_newlines=True)
pyqt5 = os.path.dirname(os.path.dirname(path))
except subprocess.CalledProcessError:
pass
return pyqt5 | [
"def",
"find_pyqt5",
"(",
"python",
")",
":",
"pyqt5",
"=",
"(",
"_state",
".",
"get",
"(",
"\"pyqt5\"",
")",
"or",
"os",
".",
"getenv",
"(",
"\"PYBLISH_QML_PYQT5\"",
")",
")",
"# If not registered, ask Python for it explicitly",
"# This avoids having to expose PyQt5 ... | Search for PyQt5 automatically | [
"Search",
"for",
"PyQt5",
"automatically"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/server.py#L359-L385 | train | 205,109 |
pyblish/pyblish-qml | pyblish_qml/ipc/server.py | which | def which(program):
"""Locate `program` in PATH
Arguments:
program (str): Name of program, e.g. "python"
"""
def is_exe(fpath):
if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
return True
return False
for path in os.environ["PATH"].split(os.pathsep):
for ext in os.getenv("PATHEXT", "").split(os.pathsep):
fname = program + ext.lower()
abspath = os.path.join(path.strip('"'), fname)
if is_exe(abspath):
return abspath
return None | python | def which(program):
"""Locate `program` in PATH
Arguments:
program (str): Name of program, e.g. "python"
"""
def is_exe(fpath):
if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
return True
return False
for path in os.environ["PATH"].split(os.pathsep):
for ext in os.getenv("PATHEXT", "").split(os.pathsep):
fname = program + ext.lower()
abspath = os.path.join(path.strip('"'), fname)
if is_exe(abspath):
return abspath
return None | [
"def",
"which",
"(",
"program",
")",
":",
"def",
"is_exe",
"(",
"fpath",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
"and",
"os",
".",
"access",
"(",
"fpath",
",",
"os",
".",
"X_OK",
")",
":",
"return",
"True",
"return",
... | Locate `program` in PATH
Arguments:
program (str): Name of program, e.g. "python" | [
"Locate",
"program",
"in",
"PATH"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/server.py#L388-L409 | train | 205,110 |
pyblish/pyblish-qml | pyblish_qml/ipc/server.py | Server.listen | def listen(self):
"""Listen to both stdout and stderr
We'll want messages of a particular origin and format to
cause QML to perform some action. Other messages are simply
forwarded, as they are expected to be plain print or error messages.
"""
def _listen():
"""This runs in a thread"""
HEADER = "pyblish-qml:popen.request"
for line in iter(self.popen.stdout.readline, b""):
if six.PY3:
line = line.decode("utf8")
try:
response = json.loads(line)
except Exception:
# This must be a regular message.
sys.stdout.write(line)
else:
if (hasattr(response, "get") and
response.get("header") == HEADER):
payload = response["payload"]
args = payload["args"]
func_name = payload["name"]
wrapper = _state.get("dispatchWrapper",
default_wrapper)
func = getattr(self.service, func_name)
result = wrapper(func, *args) # block..
# Note(marcus): This is where we wait for the host to
# finish. Technically, we could kill the GUI at this
# point which would make the following commands throw
# an exception. However, no host is capable of kill
# the GUI whilst running a command. The host is locked
# until finished, which means we are guaranteed to
# always respond.
data = json.dumps({
"header": "pyblish-qml:popen.response",
"payload": result
})
if six.PY3:
data = data.encode("ascii")
self.popen.stdin.write(data + b"\n")
self.popen.stdin.flush()
else:
# In the off chance that a message
# was successfully decoded as JSON,
# but *wasn't* a request, just print it.
sys.stdout.write(line)
if not self.listening:
self._start_pulse()
if self.modal:
_listen()
else:
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start()
self.listening = True | python | def listen(self):
"""Listen to both stdout and stderr
We'll want messages of a particular origin and format to
cause QML to perform some action. Other messages are simply
forwarded, as they are expected to be plain print or error messages.
"""
def _listen():
"""This runs in a thread"""
HEADER = "pyblish-qml:popen.request"
for line in iter(self.popen.stdout.readline, b""):
if six.PY3:
line = line.decode("utf8")
try:
response = json.loads(line)
except Exception:
# This must be a regular message.
sys.stdout.write(line)
else:
if (hasattr(response, "get") and
response.get("header") == HEADER):
payload = response["payload"]
args = payload["args"]
func_name = payload["name"]
wrapper = _state.get("dispatchWrapper",
default_wrapper)
func = getattr(self.service, func_name)
result = wrapper(func, *args) # block..
# Note(marcus): This is where we wait for the host to
# finish. Technically, we could kill the GUI at this
# point which would make the following commands throw
# an exception. However, no host is capable of kill
# the GUI whilst running a command. The host is locked
# until finished, which means we are guaranteed to
# always respond.
data = json.dumps({
"header": "pyblish-qml:popen.response",
"payload": result
})
if six.PY3:
data = data.encode("ascii")
self.popen.stdin.write(data + b"\n")
self.popen.stdin.flush()
else:
# In the off chance that a message
# was successfully decoded as JSON,
# but *wasn't* a request, just print it.
sys.stdout.write(line)
if not self.listening:
self._start_pulse()
if self.modal:
_listen()
else:
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start()
self.listening = True | [
"def",
"listen",
"(",
"self",
")",
":",
"def",
"_listen",
"(",
")",
":",
"\"\"\"This runs in a thread\"\"\"",
"HEADER",
"=",
"\"pyblish-qml:popen.request\"",
"for",
"line",
"in",
"iter",
"(",
"self",
".",
"popen",
".",
"stdout",
".",
"readline",
",",
"b\"\"",
... | Listen to both stdout and stderr
We'll want messages of a particular origin and format to
cause QML to perform some action. Other messages are simply
forwarded, as they are expected to be plain print or error messages. | [
"Listen",
"to",
"both",
"stdout",
"and",
"stderr"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/server.py#L224-L299 | train | 205,111 |
pyblish/pyblish-qml | pyblish_qml/ipc/server.py | Server._start_pulse | def _start_pulse(self):
"""Send pulse to child process
Child process will run forever if parent process encounter such
failure that not able to kill child process.
This inform child process that server is still running and child
process will auto kill itself after server stop sending pulse
message.
"""
def _pulse():
start_time = time.time()
while True:
data = json.dumps({"header": "pyblish-qml:server.pulse"})
if six.PY3:
data = data.encode("ascii")
try:
self.popen.stdin.write(data + b"\n")
self.popen.stdin.flush()
except IOError:
break
# Send pulse every 5 seconds
time.sleep(5.0 - ((time.time() - start_time) % 5.0))
thread = threading.Thread(target=_pulse)
thread.daemon = True
thread.start() | python | def _start_pulse(self):
"""Send pulse to child process
Child process will run forever if parent process encounter such
failure that not able to kill child process.
This inform child process that server is still running and child
process will auto kill itself after server stop sending pulse
message.
"""
def _pulse():
start_time = time.time()
while True:
data = json.dumps({"header": "pyblish-qml:server.pulse"})
if six.PY3:
data = data.encode("ascii")
try:
self.popen.stdin.write(data + b"\n")
self.popen.stdin.flush()
except IOError:
break
# Send pulse every 5 seconds
time.sleep(5.0 - ((time.time() - start_time) % 5.0))
thread = threading.Thread(target=_pulse)
thread.daemon = True
thread.start() | [
"def",
"_start_pulse",
"(",
"self",
")",
":",
"def",
"_pulse",
"(",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"header\"",
":",
"\"pyblish-qml:server.pulse\"",
"}",
"... | Send pulse to child process
Child process will run forever if parent process encounter such
failure that not able to kill child process.
This inform child process that server is still running and child
process will auto kill itself after server stop sending pulse
message. | [
"Send",
"pulse",
"to",
"child",
"process"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/server.py#L301-L333 | train | 205,112 |
pyblish/pyblish-qml | pyblish_qml/app.py | main | def main(demo=False, aschild=False, targets=[]):
"""Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process
"""
if aschild:
print("Starting pyblish-qml")
compat.main()
app = Application(APP_PATH, targets)
app.listen()
print("Done, don't forget to call `show()`")
return app.exec_()
else:
print("Starting pyblish-qml server..")
service = ipc.service.MockService() if demo else ipc.service.Service()
server = ipc.server.Server(service, targets=targets)
proxy = ipc.server.Proxy(server)
proxy.show(settings.to_dict())
server.listen()
server.wait() | python | def main(demo=False, aschild=False, targets=[]):
"""Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process
"""
if aschild:
print("Starting pyblish-qml")
compat.main()
app = Application(APP_PATH, targets)
app.listen()
print("Done, don't forget to call `show()`")
return app.exec_()
else:
print("Starting pyblish-qml server..")
service = ipc.service.MockService() if demo else ipc.service.Service()
server = ipc.server.Server(service, targets=targets)
proxy = ipc.server.Proxy(server)
proxy.show(settings.to_dict())
server.listen()
server.wait() | [
"def",
"main",
"(",
"demo",
"=",
"False",
",",
"aschild",
"=",
"False",
",",
"targets",
"=",
"[",
"]",
")",
":",
"if",
"aschild",
":",
"print",
"(",
"\"Starting pyblish-qml\"",
")",
"compat",
".",
"main",
"(",
")",
"app",
"=",
"Application",
"(",
"AP... | Start the Qt-runtime and show the window
Arguments:
aschild (bool, optional): Run as child of parent process | [
"Start",
"the",
"Qt",
"-",
"runtime",
"and",
"show",
"the",
"window"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/app.py#L273-L299 | train | 205,113 |
pyblish/pyblish-qml | pyblish_qml/app.py | Window.event | def event(self, event):
"""Allow GUI to be closed upon holding Shift"""
if event.type() == QtCore.QEvent.Close:
modifiers = self.app.queryKeyboardModifiers()
shift_pressed = QtCore.Qt.ShiftModifier & modifiers
states = self.app.controller.states
if shift_pressed:
print("Force quitted..")
self.app.controller.host.emit("pyblishQmlCloseForced")
event.accept()
elif any(state in states for state in ("ready", "finished")):
self.app.controller.host.emit("pyblishQmlClose")
event.accept()
else:
print("Not ready, hold SHIFT to force an exit")
event.ignore()
return super(Window, self).event(event) | python | def event(self, event):
"""Allow GUI to be closed upon holding Shift"""
if event.type() == QtCore.QEvent.Close:
modifiers = self.app.queryKeyboardModifiers()
shift_pressed = QtCore.Qt.ShiftModifier & modifiers
states = self.app.controller.states
if shift_pressed:
print("Force quitted..")
self.app.controller.host.emit("pyblishQmlCloseForced")
event.accept()
elif any(state in states for state in ("ready", "finished")):
self.app.controller.host.emit("pyblishQmlClose")
event.accept()
else:
print("Not ready, hold SHIFT to force an exit")
event.ignore()
return super(Window, self).event(event) | [
"def",
"event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"type",
"(",
")",
"==",
"QtCore",
".",
"QEvent",
".",
"Close",
":",
"modifiers",
"=",
"self",
".",
"app",
".",
"queryKeyboardModifiers",
"(",
")",
"shift_pressed",
"=",
"QtCore",
... | Allow GUI to be closed upon holding Shift | [
"Allow",
"GUI",
"to",
"be",
"closed",
"upon",
"holding",
"Shift"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/app.py#L36-L56 | train | 205,114 |
pyblish/pyblish-qml | pyblish_qml/app.py | Application.inFocus | def inFocus(self):
"""Set GUI on-top flag"""
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) | python | def inFocus(self):
"""Set GUI on-top flag"""
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) | [
"def",
"inFocus",
"(",
"self",
")",
":",
"previous_flags",
"=",
"self",
".",
"window",
".",
"flags",
"(",
")",
"self",
".",
"window",
".",
"setFlags",
"(",
"previous_flags",
"|",
"QtCore",
".",
"Qt",
".",
"WindowStaysOnTopHint",
")"
] | Set GUI on-top flag | [
"Set",
"GUI",
"on",
"-",
"top",
"flag"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/app.py#L206-L210 | train | 205,115 |
pyblish/pyblish-qml | pyblish_qml/app.py | Application.listen | def listen(self):
"""Listen on incoming messages from host
TODO(marcus): We can't use this, as we are already listening on stdin
through client.py. Do use this, we will have to find a way to
receive multiple signals from the same stdin, and channel them
to their corresponding source.
"""
def _listen():
while True:
line = self.host.channels["parent"].get()
payload = json.loads(line)["payload"]
# We can't call methods directly, as we are running
# in a thread. Instead, we emit signals that do the
# job for us.
signal = {
"show": "shown",
"hide": "hidden",
"quit": "quitted",
"publish": "published",
"validate": "validated",
"rise": "risen",
"inFocus": "inFocused",
"outFocus": "outFocused",
}.get(payload["name"])
if not signal:
print("'{name}' was unavailable.".format(
**payload))
else:
try:
getattr(self, signal).emit(
*payload.get("args", []))
except Exception:
traceback.print_exc()
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start() | python | def listen(self):
"""Listen on incoming messages from host
TODO(marcus): We can't use this, as we are already listening on stdin
through client.py. Do use this, we will have to find a way to
receive multiple signals from the same stdin, and channel them
to their corresponding source.
"""
def _listen():
while True:
line = self.host.channels["parent"].get()
payload = json.loads(line)["payload"]
# We can't call methods directly, as we are running
# in a thread. Instead, we emit signals that do the
# job for us.
signal = {
"show": "shown",
"hide": "hidden",
"quit": "quitted",
"publish": "published",
"validate": "validated",
"rise": "risen",
"inFocus": "inFocused",
"outFocus": "outFocused",
}.get(payload["name"])
if not signal:
print("'{name}' was unavailable.".format(
**payload))
else:
try:
getattr(self, signal).emit(
*payload.get("args", []))
except Exception:
traceback.print_exc()
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start() | [
"def",
"listen",
"(",
"self",
")",
":",
"def",
"_listen",
"(",
")",
":",
"while",
"True",
":",
"line",
"=",
"self",
".",
"host",
".",
"channels",
"[",
"\"parent\"",
"]",
".",
"get",
"(",
")",
"payload",
"=",
"json",
".",
"loads",
"(",
"line",
")"... | Listen on incoming messages from host
TODO(marcus): We can't use this, as we are already listening on stdin
through client.py. Do use this, we will have to find a way to
receive multiple signals from the same stdin, and channel them
to their corresponding source. | [
"Listen",
"on",
"incoming",
"messages",
"from",
"host"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/app.py#L226-L270 | train | 205,116 |
pyblish/pyblish-qml | pyblish_qml/util.py | defer | def defer(target, args=None, kwargs=None, callback=None):
"""Perform operation in thread with callback
Instances are cached until finished, at which point
they are garbage collected. If we didn't do this,
Python would step in and garbage collect the thread
before having had time to finish, resulting in an
exception.
Arguments:
target (callable): Method or function to call
callback (callable, optional): Method or function to call
once `target` has finished.
Returns:
None
"""
obj = _defer(target, args, kwargs, callback)
obj.finished.connect(lambda: _defer_cleanup(obj))
obj.start()
_defer_threads.append(obj)
return obj | python | def defer(target, args=None, kwargs=None, callback=None):
"""Perform operation in thread with callback
Instances are cached until finished, at which point
they are garbage collected. If we didn't do this,
Python would step in and garbage collect the thread
before having had time to finish, resulting in an
exception.
Arguments:
target (callable): Method or function to call
callback (callable, optional): Method or function to call
once `target` has finished.
Returns:
None
"""
obj = _defer(target, args, kwargs, callback)
obj.finished.connect(lambda: _defer_cleanup(obj))
obj.start()
_defer_threads.append(obj)
return obj | [
"def",
"defer",
"(",
"target",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"obj",
"=",
"_defer",
"(",
"target",
",",
"args",
",",
"kwargs",
",",
"callback",
")",
"obj",
".",
"finished",
".",
"connec... | Perform operation in thread with callback
Instances are cached until finished, at which point
they are garbage collected. If we didn't do this,
Python would step in and garbage collect the thread
before having had time to finish, resulting in an
exception.
Arguments:
target (callable): Method or function to call
callback (callable, optional): Method or function to call
once `target` has finished.
Returns:
None | [
"Perform",
"operation",
"in",
"thread",
"with",
"callback"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/util.py#L121-L144 | train | 205,117 |
pyblish/pyblish-qml | pyblish_qml/util.py | schedule | def schedule(func, time, channel="default"):
"""Run `func` at a later `time` in a dedicated `channel`
Given an arbitrary function, call this function after a given
timeout. It will ensure that only one "job" is running within
the given channel at any one time and cancel any currently
running job if a new job is submitted before the timeout.
"""
try:
_jobs[channel].stop()
except (AttributeError, KeyError):
pass
timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(func)
timer.start(time)
_jobs[channel] = timer | python | def schedule(func, time, channel="default"):
"""Run `func` at a later `time` in a dedicated `channel`
Given an arbitrary function, call this function after a given
timeout. It will ensure that only one "job" is running within
the given channel at any one time and cancel any currently
running job if a new job is submitted before the timeout.
"""
try:
_jobs[channel].stop()
except (AttributeError, KeyError):
pass
timer = QtCore.QTimer()
timer.setSingleShot(True)
timer.timeout.connect(func)
timer.start(time)
_jobs[channel] = timer | [
"def",
"schedule",
"(",
"func",
",",
"time",
",",
"channel",
"=",
"\"default\"",
")",
":",
"try",
":",
"_jobs",
"[",
"channel",
"]",
".",
"stop",
"(",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"pass",
"timer",
"=",
"QtCore",
".... | Run `func` at a later `time` in a dedicated `channel`
Given an arbitrary function, call this function after a given
timeout. It will ensure that only one "job" is running within
the given channel at any one time and cancel any currently
running job if a new job is submitted before the timeout. | [
"Run",
"func",
"at",
"a",
"later",
"time",
"in",
"a",
"dedicated",
"channel"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/util.py#L176-L196 | train | 205,118 |
pyblish/pyblish-qml | pyblish_qml/util.py | format_text | def format_text(text):
"""Remove newlines, but preserve paragraphs"""
result = ""
for paragraph in text.split("\n\n"):
result += " ".join(paragraph.split()) + "\n\n"
result = result.rstrip("\n") # Remove last newlines
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
if re.search(pattern, result):
html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
result = re.sub(pattern, html, result)
return result | python | def format_text(text):
"""Remove newlines, but preserve paragraphs"""
result = ""
for paragraph in text.split("\n\n"):
result += " ".join(paragraph.split()) + "\n\n"
result = result.rstrip("\n") # Remove last newlines
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
if re.search(pattern, result):
html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
result = re.sub(pattern, html, result)
return result | [
"def",
"format_text",
"(",
"text",
")",
":",
"result",
"=",
"\"\"",
"for",
"paragraph",
"in",
"text",
".",
"split",
"(",
"\"\\n\\n\"",
")",
":",
"result",
"+=",
"\" \"",
".",
"join",
"(",
"paragraph",
".",
"split",
"(",
")",
")",
"+",
"\"\\n\\n\"",
"... | Remove newlines, but preserve paragraphs | [
"Remove",
"newlines",
"but",
"preserve",
"paragraphs"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/util.py#L217-L232 | train | 205,119 |
pyblish/pyblish-qml | pyblish_qml/util.py | SlotSentinel | def SlotSentinel(*args):
"""Provides exception handling for all slots"""
# (NOTE) davidlatwe
# Thanks to this answer
# https://stackoverflow.com/questions/18740884
if len(args) == 0 or isinstance(args[0], types.FunctionType):
args = []
@QtCore.pyqtSlot(*args)
def slotdecorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args)
except Exception:
traceback.print_exc()
return wrapper
return slotdecorator | python | def SlotSentinel(*args):
"""Provides exception handling for all slots"""
# (NOTE) davidlatwe
# Thanks to this answer
# https://stackoverflow.com/questions/18740884
if len(args) == 0 or isinstance(args[0], types.FunctionType):
args = []
@QtCore.pyqtSlot(*args)
def slotdecorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args)
except Exception:
traceback.print_exc()
return wrapper
return slotdecorator | [
"def",
"SlotSentinel",
"(",
"*",
"args",
")",
":",
"# (NOTE) davidlatwe",
"# Thanks to this answer",
"# https://stackoverflow.com/questions/18740884",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"or",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"types",
".",
"F... | Provides exception handling for all slots | [
"Provides",
"exception",
"handling",
"for",
"all",
"slots"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/util.py#L241-L261 | train | 205,120 |
pyblish/pyblish-qml | pyblish_qml/ipc/client.py | _byteify | def _byteify(data):
"""Convert unicode to bytes"""
# Unicode
if isinstance(data, six.text_type):
return data.encode("utf-8")
# Members of lists
if isinstance(data, list):
return [_byteify(item) for item in data]
# Members of dicts
if isinstance(data, dict):
return {
_byteify(key): _byteify(value) for key, value in data.items()
}
# Anything else, return the original form
return data | python | def _byteify(data):
"""Convert unicode to bytes"""
# Unicode
if isinstance(data, six.text_type):
return data.encode("utf-8")
# Members of lists
if isinstance(data, list):
return [_byteify(item) for item in data]
# Members of dicts
if isinstance(data, dict):
return {
_byteify(key): _byteify(value) for key, value in data.items()
}
# Anything else, return the original form
return data | [
"def",
"_byteify",
"(",
"data",
")",
":",
"# Unicode",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"return",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
"# Members of lists",
"if",
"isinstance",
"(",
"data",
",",
"list",
")... | Convert unicode to bytes | [
"Convert",
"unicode",
"to",
"bytes"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/client.py#L190-L208 | train | 205,121 |
pyblish/pyblish-qml | pyblish_qml/ipc/client.py | Proxy.process | def process(self, plugin, context, instance=None, action=None):
"""Transmit a `process` request to host
Arguments:
plugin (PluginProxy): Plug-in to process
context (ContextProxy): Filtered context
instance (InstanceProxy, optional): Instance to process
action (str, optional): Action to process
"""
plugin = plugin.to_json()
instance = instance.to_json() if instance is not None else None
return self._dispatch("process", args=[plugin, instance, action]) | python | def process(self, plugin, context, instance=None, action=None):
"""Transmit a `process` request to host
Arguments:
plugin (PluginProxy): Plug-in to process
context (ContextProxy): Filtered context
instance (InstanceProxy, optional): Instance to process
action (str, optional): Action to process
"""
plugin = plugin.to_json()
instance = instance.to_json() if instance is not None else None
return self._dispatch("process", args=[plugin, instance, action]) | [
"def",
"process",
"(",
"self",
",",
"plugin",
",",
"context",
",",
"instance",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"plugin",
"=",
"plugin",
".",
"to_json",
"(",
")",
"instance",
"=",
"instance",
".",
"to_json",
"(",
")",
"if",
"instanc... | Transmit a `process` request to host
Arguments:
plugin (PluginProxy): Plug-in to process
context (ContextProxy): Filtered context
instance (InstanceProxy, optional): Instance to process
action (str, optional): Action to process | [
"Transmit",
"a",
"process",
"request",
"to",
"host"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/client.py#L57-L70 | train | 205,122 |
pyblish/pyblish-qml | pyblish_qml/ipc/client.py | Proxy._self_destruct | def _self_destruct(self):
"""Auto quit exec if parent process failed
"""
# This will give parent process 15 seconds to reset.
self._kill = threading.Timer(15, lambda: os._exit(0))
self._kill.start() | python | def _self_destruct(self):
"""Auto quit exec if parent process failed
"""
# This will give parent process 15 seconds to reset.
self._kill = threading.Timer(15, lambda: os._exit(0))
self._kill.start() | [
"def",
"_self_destruct",
"(",
"self",
")",
":",
"# This will give parent process 15 seconds to reset.",
"self",
".",
"_kill",
"=",
"threading",
".",
"Timer",
"(",
"15",
",",
"lambda",
":",
"os",
".",
"_exit",
"(",
"0",
")",
")",
"self",
".",
"_kill",
".",
... | Auto quit exec if parent process failed | [
"Auto",
"quit",
"exec",
"if",
"parent",
"process",
"failed"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/client.py#L94-L99 | train | 205,123 |
pyblish/pyblish-qml | pyblish_qml/ipc/client.py | Proxy._listen | def _listen(self):
"""Listen for messages passed from parent
This method distributes messages received via stdin to their
corresponding channel. Based on the format of the incoming
message, the message is forwarded to its corresponding channel
to be processed by its corresponding handler.
"""
def _listen():
"""This runs in a thread"""
for line in iter(sys.stdin.readline, b""):
try:
response = json.loads(line)
except Exception as e:
# The parent has passed on a message that
# isn't formatted in any particular way.
# This is likely a bug.
raise e
else:
if response.get("header") == "pyblish-qml:popen.response":
self.channels["response"].put(line)
elif response.get("header") == "pyblish-qml:popen.parent":
self.channels["parent"].put(line)
elif response.get("header") == "pyblish-qml:server.pulse":
self._kill.cancel() # reset timer
self._self_destruct()
else:
# The parent has passed on a message that
# is JSON, but not in any format we recognise.
# This is likely a bug.
raise Exception("Unhandled message "
"passed to Popen, '%s'" % line)
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start() | python | def _listen(self):
"""Listen for messages passed from parent
This method distributes messages received via stdin to their
corresponding channel. Based on the format of the incoming
message, the message is forwarded to its corresponding channel
to be processed by its corresponding handler.
"""
def _listen():
"""This runs in a thread"""
for line in iter(sys.stdin.readline, b""):
try:
response = json.loads(line)
except Exception as e:
# The parent has passed on a message that
# isn't formatted in any particular way.
# This is likely a bug.
raise e
else:
if response.get("header") == "pyblish-qml:popen.response":
self.channels["response"].put(line)
elif response.get("header") == "pyblish-qml:popen.parent":
self.channels["parent"].put(line)
elif response.get("header") == "pyblish-qml:server.pulse":
self._kill.cancel() # reset timer
self._self_destruct()
else:
# The parent has passed on a message that
# is JSON, but not in any format we recognise.
# This is likely a bug.
raise Exception("Unhandled message "
"passed to Popen, '%s'" % line)
thread = threading.Thread(target=_listen)
thread.daemon = True
thread.start() | [
"def",
"_listen",
"(",
"self",
")",
":",
"def",
"_listen",
"(",
")",
":",
"\"\"\"This runs in a thread\"\"\"",
"for",
"line",
"in",
"iter",
"(",
"sys",
".",
"stdin",
".",
"readline",
",",
"b\"\"",
")",
":",
"try",
":",
"response",
"=",
"json",
".",
"lo... | Listen for messages passed from parent
This method distributes messages received via stdin to their
corresponding channel. Based on the format of the incoming
message, the message is forwarded to its corresponding channel
to be processed by its corresponding handler. | [
"Listen",
"for",
"messages",
"passed",
"from",
"parent"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/client.py#L101-L143 | train | 205,124 |
pyblish/pyblish-qml | pyblish_qml/ipc/client.py | Proxy._dispatch | def _dispatch(self, func, args=None):
"""Send message to parent process
Arguments:
func (str): Name of function for parent to call
args (list, optional): Arguments passed to function when called
"""
data = json.dumps(
{
"header": "pyblish-qml:popen.request",
"payload": {
"name": func,
"args": args or list(),
}
}
)
# This should never happen. Each request is immediately
# responded to, always. If it isn't the next line will block.
# If multiple responses were made, then this will fail.
# Both scenarios are bugs.
assert self.channels["response"].empty(), (
"There were pending messages in the response channel")
sys.stdout.write(data + "\n")
sys.stdout.flush()
try:
message = self.channels["response"].get()
if six.PY3:
response = json.loads(message)
else:
response = _byteify(json.loads(message, object_hook=_byteify))
except TypeError as e:
raise e
else:
assert response["header"] == "pyblish-qml:popen.response", response
return response["payload"] | python | def _dispatch(self, func, args=None):
"""Send message to parent process
Arguments:
func (str): Name of function for parent to call
args (list, optional): Arguments passed to function when called
"""
data = json.dumps(
{
"header": "pyblish-qml:popen.request",
"payload": {
"name": func,
"args": args or list(),
}
}
)
# This should never happen. Each request is immediately
# responded to, always. If it isn't the next line will block.
# If multiple responses were made, then this will fail.
# Both scenarios are bugs.
assert self.channels["response"].empty(), (
"There were pending messages in the response channel")
sys.stdout.write(data + "\n")
sys.stdout.flush()
try:
message = self.channels["response"].get()
if six.PY3:
response = json.loads(message)
else:
response = _byteify(json.loads(message, object_hook=_byteify))
except TypeError as e:
raise e
else:
assert response["header"] == "pyblish-qml:popen.response", response
return response["payload"] | [
"def",
"_dispatch",
"(",
"self",
",",
"func",
",",
"args",
"=",
"None",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"header\"",
":",
"\"pyblish-qml:popen.request\"",
",",
"\"payload\"",
":",
"{",
"\"name\"",
":",
"func",
",",
"\"args\"",
":"... | Send message to parent process
Arguments:
func (str): Name of function for parent to call
args (list, optional): Arguments passed to function when called | [
"Send",
"message",
"to",
"parent",
"process"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/client.py#L145-L187 | train | 205,125 |
pyblish/pyblish-qml | pyblish_qml/ipc/client.py | PluginProxy.from_json | def from_json(cls, plugin):
"""Build PluginProxy object from incoming dictionary
Emulate a plug-in by providing access to attributes
in the same way they are accessed using the remote object.
This allows for it to be used by members of :mod:`pyblish.logic`.
"""
process = None
repair = None
name = plugin["name"] + "Proxy"
cls = type(name, (cls,), plugin)
# Emulate function
for name in ("process", "repair"):
args = ", ".join(plugin["process"]["args"])
func = "def {name}({args}): pass".format(name=name,
args=args)
exec(func)
cls.process = process
cls.repair = repair
cls.__orig__ = plugin
return cls | python | def from_json(cls, plugin):
"""Build PluginProxy object from incoming dictionary
Emulate a plug-in by providing access to attributes
in the same way they are accessed using the remote object.
This allows for it to be used by members of :mod:`pyblish.logic`.
"""
process = None
repair = None
name = plugin["name"] + "Proxy"
cls = type(name, (cls,), plugin)
# Emulate function
for name in ("process", "repair"):
args = ", ".join(plugin["process"]["args"])
func = "def {name}({args}): pass".format(name=name,
args=args)
exec(func)
cls.process = process
cls.repair = repair
cls.__orig__ = plugin
return cls | [
"def",
"from_json",
"(",
"cls",
",",
"plugin",
")",
":",
"process",
"=",
"None",
"repair",
"=",
"None",
"name",
"=",
"plugin",
"[",
"\"name\"",
"]",
"+",
"\"Proxy\"",
"cls",
"=",
"type",
"(",
"name",
",",
"(",
"cls",
",",
")",
",",
"plugin",
")",
... | Build PluginProxy object from incoming dictionary
Emulate a plug-in by providing access to attributes
in the same way they are accessed using the remote object.
This allows for it to be used by members of :mod:`pyblish.logic`. | [
"Build",
"PluginProxy",
"object",
"from",
"incoming",
"dictionary"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/client.py#L281-L308 | train | 205,126 |
pyblish/pyblish-qml | pyblish_qml/models.py | Item | def Item(**kwargs):
"""Factory function for QAbstractListModel items
Any class attributes are converted into pyqtProperties
and must be declared with its type as value.
Special keyword "parent" is not passed as object properties
but instead passed to the QObject constructor.
Usage:
>>> item = Item(name="default name",
... age=5,
... alive=True)
>>> assert item.name == "default name"
>>> assert item.age == 5
>>> assert item.alive == True
>>>
>>> # Jsonifyable content
>>> assert item.json == {
... "name": "default name",
... "age": 5,
... "alive": True
... }, item.json
"""
parent = kwargs.pop("parent", None)
cls = type("Item", (AbstractItem,), kwargs.copy())
self = cls(parent)
self.json = kwargs # Store as json
for key, value in kwargs.items():
if hasattr(self, key):
key = PropertyType.prefix + key
setattr(self, key, value)
return self | python | def Item(**kwargs):
"""Factory function for QAbstractListModel items
Any class attributes are converted into pyqtProperties
and must be declared with its type as value.
Special keyword "parent" is not passed as object properties
but instead passed to the QObject constructor.
Usage:
>>> item = Item(name="default name",
... age=5,
... alive=True)
>>> assert item.name == "default name"
>>> assert item.age == 5
>>> assert item.alive == True
>>>
>>> # Jsonifyable content
>>> assert item.json == {
... "name": "default name",
... "age": 5,
... "alive": True
... }, item.json
"""
parent = kwargs.pop("parent", None)
cls = type("Item", (AbstractItem,), kwargs.copy())
self = cls(parent)
self.json = kwargs # Store as json
for key, value in kwargs.items():
if hasattr(self, key):
key = PropertyType.prefix + key
setattr(self, key, value)
return self | [
"def",
"Item",
"(",
"*",
"*",
"kwargs",
")",
":",
"parent",
"=",
"kwargs",
".",
"pop",
"(",
"\"parent\"",
",",
"None",
")",
"cls",
"=",
"type",
"(",
"\"Item\"",
",",
"(",
"AbstractItem",
",",
")",
",",
"kwargs",
".",
"copy",
"(",
")",
")",
"self"... | Factory function for QAbstractListModel items
Any class attributes are converted into pyqtProperties
and must be declared with its type as value.
Special keyword "parent" is not passed as object properties
but instead passed to the QObject constructor.
Usage:
>>> item = Item(name="default name",
... age=5,
... alive=True)
>>> assert item.name == "default name"
>>> assert item.age == 5
>>> assert item.alive == True
>>>
>>> # Jsonifyable content
>>> assert item.json == {
... "name": "default name",
... "age": 5,
... "alive": True
... }, item.json | [
"Factory",
"function",
"for",
"QAbstractListModel",
"items"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L157-L194 | train | 205,127 |
pyblish/pyblish-qml | pyblish_qml/models.py | AbstractModel.add_item | def add_item(self, item):
"""Add new item to model
Each keyword argument is passed to the :func:Item
factory function.
"""
self.beginInsertRows(QtCore.QModelIndex(),
self.rowCount(),
self.rowCount())
item["parent"] = self
item = Item(**item)
self.items.append(item)
self.endInsertRows()
item.__datachanged__.connect(self._dataChanged)
return item | python | def add_item(self, item):
"""Add new item to model
Each keyword argument is passed to the :func:Item
factory function.
"""
self.beginInsertRows(QtCore.QModelIndex(),
self.rowCount(),
self.rowCount())
item["parent"] = self
item = Item(**item)
self.items.append(item)
self.endInsertRows()
item.__datachanged__.connect(self._dataChanged)
return item | [
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"beginInsertRows",
"(",
"QtCore",
".",
"QModelIndex",
"(",
")",
",",
"self",
".",
"rowCount",
"(",
")",
",",
"self",
".",
"rowCount",
"(",
")",
")",
"item",
"[",
"\"parent\"",
"]",
... | Add new item to model
Each keyword argument is passed to the :func:Item
factory function. | [
"Add",
"new",
"item",
"to",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L206-L225 | train | 205,128 |
pyblish/pyblish-qml | pyblish_qml/models.py | AbstractModel.remove_item | def remove_item(self, item):
"""Remove item from model"""
index = self.items.index(item)
self.beginRemoveRows(QtCore.QModelIndex(), index, index)
self.items.remove(item)
self.endRemoveRows() | python | def remove_item(self, item):
"""Remove item from model"""
index = self.items.index(item)
self.beginRemoveRows(QtCore.QModelIndex(), index, index)
self.items.remove(item)
self.endRemoveRows() | [
"def",
"remove_item",
"(",
"self",
",",
"item",
")",
":",
"index",
"=",
"self",
".",
"items",
".",
"index",
"(",
"item",
")",
"self",
".",
"beginRemoveRows",
"(",
"QtCore",
".",
"QModelIndex",
"(",
")",
",",
"index",
",",
"index",
")",
"self",
".",
... | Remove item from model | [
"Remove",
"item",
"from",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L227-L232 | train | 205,129 |
pyblish/pyblish-qml | pyblish_qml/models.py | AbstractModel._dataChanged | def _dataChanged(self, item):
"""Explicitly emit dataChanged upon item changing"""
index = self.items.index(item)
qindex = self.createIndex(index, 0)
self.dataChanged.emit(qindex, qindex) | python | def _dataChanged(self, item):
"""Explicitly emit dataChanged upon item changing"""
index = self.items.index(item)
qindex = self.createIndex(index, 0)
self.dataChanged.emit(qindex, qindex) | [
"def",
"_dataChanged",
"(",
"self",
",",
"item",
")",
":",
"index",
"=",
"self",
".",
"items",
".",
"index",
"(",
"item",
")",
"qindex",
"=",
"self",
".",
"createIndex",
"(",
"index",
",",
"0",
")",
"self",
".",
"dataChanged",
".",
"emit",
"(",
"qi... | Explicitly emit dataChanged upon item changing | [
"Explicitly",
"emit",
"dataChanged",
"upon",
"item",
"changing"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L234-L238 | train | 205,130 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.add_plugin | def add_plugin(self, plugin):
"""Append `plugin` to model
Arguments:
plugin (dict): Serialised plug-in from pyblish-rpc
Schema:
plugin.json
"""
item = {}
item.update(defaults["common"])
item.update(defaults["plugin"])
for member in ["pre11",
"name",
"label",
"optional",
"category",
"actions",
"id",
"order",
"doc",
"type",
"module",
"match",
"hasRepair",
"families",
"contextEnabled",
"instanceEnabled",
"__instanceEnabled__",
"path"]:
item[member] = plugin[member]
# Visualised in Perspective
item["familiesConcatenated"] = ", ".join(plugin["families"])
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
if item["doc"] and re.search(pattern, item["doc"]):
html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
item["doc"] = re.sub(pattern, html, item["doc"])
# Append GUI-only data
item["itemType"] = "plugin"
item["hasCompatible"] = True
item["isToggled"] = plugin.get("active", True)
item["verb"] = {
"Selector": "Collect",
"Collector": "Collect",
"Validator": "Validate",
"Extractor": "Extract",
"Integrator": "Integrate",
"Conformer": "Integrate",
}.get(item["type"], "Other")
for action in item["actions"]:
if action["on"] == "all":
item["actionsIconVisible"] = True
self.add_section(item["verb"])
item = self.add_item(item)
self.plugins.append(item) | python | def add_plugin(self, plugin):
"""Append `plugin` to model
Arguments:
plugin (dict): Serialised plug-in from pyblish-rpc
Schema:
plugin.json
"""
item = {}
item.update(defaults["common"])
item.update(defaults["plugin"])
for member in ["pre11",
"name",
"label",
"optional",
"category",
"actions",
"id",
"order",
"doc",
"type",
"module",
"match",
"hasRepair",
"families",
"contextEnabled",
"instanceEnabled",
"__instanceEnabled__",
"path"]:
item[member] = plugin[member]
# Visualised in Perspective
item["familiesConcatenated"] = ", ".join(plugin["families"])
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s]*?(?:\.[a-z]+)+)"
pattern += r"(?![^<]*?(?:<\/\w+>|\/?>))"
if item["doc"] and re.search(pattern, item["doc"]):
html = r"<a href='\1'><font color='FF00CC'>\1</font></a>"
item["doc"] = re.sub(pattern, html, item["doc"])
# Append GUI-only data
item["itemType"] = "plugin"
item["hasCompatible"] = True
item["isToggled"] = plugin.get("active", True)
item["verb"] = {
"Selector": "Collect",
"Collector": "Collect",
"Validator": "Validate",
"Extractor": "Extract",
"Integrator": "Integrate",
"Conformer": "Integrate",
}.get(item["type"], "Other")
for action in item["actions"]:
if action["on"] == "all":
item["actionsIconVisible"] = True
self.add_section(item["verb"])
item = self.add_item(item)
self.plugins.append(item) | [
"def",
"add_plugin",
"(",
"self",
",",
"plugin",
")",
":",
"item",
"=",
"{",
"}",
"item",
".",
"update",
"(",
"defaults",
"[",
"\"common\"",
"]",
")",
"item",
".",
"update",
"(",
"defaults",
"[",
"\"plugin\"",
"]",
")",
"for",
"member",
"in",
"[",
... | Append `plugin` to model
Arguments:
plugin (dict): Serialised plug-in from pyblish-rpc
Schema:
plugin.json | [
"Append",
"plugin",
"to",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L313-L378 | train | 205,131 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.add_instance | def add_instance(self, instance):
"""Append `instance` to model
Arguments:
instance (dict): Serialised instance
Schema:
instance.json
"""
assert isinstance(instance, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(instance["data"])
item.update(instance)
item["itemType"] = "instance"
item["isToggled"] = instance["data"].get("publish", True)
item["hasCompatible"] = True
item["category"] = item["category"] or item["family"]
self.add_section(item["category"])
# Visualised in Perspective
families = [instance["data"]["family"]]
families.extend(instance["data"].get("families", []))
item["familiesConcatenated"] += ", ".join(families)
item = self.add_item(item)
self.instances.append(item) | python | def add_instance(self, instance):
"""Append `instance` to model
Arguments:
instance (dict): Serialised instance
Schema:
instance.json
"""
assert isinstance(instance, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(instance["data"])
item.update(instance)
item["itemType"] = "instance"
item["isToggled"] = instance["data"].get("publish", True)
item["hasCompatible"] = True
item["category"] = item["category"] or item["family"]
self.add_section(item["category"])
# Visualised in Perspective
families = [instance["data"]["family"]]
families.extend(instance["data"].get("families", []))
item["familiesConcatenated"] += ", ".join(families)
item = self.add_item(item)
self.instances.append(item) | [
"def",
"add_instance",
"(",
"self",
",",
"instance",
")",
":",
"assert",
"isinstance",
"(",
"instance",
",",
"dict",
")",
"item",
"=",
"defaults",
"[",
"\"common\"",
"]",
".",
"copy",
"(",
")",
"item",
".",
"update",
"(",
"defaults",
"[",
"\"instance\"",... | Append `instance` to model
Arguments:
instance (dict): Serialised instance
Schema:
instance.json | [
"Append",
"instance",
"to",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L381-L413 | train | 205,132 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.remove_instance | def remove_instance(self, item):
"""Remove `instance` from model"""
self.instances.remove(item)
self.remove_item(item) | python | def remove_instance(self, item):
"""Remove `instance` from model"""
self.instances.remove(item)
self.remove_item(item) | [
"def",
"remove_instance",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"instances",
".",
"remove",
"(",
"item",
")",
"self",
".",
"remove_item",
"(",
"item",
")"
] | Remove `instance` from model | [
"Remove",
"instance",
"from",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L415-L418 | train | 205,133 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.add_section | def add_section(self, name):
"""Append `section` to model
Arguments:
name (str): Name of section
"""
assert isinstance(name, str)
# Skip existing sections
for section in self.sections:
if section.name == name:
return section
item = defaults["common"].copy()
item["name"] = name
item["itemType"] = "section"
item = self.add_item(item)
self.sections.append(item)
return item | python | def add_section(self, name):
"""Append `section` to model
Arguments:
name (str): Name of section
"""
assert isinstance(name, str)
# Skip existing sections
for section in self.sections:
if section.name == name:
return section
item = defaults["common"].copy()
item["name"] = name
item["itemType"] = "section"
item = self.add_item(item)
self.sections.append(item)
return item | [
"def",
"add_section",
"(",
"self",
",",
"name",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"str",
")",
"# Skip existing sections",
"for",
"section",
"in",
"self",
".",
"sections",
":",
"if",
"section",
".",
"name",
"==",
"name",
":",
"return",
"... | Append `section` to model
Arguments:
name (str): Name of section | [
"Append",
"section",
"to",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L420-L442 | train | 205,134 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.add_context | def add_context(self, context, label=None):
"""Append `context` to model
Arguments:
context (dict): Serialised to add
Schema:
context.json
"""
assert isinstance(context, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(context)
item["family"] = None
item["label"] = context["data"].get("label") or settings.ContextLabel
item["itemType"] = "instance"
item["isToggled"] = True
item["optional"] = False
item["hasCompatible"] = True
item = self.add_item(item)
self.instances.append(item) | python | def add_context(self, context, label=None):
"""Append `context` to model
Arguments:
context (dict): Serialised to add
Schema:
context.json
"""
assert isinstance(context, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(context)
item["family"] = None
item["label"] = context["data"].get("label") or settings.ContextLabel
item["itemType"] = "instance"
item["isToggled"] = True
item["optional"] = False
item["hasCompatible"] = True
item = self.add_item(item)
self.instances.append(item) | [
"def",
"add_context",
"(",
"self",
",",
"context",
",",
"label",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"context",
",",
"dict",
")",
"item",
"=",
"defaults",
"[",
"\"common\"",
"]",
".",
"copy",
"(",
")",
"item",
".",
"update",
"(",
"def... | Append `context` to model
Arguments:
context (dict): Serialised to add
Schema:
context.json | [
"Append",
"context",
"to",
"model"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L445-L470 | train | 205,135 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.update_with_result | def update_with_result(self, result):
"""Update item-model with result from host
State is sent from host after processing had taken place
and represents the events that took place; including
log messages and completion status.
Arguments:
result (dict): Dictionary following the Result schema
"""
assert isinstance(result, dict), "%s is not a dictionary" % result
for type in ("instance", "plugin"):
id = (result[type] or {}).get("id")
is_context = not id
if is_context:
item = self.instances[0]
else:
item = self.items.get(id)
if item is None:
# If an item isn't there yet
# no worries. It's probably because
# reset is still running and the
# item in question is a new instance
# not yet added to the model.
continue
item.isProcessing = False
item.currentProgress = 1
item.processed = True
item.hasWarning = item.hasWarning or any([
record["levelno"] == logging.WARNING
for record in result["records"]
])
if result.get("error"):
item.hasError = True
item.amountFailed += 1
else:
item.succeeded = True
item.amountPassed += 1
item.duration += result["duration"]
item.finishedAt = time.time()
if item.itemType == "plugin" and not item.actionsIconVisible:
actions = list(item.actions)
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if actions:
item.actionsIconVisible = True
# Update section item
class DummySection(object):
hasWarning = False
hasError = False
succeeded = False
section_item = DummySection()
for section in self.sections:
if item.itemType == "plugin" and section.name == item.verb:
section_item = section
if (item.itemType == "instance" and
section.name == item.category):
section_item = section
section_item.hasWarning = (
section_item.hasWarning or item.hasWarning
)
section_item.hasError = section_item.hasError or item.hasError
section_item.succeeded = section_item.succeeded or item.succeeded
section_item.isProcessing = False | python | def update_with_result(self, result):
"""Update item-model with result from host
State is sent from host after processing had taken place
and represents the events that took place; including
log messages and completion status.
Arguments:
result (dict): Dictionary following the Result schema
"""
assert isinstance(result, dict), "%s is not a dictionary" % result
for type in ("instance", "plugin"):
id = (result[type] or {}).get("id")
is_context = not id
if is_context:
item = self.instances[0]
else:
item = self.items.get(id)
if item is None:
# If an item isn't there yet
# no worries. It's probably because
# reset is still running and the
# item in question is a new instance
# not yet added to the model.
continue
item.isProcessing = False
item.currentProgress = 1
item.processed = True
item.hasWarning = item.hasWarning or any([
record["levelno"] == logging.WARNING
for record in result["records"]
])
if result.get("error"):
item.hasError = True
item.amountFailed += 1
else:
item.succeeded = True
item.amountPassed += 1
item.duration += result["duration"]
item.finishedAt = time.time()
if item.itemType == "plugin" and not item.actionsIconVisible:
actions = list(item.actions)
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if actions:
item.actionsIconVisible = True
# Update section item
class DummySection(object):
hasWarning = False
hasError = False
succeeded = False
section_item = DummySection()
for section in self.sections:
if item.itemType == "plugin" and section.name == item.verb:
section_item = section
if (item.itemType == "instance" and
section.name == item.category):
section_item = section
section_item.hasWarning = (
section_item.hasWarning or item.hasWarning
)
section_item.hasError = section_item.hasError or item.hasError
section_item.succeeded = section_item.succeeded or item.succeeded
section_item.isProcessing = False | [
"def",
"update_with_result",
"(",
"self",
",",
"result",
")",
":",
"assert",
"isinstance",
"(",
"result",
",",
"dict",
")",
",",
"\"%s is not a dictionary\"",
"%",
"result",
"for",
"type",
"in",
"(",
"\"instance\"",
",",
"\"plugin\"",
")",
":",
"id",
"=",
... | Update item-model with result from host
State is sent from host after processing had taken place
and represents the events that took place; including
log messages and completion status.
Arguments:
result (dict): Dictionary following the Result schema | [
"Update",
"item",
"-",
"model",
"with",
"result",
"from",
"host"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L472-L557 | train | 205,136 |
pyblish/pyblish-qml | pyblish_qml/models.py | ItemModel.reset_status | def reset_status(self):
"""Reset progress bars"""
for item in self.items:
item.isProcessing = False
item.currentProgress = 0 | python | def reset_status(self):
"""Reset progress bars"""
for item in self.items:
item.isProcessing = False
item.currentProgress = 0 | [
"def",
"reset_status",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"items",
":",
"item",
".",
"isProcessing",
"=",
"False",
"item",
".",
"currentProgress",
"=",
"0"
] | Reset progress bars | [
"Reset",
"progress",
"bars"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L567-L571 | train | 205,137 |
pyblish/pyblish-qml | pyblish_qml/models.py | ProxyModel.add_exclusion | def add_exclusion(self, role, value):
"""Exclude item if `role` equals `value`
Attributes:
role (int, string): Qt role or name to compare `value` to
value (object): Value to exclude
"""
self._add_rule(self.excludes, role, value) | python | def add_exclusion(self, role, value):
"""Exclude item if `role` equals `value`
Attributes:
role (int, string): Qt role or name to compare `value` to
value (object): Value to exclude
"""
self._add_rule(self.excludes, role, value) | [
"def",
"add_exclusion",
"(",
"self",
",",
"role",
",",
"value",
")",
":",
"self",
".",
"_add_rule",
"(",
"self",
".",
"excludes",
",",
"role",
",",
"value",
")"
] | Exclude item if `role` equals `value`
Attributes:
role (int, string): Qt role or name to compare `value` to
value (object): Value to exclude | [
"Exclude",
"item",
"if",
"role",
"equals",
"value"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L757-L766 | train | 205,138 |
pyblish/pyblish-qml | pyblish_qml/models.py | ProxyModel.add_inclusion | def add_inclusion(self, role, value):
"""Include item if `role` equals `value`
Attributes:
role (int): Qt role to compare `value` to
value (object): Value to exclude
"""
self._add_rule(self.includes, role, value) | python | def add_inclusion(self, role, value):
"""Include item if `role` equals `value`
Attributes:
role (int): Qt role to compare `value` to
value (object): Value to exclude
"""
self._add_rule(self.includes, role, value) | [
"def",
"add_inclusion",
"(",
"self",
",",
"role",
",",
"value",
")",
":",
"self",
".",
"_add_rule",
"(",
"self",
".",
"includes",
",",
"role",
",",
"value",
")"
] | Include item if `role` equals `value`
Attributes:
role (int): Qt role to compare `value` to
value (object): Value to exclude | [
"Include",
"item",
"if",
"role",
"equals",
"value"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/models.py#L798-L807 | train | 205,139 |
pyblish/pyblish-qml | pyblish_qml/ipc/formatting.py | format_records | def format_records(records):
"""Serialise multiple records"""
formatted = list()
for record_ in records:
formatted.append(format_record(record_))
return formatted | python | def format_records(records):
"""Serialise multiple records"""
formatted = list()
for record_ in records:
formatted.append(format_record(record_))
return formatted | [
"def",
"format_records",
"(",
"records",
")",
":",
"formatted",
"=",
"list",
"(",
")",
"for",
"record_",
"in",
"records",
":",
"formatted",
".",
"append",
"(",
"format_record",
"(",
"record_",
")",
")",
"return",
"formatted"
] | Serialise multiple records | [
"Serialise",
"multiple",
"records"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/formatting.py#L53-L58 | train | 205,140 |
pyblish/pyblish-qml | pyblish_qml/ipc/formatting.py | format_record | def format_record(record):
"""Serialise LogRecord instance"""
record = dict(
(key, getattr(record, key, None))
for key in (
"threadName",
"name",
"thread",
"created",
"process",
"processName",
"args",
"module",
"filename",
"levelno",
"exc_text",
"pathname",
"lineno",
"msg",
"exc_info",
"funcName",
"relativeCreated",
"levelname",
"msecs")
)
# Humanise output and conform to Exceptions
record["message"] = str(record.pop("msg"))
if os.getenv("PYBLISH_SAFE"):
schema.validate(record, "record")
return record | python | def format_record(record):
"""Serialise LogRecord instance"""
record = dict(
(key, getattr(record, key, None))
for key in (
"threadName",
"name",
"thread",
"created",
"process",
"processName",
"args",
"module",
"filename",
"levelno",
"exc_text",
"pathname",
"lineno",
"msg",
"exc_info",
"funcName",
"relativeCreated",
"levelname",
"msecs")
)
# Humanise output and conform to Exceptions
record["message"] = str(record.pop("msg"))
if os.getenv("PYBLISH_SAFE"):
schema.validate(record, "record")
return record | [
"def",
"format_record",
"(",
"record",
")",
":",
"record",
"=",
"dict",
"(",
"(",
"key",
",",
"getattr",
"(",
"record",
",",
"key",
",",
"None",
")",
")",
"for",
"key",
"in",
"(",
"\"threadName\"",
",",
"\"name\"",
",",
"\"thread\"",
",",
"\"created\""... | Serialise LogRecord instance | [
"Serialise",
"LogRecord",
"instance"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/formatting.py#L61-L94 | train | 205,141 |
pyblish/pyblish-qml | pyblish_qml/ipc/formatting.py | format_plugins | def format_plugins(plugins):
"""Serialise multiple plug-in
Returns:
List of JSON-compatible plug-ins
"""
formatted = []
for plugin_ in plugins:
formatted_plugin = format_plugin(plugin_)
formatted.append(formatted_plugin)
return formatted | python | def format_plugins(plugins):
"""Serialise multiple plug-in
Returns:
List of JSON-compatible plug-ins
"""
formatted = []
for plugin_ in plugins:
formatted_plugin = format_plugin(plugin_)
formatted.append(formatted_plugin)
return formatted | [
"def",
"format_plugins",
"(",
"plugins",
")",
":",
"formatted",
"=",
"[",
"]",
"for",
"plugin_",
"in",
"plugins",
":",
"formatted_plugin",
"=",
"format_plugin",
"(",
"plugin_",
")",
"formatted",
".",
"append",
"(",
"formatted_plugin",
")",
"return",
"formatted... | Serialise multiple plug-in
Returns:
List of JSON-compatible plug-ins | [
"Serialise",
"multiple",
"plug",
"-",
"in"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/formatting.py#L197-L210 | train | 205,142 |
pyblish/pyblish-qml | pyblish_qml/control.py | iterator | def iterator(plugins, context):
"""An iterator for plug-in and instance pairs"""
test = pyblish.logic.registered_test()
state = {
"nextOrder": None,
"ordersWithError": set()
}
for plugin in plugins:
state["nextOrder"] = plugin.order
message = test(**state)
if message:
raise StopIteration("Stopped due to %s" % message)
instances = pyblish.api.instances_by_plugin(context, plugin)
if plugin.__instanceEnabled__:
for instance in instances:
yield plugin, instance
else:
yield plugin, None | python | def iterator(plugins, context):
"""An iterator for plug-in and instance pairs"""
test = pyblish.logic.registered_test()
state = {
"nextOrder": None,
"ordersWithError": set()
}
for plugin in plugins:
state["nextOrder"] = plugin.order
message = test(**state)
if message:
raise StopIteration("Stopped due to %s" % message)
instances = pyblish.api.instances_by_plugin(context, plugin)
if plugin.__instanceEnabled__:
for instance in instances:
yield plugin, instance
else:
yield plugin, None | [
"def",
"iterator",
"(",
"plugins",
",",
"context",
")",
":",
"test",
"=",
"pyblish",
".",
"logic",
".",
"registered_test",
"(",
")",
"state",
"=",
"{",
"\"nextOrder\"",
":",
"None",
",",
"\"ordersWithError\"",
":",
"set",
"(",
")",
"}",
"for",
"plugin",
... | An iterator for plug-in and instance pairs | [
"An",
"iterator",
"for",
"plug",
"-",
"in",
"and",
"instance",
"pairs"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L1167-L1188 | train | 205,143 |
pyblish/pyblish-qml | pyblish_qml/control.py | Controller.getPluginActions | def getPluginActions(self, index):
"""Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model
"""
index = self.data["proxies"]["plugin"].mapToSource(
self.data["proxies"]["plugin"].index(
index, 0, QtCore.QModelIndex())).row()
item = self.data["models"]["item"].items[index]
# Inject reference to the original index
actions = [
dict(action, **{"index": index})
for action in item.actions
]
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if action["on"] == "notProcessed" and item.processed:
actions.remove(action)
# Discard empty categories, separators
remaining_actions = list()
index = 0
try:
action = actions[index]
except IndexError:
pass
else:
while action:
try:
action = actions[index]
except IndexError:
break
isempty = False
if action["__type__"] in ("category", "separator"):
try:
next_ = actions[index + 1]
if next_["__type__"] != "action":
isempty = True
except IndexError:
isempty = True
if not isempty:
remaining_actions.append(action)
index += 1
return remaining_actions | python | def getPluginActions(self, index):
"""Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model
"""
index = self.data["proxies"]["plugin"].mapToSource(
self.data["proxies"]["plugin"].index(
index, 0, QtCore.QModelIndex())).row()
item = self.data["models"]["item"].items[index]
# Inject reference to the original index
actions = [
dict(action, **{"index": index})
for action in item.actions
]
# Context specific actions
for action in list(actions):
if action["on"] == "failed" and not item.hasError:
actions.remove(action)
if action["on"] == "succeeded" and not item.succeeded:
actions.remove(action)
if action["on"] == "processed" and not item.processed:
actions.remove(action)
if action["on"] == "notProcessed" and item.processed:
actions.remove(action)
# Discard empty categories, separators
remaining_actions = list()
index = 0
try:
action = actions[index]
except IndexError:
pass
else:
while action:
try:
action = actions[index]
except IndexError:
break
isempty = False
if action["__type__"] in ("category", "separator"):
try:
next_ = actions[index + 1]
if next_["__type__"] != "action":
isempty = True
except IndexError:
isempty = True
if not isempty:
remaining_actions.append(action)
index += 1
return remaining_actions | [
"def",
"getPluginActions",
"(",
"self",
",",
"index",
")",
":",
"index",
"=",
"self",
".",
"data",
"[",
"\"proxies\"",
"]",
"[",
"\"plugin\"",
"]",
".",
"mapToSource",
"(",
"self",
".",
"data",
"[",
"\"proxies\"",
"]",
"[",
"\"plugin\"",
"]",
".",
"ind... | Return actions from plug-in at `index`
Arguments:
index (int): Index at which item is located in model | [
"Return",
"actions",
"from",
"plug",
"-",
"in",
"at",
"index"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L376-L435 | train | 205,144 |
pyblish/pyblish-qml | pyblish_qml/control.py | Controller.exclude | def exclude(self, target, operation, role, value):
"""Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude
"""
target = {"result": self.data["proxies"]["result"],
"instance": self.data["proxies"]["instance"],
"plugin": self.data["proxies"]["plugin"]}[target]
if operation == "add":
target.add_exclusion(role, value)
elif operation == "remove":
target.remove_exclusion(role, value)
else:
raise TypeError("operation must be either `add` or `remove`") | python | def exclude(self, target, operation, role, value):
"""Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude
"""
target = {"result": self.data["proxies"]["result"],
"instance": self.data["proxies"]["instance"],
"plugin": self.data["proxies"]["plugin"]}[target]
if operation == "add":
target.add_exclusion(role, value)
elif operation == "remove":
target.remove_exclusion(role, value)
else:
raise TypeError("operation must be either `add` or `remove`") | [
"def",
"exclude",
"(",
"self",
",",
"target",
",",
"operation",
",",
"role",
",",
"value",
")",
":",
"target",
"=",
"{",
"\"result\"",
":",
"self",
".",
"data",
"[",
"\"proxies\"",
"]",
"[",
"\"result\"",
"]",
",",
"\"instance\"",
":",
"self",
".",
"... | Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude | [
"Exclude",
"a",
"role",
"of",
"value",
"at",
"target"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L583-L605 | train | 205,145 |
pyblish/pyblish-qml | pyblish_qml/control.py | Controller.__item_data | def __item_data(self, model, index):
"""Return item data as dict"""
item = model.items[index]
data = {
"name": item.name,
"data": item.data,
"doc": getattr(item, "doc", None),
"path": getattr(item, "path", None),
}
return data | python | def __item_data(self, model, index):
"""Return item data as dict"""
item = model.items[index]
data = {
"name": item.name,
"data": item.data,
"doc": getattr(item, "doc", None),
"path": getattr(item, "path", None),
}
return data | [
"def",
"__item_data",
"(",
"self",
",",
"model",
",",
"index",
")",
":",
"item",
"=",
"model",
".",
"items",
"[",
"index",
"]",
"data",
"=",
"{",
"\"name\"",
":",
"item",
".",
"name",
",",
"\"data\"",
":",
"item",
".",
"data",
",",
"\"doc\"",
":",
... | Return item data as dict | [
"Return",
"item",
"data",
"as",
"dict"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L612-L623 | train | 205,146 |
pyblish/pyblish-qml | pyblish_qml/control.py | Controller.comment_sync | def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) | python | def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) | [
"def",
"comment_sync",
"(",
"self",
",",
"comment",
")",
":",
"self",
".",
"host",
".",
"update",
"(",
"key",
"=",
"\"comment\"",
",",
"value",
"=",
"comment",
")",
"self",
".",
"host",
".",
"emit",
"(",
"\"commented\"",
",",
"comment",
"=",
"comment",... | Update comments to host and notify subscribers | [
"Update",
"comments",
"to",
"host",
"and",
"notify",
"subscribers"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L657-L660 | train | 205,147 |
pyblish/pyblish-qml | pyblish_qml/control.py | Controller.on_commenting | def on_commenting(self, comment):
"""The user is entering a comment"""
def update():
context = self.host.cached_context
context.data["comment"] = comment
self.data["comment"] = comment
# Notify subscribers of the comment
self.comment_sync(comment)
self.commented.emit()
# Update local cache a little later
util.schedule(update, 100, channel="commenting") | python | def on_commenting(self, comment):
"""The user is entering a comment"""
def update():
context = self.host.cached_context
context.data["comment"] = comment
self.data["comment"] = comment
# Notify subscribers of the comment
self.comment_sync(comment)
self.commented.emit()
# Update local cache a little later
util.schedule(update, 100, channel="commenting") | [
"def",
"on_commenting",
"(",
"self",
",",
"comment",
")",
":",
"def",
"update",
"(",
")",
":",
"context",
"=",
"self",
".",
"host",
".",
"cached_context",
"context",
".",
"data",
"[",
"\"comment\"",
"]",
"=",
"comment",
"self",
".",
"data",
"[",
"\"com... | The user is entering a comment | [
"The",
"user",
"is",
"entering",
"a",
"comment"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L664-L678 | train | 205,148 |
pyblish/pyblish-qml | pyblish_qml/control.py | Controller.publish | def publish(self):
"""Start asynchonous publishing
Publishing takes into account all available and currently
toggled plug-ins and instances.
"""
def get_data():
model = self.data["models"]["item"]
# Communicate with host to retrieve current plugins and instances
# This can potentially take a very long time; it is run
# asynchronously and initiates processing once complete.
host_plugins = dict((p.id, p) for p in self.host.cached_discover)
host_context = dict((i.id, i) for i in self.host.cached_context)
plugins = list()
instances = list()
for plugin in models.ItemIterator(model.plugins):
# Exclude Collectors
if pyblish.lib.inrange(
number=plugin.order,
base=pyblish.api.Collector.order):
continue
plugins.append(host_plugins[plugin.id])
for instance in models.ItemIterator(model.instances):
instances.append(host_context[instance.id])
return plugins, instances
def on_data_received(args):
self.run(*args, callback=on_finished)
def on_finished():
self.host.emit("published", context=None)
util.defer(get_data, callback=on_data_received) | python | def publish(self):
"""Start asynchonous publishing
Publishing takes into account all available and currently
toggled plug-ins and instances.
"""
def get_data():
model = self.data["models"]["item"]
# Communicate with host to retrieve current plugins and instances
# This can potentially take a very long time; it is run
# asynchronously and initiates processing once complete.
host_plugins = dict((p.id, p) for p in self.host.cached_discover)
host_context = dict((i.id, i) for i in self.host.cached_context)
plugins = list()
instances = list()
for plugin in models.ItemIterator(model.plugins):
# Exclude Collectors
if pyblish.lib.inrange(
number=plugin.order,
base=pyblish.api.Collector.order):
continue
plugins.append(host_plugins[plugin.id])
for instance in models.ItemIterator(model.instances):
instances.append(host_context[instance.id])
return plugins, instances
def on_data_received(args):
self.run(*args, callback=on_finished)
def on_finished():
self.host.emit("published", context=None)
util.defer(get_data, callback=on_data_received) | [
"def",
"publish",
"(",
"self",
")",
":",
"def",
"get_data",
"(",
")",
":",
"model",
"=",
"self",
".",
"data",
"[",
"\"models\"",
"]",
"[",
"\"item\"",
"]",
"# Communicate with host to retrieve current plugins and instances",
"# This can potentially take a very long time... | Start asynchonous publishing
Publishing takes into account all available and currently
toggled plug-ins and instances. | [
"Start",
"asynchonous",
"publishing"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L884-L925 | train | 205,149 |
pyblish/pyblish-qml | pyblish_qml/settings.py | from_dict | def from_dict(settings):
"""Apply settings from dictionary
Arguments:
settings (dict): Settings in the form of a dictionary
"""
assert isinstance(settings, dict), "`settings` must be of type dict"
for key, value in settings.items():
setattr(self, key, value) | python | def from_dict(settings):
"""Apply settings from dictionary
Arguments:
settings (dict): Settings in the form of a dictionary
"""
assert isinstance(settings, dict), "`settings` must be of type dict"
for key, value in settings.items():
setattr(self, key, value) | [
"def",
"from_dict",
"(",
"settings",
")",
":",
"assert",
"isinstance",
"(",
"settings",
",",
"dict",
")",
",",
"\"`settings` must be of type dict\"",
"for",
"key",
",",
"value",
"in",
"settings",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k... | Apply settings from dictionary
Arguments:
settings (dict): Settings in the form of a dictionary | [
"Apply",
"settings",
"from",
"dictionary"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/settings.py#L18-L28 | train | 205,150 |
pyblish/pyblish-qml | pyblish_qml/vendor/mock.py | create_autospec | def create_autospec(spec, spec_set=False, instance=False, _parent=None,
_name=None, **kwargs):
"""Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the `spec` object as their
spec.
Functions or methods being mocked will have their arguments checked
to check that they are called with the correct signature.
If `spec_set` is True then attempting to set attributes that don't exist
on the spec object will raise an `AttributeError`.
If a class is used as a spec then the return value of the mock (the
instance of the class) will have the same spec. You can use a class as the
spec for an instance object by passing `instance=True`. The returned mock
will only be callable if instances of the mock are callable.
`create_autospec` also takes arbitrary keyword arguments that are passed to
the constructor of the created mock."""
if _is_list(spec):
# can't pass a list instance to the mock constructor as it will be
# interpreted as a list of strings
spec = type(spec)
is_type = isinstance(spec, ClassTypes)
_kwargs = {'spec': spec}
if spec_set:
_kwargs = {'spec_set': spec}
elif spec is None:
# None we mock with a normal mock without a spec
_kwargs = {}
_kwargs.update(kwargs)
Klass = MagicMock
if type(spec) in DescriptorTypes:
# descriptors don't have a spec
# because we don't know what type they return
_kwargs = {}
elif not _callable(spec):
Klass = NonCallableMagicMock
elif is_type and instance and not _instance_callable(spec):
Klass = NonCallableMagicMock
_new_name = _name
if _parent is None:
# for a top level object no _new_name should be set
_new_name = ''
mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
name=_name, **_kwargs)
if isinstance(spec, FunctionTypes):
# should only happen at the top level because we don't
# recurse for functions
mock = _set_signature(mock, spec)
else:
_check_signature(spec, mock, is_type, instance)
if _parent is not None and not instance:
_parent._mock_children[_name] = mock
if is_type and not instance and 'return_value' not in kwargs:
mock.return_value = create_autospec(spec, spec_set, instance=True,
_name='()', _parent=mock)
for entry in dir(spec):
if _is_magic(entry):
# MagicMock already does the useful magic methods for us
continue
if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
# allow a mock to actually be a function
continue
# XXXX do we need a better way of getting attributes without
# triggering code execution (?) Probably not - we need the actual
# object to mock it so we would rather trigger a property than mock
# the property descriptor. Likewise we want to mock out dynamically
# provided attributes.
# XXXX what about attributes that raise exceptions other than
# AttributeError on being fetched?
# we could be resilient against it, or catch and propagate the
# exception when the attribute is fetched from the mock
try:
original = getattr(spec, entry)
except AttributeError:
continue
kwargs = {'spec': original}
if spec_set:
kwargs = {'spec_set': original}
if not isinstance(original, FunctionTypes):
new = _SpecState(original, spec_set, mock, entry, instance)
mock._mock_children[entry] = new
else:
parent = mock
if isinstance(spec, FunctionTypes):
parent = mock.mock
new = MagicMock(parent=parent, name=entry, _new_name=entry,
_new_parent=parent, **kwargs)
mock._mock_children[entry] = new
skipfirst = _must_skip(spec, entry, is_type)
_check_signature(original, new, skipfirst=skipfirst)
# so functions created with _set_signature become instance attributes,
# *plus* their underlying mock exists in _mock_children of the parent
# mock. Adding to _mock_children may be unnecessary where we are also
# setting as an instance attribute?
if isinstance(new, FunctionTypes):
setattr(mock, entry, new)
return mock | python | def create_autospec(spec, spec_set=False, instance=False, _parent=None,
_name=None, **kwargs):
"""Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the `spec` object as their
spec.
Functions or methods being mocked will have their arguments checked
to check that they are called with the correct signature.
If `spec_set` is True then attempting to set attributes that don't exist
on the spec object will raise an `AttributeError`.
If a class is used as a spec then the return value of the mock (the
instance of the class) will have the same spec. You can use a class as the
spec for an instance object by passing `instance=True`. The returned mock
will only be callable if instances of the mock are callable.
`create_autospec` also takes arbitrary keyword arguments that are passed to
the constructor of the created mock."""
if _is_list(spec):
# can't pass a list instance to the mock constructor as it will be
# interpreted as a list of strings
spec = type(spec)
is_type = isinstance(spec, ClassTypes)
_kwargs = {'spec': spec}
if spec_set:
_kwargs = {'spec_set': spec}
elif spec is None:
# None we mock with a normal mock without a spec
_kwargs = {}
_kwargs.update(kwargs)
Klass = MagicMock
if type(spec) in DescriptorTypes:
# descriptors don't have a spec
# because we don't know what type they return
_kwargs = {}
elif not _callable(spec):
Klass = NonCallableMagicMock
elif is_type and instance and not _instance_callable(spec):
Klass = NonCallableMagicMock
_new_name = _name
if _parent is None:
# for a top level object no _new_name should be set
_new_name = ''
mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
name=_name, **_kwargs)
if isinstance(spec, FunctionTypes):
# should only happen at the top level because we don't
# recurse for functions
mock = _set_signature(mock, spec)
else:
_check_signature(spec, mock, is_type, instance)
if _parent is not None and not instance:
_parent._mock_children[_name] = mock
if is_type and not instance and 'return_value' not in kwargs:
mock.return_value = create_autospec(spec, spec_set, instance=True,
_name='()', _parent=mock)
for entry in dir(spec):
if _is_magic(entry):
# MagicMock already does the useful magic methods for us
continue
if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
# allow a mock to actually be a function
continue
# XXXX do we need a better way of getting attributes without
# triggering code execution (?) Probably not - we need the actual
# object to mock it so we would rather trigger a property than mock
# the property descriptor. Likewise we want to mock out dynamically
# provided attributes.
# XXXX what about attributes that raise exceptions other than
# AttributeError on being fetched?
# we could be resilient against it, or catch and propagate the
# exception when the attribute is fetched from the mock
try:
original = getattr(spec, entry)
except AttributeError:
continue
kwargs = {'spec': original}
if spec_set:
kwargs = {'spec_set': original}
if not isinstance(original, FunctionTypes):
new = _SpecState(original, spec_set, mock, entry, instance)
mock._mock_children[entry] = new
else:
parent = mock
if isinstance(spec, FunctionTypes):
parent = mock.mock
new = MagicMock(parent=parent, name=entry, _new_name=entry,
_new_parent=parent, **kwargs)
mock._mock_children[entry] = new
skipfirst = _must_skip(spec, entry, is_type)
_check_signature(original, new, skipfirst=skipfirst)
# so functions created with _set_signature become instance attributes,
# *plus* their underlying mock exists in _mock_children of the parent
# mock. Adding to _mock_children may be unnecessary where we are also
# setting as an instance attribute?
if isinstance(new, FunctionTypes):
setattr(mock, entry, new)
return mock | [
"def",
"create_autospec",
"(",
"spec",
",",
"spec_set",
"=",
"False",
",",
"instance",
"=",
"False",
",",
"_parent",
"=",
"None",
",",
"_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_is_list",
"(",
"spec",
")",
":",
"# can't pass a lis... | Create a mock object using another object as a spec. Attributes on the
mock will use the corresponding attribute on the `spec` object as their
spec.
Functions or methods being mocked will have their arguments checked
to check that they are called with the correct signature.
If `spec_set` is True then attempting to set attributes that don't exist
on the spec object will raise an `AttributeError`.
If a class is used as a spec then the return value of the mock (the
instance of the class) will have the same spec. You can use a class as the
spec for an instance object by passing `instance=True`. The returned mock
will only be callable if instances of the mock are callable.
`create_autospec` also takes arbitrary keyword arguments that are passed to
the constructor of the created mock. | [
"Create",
"a",
"mock",
"object",
"using",
"another",
"object",
"as",
"a",
"spec",
".",
"Attributes",
"on",
"the",
"mock",
"will",
"use",
"the",
"corresponding",
"attribute",
"on",
"the",
"spec",
"object",
"as",
"their",
"spec",
"."
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L2135-L2250 | train | 205,151 |
pyblish/pyblish-qml | pyblish_qml/vendor/mock.py | NonCallableMock.attach_mock | def attach_mock(self, mock, attribute):
"""
Attach a mock as an attribute of this one, replacing its name and
parent. Calls to the attached mock will be recorded in the
`method_calls` and `mock_calls` attributes of this one."""
mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name = ''
mock._mock_new_name = None
setattr(self, attribute, mock) | python | def attach_mock(self, mock, attribute):
"""
Attach a mock as an attribute of this one, replacing its name and
parent. Calls to the attached mock will be recorded in the
`method_calls` and `mock_calls` attributes of this one."""
mock._mock_parent = None
mock._mock_new_parent = None
mock._mock_name = ''
mock._mock_new_name = None
setattr(self, attribute, mock) | [
"def",
"attach_mock",
"(",
"self",
",",
"mock",
",",
"attribute",
")",
":",
"mock",
".",
"_mock_parent",
"=",
"None",
"mock",
".",
"_mock_new_parent",
"=",
"None",
"mock",
".",
"_mock_name",
"=",
"''",
"mock",
".",
"_mock_new_name",
"=",
"None",
"setattr",... | Attach a mock as an attribute of this one, replacing its name and
parent. Calls to the attached mock will be recorded in the
`method_calls` and `mock_calls` attributes of this one. | [
"Attach",
"a",
"mock",
"as",
"an",
"attribute",
"of",
"this",
"one",
"replacing",
"its",
"name",
"and",
"parent",
".",
"Calls",
"to",
"the",
"attached",
"mock",
"will",
"be",
"recorded",
"in",
"the",
"method_calls",
"and",
"mock_calls",
"attributes",
"of",
... | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L518-L528 | train | 205,152 |
pyblish/pyblish-qml | pyblish_qml/vendor/mock.py | NonCallableMock.configure_mock | def configure_mock(self, **kwargs):
"""Set attributes on the mock through keyword arguments.
Attributes plus return values and side effects can be set on child
mocks using standard dot notation and unpacking a dictionary in the
method call:
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock.configure_mock(**attrs)"""
for arg, val in sorted(kwargs.items(),
# we sort on the number of dots so that
# attributes are set before we set attributes on
# attributes
key=lambda entry: entry[0].count('.')):
args = arg.split('.')
final = args.pop()
obj = self
for entry in args:
obj = getattr(obj, entry)
setattr(obj, final, val) | python | def configure_mock(self, **kwargs):
"""Set attributes on the mock through keyword arguments.
Attributes plus return values and side effects can be set on child
mocks using standard dot notation and unpacking a dictionary in the
method call:
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock.configure_mock(**attrs)"""
for arg, val in sorted(kwargs.items(),
# we sort on the number of dots so that
# attributes are set before we set attributes on
# attributes
key=lambda entry: entry[0].count('.')):
args = arg.split('.')
final = args.pop()
obj = self
for entry in args:
obj = getattr(obj, entry)
setattr(obj, final, val) | [
"def",
"configure_mock",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arg",
",",
"val",
"in",
"sorted",
"(",
"kwargs",
".",
"items",
"(",
")",
",",
"# we sort on the number of dots so that",
"# attributes are set before we set attributes on",
"# attribute... | Set attributes on the mock through keyword arguments.
Attributes plus return values and side effects can be set on child
mocks using standard dot notation and unpacking a dictionary in the
method call:
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock.configure_mock(**attrs) | [
"Set",
"attributes",
"on",
"the",
"mock",
"through",
"keyword",
"arguments",
"."
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L631-L650 | train | 205,153 |
pyblish/pyblish-qml | pyblish_qml/vendor/mock.py | NonCallableMock._get_child_mock | def _get_child_mock(self, **kw):
"""Create the child mocks for attributes and return value.
By default child mocks will be the same type as the parent.
Subclasses of Mock may want to override this to customize the way
child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass)."""
_type = type(self)
if not issubclass(_type, CallableMixin):
if issubclass(_type, NonCallableMagicMock):
klass = MagicMock
elif issubclass(_type, NonCallableMock) :
klass = Mock
else:
klass = _type.__mro__[1]
return klass(**kw) | python | def _get_child_mock(self, **kw):
"""Create the child mocks for attributes and return value.
By default child mocks will be the same type as the parent.
Subclasses of Mock may want to override this to customize the way
child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass)."""
_type = type(self)
if not issubclass(_type, CallableMixin):
if issubclass(_type, NonCallableMagicMock):
klass = MagicMock
elif issubclass(_type, NonCallableMock) :
klass = Mock
else:
klass = _type.__mro__[1]
return klass(**kw) | [
"def",
"_get_child_mock",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"_type",
"=",
"type",
"(",
"self",
")",
"if",
"not",
"issubclass",
"(",
"_type",
",",
"CallableMixin",
")",
":",
"if",
"issubclass",
"(",
"_type",
",",
"NonCallableMagicMock",
")",
"... | Create the child mocks for attributes and return value.
By default child mocks will be the same type as the parent.
Subclasses of Mock may want to override this to customize the way
child mocks are made.
For non-callable mocks the callable variant will be used (rather than
any custom subclass). | [
"Create",
"the",
"child",
"mocks",
"for",
"attributes",
"and",
"return",
"value",
".",
"By",
"default",
"child",
"mocks",
"will",
"be",
"the",
"same",
"type",
"as",
"the",
"parent",
".",
"Subclasses",
"of",
"Mock",
"may",
"want",
"to",
"override",
"this",
... | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L895-L911 | train | 205,154 |
pyblish/pyblish-qml | pyblish_qml/vendor/mock.py | NonCallableMagicMock.mock_add_spec | def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() | python | def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() | [
"def",
"mock_add_spec",
"(",
"self",
",",
"spec",
",",
"spec_set",
"=",
"False",
")",
":",
"self",
".",
"_mock_add_spec",
"(",
"spec",
",",
"spec_set",
")",
"self",
".",
"_mock_set_magics",
"(",
")"
] | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set. | [
"Add",
"a",
"spec",
"to",
"a",
"mock",
".",
"spec",
"can",
"either",
"be",
"an",
"object",
"or",
"a",
"list",
"of",
"strings",
".",
"Only",
"attributes",
"on",
"the",
"spec",
"can",
"be",
"fetched",
"as",
"attributes",
"from",
"the",
"mock",
"."
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L1879-L1886 | train | 205,155 |
pyblish/pyblish-qml | pyblish_qml/vendor/mock.py | _Call.call_list | def call_list(self):
"""For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call."""
vals = []
thing = self
while thing is not None:
if thing.from_kall:
vals.append(thing)
thing = thing.parent
return _CallList(reversed(vals)) | python | def call_list(self):
"""For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call."""
vals = []
thing = self
while thing is not None:
if thing.from_kall:
vals.append(thing)
thing = thing.parent
return _CallList(reversed(vals)) | [
"def",
"call_list",
"(",
"self",
")",
":",
"vals",
"=",
"[",
"]",
"thing",
"=",
"self",
"while",
"thing",
"is",
"not",
"None",
":",
"if",
"thing",
".",
"from_kall",
":",
"vals",
".",
"append",
"(",
"thing",
")",
"thing",
"=",
"thing",
".",
"parent"... | For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call. | [
"For",
"a",
"call",
"object",
"that",
"represents",
"multiple",
"calls",
"call_list",
"returns",
"a",
"list",
"of",
"all",
"the",
"intermediate",
"calls",
"as",
"well",
"as",
"the",
"final",
"call",
"."
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L2118-L2128 | train | 205,156 |
pyblish/pyblish-qml | pyblish_qml/host.py | register_dispatch_wrapper | def register_dispatch_wrapper(wrapper):
"""Register a dispatch wrapper for servers
The wrapper must have this exact signature:
(func, *args, **kwargs)
"""
signature = inspect.getargspec(wrapper)
if any([len(signature.args) != 1,
signature.varargs is None,
signature.keywords is None]):
raise TypeError("Wrapper signature mismatch")
def _wrapper(func, *args, **kwargs):
"""Exception handling"""
try:
return wrapper(func, *args, **kwargs)
except Exception as e:
# Kill subprocess
_state["currentServer"].stop()
traceback.print_exc()
raise e
_state["dispatchWrapper"] = _wrapper | python | def register_dispatch_wrapper(wrapper):
"""Register a dispatch wrapper for servers
The wrapper must have this exact signature:
(func, *args, **kwargs)
"""
signature = inspect.getargspec(wrapper)
if any([len(signature.args) != 1,
signature.varargs is None,
signature.keywords is None]):
raise TypeError("Wrapper signature mismatch")
def _wrapper(func, *args, **kwargs):
"""Exception handling"""
try:
return wrapper(func, *args, **kwargs)
except Exception as e:
# Kill subprocess
_state["currentServer"].stop()
traceback.print_exc()
raise e
_state["dispatchWrapper"] = _wrapper | [
"def",
"register_dispatch_wrapper",
"(",
"wrapper",
")",
":",
"signature",
"=",
"inspect",
".",
"getargspec",
"(",
"wrapper",
")",
"if",
"any",
"(",
"[",
"len",
"(",
"signature",
".",
"args",
")",
"!=",
"1",
",",
"signature",
".",
"varargs",
"is",
"None"... | Register a dispatch wrapper for servers
The wrapper must have this exact signature:
(func, *args, **kwargs) | [
"Register",
"a",
"dispatch",
"wrapper",
"for",
"servers"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L19-L43 | train | 205,157 |
pyblish/pyblish-qml | pyblish_qml/host.py | install | def install(modal):
"""Perform first time install"""
if _state.get("installed"):
sys.stdout.write("Already installed, uninstalling..\n")
uninstall()
use_threaded_wrapper = not modal
install_callbacks()
install_host(use_threaded_wrapper)
_state["installed"] = True | python | def install(modal):
"""Perform first time install"""
if _state.get("installed"):
sys.stdout.write("Already installed, uninstalling..\n")
uninstall()
use_threaded_wrapper = not modal
install_callbacks()
install_host(use_threaded_wrapper)
_state["installed"] = True | [
"def",
"install",
"(",
"modal",
")",
":",
"if",
"_state",
".",
"get",
"(",
"\"installed\"",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Already installed, uninstalling..\\n\"",
")",
"uninstall",
"(",
")",
"use_threaded_wrapper",
"=",
"not",
"modal",
... | Perform first time install | [
"Perform",
"first",
"time",
"install"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L58-L70 | train | 205,158 |
pyblish/pyblish-qml | pyblish_qml/host.py | show | def show(parent=None, targets=[], modal=None, auto_publish=False, auto_validate=False):
"""Attempt to show GUI
Requires install() to have been run first, and
a live instance of Pyblish QML in the background.
Arguments:
parent (None, optional): Deprecated
targets (list, optional): Publishing targets
modal (bool, optional): Block interactions to parent
"""
# Get modal mode from environment
if modal is None:
modal = bool(os.environ.get("PYBLISH_QML_MODAL", False))
# Automatically install if not already installed.
install(modal)
show_settings = settings.to_dict()
show_settings['autoPublish'] = auto_publish
show_settings['autoValidate'] = auto_validate
# Show existing GUI
if _state.get("currentServer"):
server = _state["currentServer"]
proxy = ipc.server.Proxy(server)
try:
proxy.show(show_settings)
return server
except IOError:
# The running instance has already been closed.
_state.pop("currentServer")
if not host.is_headless():
host.splash()
try:
service = ipc.service.Service()
server = ipc.server.Server(service, targets=targets, modal=modal)
except Exception:
# If for some reason, the GUI fails to show.
traceback.print_exc()
return host.desplash()
proxy = ipc.server.Proxy(server)
proxy.show(show_settings)
# Store reference to server for future calls
_state["currentServer"] = server
log.info("Success. QML server available as "
"pyblish_qml.api.current_server()")
server.listen()
return server | python | def show(parent=None, targets=[], modal=None, auto_publish=False, auto_validate=False):
"""Attempt to show GUI
Requires install() to have been run first, and
a live instance of Pyblish QML in the background.
Arguments:
parent (None, optional): Deprecated
targets (list, optional): Publishing targets
modal (bool, optional): Block interactions to parent
"""
# Get modal mode from environment
if modal is None:
modal = bool(os.environ.get("PYBLISH_QML_MODAL", False))
# Automatically install if not already installed.
install(modal)
show_settings = settings.to_dict()
show_settings['autoPublish'] = auto_publish
show_settings['autoValidate'] = auto_validate
# Show existing GUI
if _state.get("currentServer"):
server = _state["currentServer"]
proxy = ipc.server.Proxy(server)
try:
proxy.show(show_settings)
return server
except IOError:
# The running instance has already been closed.
_state.pop("currentServer")
if not host.is_headless():
host.splash()
try:
service = ipc.service.Service()
server = ipc.server.Server(service, targets=targets, modal=modal)
except Exception:
# If for some reason, the GUI fails to show.
traceback.print_exc()
return host.desplash()
proxy = ipc.server.Proxy(server)
proxy.show(show_settings)
# Store reference to server for future calls
_state["currentServer"] = server
log.info("Success. QML server available as "
"pyblish_qml.api.current_server()")
server.listen()
return server | [
"def",
"show",
"(",
"parent",
"=",
"None",
",",
"targets",
"=",
"[",
"]",
",",
"modal",
"=",
"None",
",",
"auto_publish",
"=",
"False",
",",
"auto_validate",
"=",
"False",
")",
":",
"# Get modal mode from environment",
"if",
"modal",
"is",
"None",
":",
"... | Attempt to show GUI
Requires install() to have been run first, and
a live instance of Pyblish QML in the background.
Arguments:
parent (None, optional): Deprecated
targets (list, optional): Publishing targets
modal (bool, optional): Block interactions to parent | [
"Attempt",
"to",
"show",
"GUI"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L79-L138 | train | 205,159 |
pyblish/pyblish-qml | pyblish_qml/host.py | install_host | def install_host(use_threaded_wrapper):
"""Install required components into supported hosts
An unsupported host will still run, but may encounter issues,
especially with threading.
"""
for install in (_install_maya,
_install_houdini,
_install_nuke,
_install_nukeassist,
_install_hiero,
_install_nukestudio,
_install_blender):
try:
install(use_threaded_wrapper)
except ImportError:
pass
else:
break | python | def install_host(use_threaded_wrapper):
"""Install required components into supported hosts
An unsupported host will still run, but may encounter issues,
especially with threading.
"""
for install in (_install_maya,
_install_houdini,
_install_nuke,
_install_nukeassist,
_install_hiero,
_install_nukestudio,
_install_blender):
try:
install(use_threaded_wrapper)
except ImportError:
pass
else:
break | [
"def",
"install_host",
"(",
"use_threaded_wrapper",
")",
":",
"for",
"install",
"in",
"(",
"_install_maya",
",",
"_install_houdini",
",",
"_install_nuke",
",",
"_install_nukeassist",
",",
"_install_hiero",
",",
"_install_nukestudio",
",",
"_install_blender",
")",
":",... | Install required components into supported hosts
An unsupported host will still run, but may encounter issues,
especially with threading. | [
"Install",
"required",
"components",
"into",
"supported",
"hosts"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L226-L246 | train | 205,160 |
pyblish/pyblish-qml | pyblish_qml/host.py | _remove_googleapiclient | def _remove_googleapiclient():
"""Check if the compatibility must be maintained
The Maya 2018 version tries to import the `http` module from
Maya2018\plug-ins\MASH\scripts\googleapiclient\http.py in stead of the
module from six.py. This import conflict causes a crash Avalon's publisher.
This is due to Autodesk adding paths to the PYTHONPATH environment variable
which contain modules instead of only packages.
"""
keyword = "googleapiclient"
# reconstruct python paths
python_paths = os.environ["PYTHONPATH"].split(os.pathsep)
paths = [path for path in python_paths if keyword not in path]
os.environ["PYTHONPATH"] = os.pathsep.join(paths) | python | def _remove_googleapiclient():
"""Check if the compatibility must be maintained
The Maya 2018 version tries to import the `http` module from
Maya2018\plug-ins\MASH\scripts\googleapiclient\http.py in stead of the
module from six.py. This import conflict causes a crash Avalon's publisher.
This is due to Autodesk adding paths to the PYTHONPATH environment variable
which contain modules instead of only packages.
"""
keyword = "googleapiclient"
# reconstruct python paths
python_paths = os.environ["PYTHONPATH"].split(os.pathsep)
paths = [path for path in python_paths if keyword not in path]
os.environ["PYTHONPATH"] = os.pathsep.join(paths) | [
"def",
"_remove_googleapiclient",
"(",
")",
":",
"keyword",
"=",
"\"googleapiclient\"",
"# reconstruct python paths",
"python_paths",
"=",
"os",
".",
"environ",
"[",
"\"PYTHONPATH\"",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"paths",
"=",
"[",
"path",
... | Check if the compatibility must be maintained
The Maya 2018 version tries to import the `http` module from
Maya2018\plug-ins\MASH\scripts\googleapiclient\http.py in stead of the
module from six.py. This import conflict causes a crash Avalon's publisher.
This is due to Autodesk adding paths to the PYTHONPATH environment variable
which contain modules instead of only packages. | [
"Check",
"if",
"the",
"compatibility",
"must",
"be",
"maintained"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L486-L501 | train | 205,161 |
pyblish/pyblish-qml | pyblish_qml/host.py | _install_maya | def _install_maya(use_threaded_wrapper):
"""Helper function to Autodesk Maya support"""
from maya import utils, cmds
def threaded_wrapper(func, *args, **kwargs):
return utils.executeInMainThreadWithResult(
func, *args, **kwargs)
sys.stdout.write("Setting up Pyblish QML in Maya\n")
if cmds.about(version=True) == "2018":
_remove_googleapiclient()
_common_setup("Maya", threaded_wrapper, use_threaded_wrapper) | python | def _install_maya(use_threaded_wrapper):
"""Helper function to Autodesk Maya support"""
from maya import utils, cmds
def threaded_wrapper(func, *args, **kwargs):
return utils.executeInMainThreadWithResult(
func, *args, **kwargs)
sys.stdout.write("Setting up Pyblish QML in Maya\n")
if cmds.about(version=True) == "2018":
_remove_googleapiclient()
_common_setup("Maya", threaded_wrapper, use_threaded_wrapper) | [
"def",
"_install_maya",
"(",
"use_threaded_wrapper",
")",
":",
"from",
"maya",
"import",
"utils",
",",
"cmds",
"def",
"threaded_wrapper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"utils",
".",
"executeInMainThreadWithResult",... | Helper function to Autodesk Maya support | [
"Helper",
"function",
"to",
"Autodesk",
"Maya",
"support"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L516-L529 | train | 205,162 |
pyblish/pyblish-qml | pyblish_qml/host.py | _install_houdini | def _install_houdini(use_threaded_wrapper):
"""Helper function to SideFx Houdini support"""
import hdefereval
def threaded_wrapper(func, *args, **kwargs):
return hdefereval.executeInMainThreadWithResult(
func, *args, **kwargs)
_common_setup("Houdini", threaded_wrapper, use_threaded_wrapper) | python | def _install_houdini(use_threaded_wrapper):
"""Helper function to SideFx Houdini support"""
import hdefereval
def threaded_wrapper(func, *args, **kwargs):
return hdefereval.executeInMainThreadWithResult(
func, *args, **kwargs)
_common_setup("Houdini", threaded_wrapper, use_threaded_wrapper) | [
"def",
"_install_houdini",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"hdefereval",
"def",
"threaded_wrapper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"hdefereval",
".",
"executeInMainThreadWithResult",
"(",
"func",
",",... | Helper function to SideFx Houdini support | [
"Helper",
"function",
"to",
"SideFx",
"Houdini",
"support"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L532-L540 | train | 205,163 |
pyblish/pyblish-qml | pyblish_qml/host.py | _install_nuke | def _install_nuke(use_threaded_wrapper):
"""Helper function to The Foundry Nuke support"""
import nuke
not_nuke_launch = (
"--hiero" in nuke.rawArgs or
"--studio" in nuke.rawArgs or
"--nukeassist" in nuke.rawArgs
)
if not_nuke_launch:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("Nuke", threaded_wrapper, use_threaded_wrapper) | python | def _install_nuke(use_threaded_wrapper):
"""Helper function to The Foundry Nuke support"""
import nuke
not_nuke_launch = (
"--hiero" in nuke.rawArgs or
"--studio" in nuke.rawArgs or
"--nukeassist" in nuke.rawArgs
)
if not_nuke_launch:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("Nuke", threaded_wrapper, use_threaded_wrapper) | [
"def",
"_install_nuke",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"nuke",
"not_nuke_launch",
"=",
"(",
"\"--hiero\"",
"in",
"nuke",
".",
"rawArgs",
"or",
"\"--studio\"",
"in",
"nuke",
".",
"rawArgs",
"or",
"\"--nukeassist\"",
"in",
"nuke",
".",
"rawArgs",... | Helper function to The Foundry Nuke support | [
"Helper",
"function",
"to",
"The",
"Foundry",
"Nuke",
"support"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L543-L559 | train | 205,164 |
pyblish/pyblish-qml | pyblish_qml/host.py | _install_nukeassist | def _install_nukeassist(use_threaded_wrapper):
"""Helper function to The Foundry NukeAssist support"""
import nuke
if "--nukeassist" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("NukeAssist", threaded_wrapper, use_threaded_wrapper) | python | def _install_nukeassist(use_threaded_wrapper):
"""Helper function to The Foundry NukeAssist support"""
import nuke
if "--nukeassist" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return nuke.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("NukeAssist", threaded_wrapper, use_threaded_wrapper) | [
"def",
"_install_nukeassist",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"nuke",
"if",
"\"--nukeassist\"",
"not",
"in",
"nuke",
".",
"rawArgs",
":",
"raise",
"ImportError",
"def",
"threaded_wrapper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs"... | Helper function to The Foundry NukeAssist support | [
"Helper",
"function",
"to",
"The",
"Foundry",
"NukeAssist",
"support"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L562-L573 | train | 205,165 |
pyblish/pyblish-qml | pyblish_qml/host.py | _install_hiero | def _install_hiero(use_threaded_wrapper):
"""Helper function to The Foundry Hiero support"""
import hiero
import nuke
if "--hiero" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return hiero.core.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("Hiero", threaded_wrapper, use_threaded_wrapper) | python | def _install_hiero(use_threaded_wrapper):
"""Helper function to The Foundry Hiero support"""
import hiero
import nuke
if "--hiero" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return hiero.core.executeInMainThreadWithResult(
func, args, kwargs)
_common_setup("Hiero", threaded_wrapper, use_threaded_wrapper) | [
"def",
"_install_hiero",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"hiero",
"import",
"nuke",
"if",
"\"--hiero\"",
"not",
"in",
"nuke",
".",
"rawArgs",
":",
"raise",
"ImportError",
"def",
"threaded_wrapper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*... | Helper function to The Foundry Hiero support | [
"Helper",
"function",
"to",
"The",
"Foundry",
"Hiero",
"support"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L576-L588 | train | 205,166 |
pyblish/pyblish-qml | pyblish_qml/host.py | _install_blender | def _install_blender(use_threaded_wrapper):
"""Blender is a special snowflake
It doesn't have a mechanism with which to call commands from a thread
other than the main thread. So what's happening below is we run a polling
command every 10 milliseconds to see whether QML has any tasks for us.
If it does, then Blender runs this command (blocking while it does it),
and passes the result back to QML when ready.
The consequence of this is that we're polling even though nothing is
expected to arrive. The cost of polling is expected to be neglible,
but it's worth keeping in mind and ideally optimise away. E.g. only
poll when the QML window is actually open.
"""
import bpy
qml_to_blender = queue.Queue()
blender_to_qml = queue.Queue()
def threaded_wrapper(func, *args, **kwargs):
qml_to_blender.put((func, args, kwargs))
return blender_to_qml.get()
class PyblishQMLOperator(bpy.types.Operator):
"""Operator which runs its self from a timer"""
bl_idname = "wm.pyblish_qml_timer"
bl_label = "Pyblish QML Timer Operator"
_timer = None
def modal(self, context, event):
if event.type == 'TIMER':
try:
func, args, kwargs = qml_to_blender.get_nowait()
except queue.Empty:
pass
else:
result = func(*args, **kwargs)
blender_to_qml.put(result)
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
# Check the queue ever 10 ms
# The cost of checking the queue is neglible, but it
# does mean having Python execute a command all the time,
# even as the artist is working normally and is nowhere
# near publishing anything.
self._timer = wm.event_timer_add(0.01, context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
log.info("Registering Blender + Pyblish operator")
bpy.utils.register_class(PyblishQMLOperator)
# Start the timer
bpy.ops.wm.pyblish_qml_timer()
# Expose externally, for debugging. It enables you to
# pause the timer, and add/remove commands by hand.
_state["QmlToBlenderQueue"] = qml_to_blender
_state["BlenderToQmlQueue"] = blender_to_qml
_common_setup("Blender", threaded_wrapper, use_threaded_wrapper) | python | def _install_blender(use_threaded_wrapper):
"""Blender is a special snowflake
It doesn't have a mechanism with which to call commands from a thread
other than the main thread. So what's happening below is we run a polling
command every 10 milliseconds to see whether QML has any tasks for us.
If it does, then Blender runs this command (blocking while it does it),
and passes the result back to QML when ready.
The consequence of this is that we're polling even though nothing is
expected to arrive. The cost of polling is expected to be neglible,
but it's worth keeping in mind and ideally optimise away. E.g. only
poll when the QML window is actually open.
"""
import bpy
qml_to_blender = queue.Queue()
blender_to_qml = queue.Queue()
def threaded_wrapper(func, *args, **kwargs):
qml_to_blender.put((func, args, kwargs))
return blender_to_qml.get()
class PyblishQMLOperator(bpy.types.Operator):
"""Operator which runs its self from a timer"""
bl_idname = "wm.pyblish_qml_timer"
bl_label = "Pyblish QML Timer Operator"
_timer = None
def modal(self, context, event):
if event.type == 'TIMER':
try:
func, args, kwargs = qml_to_blender.get_nowait()
except queue.Empty:
pass
else:
result = func(*args, **kwargs)
blender_to_qml.put(result)
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
# Check the queue ever 10 ms
# The cost of checking the queue is neglible, but it
# does mean having Python execute a command all the time,
# even as the artist is working normally and is nowhere
# near publishing anything.
self._timer = wm.event_timer_add(0.01, context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
log.info("Registering Blender + Pyblish operator")
bpy.utils.register_class(PyblishQMLOperator)
# Start the timer
bpy.ops.wm.pyblish_qml_timer()
# Expose externally, for debugging. It enables you to
# pause the timer, and add/remove commands by hand.
_state["QmlToBlenderQueue"] = qml_to_blender
_state["BlenderToQmlQueue"] = blender_to_qml
_common_setup("Blender", threaded_wrapper, use_threaded_wrapper) | [
"def",
"_install_blender",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"bpy",
"qml_to_blender",
"=",
"queue",
".",
"Queue",
"(",
")",
"blender_to_qml",
"=",
"queue",
".",
"Queue",
"(",
")",
"def",
"threaded_wrapper",
"(",
"func",
",",
"*",
"args",
",",
... | Blender is a special snowflake
It doesn't have a mechanism with which to call commands from a thread
other than the main thread. So what's happening below is we run a polling
command every 10 milliseconds to see whether QML has any tasks for us.
If it does, then Blender runs this command (blocking while it does it),
and passes the result back to QML when ready.
The consequence of this is that we're polling even though nothing is
expected to arrive. The cost of polling is expected to be neglible,
but it's worth keeping in mind and ideally optimise away. E.g. only
poll when the QML window is actually open. | [
"Blender",
"is",
"a",
"special",
"snowflake"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L605-L679 | train | 205,167 |
pyblish/pyblish-qml | pyblish_qml/host.py | QtHost.install | def install(self, host):
"""Setup common to all Qt-based hosts"""
print("Installing..")
if self._state["installed"]:
return
if self.is_headless():
log.info("Headless host")
return
print("aboutToQuit..")
self.app.aboutToQuit.connect(self._on_application_quit)
if host == "Maya":
print("Maya host..")
window = {
widget.objectName(): widget
for widget in self.app.topLevelWidgets()
}["MayaWindow"]
else:
window = self.find_window()
# Install event filter
print("event filter..")
event_filter = self.EventFilter(window)
window.installEventFilter(event_filter)
for signal in SIGNALS_TO_REMOVE_EVENT_FILTER:
pyblish.api.register_callback(signal, self.uninstall)
log.info("Installed event filter")
self.window = window
self._state["installed"] = True
self._state["eventFilter"] = event_filter | python | def install(self, host):
"""Setup common to all Qt-based hosts"""
print("Installing..")
if self._state["installed"]:
return
if self.is_headless():
log.info("Headless host")
return
print("aboutToQuit..")
self.app.aboutToQuit.connect(self._on_application_quit)
if host == "Maya":
print("Maya host..")
window = {
widget.objectName(): widget
for widget in self.app.topLevelWidgets()
}["MayaWindow"]
else:
window = self.find_window()
# Install event filter
print("event filter..")
event_filter = self.EventFilter(window)
window.installEventFilter(event_filter)
for signal in SIGNALS_TO_REMOVE_EVENT_FILTER:
pyblish.api.register_callback(signal, self.uninstall)
log.info("Installed event filter")
self.window = window
self._state["installed"] = True
self._state["eventFilter"] = event_filter | [
"def",
"install",
"(",
"self",
",",
"host",
")",
":",
"print",
"(",
"\"Installing..\"",
")",
"if",
"self",
".",
"_state",
"[",
"\"installed\"",
"]",
":",
"return",
"if",
"self",
".",
"is_headless",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Headless ho... | Setup common to all Qt-based hosts | [
"Setup",
"common",
"to",
"all",
"Qt",
"-",
"based",
"hosts"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L393-L428 | train | 205,168 |
pyblish/pyblish-qml | pyblish_qml/host.py | QtHost.find_window | def find_window(self):
"""Get top window in host"""
window = self.app.activeWindow()
while True:
parent_window = window.parent()
if parent_window:
window = parent_window
else:
break
return window | python | def find_window(self):
"""Get top window in host"""
window = self.app.activeWindow()
while True:
parent_window = window.parent()
if parent_window:
window = parent_window
else:
break
return window | [
"def",
"find_window",
"(",
"self",
")",
":",
"window",
"=",
"self",
".",
"app",
".",
"activeWindow",
"(",
")",
"while",
"True",
":",
"parent_window",
"=",
"window",
".",
"parent",
"(",
")",
"if",
"parent_window",
":",
"window",
"=",
"parent_window",
"els... | Get top window in host | [
"Get",
"top",
"window",
"in",
"host"
] | 6095d18b2ec0afd0409a9b1a17e53b0658887283 | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/host.py#L465-L476 | train | 205,169 |
prompt-toolkit/ptpython | ptpython/key_bindings.py | tab_should_insert_whitespace | def tab_should_insert_whitespace():
"""
When the 'tab' key is pressed with only whitespace character before the
cursor, do autocompletion. Otherwise, insert indentation.
Except for the first character at the first line. Then always do a
completion. It doesn't make sense to start the first line with
indentation.
"""
b = get_app().current_buffer
before_cursor = b.document.current_line_before_cursor
return bool(b.text and (not before_cursor or before_cursor.isspace())) | python | def tab_should_insert_whitespace():
"""
When the 'tab' key is pressed with only whitespace character before the
cursor, do autocompletion. Otherwise, insert indentation.
Except for the first character at the first line. Then always do a
completion. It doesn't make sense to start the first line with
indentation.
"""
b = get_app().current_buffer
before_cursor = b.document.current_line_before_cursor
return bool(b.text and (not before_cursor or before_cursor.isspace())) | [
"def",
"tab_should_insert_whitespace",
"(",
")",
":",
"b",
"=",
"get_app",
"(",
")",
".",
"current_buffer",
"before_cursor",
"=",
"b",
".",
"document",
".",
"current_line_before_cursor",
"return",
"bool",
"(",
"b",
".",
"text",
"and",
"(",
"not",
"before_curso... | When the 'tab' key is pressed with only whitespace character before the
cursor, do autocompletion. Otherwise, insert indentation.
Except for the first character at the first line. Then always do a
completion. It doesn't make sense to start the first line with
indentation. | [
"When",
"the",
"tab",
"key",
"is",
"pressed",
"with",
"only",
"whitespace",
"character",
"before",
"the",
"cursor",
"do",
"autocompletion",
".",
"Otherwise",
"insert",
"indentation",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/key_bindings.py#L19-L31 | train | 205,170 |
prompt-toolkit/ptpython | ptpython/key_bindings.py | load_sidebar_bindings | def load_sidebar_bindings(python_input):
"""
Load bindings for the navigation in the sidebar.
"""
bindings = KeyBindings()
handle = bindings.add
sidebar_visible = Condition(lambda: python_input.show_sidebar)
@handle('up', filter=sidebar_visible)
@handle('c-p', filter=sidebar_visible)
@handle('k', filter=sidebar_visible)
def _(event):
" Go to previous option. "
python_input.selected_option_index = (
(python_input.selected_option_index - 1) % python_input.option_count)
@handle('down', filter=sidebar_visible)
@handle('c-n', filter=sidebar_visible)
@handle('j', filter=sidebar_visible)
def _(event):
" Go to next option. "
python_input.selected_option_index = (
(python_input.selected_option_index + 1) % python_input.option_count)
@handle('right', filter=sidebar_visible)
@handle('l', filter=sidebar_visible)
@handle(' ', filter=sidebar_visible)
def _(event):
" Select next value for current option. "
option = python_input.selected_option
option.activate_next()
@handle('left', filter=sidebar_visible)
@handle('h', filter=sidebar_visible)
def _(event):
" Select previous value for current option. "
option = python_input.selected_option
option.activate_previous()
@handle('c-c', filter=sidebar_visible)
@handle('c-d', filter=sidebar_visible)
@handle('c-d', filter=sidebar_visible)
@handle('enter', filter=sidebar_visible)
@handle('escape', filter=sidebar_visible)
def _(event):
" Hide sidebar. "
python_input.show_sidebar = False
event.app.layout.focus_last()
return bindings | python | def load_sidebar_bindings(python_input):
"""
Load bindings for the navigation in the sidebar.
"""
bindings = KeyBindings()
handle = bindings.add
sidebar_visible = Condition(lambda: python_input.show_sidebar)
@handle('up', filter=sidebar_visible)
@handle('c-p', filter=sidebar_visible)
@handle('k', filter=sidebar_visible)
def _(event):
" Go to previous option. "
python_input.selected_option_index = (
(python_input.selected_option_index - 1) % python_input.option_count)
@handle('down', filter=sidebar_visible)
@handle('c-n', filter=sidebar_visible)
@handle('j', filter=sidebar_visible)
def _(event):
" Go to next option. "
python_input.selected_option_index = (
(python_input.selected_option_index + 1) % python_input.option_count)
@handle('right', filter=sidebar_visible)
@handle('l', filter=sidebar_visible)
@handle(' ', filter=sidebar_visible)
def _(event):
" Select next value for current option. "
option = python_input.selected_option
option.activate_next()
@handle('left', filter=sidebar_visible)
@handle('h', filter=sidebar_visible)
def _(event):
" Select previous value for current option. "
option = python_input.selected_option
option.activate_previous()
@handle('c-c', filter=sidebar_visible)
@handle('c-d', filter=sidebar_visible)
@handle('c-d', filter=sidebar_visible)
@handle('enter', filter=sidebar_visible)
@handle('escape', filter=sidebar_visible)
def _(event):
" Hide sidebar. "
python_input.show_sidebar = False
event.app.layout.focus_last()
return bindings | [
"def",
"load_sidebar_bindings",
"(",
"python_input",
")",
":",
"bindings",
"=",
"KeyBindings",
"(",
")",
"handle",
"=",
"bindings",
".",
"add",
"sidebar_visible",
"=",
"Condition",
"(",
"lambda",
":",
"python_input",
".",
"show_sidebar",
")",
"@",
"handle",
"(... | Load bindings for the navigation in the sidebar. | [
"Load",
"bindings",
"for",
"the",
"navigation",
"in",
"the",
"sidebar",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/key_bindings.py#L178-L228 | train | 205,171 |
prompt-toolkit/ptpython | ptpython/key_bindings.py | auto_newline | def auto_newline(buffer):
r"""
Insert \n at the cursor position. Also add necessary padding.
"""
insert_text = buffer.insert_text
if buffer.document.current_line_after_cursor:
# When we are in the middle of a line. Always insert a newline.
insert_text('\n')
else:
# Go to new line, but also add indentation.
current_line = buffer.document.current_line_before_cursor.rstrip()
insert_text('\n')
# Unident if the last line ends with 'pass', remove four spaces.
unindent = current_line.rstrip().endswith(' pass')
# Copy whitespace from current line
current_line2 = current_line[4:] if unindent else current_line
for c in current_line2:
if c.isspace():
insert_text(c)
else:
break
# If the last line ends with a colon, add four extra spaces.
if current_line[-1:] == ':':
for x in range(4):
insert_text(' ') | python | def auto_newline(buffer):
r"""
Insert \n at the cursor position. Also add necessary padding.
"""
insert_text = buffer.insert_text
if buffer.document.current_line_after_cursor:
# When we are in the middle of a line. Always insert a newline.
insert_text('\n')
else:
# Go to new line, but also add indentation.
current_line = buffer.document.current_line_before_cursor.rstrip()
insert_text('\n')
# Unident if the last line ends with 'pass', remove four spaces.
unindent = current_line.rstrip().endswith(' pass')
# Copy whitespace from current line
current_line2 = current_line[4:] if unindent else current_line
for c in current_line2:
if c.isspace():
insert_text(c)
else:
break
# If the last line ends with a colon, add four extra spaces.
if current_line[-1:] == ':':
for x in range(4):
insert_text(' ') | [
"def",
"auto_newline",
"(",
"buffer",
")",
":",
"insert_text",
"=",
"buffer",
".",
"insert_text",
"if",
"buffer",
".",
"document",
".",
"current_line_after_cursor",
":",
"# When we are in the middle of a line. Always insert a newline.",
"insert_text",
"(",
"'\\n'",
")",
... | r"""
Insert \n at the cursor position. Also add necessary padding. | [
"r",
"Insert",
"\\",
"n",
"at",
"the",
"cursor",
"position",
".",
"Also",
"add",
"necessary",
"padding",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/key_bindings.py#L260-L289 | train | 205,172 |
prompt-toolkit/ptpython | ptpython/completer.py | PythonCompleter._path_completer_grammar | def _path_completer_grammar(self):
"""
Return the grammar for matching paths inside strings inside Python
code.
"""
# We make this lazy, because it delays startup time a little bit.
# This way, the grammar is build during the first completion.
if self._path_completer_grammar_cache is None:
self._path_completer_grammar_cache = self._create_path_completer_grammar()
return self._path_completer_grammar_cache | python | def _path_completer_grammar(self):
"""
Return the grammar for matching paths inside strings inside Python
code.
"""
# We make this lazy, because it delays startup time a little bit.
# This way, the grammar is build during the first completion.
if self._path_completer_grammar_cache is None:
self._path_completer_grammar_cache = self._create_path_completer_grammar()
return self._path_completer_grammar_cache | [
"def",
"_path_completer_grammar",
"(",
"self",
")",
":",
"# We make this lazy, because it delays startup time a little bit.",
"# This way, the grammar is build during the first completion.",
"if",
"self",
".",
"_path_completer_grammar_cache",
"is",
"None",
":",
"self",
".",
"_path_... | Return the grammar for matching paths inside strings inside Python
code. | [
"Return",
"the",
"grammar",
"for",
"matching",
"paths",
"inside",
"strings",
"inside",
"Python",
"code",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/completer.py#L40-L49 | train | 205,173 |
prompt-toolkit/ptpython | ptpython/completer.py | PythonCompleter.get_completions | def get_completions(self, document, complete_event):
"""
Get Python completions.
"""
# Do Path completions
if complete_event.completion_requested or self._complete_path_while_typing(document):
for c in self._path_completer.get_completions(document, complete_event):
yield c
# If we are inside a string, Don't do Jedi completion.
if self._path_completer_grammar.match(document.text_before_cursor):
return
# Do Jedi Python completions.
if complete_event.completion_requested or self._complete_python_while_typing(document):
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
if script:
try:
completions = script.completions()
except TypeError:
# Issue #9: bad syntax causes completions() to fail in jedi.
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/9
pass
except UnicodeDecodeError:
# Issue #43: UnicodeDecodeError on OpenBSD
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/43
pass
except AttributeError:
# Jedi issue #513: https://github.com/davidhalter/jedi/issues/513
pass
except ValueError:
# Jedi issue: "ValueError: invalid \x escape"
pass
except KeyError:
# Jedi issue: "KeyError: u'a_lambda'."
# https://github.com/jonathanslenders/ptpython/issues/89
pass
except IOError:
# Jedi issue: "IOError: No such file or directory."
# https://github.com/jonathanslenders/ptpython/issues/71
pass
except AssertionError:
# In jedi.parser.__init__.py: 227, in remove_last_newline,
# the assertion "newline.value.endswith('\n')" can fail.
pass
except SystemError:
# In jedi.api.helpers.py: 144, in get_stack_at_position
# raise SystemError("This really shouldn't happen. There's a bug in Jedi.")
pass
except NotImplementedError:
# See: https://github.com/jonathanslenders/ptpython/issues/223
pass
except Exception:
# Supress all other Jedi exceptions.
pass
else:
for c in completions:
yield Completion(c.name_with_symbols, len(c.complete) - len(c.name_with_symbols),
display=c.name_with_symbols) | python | def get_completions(self, document, complete_event):
"""
Get Python completions.
"""
# Do Path completions
if complete_event.completion_requested or self._complete_path_while_typing(document):
for c in self._path_completer.get_completions(document, complete_event):
yield c
# If we are inside a string, Don't do Jedi completion.
if self._path_completer_grammar.match(document.text_before_cursor):
return
# Do Jedi Python completions.
if complete_event.completion_requested or self._complete_python_while_typing(document):
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
if script:
try:
completions = script.completions()
except TypeError:
# Issue #9: bad syntax causes completions() to fail in jedi.
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/9
pass
except UnicodeDecodeError:
# Issue #43: UnicodeDecodeError on OpenBSD
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/43
pass
except AttributeError:
# Jedi issue #513: https://github.com/davidhalter/jedi/issues/513
pass
except ValueError:
# Jedi issue: "ValueError: invalid \x escape"
pass
except KeyError:
# Jedi issue: "KeyError: u'a_lambda'."
# https://github.com/jonathanslenders/ptpython/issues/89
pass
except IOError:
# Jedi issue: "IOError: No such file or directory."
# https://github.com/jonathanslenders/ptpython/issues/71
pass
except AssertionError:
# In jedi.parser.__init__.py: 227, in remove_last_newline,
# the assertion "newline.value.endswith('\n')" can fail.
pass
except SystemError:
# In jedi.api.helpers.py: 144, in get_stack_at_position
# raise SystemError("This really shouldn't happen. There's a bug in Jedi.")
pass
except NotImplementedError:
# See: https://github.com/jonathanslenders/ptpython/issues/223
pass
except Exception:
# Supress all other Jedi exceptions.
pass
else:
for c in completions:
yield Completion(c.name_with_symbols, len(c.complete) - len(c.name_with_symbols),
display=c.name_with_symbols) | [
"def",
"get_completions",
"(",
"self",
",",
"document",
",",
"complete_event",
")",
":",
"# Do Path completions",
"if",
"complete_event",
".",
"completion_requested",
"or",
"self",
".",
"_complete_path_while_typing",
"(",
"document",
")",
":",
"for",
"c",
"in",
"s... | Get Python completions. | [
"Get",
"Python",
"completions",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/completer.py#L107-L166 | train | 205,174 |
prompt-toolkit/ptpython | ptpython/eventloop.py | _inputhook_tk | def _inputhook_tk(inputhook_context):
"""
Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input.
"""
# Get the current TK application.
import _tkinter # Keep this imports inline!
from six.moves import tkinter
root = tkinter._default_root
def wait_using_filehandler():
"""
Run the TK eventloop until the file handler that we got from the
inputhook becomes readable.
"""
# Add a handler that sets the stop flag when `prompt-toolkit` has input
# to process.
stop = [False]
def done(*a):
stop[0] = True
root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
# Run the TK event loop as long as we don't receive input.
while root.dooneevent(_tkinter.ALL_EVENTS):
if stop[0]:
break
root.deletefilehandler(inputhook_context.fileno())
def wait_using_polling():
"""
Windows TK doesn't support 'createfilehandler'.
So, run the TK eventloop and poll until input is ready.
"""
while not inputhook_context.input_is_ready():
while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
pass
# Sleep to make the CPU idle, but not too long, so that the UI
# stays responsive.
time.sleep(.01)
if root is not None:
if hasattr(root, 'createfilehandler'):
wait_using_filehandler()
else:
wait_using_polling() | python | def _inputhook_tk(inputhook_context):
"""
Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input.
"""
# Get the current TK application.
import _tkinter # Keep this imports inline!
from six.moves import tkinter
root = tkinter._default_root
def wait_using_filehandler():
"""
Run the TK eventloop until the file handler that we got from the
inputhook becomes readable.
"""
# Add a handler that sets the stop flag when `prompt-toolkit` has input
# to process.
stop = [False]
def done(*a):
stop[0] = True
root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
# Run the TK event loop as long as we don't receive input.
while root.dooneevent(_tkinter.ALL_EVENTS):
if stop[0]:
break
root.deletefilehandler(inputhook_context.fileno())
def wait_using_polling():
"""
Windows TK doesn't support 'createfilehandler'.
So, run the TK eventloop and poll until input is ready.
"""
while not inputhook_context.input_is_ready():
while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
pass
# Sleep to make the CPU idle, but not too long, so that the UI
# stays responsive.
time.sleep(.01)
if root is not None:
if hasattr(root, 'createfilehandler'):
wait_using_filehandler()
else:
wait_using_polling() | [
"def",
"_inputhook_tk",
"(",
"inputhook_context",
")",
":",
"# Get the current TK application.",
"import",
"_tkinter",
"# Keep this imports inline!",
"from",
"six",
".",
"moves",
"import",
"tkinter",
"root",
"=",
"tkinter",
".",
"_default_root",
"def",
"wait_using_filehan... | Inputhook for Tk.
Run the Tk eventloop until prompt-toolkit needs to process the next input. | [
"Inputhook",
"for",
"Tk",
".",
"Run",
"the",
"Tk",
"eventloop",
"until",
"prompt",
"-",
"toolkit",
"needs",
"to",
"process",
"the",
"next",
"input",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/eventloop.py#L18-L64 | train | 205,175 |
prompt-toolkit/ptpython | ptpython/repl.py | run_config | def run_config(repl, config_file='~/.ptpython/config.py'):
"""
Execute REPL config file.
:param repl: `PythonInput` instance.
:param config_file: Path of the configuration file.
"""
assert isinstance(repl, PythonInput)
assert isinstance(config_file, six.text_type)
# Expand tildes.
config_file = os.path.expanduser(config_file)
def enter_to_continue():
six.moves.input('\nPress ENTER to continue...')
# Check whether this file exists.
if not os.path.exists(config_file):
print('Impossible to read %r' % config_file)
enter_to_continue()
return
# Run the config file in an empty namespace.
try:
namespace = {}
with open(config_file, 'rb') as f:
code = compile(f.read(), config_file, 'exec')
six.exec_(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with the repl as an argument.
if 'configure' in namespace:
namespace['configure'](repl)
except Exception:
traceback.print_exc()
enter_to_continue() | python | def run_config(repl, config_file='~/.ptpython/config.py'):
"""
Execute REPL config file.
:param repl: `PythonInput` instance.
:param config_file: Path of the configuration file.
"""
assert isinstance(repl, PythonInput)
assert isinstance(config_file, six.text_type)
# Expand tildes.
config_file = os.path.expanduser(config_file)
def enter_to_continue():
six.moves.input('\nPress ENTER to continue...')
# Check whether this file exists.
if not os.path.exists(config_file):
print('Impossible to read %r' % config_file)
enter_to_continue()
return
# Run the config file in an empty namespace.
try:
namespace = {}
with open(config_file, 'rb') as f:
code = compile(f.read(), config_file, 'exec')
six.exec_(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with the repl as an argument.
if 'configure' in namespace:
namespace['configure'](repl)
except Exception:
traceback.print_exc()
enter_to_continue() | [
"def",
"run_config",
"(",
"repl",
",",
"config_file",
"=",
"'~/.ptpython/config.py'",
")",
":",
"assert",
"isinstance",
"(",
"repl",
",",
"PythonInput",
")",
"assert",
"isinstance",
"(",
"config_file",
",",
"six",
".",
"text_type",
")",
"# Expand tildes.",
"conf... | Execute REPL config file.
:param repl: `PythonInput` instance.
:param config_file: Path of the configuration file. | [
"Execute",
"REPL",
"config",
"file",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/repl.py#L244-L281 | train | 205,176 |
prompt-toolkit/ptpython | ptpython/repl.py | PythonRepl._load_start_paths | def _load_start_paths(self):
" Start the Read-Eval-Print Loop. "
if self._startup_paths:
for path in self._startup_paths:
if os.path.exists(path):
with open(path, 'rb') as f:
code = compile(f.read(), path, 'exec')
six.exec_(code, self.get_globals(), self.get_locals())
else:
output = self.app.output
output.write('WARNING | File not found: {}\n\n'.format(path)) | python | def _load_start_paths(self):
" Start the Read-Eval-Print Loop. "
if self._startup_paths:
for path in self._startup_paths:
if os.path.exists(path):
with open(path, 'rb') as f:
code = compile(f.read(), path, 'exec')
six.exec_(code, self.get_globals(), self.get_locals())
else:
output = self.app.output
output.write('WARNING | File not found: {}\n\n'.format(path)) | [
"def",
"_load_start_paths",
"(",
"self",
")",
":",
"if",
"self",
".",
"_startup_paths",
":",
"for",
"path",
"in",
"self",
".",
"_startup_paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r... | Start the Read-Eval-Print Loop. | [
"Start",
"the",
"Read",
"-",
"Eval",
"-",
"Print",
"Loop",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/repl.py#L48-L58 | train | 205,177 |
prompt-toolkit/ptpython | ptpython/repl.py | PythonRepl._execute | def _execute(self, line):
"""
Evaluate the line and print the result.
"""
output = self.app.output
# WORKAROUND: Due to a bug in Jedi, the current directory is removed
# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
if '' not in sys.path:
sys.path.insert(0, '')
def compile_with_flags(code, mode):
" Compile code with the right compiler flags. "
return compile(code, '<stdin>', mode,
flags=self.get_compiler_flags(),
dont_inherit=True)
if line.lstrip().startswith('\x1a'):
# When the input starts with Ctrl-Z, quit the REPL.
self.app.exit()
elif line.lstrip().startswith('!'):
# Run as shell command
os.system(line[1:])
else:
# Try eval first
try:
code = compile_with_flags(line, 'eval')
result = eval(code, self.get_globals(), self.get_locals())
locals = self.get_locals()
locals['_'] = locals['_%i' % self.current_statement_index] = result
if result is not None:
out_prompt = self.get_output_prompt()
try:
result_str = '%r\n' % (result, )
except UnicodeDecodeError:
# In Python 2: `__repr__` should return a bytestring,
# so to put it in a unicode context could raise an
# exception that the 'ascii' codec can't decode certain
# characters. Decode as utf-8 in that case.
result_str = '%s\n' % repr(result).decode('utf-8')
# Align every line to the first one.
line_sep = '\n' + ' ' * fragment_list_width(out_prompt)
result_str = line_sep.join(result_str.splitlines()) + '\n'
# Write output tokens.
if self.enable_syntax_highlighting:
formatted_output = merge_formatted_text([
out_prompt,
PygmentsTokens(list(_lex_python_result(result_str))),
])
else:
formatted_output = FormattedText(
out_prompt + [('', result_str)])
print_formatted_text(
formatted_output, style=self._current_style,
style_transformation=self.style_transformation,
include_default_pygments_style=False)
# If not a valid `eval` expression, run using `exec` instead.
except SyntaxError:
code = compile_with_flags(line, 'exec')
six.exec_(code, self.get_globals(), self.get_locals())
output.flush() | python | def _execute(self, line):
"""
Evaluate the line and print the result.
"""
output = self.app.output
# WORKAROUND: Due to a bug in Jedi, the current directory is removed
# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
if '' not in sys.path:
sys.path.insert(0, '')
def compile_with_flags(code, mode):
" Compile code with the right compiler flags. "
return compile(code, '<stdin>', mode,
flags=self.get_compiler_flags(),
dont_inherit=True)
if line.lstrip().startswith('\x1a'):
# When the input starts with Ctrl-Z, quit the REPL.
self.app.exit()
elif line.lstrip().startswith('!'):
# Run as shell command
os.system(line[1:])
else:
# Try eval first
try:
code = compile_with_flags(line, 'eval')
result = eval(code, self.get_globals(), self.get_locals())
locals = self.get_locals()
locals['_'] = locals['_%i' % self.current_statement_index] = result
if result is not None:
out_prompt = self.get_output_prompt()
try:
result_str = '%r\n' % (result, )
except UnicodeDecodeError:
# In Python 2: `__repr__` should return a bytestring,
# so to put it in a unicode context could raise an
# exception that the 'ascii' codec can't decode certain
# characters. Decode as utf-8 in that case.
result_str = '%s\n' % repr(result).decode('utf-8')
# Align every line to the first one.
line_sep = '\n' + ' ' * fragment_list_width(out_prompt)
result_str = line_sep.join(result_str.splitlines()) + '\n'
# Write output tokens.
if self.enable_syntax_highlighting:
formatted_output = merge_formatted_text([
out_prompt,
PygmentsTokens(list(_lex_python_result(result_str))),
])
else:
formatted_output = FormattedText(
out_prompt + [('', result_str)])
print_formatted_text(
formatted_output, style=self._current_style,
style_transformation=self.style_transformation,
include_default_pygments_style=False)
# If not a valid `eval` expression, run using `exec` instead.
except SyntaxError:
code = compile_with_flags(line, 'exec')
six.exec_(code, self.get_globals(), self.get_locals())
output.flush() | [
"def",
"_execute",
"(",
"self",
",",
"line",
")",
":",
"output",
"=",
"self",
".",
"app",
".",
"output",
"# WORKAROUND: Due to a bug in Jedi, the current directory is removed",
"# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148",
"if",
"''",
"not",
"in",
... | Evaluate the line and print the result. | [
"Evaluate",
"the",
"line",
"and",
"print",
"the",
"result",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/repl.py#L97-L166 | train | 205,178 |
prompt-toolkit/ptpython | examples/asyncio-python-embed.py | interactive_shell | def interactive_shell():
"""
Coroutine that starts a Python REPL from which we can access the global
counter variable.
"""
print('You should be able to read and update the "counter[0]" variable from this shell.')
try:
yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)
except EOFError:
# Stop the loop when quitting the repl. (Ctrl-D press.)
loop.stop() | python | def interactive_shell():
"""
Coroutine that starts a Python REPL from which we can access the global
counter variable.
"""
print('You should be able to read and update the "counter[0]" variable from this shell.')
try:
yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)
except EOFError:
# Stop the loop when quitting the repl. (Ctrl-D press.)
loop.stop() | [
"def",
"interactive_shell",
"(",
")",
":",
"print",
"(",
"'You should be able to read and update the \"counter[0]\" variable from this shell.'",
")",
"try",
":",
"yield",
"from",
"embed",
"(",
"globals",
"=",
"globals",
"(",
")",
",",
"return_asyncio_coroutine",
"=",
"T... | Coroutine that starts a Python REPL from which we can access the global
counter variable. | [
"Coroutine",
"that",
"starts",
"a",
"Python",
"REPL",
"from",
"which",
"we",
"can",
"access",
"the",
"global",
"counter",
"variable",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/examples/asyncio-python-embed.py#L35-L45 | train | 205,179 |
prompt-toolkit/ptpython | ptpython/validator.py | PythonValidator.validate | def validate(self, document):
"""
Check input for Python syntax errors.
"""
# When the input starts with Ctrl-Z, always accept. This means EOF in a
# Python REPL.
if document.text.startswith('\x1a'):
return
try:
if self.get_compiler_flags:
flags = self.get_compiler_flags()
else:
flags = 0
compile(document.text, '<input>', 'exec', flags=flags, dont_inherit=True)
except SyntaxError as e:
# Note, the 'or 1' for offset is required because Python 2.7
# gives `None` as offset in case of '4=4' as input. (Looks like
# fixed in Python 3.)
index = document.translate_row_col_to_index(e.lineno - 1, (e.offset or 1) - 1)
raise ValidationError(index, 'Syntax Error')
except TypeError as e:
# e.g. "compile() expected string without null bytes"
raise ValidationError(0, str(e))
except ValueError as e:
# In Python 2, compiling "\x9" (an invalid escape sequence) raises
# ValueError instead of SyntaxError.
raise ValidationError(0, 'Syntax Error: %s' % e) | python | def validate(self, document):
"""
Check input for Python syntax errors.
"""
# When the input starts with Ctrl-Z, always accept. This means EOF in a
# Python REPL.
if document.text.startswith('\x1a'):
return
try:
if self.get_compiler_flags:
flags = self.get_compiler_flags()
else:
flags = 0
compile(document.text, '<input>', 'exec', flags=flags, dont_inherit=True)
except SyntaxError as e:
# Note, the 'or 1' for offset is required because Python 2.7
# gives `None` as offset in case of '4=4' as input. (Looks like
# fixed in Python 3.)
index = document.translate_row_col_to_index(e.lineno - 1, (e.offset or 1) - 1)
raise ValidationError(index, 'Syntax Error')
except TypeError as e:
# e.g. "compile() expected string without null bytes"
raise ValidationError(0, str(e))
except ValueError as e:
# In Python 2, compiling "\x9" (an invalid escape sequence) raises
# ValueError instead of SyntaxError.
raise ValidationError(0, 'Syntax Error: %s' % e) | [
"def",
"validate",
"(",
"self",
",",
"document",
")",
":",
"# When the input starts with Ctrl-Z, always accept. This means EOF in a",
"# Python REPL.",
"if",
"document",
".",
"text",
".",
"startswith",
"(",
"'\\x1a'",
")",
":",
"return",
"try",
":",
"if",
"self",
".... | Check input for Python syntax errors. | [
"Check",
"input",
"for",
"Python",
"syntax",
"errors",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/validator.py#L19-L47 | train | 205,180 |
prompt-toolkit/ptpython | examples/asyncio-ssh-python-embed.py | main | def main(port=8222):
"""
Example that starts the REPL through an SSH server.
"""
loop = asyncio.get_event_loop()
# Namespace exposed in the REPL.
environ = {'hello': 'world'}
# Start SSH server.
def create_server():
return MySSHServer(lambda: environ)
print('Listening on :%i' % port)
print('To connect, do "ssh localhost -p %i"' % port)
loop.run_until_complete(
asyncssh.create_server(create_server, '', port,
server_host_keys=['/etc/ssh/ssh_host_dsa_key']))
# Run eventloop.
loop.run_forever() | python | def main(port=8222):
"""
Example that starts the REPL through an SSH server.
"""
loop = asyncio.get_event_loop()
# Namespace exposed in the REPL.
environ = {'hello': 'world'}
# Start SSH server.
def create_server():
return MySSHServer(lambda: environ)
print('Listening on :%i' % port)
print('To connect, do "ssh localhost -p %i"' % port)
loop.run_until_complete(
asyncssh.create_server(create_server, '', port,
server_host_keys=['/etc/ssh/ssh_host_dsa_key']))
# Run eventloop.
loop.run_forever() | [
"def",
"main",
"(",
"port",
"=",
"8222",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"# Namespace exposed in the REPL.",
"environ",
"=",
"{",
"'hello'",
":",
"'world'",
"}",
"# Start SSH server.",
"def",
"create_server",
"(",
")",
":",
... | Example that starts the REPL through an SSH server. | [
"Example",
"that",
"starts",
"the",
"REPL",
"through",
"an",
"SSH",
"server",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/examples/asyncio-ssh-python-embed.py#L33-L54 | train | 205,181 |
prompt-toolkit/ptpython | ptpython/contrib/asyncssh_repl.py | ReplSSHServerSession._get_size | def _get_size(self):
"""
Callable that returns the current `Size`, required by Vt100_Output.
"""
if self._chan is None:
return Size(rows=20, columns=79)
else:
width, height, pixwidth, pixheight = self._chan.get_terminal_size()
return Size(rows=height, columns=width) | python | def _get_size(self):
"""
Callable that returns the current `Size`, required by Vt100_Output.
"""
if self._chan is None:
return Size(rows=20, columns=79)
else:
width, height, pixwidth, pixheight = self._chan.get_terminal_size()
return Size(rows=height, columns=width) | [
"def",
"_get_size",
"(",
"self",
")",
":",
"if",
"self",
".",
"_chan",
"is",
"None",
":",
"return",
"Size",
"(",
"rows",
"=",
"20",
",",
"columns",
"=",
"79",
")",
"else",
":",
"width",
",",
"height",
",",
"pixwidth",
",",
"pixheight",
"=",
"self",... | Callable that returns the current `Size`, required by Vt100_Output. | [
"Callable",
"that",
"returns",
"the",
"current",
"Size",
"required",
"by",
"Vt100_Output",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/contrib/asyncssh_repl.py#L78-L86 | train | 205,182 |
prompt-toolkit/ptpython | ptpython/contrib/asyncssh_repl.py | ReplSSHServerSession.connection_made | def connection_made(self, chan):
"""
Client connected, run repl in coroutine.
"""
self._chan = chan
# Run REPL interface.
f = asyncio.ensure_future(self.cli.run_async())
# Close channel when done.
def done(_):
chan.close()
self._chan = None
f.add_done_callback(done) | python | def connection_made(self, chan):
"""
Client connected, run repl in coroutine.
"""
self._chan = chan
# Run REPL interface.
f = asyncio.ensure_future(self.cli.run_async())
# Close channel when done.
def done(_):
chan.close()
self._chan = None
f.add_done_callback(done) | [
"def",
"connection_made",
"(",
"self",
",",
"chan",
")",
":",
"self",
".",
"_chan",
"=",
"chan",
"# Run REPL interface.",
"f",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"cli",
".",
"run_async",
"(",
")",
")",
"# Close channel when done.",
"def"... | Client connected, run repl in coroutine. | [
"Client",
"connected",
"run",
"repl",
"in",
"coroutine",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/contrib/asyncssh_repl.py#L88-L101 | train | 205,183 |
prompt-toolkit/ptpython | examples/ptpython_config/config.py | configure | def configure(repl):
"""
Configuration method. This is called during the start-up of ptpython.
:param repl: `PythonRepl` instance.
"""
# Show function signature (bool).
repl.show_signature = True
# Show docstring (bool).
repl.show_docstring = False
# Show the "[Meta+Enter] Execute" message when pressing [Enter] only
# inserts a newline instead of executing the code.
repl.show_meta_enter_message = True
# Show completions. (NONE, POP_UP, MULTI_COLUMN or TOOLBAR)
repl.completion_visualisation = CompletionVisualisation.POP_UP
# When CompletionVisualisation.POP_UP has been chosen, use this
# scroll_offset in the completion menu.
repl.completion_menu_scroll_offset = 0
# Show line numbers (when the input contains multiple lines.)
repl.show_line_numbers = False
# Show status bar.
repl.show_status_bar = True
# When the sidebar is visible, also show the help text.
repl.show_sidebar_help = True
# Highlight matching parethesis.
repl.highlight_matching_parenthesis = True
# Line wrapping. (Instead of horizontal scrolling.)
repl.wrap_lines = True
# Mouse support.
repl.enable_mouse_support = True
# Complete while typing. (Don't require tab before the
# completion menu is shown.)
repl.complete_while_typing = True
# Vi mode.
repl.vi_mode = False
# Paste mode. (When True, don't insert whitespace after new line.)
repl.paste_mode = False
# Use the classic prompt. (Display '>>>' instead of 'In [1]'.)
repl.prompt_style = 'classic' # 'classic' or 'ipython'
# Don't insert a blank line after the output.
repl.insert_blank_line_after_output = False
# History Search.
# When True, going back in history will filter the history on the records
# starting with the current input. (Like readline.)
# Note: When enable, please disable the `complete_while_typing` option.
# otherwise, when there is a completion available, the arrows will
# browse through the available completions instead of the history.
repl.enable_history_search = False
# Enable auto suggestions. (Pressing right arrow will complete the input,
# based on the history.)
repl.enable_auto_suggest = False
# Enable open-in-editor. Pressing C-X C-E in emacs mode or 'v' in
# Vi navigation mode will open the input in the current editor.
repl.enable_open_in_editor = True
# Enable system prompt. Pressing meta-! will display the system prompt.
# Also enables Control-Z suspend.
repl.enable_system_bindings = True
# Ask for confirmation on exit.
repl.confirm_exit = True
# Enable input validation. (Don't try to execute when the input contains
# syntax errors.)
repl.enable_input_validation = True
# Use this colorscheme for the code.
repl.use_code_colorscheme('pastie')
# Set color depth (keep in mind that not all terminals support true color).
#repl.color_depth = 'DEPTH_1_BIT' # Monochrome.
#repl.color_depth = 'DEPTH_4_BIT' # ANSI colors only.
repl.color_depth = 'DEPTH_8_BIT' # The default, 256 colors.
#repl.color_depth = 'DEPTH_24_BIT' # True color.
# Syntax.
repl.enable_syntax_highlighting = True
# Install custom colorscheme named 'my-colorscheme' and use it.
"""
repl.install_ui_colorscheme('my-colorscheme', _custom_ui_colorscheme)
repl.use_ui_colorscheme('my-colorscheme')
"""
# Add custom key binding for PDB.
"""
@repl.add_key_binding(Keys.ControlB)
def _(event):
' Pressing Control-B will insert "pdb.set_trace()" '
event.cli.current_buffer.insert_text('\nimport pdb; pdb.set_trace()\n')
"""
# Typing ControlE twice should also execute the current command.
# (Alternative for Meta-Enter.)
"""
@repl.add_key_binding(Keys.ControlE, Keys.ControlE)
def _(event):
event.current_buffer.validate_and_handle()
"""
# Typing 'jj' in Vi Insert mode, should send escape. (Go back to navigation
# mode.)
"""
@repl.add_key_binding('j', 'j', filter=ViInsertMode())
def _(event):
" Map 'jj' to Escape. "
event.cli.key_processor.feed(KeyPress(Keys.Escape))
"""
# Custom key binding for some simple autocorrection while typing.
"""
corrections = {
'impotr': 'import',
'pritn': 'print',
}
@repl.add_key_binding(' ')
def _(event):
' When a space is pressed. Check & correct word before cursor. '
b = event.cli.current_buffer
w = b.document.get_word_before_cursor()
if w is not None:
if w in corrections:
b.delete_before_cursor(count=len(w))
b.insert_text(corrections[w])
b.insert_text(' ')
""" | python | def configure(repl):
"""
Configuration method. This is called during the start-up of ptpython.
:param repl: `PythonRepl` instance.
"""
# Show function signature (bool).
repl.show_signature = True
# Show docstring (bool).
repl.show_docstring = False
# Show the "[Meta+Enter] Execute" message when pressing [Enter] only
# inserts a newline instead of executing the code.
repl.show_meta_enter_message = True
# Show completions. (NONE, POP_UP, MULTI_COLUMN or TOOLBAR)
repl.completion_visualisation = CompletionVisualisation.POP_UP
# When CompletionVisualisation.POP_UP has been chosen, use this
# scroll_offset in the completion menu.
repl.completion_menu_scroll_offset = 0
# Show line numbers (when the input contains multiple lines.)
repl.show_line_numbers = False
# Show status bar.
repl.show_status_bar = True
# When the sidebar is visible, also show the help text.
repl.show_sidebar_help = True
# Highlight matching parethesis.
repl.highlight_matching_parenthesis = True
# Line wrapping. (Instead of horizontal scrolling.)
repl.wrap_lines = True
# Mouse support.
repl.enable_mouse_support = True
# Complete while typing. (Don't require tab before the
# completion menu is shown.)
repl.complete_while_typing = True
# Vi mode.
repl.vi_mode = False
# Paste mode. (When True, don't insert whitespace after new line.)
repl.paste_mode = False
# Use the classic prompt. (Display '>>>' instead of 'In [1]'.)
repl.prompt_style = 'classic' # 'classic' or 'ipython'
# Don't insert a blank line after the output.
repl.insert_blank_line_after_output = False
# History Search.
# When True, going back in history will filter the history on the records
# starting with the current input. (Like readline.)
# Note: When enable, please disable the `complete_while_typing` option.
# otherwise, when there is a completion available, the arrows will
# browse through the available completions instead of the history.
repl.enable_history_search = False
# Enable auto suggestions. (Pressing right arrow will complete the input,
# based on the history.)
repl.enable_auto_suggest = False
# Enable open-in-editor. Pressing C-X C-E in emacs mode or 'v' in
# Vi navigation mode will open the input in the current editor.
repl.enable_open_in_editor = True
# Enable system prompt. Pressing meta-! will display the system prompt.
# Also enables Control-Z suspend.
repl.enable_system_bindings = True
# Ask for confirmation on exit.
repl.confirm_exit = True
# Enable input validation. (Don't try to execute when the input contains
# syntax errors.)
repl.enable_input_validation = True
# Use this colorscheme for the code.
repl.use_code_colorscheme('pastie')
# Set color depth (keep in mind that not all terminals support true color).
#repl.color_depth = 'DEPTH_1_BIT' # Monochrome.
#repl.color_depth = 'DEPTH_4_BIT' # ANSI colors only.
repl.color_depth = 'DEPTH_8_BIT' # The default, 256 colors.
#repl.color_depth = 'DEPTH_24_BIT' # True color.
# Syntax.
repl.enable_syntax_highlighting = True
# Install custom colorscheme named 'my-colorscheme' and use it.
"""
repl.install_ui_colorscheme('my-colorscheme', _custom_ui_colorscheme)
repl.use_ui_colorscheme('my-colorscheme')
"""
# Add custom key binding for PDB.
"""
@repl.add_key_binding(Keys.ControlB)
def _(event):
' Pressing Control-B will insert "pdb.set_trace()" '
event.cli.current_buffer.insert_text('\nimport pdb; pdb.set_trace()\n')
"""
# Typing ControlE twice should also execute the current command.
# (Alternative for Meta-Enter.)
"""
@repl.add_key_binding(Keys.ControlE, Keys.ControlE)
def _(event):
event.current_buffer.validate_and_handle()
"""
# Typing 'jj' in Vi Insert mode, should send escape. (Go back to navigation
# mode.)
"""
@repl.add_key_binding('j', 'j', filter=ViInsertMode())
def _(event):
" Map 'jj' to Escape. "
event.cli.key_processor.feed(KeyPress(Keys.Escape))
"""
# Custom key binding for some simple autocorrection while typing.
"""
corrections = {
'impotr': 'import',
'pritn': 'print',
}
@repl.add_key_binding(' ')
def _(event):
' When a space is pressed. Check & correct word before cursor. '
b = event.cli.current_buffer
w = b.document.get_word_before_cursor()
if w is not None:
if w in corrections:
b.delete_before_cursor(count=len(w))
b.insert_text(corrections[w])
b.insert_text(' ')
""" | [
"def",
"configure",
"(",
"repl",
")",
":",
"# Show function signature (bool).",
"repl",
".",
"show_signature",
"=",
"True",
"# Show docstring (bool).",
"repl",
".",
"show_docstring",
"=",
"False",
"# Show the \"[Meta+Enter] Execute\" message when pressing [Enter] only",
"# inse... | Configuration method. This is called during the start-up of ptpython.
:param repl: `PythonRepl` instance. | [
"Configuration",
"method",
".",
"This",
"is",
"called",
"during",
"the",
"start",
"-",
"up",
"of",
"ptpython",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/examples/ptpython_config/config.py#L19-L167 | train | 205,184 |
prompt-toolkit/ptpython | ptpython/utils.py | has_unclosed_brackets | def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False | python | def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False | [
"def",
"has_unclosed_brackets",
"(",
"text",
")",
":",
"stack",
"=",
"[",
"]",
"# Ignore braces inside strings",
"text",
"=",
"re",
".",
"sub",
"(",
"r'''('[^']*'|\"[^\"]*\")'''",
",",
"''",
",",
"text",
")",
"# XXX: handle escaped quotes.!",
"for",
"c",
"in",
"... | Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True. | [
"Starting",
"at",
"the",
"end",
"of",
"the",
"string",
".",
"If",
"we",
"find",
"an",
"opening",
"bracket",
"for",
"which",
"we",
"didn",
"t",
"had",
"a",
"closing",
"one",
"yet",
"return",
"True",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/utils.py#L16-L40 | train | 205,185 |
prompt-toolkit/ptpython | ptpython/utils.py | document_is_multiline_python | def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False | python | def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False | [
"def",
"document_is_multiline_python",
"(",
"document",
")",
":",
"def",
"ends_in_multiline_string",
"(",
")",
":",
"\"\"\"\n ``True`` if we're inside a multiline string at the end of the text.\n \"\"\"",
"delims",
"=",
"_multiline_string_delims",
".",
"findall",
"(",... | Determine whether this is a multiline Python document. | [
"Determine",
"whether",
"this",
"is",
"a",
"multiline",
"Python",
"document",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/utils.py#L76-L111 | train | 205,186 |
prompt-toolkit/ptpython | ptpython/utils.py | if_mousedown | def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(mouse_event):
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
return handler(mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | python | def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(mouse_event):
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
return handler(mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | [
"def",
"if_mousedown",
"(",
"handler",
")",
":",
"def",
"handle_if_mouse_down",
"(",
"mouse_event",
")",
":",
"if",
"mouse_event",
".",
"event_type",
"==",
"MouseEventType",
".",
"MOUSE_DOWN",
":",
"return",
"handler",
"(",
"mouse_event",
")",
"else",
":",
"re... | Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.) | [
"Decorator",
"for",
"mouse",
"handlers",
".",
"Only",
"handle",
"event",
"when",
"the",
"user",
"pressed",
"mouse",
"down",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/utils.py#L114-L127 | train | 205,187 |
prompt-toolkit/ptpython | ptpython/history_browser.py | _create_popup_window | def _create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return Frame(body=body, title=title) | python | def _create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return Frame(body=body, title=title) | [
"def",
"_create_popup_window",
"(",
"title",
",",
"body",
")",
":",
"assert",
"isinstance",
"(",
"title",
",",
"six",
".",
"text_type",
")",
"assert",
"isinstance",
"(",
"body",
",",
"Container",
")",
"return",
"Frame",
"(",
"body",
"=",
"body",
",",
"ti... | Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders. | [
"Return",
"the",
"layout",
"for",
"a",
"pop",
"-",
"up",
"window",
".",
"It",
"consists",
"of",
"a",
"title",
"bar",
"showing",
"the",
"title",
"text",
"and",
"a",
"body",
"layout",
".",
"The",
"window",
"is",
"surrounded",
"by",
"borders",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/history_browser.py#L97-L104 | train | 205,188 |
prompt-toolkit/ptpython | ptpython/history_browser.py | HistoryMapping.get_new_document | def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos) | python | def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos) | [
"def",
"get_new_document",
"(",
"self",
",",
"cursor_pos",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"# Original text, before cursor.",
"if",
"self",
".",
"original_document",
".",
"text_before_cursor",
":",
"lines",
".",
"append",
"(",
"self",
".",
"orig... | Create a `Document` instance that contains the resulting text. | [
"Create",
"a",
"Document",
"instance",
"that",
"contains",
"the",
"resulting",
"text",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/history_browser.py#L353-L375 | train | 205,189 |
prompt-toolkit/ptpython | ptpython/history_browser.py | History._default_buffer_pos_changed | def _default_buffer_pos_changed(self, _):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if self.app.current_buffer == self.default_buffer:
try:
line_no = self.default_buffer.document.cursor_position_row - \
self.history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(self.history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
self.history_buffer.cursor_position = \
self.history_buffer.document.translate_row_col_to_index(history_lineno, 0) | python | def _default_buffer_pos_changed(self, _):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if self.app.current_buffer == self.default_buffer:
try:
line_no = self.default_buffer.document.cursor_position_row - \
self.history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(self.history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
self.history_buffer.cursor_position = \
self.history_buffer.document.translate_row_col_to_index(history_lineno, 0) | [
"def",
"_default_buffer_pos_changed",
"(",
"self",
",",
"_",
")",
":",
"# Only when this buffer has the focus.",
"if",
"self",
".",
"app",
".",
"current_buffer",
"==",
"self",
".",
"default_buffer",
":",
"try",
":",
"line_no",
"=",
"self",
".",
"default_buffer",
... | When the cursor changes in the default buffer. Synchronize with
history buffer. | [
"When",
"the",
"cursor",
"changes",
"in",
"the",
"default",
"buffer",
".",
"Synchronize",
"with",
"history",
"buffer",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/history_browser.py#L563-L580 | train | 205,190 |
prompt-toolkit/ptpython | ptpython/history_browser.py | History._history_buffer_pos_changed | def _history_buffer_pos_changed(self, _):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if self.app.current_buffer == self.history_buffer:
line_no = self.history_buffer.document.cursor_position_row
if line_no in self.history_mapping.selected_lines:
default_lineno = sorted(self.history_mapping.selected_lines).index(line_no) + \
self.history_mapping.result_line_offset
self.default_buffer.cursor_position = \
self.default_buffer.document.translate_row_col_to_index(default_lineno, 0) | python | def _history_buffer_pos_changed(self, _):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if self.app.current_buffer == self.history_buffer:
line_no = self.history_buffer.document.cursor_position_row
if line_no in self.history_mapping.selected_lines:
default_lineno = sorted(self.history_mapping.selected_lines).index(line_no) + \
self.history_mapping.result_line_offset
self.default_buffer.cursor_position = \
self.default_buffer.document.translate_row_col_to_index(default_lineno, 0) | [
"def",
"_history_buffer_pos_changed",
"(",
"self",
",",
"_",
")",
":",
"# Only when this buffer has the focus.",
"if",
"self",
".",
"app",
".",
"current_buffer",
"==",
"self",
".",
"history_buffer",
":",
"line_no",
"=",
"self",
".",
"history_buffer",
".",
"documen... | When the cursor changes in the history buffer. Synchronize. | [
"When",
"the",
"cursor",
"changes",
"in",
"the",
"history",
"buffer",
".",
"Synchronize",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/history_browser.py#L582-L593 | train | 205,191 |
prompt-toolkit/ptpython | ptpython/layout.py | python_sidebar | def python_sidebar(python_input):
"""
Create the `Layout` for the sidebar with the configurable options.
"""
def get_text_fragments():
tokens = []
def append_category(category):
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.title', ' %-36s' % category.title),
('class:sidebar', '\n'),
])
def append(index, label, status):
selected = index == python_input.selected_option_index
@if_mousedown
def select_item(mouse_event):
python_input.selected_option_index = index
@if_mousedown
def goto_next(mouse_event):
" Select item and go to next value. "
python_input.selected_option_index = index
option = python_input.selected_option
option.activate_next()
sel = ',selected' if selected else ''
tokens.append(('class:sidebar' + sel, ' >' if selected else ' '))
tokens.append(('class:sidebar.label' + sel, '%-24s' % label, select_item))
tokens.append(('class:sidebar.status' + sel, ' ', select_item))
tokens.append(('class:sidebar.status' + sel, '%s' % status, goto_next))
if selected:
tokens.append(('[SetCursorPosition]', ''))
tokens.append(('class:sidebar.status' + sel, ' ' * (13 - len(status)), goto_next))
tokens.append(('class:sidebar', '<' if selected else ''))
tokens.append(('class:sidebar', '\n'))
i = 0
for category in python_input.options:
append_category(category)
for option in category.options:
append(i, option.title, '%s' % option.get_current_value())
i += 1
tokens.pop() # Remove last newline.
return tokens
class Control(FormattedTextControl):
def move_cursor_down(self):
python_input.selected_option_index += 1
def move_cursor_up(self):
python_input.selected_option_index -= 1
return Window(
Control(get_text_fragments),
style='class:sidebar',
width=Dimension.exact(43),
height=Dimension(min=3),
scroll_offsets=ScrollOffsets(top=1, bottom=1)) | python | def python_sidebar(python_input):
"""
Create the `Layout` for the sidebar with the configurable options.
"""
def get_text_fragments():
tokens = []
def append_category(category):
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.title', ' %-36s' % category.title),
('class:sidebar', '\n'),
])
def append(index, label, status):
selected = index == python_input.selected_option_index
@if_mousedown
def select_item(mouse_event):
python_input.selected_option_index = index
@if_mousedown
def goto_next(mouse_event):
" Select item and go to next value. "
python_input.selected_option_index = index
option = python_input.selected_option
option.activate_next()
sel = ',selected' if selected else ''
tokens.append(('class:sidebar' + sel, ' >' if selected else ' '))
tokens.append(('class:sidebar.label' + sel, '%-24s' % label, select_item))
tokens.append(('class:sidebar.status' + sel, ' ', select_item))
tokens.append(('class:sidebar.status' + sel, '%s' % status, goto_next))
if selected:
tokens.append(('[SetCursorPosition]', ''))
tokens.append(('class:sidebar.status' + sel, ' ' * (13 - len(status)), goto_next))
tokens.append(('class:sidebar', '<' if selected else ''))
tokens.append(('class:sidebar', '\n'))
i = 0
for category in python_input.options:
append_category(category)
for option in category.options:
append(i, option.title, '%s' % option.get_current_value())
i += 1
tokens.pop() # Remove last newline.
return tokens
class Control(FormattedTextControl):
def move_cursor_down(self):
python_input.selected_option_index += 1
def move_cursor_up(self):
python_input.selected_option_index -= 1
return Window(
Control(get_text_fragments),
style='class:sidebar',
width=Dimension.exact(43),
height=Dimension(min=3),
scroll_offsets=ScrollOffsets(top=1, bottom=1)) | [
"def",
"python_sidebar",
"(",
"python_input",
")",
":",
"def",
"get_text_fragments",
"(",
")",
":",
"tokens",
"=",
"[",
"]",
"def",
"append_category",
"(",
"category",
")",
":",
"tokens",
".",
"extend",
"(",
"[",
"(",
"'class:sidebar'",
",",
"' '",
")",
... | Create the `Layout` for the sidebar with the configurable options. | [
"Create",
"the",
"Layout",
"for",
"the",
"sidebar",
"with",
"the",
"configurable",
"options",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L70-L136 | train | 205,192 |
prompt-toolkit/ptpython | ptpython/layout.py | python_sidebar_navigation | def python_sidebar_navigation(python_input):
"""
Create the `Layout` showing the navigation information for the sidebar.
"""
def get_text_fragments():
tokens = []
# Show navigation info.
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.key', '[Arrows]'),
('class:sidebar', ' '),
('class:sidebar.description', 'Navigate'),
('class:sidebar', ' '),
('class:sidebar.key', '[Enter]'),
('class:sidebar', ' '),
('class:sidebar.description', 'Hide menu'),
])
return tokens
return Window(
FormattedTextControl(get_text_fragments),
style='class:sidebar',
width=Dimension.exact(43),
height=Dimension.exact(1)) | python | def python_sidebar_navigation(python_input):
"""
Create the `Layout` showing the navigation information for the sidebar.
"""
def get_text_fragments():
tokens = []
# Show navigation info.
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.key', '[Arrows]'),
('class:sidebar', ' '),
('class:sidebar.description', 'Navigate'),
('class:sidebar', ' '),
('class:sidebar.key', '[Enter]'),
('class:sidebar', ' '),
('class:sidebar.description', 'Hide menu'),
])
return tokens
return Window(
FormattedTextControl(get_text_fragments),
style='class:sidebar',
width=Dimension.exact(43),
height=Dimension.exact(1)) | [
"def",
"python_sidebar_navigation",
"(",
"python_input",
")",
":",
"def",
"get_text_fragments",
"(",
")",
":",
"tokens",
"=",
"[",
"]",
"# Show navigation info.",
"tokens",
".",
"extend",
"(",
"[",
"(",
"'class:sidebar'",
",",
"' '",
")",
",",
"(",
"'class:... | Create the `Layout` showing the navigation information for the sidebar. | [
"Create",
"the",
"Layout",
"showing",
"the",
"navigation",
"information",
"for",
"the",
"sidebar",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L139-L164 | train | 205,193 |
prompt-toolkit/ptpython | ptpython/layout.py | python_sidebar_help | def python_sidebar_help(python_input):
"""
Create the `Layout` for the help text for the current item in the sidebar.
"""
token = 'class:sidebar.helptext'
def get_current_description():
"""
Return the description of the selected option.
"""
i = 0
for category in python_input.options:
for option in category.options:
if i == python_input.selected_option_index:
return option.description
i += 1
return ''
def get_help_text():
return [(token, get_current_description())]
return ConditionalContainer(
content=Window(
FormattedTextControl(get_help_text),
style=token,
height=Dimension(min=3)),
filter=ShowSidebar(python_input) &
Condition(lambda: python_input.show_sidebar_help) & ~is_done) | python | def python_sidebar_help(python_input):
"""
Create the `Layout` for the help text for the current item in the sidebar.
"""
token = 'class:sidebar.helptext'
def get_current_description():
"""
Return the description of the selected option.
"""
i = 0
for category in python_input.options:
for option in category.options:
if i == python_input.selected_option_index:
return option.description
i += 1
return ''
def get_help_text():
return [(token, get_current_description())]
return ConditionalContainer(
content=Window(
FormattedTextControl(get_help_text),
style=token,
height=Dimension(min=3)),
filter=ShowSidebar(python_input) &
Condition(lambda: python_input.show_sidebar_help) & ~is_done) | [
"def",
"python_sidebar_help",
"(",
"python_input",
")",
":",
"token",
"=",
"'class:sidebar.helptext'",
"def",
"get_current_description",
"(",
")",
":",
"\"\"\"\n Return the description of the selected option.\n \"\"\"",
"i",
"=",
"0",
"for",
"category",
"in",
... | Create the `Layout` for the help text for the current item in the sidebar. | [
"Create",
"the",
"Layout",
"for",
"the",
"help",
"text",
"for",
"the",
"current",
"item",
"in",
"the",
"sidebar",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L167-L194 | train | 205,194 |
prompt-toolkit/ptpython | ptpython/layout.py | signature_toolbar | def signature_toolbar(python_input):
"""
Return the `Layout` for the signature.
"""
def get_text_fragments():
result = []
append = result.append
Signature = 'class:signature-toolbar'
if python_input.signatures:
sig = python_input.signatures[0] # Always take the first one.
append((Signature, ' '))
try:
append((Signature, sig.full_name))
except IndexError:
# Workaround for #37: https://github.com/jonathanslenders/python-prompt-toolkit/issues/37
# See also: https://github.com/davidhalter/jedi/issues/490
return []
append((Signature + ',operator', '('))
try:
enumerated_params = enumerate(sig.params)
except AttributeError:
# Workaround for #136: https://github.com/jonathanslenders/ptpython/issues/136
# AttributeError: 'Lambda' object has no attribute 'get_subscope_by_name'
return []
for i, p in enumerated_params:
# Workaround for #47: 'p' is None when we hit the '*' in the signature.
# and sig has no 'index' attribute.
# See: https://github.com/jonathanslenders/ptpython/issues/47
# https://github.com/davidhalter/jedi/issues/598
description = (p.description if p else '*') #or '*'
sig_index = getattr(sig, 'index', 0)
if i == sig_index:
# Note: we use `_Param.description` instead of
# `_Param.name`, that way we also get the '*' before args.
append((Signature + ',current-name', str(description)))
else:
append((Signature, str(description)))
append((Signature + ',operator', ', '))
if sig.params:
# Pop last comma
result.pop()
append((Signature + ',operator', ')'))
append((Signature, ' '))
return result
return ConditionalContainer(
content=Window(
FormattedTextControl(get_text_fragments),
height=Dimension.exact(1)),
filter=
# Show only when there is a signature
HasSignature(python_input) &
# And there are no completions to be shown. (would cover signature pop-up.)
~(has_completions & (show_completions_menu(python_input) |
show_multi_column_completions_menu(python_input)))
# Signature needs to be shown.
& ShowSignature(python_input) &
# Not done yet.
~is_done) | python | def signature_toolbar(python_input):
"""
Return the `Layout` for the signature.
"""
def get_text_fragments():
result = []
append = result.append
Signature = 'class:signature-toolbar'
if python_input.signatures:
sig = python_input.signatures[0] # Always take the first one.
append((Signature, ' '))
try:
append((Signature, sig.full_name))
except IndexError:
# Workaround for #37: https://github.com/jonathanslenders/python-prompt-toolkit/issues/37
# See also: https://github.com/davidhalter/jedi/issues/490
return []
append((Signature + ',operator', '('))
try:
enumerated_params = enumerate(sig.params)
except AttributeError:
# Workaround for #136: https://github.com/jonathanslenders/ptpython/issues/136
# AttributeError: 'Lambda' object has no attribute 'get_subscope_by_name'
return []
for i, p in enumerated_params:
# Workaround for #47: 'p' is None when we hit the '*' in the signature.
# and sig has no 'index' attribute.
# See: https://github.com/jonathanslenders/ptpython/issues/47
# https://github.com/davidhalter/jedi/issues/598
description = (p.description if p else '*') #or '*'
sig_index = getattr(sig, 'index', 0)
if i == sig_index:
# Note: we use `_Param.description` instead of
# `_Param.name`, that way we also get the '*' before args.
append((Signature + ',current-name', str(description)))
else:
append((Signature, str(description)))
append((Signature + ',operator', ', '))
if sig.params:
# Pop last comma
result.pop()
append((Signature + ',operator', ')'))
append((Signature, ' '))
return result
return ConditionalContainer(
content=Window(
FormattedTextControl(get_text_fragments),
height=Dimension.exact(1)),
filter=
# Show only when there is a signature
HasSignature(python_input) &
# And there are no completions to be shown. (would cover signature pop-up.)
~(has_completions & (show_completions_menu(python_input) |
show_multi_column_completions_menu(python_input)))
# Signature needs to be shown.
& ShowSignature(python_input) &
# Not done yet.
~is_done) | [
"def",
"signature_toolbar",
"(",
"python_input",
")",
":",
"def",
"get_text_fragments",
"(",
")",
":",
"result",
"=",
"[",
"]",
"append",
"=",
"result",
".",
"append",
"Signature",
"=",
"'class:signature-toolbar'",
"if",
"python_input",
".",
"signatures",
":",
... | Return the `Layout` for the signature. | [
"Return",
"the",
"Layout",
"for",
"the",
"signature",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L197-L263 | train | 205,195 |
prompt-toolkit/ptpython | ptpython/layout.py | status_bar | def status_bar(python_input):
"""
Create the `Layout` for the status bar.
"""
TB = 'class:status-toolbar'
@if_mousedown
def toggle_paste_mode(mouse_event):
python_input.paste_mode = not python_input.paste_mode
@if_mousedown
def enter_history(mouse_event):
python_input.enter_history()
def get_text_fragments():
python_buffer = python_input.default_buffer
result = []
append = result.append
append((TB, ' '))
result.extend(get_inputmode_fragments(python_input))
append((TB, ' '))
# Position in history.
append((TB, '%i/%i ' % (python_buffer.working_index + 1,
len(python_buffer._working_lines))))
# Shortcuts.
app = get_app()
if not python_input.vi_mode and app.current_buffer == python_input.search_buffer:
append((TB, '[Ctrl-G] Cancel search [Enter] Go to this position.'))
elif bool(app.current_buffer.selection_state) and not python_input.vi_mode:
# Emacs cut/copy keys.
append((TB, '[Ctrl-W] Cut [Meta-W] Copy [Ctrl-Y] Paste [Ctrl-G] Cancel'))
else:
result.extend([
(TB + ' class:key', '[F3]', enter_history),
(TB, ' History ', enter_history),
(TB + ' class:key', '[F6]', toggle_paste_mode),
(TB, ' ', toggle_paste_mode),
])
if python_input.paste_mode:
append((TB + ' class:paste-mode-on', 'Paste mode (on)', toggle_paste_mode))
else:
append((TB, 'Paste mode', toggle_paste_mode))
return result
return ConditionalContainer(
content=Window(content=FormattedTextControl(get_text_fragments), style=TB),
filter=~is_done & renderer_height_is_known &
Condition(lambda: python_input.show_status_bar and
not python_input.show_exit_confirmation)) | python | def status_bar(python_input):
"""
Create the `Layout` for the status bar.
"""
TB = 'class:status-toolbar'
@if_mousedown
def toggle_paste_mode(mouse_event):
python_input.paste_mode = not python_input.paste_mode
@if_mousedown
def enter_history(mouse_event):
python_input.enter_history()
def get_text_fragments():
python_buffer = python_input.default_buffer
result = []
append = result.append
append((TB, ' '))
result.extend(get_inputmode_fragments(python_input))
append((TB, ' '))
# Position in history.
append((TB, '%i/%i ' % (python_buffer.working_index + 1,
len(python_buffer._working_lines))))
# Shortcuts.
app = get_app()
if not python_input.vi_mode and app.current_buffer == python_input.search_buffer:
append((TB, '[Ctrl-G] Cancel search [Enter] Go to this position.'))
elif bool(app.current_buffer.selection_state) and not python_input.vi_mode:
# Emacs cut/copy keys.
append((TB, '[Ctrl-W] Cut [Meta-W] Copy [Ctrl-Y] Paste [Ctrl-G] Cancel'))
else:
result.extend([
(TB + ' class:key', '[F3]', enter_history),
(TB, ' History ', enter_history),
(TB + ' class:key', '[F6]', toggle_paste_mode),
(TB, ' ', toggle_paste_mode),
])
if python_input.paste_mode:
append((TB + ' class:paste-mode-on', 'Paste mode (on)', toggle_paste_mode))
else:
append((TB, 'Paste mode', toggle_paste_mode))
return result
return ConditionalContainer(
content=Window(content=FormattedTextControl(get_text_fragments), style=TB),
filter=~is_done & renderer_height_is_known &
Condition(lambda: python_input.show_status_bar and
not python_input.show_exit_confirmation)) | [
"def",
"status_bar",
"(",
"python_input",
")",
":",
"TB",
"=",
"'class:status-toolbar'",
"@",
"if_mousedown",
"def",
"toggle_paste_mode",
"(",
"mouse_event",
")",
":",
"python_input",
".",
"paste_mode",
"=",
"not",
"python_input",
".",
"paste_mode",
"@",
"if_mouse... | Create the `Layout` for the status bar. | [
"Create",
"the",
"Layout",
"for",
"the",
"status",
"bar",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L290-L344 | train | 205,196 |
prompt-toolkit/ptpython | ptpython/layout.py | exit_confirmation | def exit_confirmation(python_input, style='class:exit-confirmation'):
"""
Create `Layout` for the exit message.
"""
def get_text_fragments():
# Show "Do you really want to exit?"
return [
(style, '\n %s ([y]/n)' % python_input.exit_message),
('[SetCursorPosition]', ''),
(style, ' \n'),
]
visible = ~is_done & Condition(lambda: python_input.show_exit_confirmation)
return ConditionalContainer(
content=Window(FormattedTextControl(get_text_fragments), style=style), # , has_focus=visible)),
filter=visible) | python | def exit_confirmation(python_input, style='class:exit-confirmation'):
"""
Create `Layout` for the exit message.
"""
def get_text_fragments():
# Show "Do you really want to exit?"
return [
(style, '\n %s ([y]/n)' % python_input.exit_message),
('[SetCursorPosition]', ''),
(style, ' \n'),
]
visible = ~is_done & Condition(lambda: python_input.show_exit_confirmation)
return ConditionalContainer(
content=Window(FormattedTextControl(get_text_fragments), style=style), # , has_focus=visible)),
filter=visible) | [
"def",
"exit_confirmation",
"(",
"python_input",
",",
"style",
"=",
"'class:exit-confirmation'",
")",
":",
"def",
"get_text_fragments",
"(",
")",
":",
"# Show \"Do you really want to exit?\"",
"return",
"[",
"(",
"style",
",",
"'\\n %s ([y]/n)'",
"%",
"python_input",
... | Create `Layout` for the exit message. | [
"Create",
"Layout",
"for",
"the",
"exit",
"message",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L440-L456 | train | 205,197 |
prompt-toolkit/ptpython | ptpython/layout.py | meta_enter_message | def meta_enter_message(python_input):
"""
Create the `Layout` for the 'Meta+Enter` message.
"""
def get_text_fragments():
return [('class:accept-message', ' [Meta+Enter] Execute ')]
def extra_condition():
" Only show when... "
b = python_input.default_buffer
return (
python_input.show_meta_enter_message and
(not b.document.is_cursor_at_the_end or
python_input.accept_input_on_enter is None) and
'\n' in b.text)
visible = ~is_done & has_focus(DEFAULT_BUFFER) & Condition(extra_condition)
return ConditionalContainer(
content=Window(FormattedTextControl(get_text_fragments)),
filter=visible) | python | def meta_enter_message(python_input):
"""
Create the `Layout` for the 'Meta+Enter` message.
"""
def get_text_fragments():
return [('class:accept-message', ' [Meta+Enter] Execute ')]
def extra_condition():
" Only show when... "
b = python_input.default_buffer
return (
python_input.show_meta_enter_message and
(not b.document.is_cursor_at_the_end or
python_input.accept_input_on_enter is None) and
'\n' in b.text)
visible = ~is_done & has_focus(DEFAULT_BUFFER) & Condition(extra_condition)
return ConditionalContainer(
content=Window(FormattedTextControl(get_text_fragments)),
filter=visible) | [
"def",
"meta_enter_message",
"(",
"python_input",
")",
":",
"def",
"get_text_fragments",
"(",
")",
":",
"return",
"[",
"(",
"'class:accept-message'",
",",
"' [Meta+Enter] Execute '",
")",
"]",
"def",
"extra_condition",
"(",
")",
":",
"\" Only show when... \"",
"b",
... | Create the `Layout` for the 'Meta+Enter` message. | [
"Create",
"the",
"Layout",
"for",
"the",
"Meta",
"+",
"Enter",
"message",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/layout.py#L459-L480 | train | 205,198 |
prompt-toolkit/ptpython | ptpython/python_input.py | Option.activate_next | def activate_next(self, _previous=False):
"""
Activate next value.
"""
current = self.get_current_value()
options = sorted(self.values.keys())
# Get current index.
try:
index = options.index(current)
except ValueError:
index = 0
# Go to previous/next index.
if _previous:
index -= 1
else:
index += 1
# Call handler for this option.
next_option = options[index % len(options)]
self.values[next_option]() | python | def activate_next(self, _previous=False):
"""
Activate next value.
"""
current = self.get_current_value()
options = sorted(self.values.keys())
# Get current index.
try:
index = options.index(current)
except ValueError:
index = 0
# Go to previous/next index.
if _previous:
index -= 1
else:
index += 1
# Call handler for this option.
next_option = options[index % len(options)]
self.values[next_option]() | [
"def",
"activate_next",
"(",
"self",
",",
"_previous",
"=",
"False",
")",
":",
"current",
"=",
"self",
".",
"get_current_value",
"(",
")",
"options",
"=",
"sorted",
"(",
"self",
".",
"values",
".",
"keys",
"(",
")",
")",
"# Get current index.",
"try",
":... | Activate next value. | [
"Activate",
"next",
"value",
"."
] | b1bba26a491324cd65e0ef46c7b818c4b88fd993 | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/python_input.py#L89-L110 | train | 205,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.