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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
xolox/python-coloredlogs | coloredlogs/__init__.py | find_hostname | def find_hostname(use_chroot=True):
"""
Find the host name to include in log messages.
:param use_chroot: Use the name of the chroot when inside a chroot?
(boolean, defaults to :data:`True`)
:returns: A suitable host name (a string).
Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
the chroot name). If none are found then :func:`socket.gethostname()` is
used as a fall back.
"""
for chroot_file in CHROOT_FILES:
try:
with open(chroot_file) as handle:
first_line = next(handle)
name = first_line.strip()
if name:
return name
except Exception:
pass
return socket.gethostname() | python | def find_hostname(use_chroot=True):
"""
Find the host name to include in log messages.
:param use_chroot: Use the name of the chroot when inside a chroot?
(boolean, defaults to :data:`True`)
:returns: A suitable host name (a string).
Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
the chroot name). If none are found then :func:`socket.gethostname()` is
used as a fall back.
"""
for chroot_file in CHROOT_FILES:
try:
with open(chroot_file) as handle:
first_line = next(handle)
name = first_line.strip()
if name:
return name
except Exception:
pass
return socket.gethostname() | [
"def",
"find_hostname",
"(",
"use_chroot",
"=",
"True",
")",
":",
"for",
"chroot_file",
"in",
"CHROOT_FILES",
":",
"try",
":",
"with",
"open",
"(",
"chroot_file",
")",
"as",
"handle",
":",
"first_line",
"=",
"next",
"(",
"handle",
")",
"name",
"=",
"firs... | Find the host name to include in log messages.
:param use_chroot: Use the name of the chroot when inside a chroot?
(boolean, defaults to :data:`True`)
:returns: A suitable host name (a string).
Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
the chroot name). If none are found then :func:`socket.gethostname()` is
used as a fall back. | [
"Find",
"the",
"host",
"name",
"to",
"include",
"in",
"log",
"messages",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L768-L789 | train | 210,300 |
xolox/python-coloredlogs | coloredlogs/__init__.py | find_program_name | def find_program_name():
"""
Select a suitable program name to embed in log messages.
:returns: One of the following strings (in decreasing order of preference):
1. The base name of the currently running Python program or
script (based on the value at index zero of :data:`sys.argv`).
2. The base name of the Python executable (based on
:data:`sys.executable`).
3. The string 'python'.
"""
# Gotcha: sys.argv[0] is '-c' if Python is started with the -c option.
return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '') or
(os.path.basename(sys.executable) if sys.executable else '') or
'python') | python | def find_program_name():
"""
Select a suitable program name to embed in log messages.
:returns: One of the following strings (in decreasing order of preference):
1. The base name of the currently running Python program or
script (based on the value at index zero of :data:`sys.argv`).
2. The base name of the Python executable (based on
:data:`sys.executable`).
3. The string 'python'.
"""
# Gotcha: sys.argv[0] is '-c' if Python is started with the -c option.
return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '') or
(os.path.basename(sys.executable) if sys.executable else '') or
'python') | [
"def",
"find_program_name",
"(",
")",
":",
"# Gotcha: sys.argv[0] is '-c' if Python is started with the -c option.",
"return",
"(",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"sys",
".",
"argv",
"and",
"sys",
".... | Select a suitable program name to embed in log messages.
:returns: One of the following strings (in decreasing order of preference):
1. The base name of the currently running Python program or
script (based on the value at index zero of :data:`sys.argv`).
2. The base name of the Python executable (based on
:data:`sys.executable`).
3. The string 'python'. | [
"Select",
"a",
"suitable",
"program",
"name",
"to",
"embed",
"in",
"log",
"messages",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L792-L807 | train | 210,301 |
xolox/python-coloredlogs | coloredlogs/__init__.py | replace_handler | def replace_handler(logger, match_handler, reconfigure):
"""
Prepare to replace a handler.
:param logger: Refer to :func:`find_handler()`.
:param match_handler: Refer to :func:`find_handler()`.
:param reconfigure: :data:`True` if an existing handler should be replaced,
:data:`False` otherwise.
:returns: A tuple of two values:
1. The matched :class:`~logging.Handler` object or :data:`None`
if no handler was matched.
2. The :class:`~logging.Logger` to which the matched handler was
attached or the logger given to :func:`replace_handler()`.
"""
handler, other_logger = find_handler(logger, match_handler)
if handler and other_logger and reconfigure:
# Remove the existing handler from the logger that its attached to
# so that we can install a new handler that behaves differently.
other_logger.removeHandler(handler)
# Switch to the logger that the existing handler was attached to so
# that reconfiguration doesn't narrow the scope of logging.
logger = other_logger
return handler, logger | python | def replace_handler(logger, match_handler, reconfigure):
"""
Prepare to replace a handler.
:param logger: Refer to :func:`find_handler()`.
:param match_handler: Refer to :func:`find_handler()`.
:param reconfigure: :data:`True` if an existing handler should be replaced,
:data:`False` otherwise.
:returns: A tuple of two values:
1. The matched :class:`~logging.Handler` object or :data:`None`
if no handler was matched.
2. The :class:`~logging.Logger` to which the matched handler was
attached or the logger given to :func:`replace_handler()`.
"""
handler, other_logger = find_handler(logger, match_handler)
if handler and other_logger and reconfigure:
# Remove the existing handler from the logger that its attached to
# so that we can install a new handler that behaves differently.
other_logger.removeHandler(handler)
# Switch to the logger that the existing handler was attached to so
# that reconfiguration doesn't narrow the scope of logging.
logger = other_logger
return handler, logger | [
"def",
"replace_handler",
"(",
"logger",
",",
"match_handler",
",",
"reconfigure",
")",
":",
"handler",
",",
"other_logger",
"=",
"find_handler",
"(",
"logger",
",",
"match_handler",
")",
"if",
"handler",
"and",
"other_logger",
"and",
"reconfigure",
":",
"# Remo... | Prepare to replace a handler.
:param logger: Refer to :func:`find_handler()`.
:param match_handler: Refer to :func:`find_handler()`.
:param reconfigure: :data:`True` if an existing handler should be replaced,
:data:`False` otherwise.
:returns: A tuple of two values:
1. The matched :class:`~logging.Handler` object or :data:`None`
if no handler was matched.
2. The :class:`~logging.Logger` to which the matched handler was
attached or the logger given to :func:`replace_handler()`. | [
"Prepare",
"to",
"replace",
"a",
"handler",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L810-L833 | train | 210,302 |
xolox/python-coloredlogs | coloredlogs/__init__.py | walk_propagation_tree | def walk_propagation_tree(logger):
"""
Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: This uses the undocumented :class:`logging.Logger.parent`
attribute to find higher level loggers, however it won't
raise an exception if the attribute isn't available.
"""
while isinstance(logger, logging.Logger):
# Yield the logger to our caller.
yield logger
# Check if the logger has propagation enabled.
if logger.propagate:
# Continue with the parent logger. We use getattr() because the
# `parent' attribute isn't documented so properly speaking we
# shouldn't break if it's not available.
logger = getattr(logger, 'parent', None)
else:
# The propagation chain stops here.
logger = None | python | def walk_propagation_tree(logger):
"""
Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: This uses the undocumented :class:`logging.Logger.parent`
attribute to find higher level loggers, however it won't
raise an exception if the attribute isn't available.
"""
while isinstance(logger, logging.Logger):
# Yield the logger to our caller.
yield logger
# Check if the logger has propagation enabled.
if logger.propagate:
# Continue with the parent logger. We use getattr() because the
# `parent' attribute isn't documented so properly speaking we
# shouldn't break if it's not available.
logger = getattr(logger, 'parent', None)
else:
# The propagation chain stops here.
logger = None | [
"def",
"walk_propagation_tree",
"(",
"logger",
")",
":",
"while",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"# Yield the logger to our caller.",
"yield",
"logger",
"# Check if the logger has propagation enabled.",
"if",
"logger",
".",
"propag... | Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: This uses the undocumented :class:`logging.Logger.parent`
attribute to find higher level loggers, however it won't
raise an exception if the attribute isn't available. | [
"Walk",
"through",
"the",
"propagation",
"hierarchy",
"of",
"the",
"given",
"logger",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L888-L911 | train | 210,303 |
xolox/python-coloredlogs | coloredlogs/__init__.py | ColoredFormatter.colorize_format | def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE):
"""
Rewrite a logging format string to inject ANSI escape sequences.
:param fmt: The log format string.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:returns: The logging format string with ANSI escape sequences.
This method takes a logging format string like the ones you give to
:class:`logging.Formatter` and processes it as follows:
1. First the logging format string is separated into formatting
directives versus surrounding text (according to the given `style`).
2. Then formatting directives and surrounding text are grouped
based on whitespace delimiters (in the surrounding text).
3. For each group styling is selected as follows:
1. If the group contains a single formatting directive that has
a style defined then the whole group is styled accordingly.
2. If the group contains multiple formatting directives that
have styles defined then each formatting directive is styled
individually and surrounding text isn't styled.
As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::
%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
`name` field but not for the `process` field, however because both fields
are part of the same whitespace delimited token they'll be highlighted
together in the style defined for the `name` field.
"""
result = []
parser = FormatStringParser(style=style)
for group in parser.get_grouped_pairs(fmt):
applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]
if sum(map(bool, applicable_styles)) == 1:
# If exactly one (1) field style is available for the group of
# tokens then all of the tokens will be styled the same way.
# This provides a limited form of backwards compatibility with
# the (intended) behavior of coloredlogs before the release of
# version 10.
result.append(ansi_wrap(
''.join(token.text for token in group),
**next(s for s in applicable_styles if s)
))
else:
for token in group:
text = token.text
if token.name:
field_styles = self.nn.get(self.field_styles, token.name)
if field_styles:
text = ansi_wrap(text, **field_styles)
result.append(text)
return ''.join(result) | python | def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE):
"""
Rewrite a logging format string to inject ANSI escape sequences.
:param fmt: The log format string.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:returns: The logging format string with ANSI escape sequences.
This method takes a logging format string like the ones you give to
:class:`logging.Formatter` and processes it as follows:
1. First the logging format string is separated into formatting
directives versus surrounding text (according to the given `style`).
2. Then formatting directives and surrounding text are grouped
based on whitespace delimiters (in the surrounding text).
3. For each group styling is selected as follows:
1. If the group contains a single formatting directive that has
a style defined then the whole group is styled accordingly.
2. If the group contains multiple formatting directives that
have styles defined then each formatting directive is styled
individually and surrounding text isn't styled.
As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::
%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
`name` field but not for the `process` field, however because both fields
are part of the same whitespace delimited token they'll be highlighted
together in the style defined for the `name` field.
"""
result = []
parser = FormatStringParser(style=style)
for group in parser.get_grouped_pairs(fmt):
applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]
if sum(map(bool, applicable_styles)) == 1:
# If exactly one (1) field style is available for the group of
# tokens then all of the tokens will be styled the same way.
# This provides a limited form of backwards compatibility with
# the (intended) behavior of coloredlogs before the release of
# version 10.
result.append(ansi_wrap(
''.join(token.text for token in group),
**next(s for s in applicable_styles if s)
))
else:
for token in group:
text = token.text
if token.name:
field_styles = self.nn.get(self.field_styles, token.name)
if field_styles:
text = ansi_wrap(text, **field_styles)
result.append(text)
return ''.join(result) | [
"def",
"colorize_format",
"(",
"self",
",",
"fmt",
",",
"style",
"=",
"DEFAULT_FORMAT_STYLE",
")",
":",
"result",
"=",
"[",
"]",
"parser",
"=",
"FormatStringParser",
"(",
"style",
"=",
"style",
")",
"for",
"group",
"in",
"parser",
".",
"get_grouped_pairs",
... | Rewrite a logging format string to inject ANSI escape sequences.
:param fmt: The log format string.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:returns: The logging format string with ANSI escape sequences.
This method takes a logging format string like the ones you give to
:class:`logging.Formatter` and processes it as follows:
1. First the logging format string is separated into formatting
directives versus surrounding text (according to the given `style`).
2. Then formatting directives and surrounding text are grouped
based on whitespace delimiters (in the surrounding text).
3. For each group styling is selected as follows:
1. If the group contains a single formatting directive that has
a style defined then the whole group is styled accordingly.
2. If the group contains multiple formatting directives that
have styles defined then each formatting directive is styled
individually and surrounding text isn't styled.
As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::
%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
`name` field but not for the `process` field, however because both fields
are part of the same whitespace delimited token they'll be highlighted
together in the style defined for the `name` field. | [
"Rewrite",
"a",
"logging",
"format",
"string",
"to",
"inject",
"ANSI",
"escape",
"sequences",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L1007-L1065 | train | 210,304 |
xolox/python-coloredlogs | coloredlogs/__init__.py | ColoredFormatter.format | def format(self, record):
"""
Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to the
level of each log record (because such logic cannot be expressed in the
syntax of a log format string). It works by making a copy of the log
record, changing the `msg` field inside the copy and passing the copy
into the :func:`~logging.Formatter.format()` method of the base
class.
"""
style = self.nn.get(self.level_styles, record.levelname)
# After the introduction of the `Empty' class it was reported in issue
# 33 that format() can be called when `Empty' has already been garbage
# collected. This explains the (otherwise rather out of place) `Empty
# is not None' check in the following `if' statement. The reasoning
# here is that it's much better to log a message without formatting
# then to raise an exception ;-).
#
# For more details refer to issue 33 on GitHub:
# https://github.com/xolox/python-coloredlogs/issues/33
if style and Empty is not None:
# Due to the way that Python's logging module is structured and
# documented the only (IMHO) clean way to customize its behavior is
# to change incoming LogRecord objects before they get to the base
# formatter. However we don't want to break other formatters and
# handlers, so we copy the log record.
#
# In the past this used copy.copy() but as reported in issue 29
# (which is reproducible) this can cause deadlocks. The following
# Python voodoo is intended to accomplish the same thing as
# copy.copy() without all of the generalization and overhead that
# we don't need for our -very limited- use case.
#
# For more details refer to issue 29 on GitHub:
# https://github.com/xolox/python-coloredlogs/issues/29
copy = Empty()
copy.__class__ = (
self.log_record_factory()
if self.log_record_factory is not None
else logging.LogRecord
)
copy.__dict__.update(record.__dict__)
copy.msg = ansi_wrap(coerce_string(record.msg), **style)
record = copy
# Delegate the remaining formatting to the base formatter.
return logging.Formatter.format(self, record) | python | def format(self, record):
"""
Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to the
level of each log record (because such logic cannot be expressed in the
syntax of a log format string). It works by making a copy of the log
record, changing the `msg` field inside the copy and passing the copy
into the :func:`~logging.Formatter.format()` method of the base
class.
"""
style = self.nn.get(self.level_styles, record.levelname)
# After the introduction of the `Empty' class it was reported in issue
# 33 that format() can be called when `Empty' has already been garbage
# collected. This explains the (otherwise rather out of place) `Empty
# is not None' check in the following `if' statement. The reasoning
# here is that it's much better to log a message without formatting
# then to raise an exception ;-).
#
# For more details refer to issue 33 on GitHub:
# https://github.com/xolox/python-coloredlogs/issues/33
if style and Empty is not None:
# Due to the way that Python's logging module is structured and
# documented the only (IMHO) clean way to customize its behavior is
# to change incoming LogRecord objects before they get to the base
# formatter. However we don't want to break other formatters and
# handlers, so we copy the log record.
#
# In the past this used copy.copy() but as reported in issue 29
# (which is reproducible) this can cause deadlocks. The following
# Python voodoo is intended to accomplish the same thing as
# copy.copy() without all of the generalization and overhead that
# we don't need for our -very limited- use case.
#
# For more details refer to issue 29 on GitHub:
# https://github.com/xolox/python-coloredlogs/issues/29
copy = Empty()
copy.__class__ = (
self.log_record_factory()
if self.log_record_factory is not None
else logging.LogRecord
)
copy.__dict__.update(record.__dict__)
copy.msg = ansi_wrap(coerce_string(record.msg), **style)
record = copy
# Delegate the remaining formatting to the base formatter.
return logging.Formatter.format(self, record) | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"style",
"=",
"self",
".",
"nn",
".",
"get",
"(",
"self",
".",
"level_styles",
",",
"record",
".",
"levelname",
")",
"# After the introduction of the `Empty' class it was reported in issue",
"# 33 that format() ... | Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to the
level of each log record (because such logic cannot be expressed in the
syntax of a log format string). It works by making a copy of the log
record, changing the `msg` field inside the copy and passing the copy
into the :func:`~logging.Formatter.format()` method of the base
class. | [
"Apply",
"level",
"-",
"specific",
"styling",
"to",
"log",
"records",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L1067-L1116 | train | 210,305 |
xolox/python-coloredlogs | coloredlogs/__init__.py | FormatStringParser.get_pairs | def get_pairs(self, format_string):
"""
Tokenize a logging format string and extract field names from tokens.
:param format_string: The logging format string.
:returns: A generator of :class:`FormatStringToken` objects.
"""
for token in self.get_tokens(format_string):
match = self.name_pattern.search(token)
name = match.group(1) if match else None
yield FormatStringToken(name=name, text=token) | python | def get_pairs(self, format_string):
"""
Tokenize a logging format string and extract field names from tokens.
:param format_string: The logging format string.
:returns: A generator of :class:`FormatStringToken` objects.
"""
for token in self.get_tokens(format_string):
match = self.name_pattern.search(token)
name = match.group(1) if match else None
yield FormatStringToken(name=name, text=token) | [
"def",
"get_pairs",
"(",
"self",
",",
"format_string",
")",
":",
"for",
"token",
"in",
"self",
".",
"get_tokens",
"(",
"format_string",
")",
":",
"match",
"=",
"self",
".",
"name_pattern",
".",
"search",
"(",
"token",
")",
"name",
"=",
"match",
".",
"g... | Tokenize a logging format string and extract field names from tokens.
:param format_string: The logging format string.
:returns: A generator of :class:`FormatStringToken` objects. | [
"Tokenize",
"a",
"logging",
"format",
"string",
"and",
"extract",
"field",
"names",
"from",
"tokens",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L1351-L1361 | train | 210,306 |
xolox/python-coloredlogs | coloredlogs/__init__.py | FormatStringParser.get_pattern | def get_pattern(self, field_name):
"""
Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object.
"""
return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE) | python | def get_pattern(self, field_name):
"""
Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object.
"""
return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE) | [
"def",
"get_pattern",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"re",
".",
"compile",
"(",
"self",
".",
"raw_pattern",
".",
"replace",
"(",
"r'\\w+'",
",",
"field_name",
")",
",",
"re",
".",
"VERBOSE",
")"
] | Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object. | [
"Get",
"a",
"regular",
"expression",
"to",
"match",
"a",
"formatting",
"directive",
"that",
"references",
"the",
"given",
"field",
"name",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L1363-L1370 | train | 210,307 |
xolox/python-coloredlogs | coloredlogs/__init__.py | FormatStringParser.get_tokens | def get_tokens(self, format_string):
"""
Tokenize a logging format string.
:param format_string: The logging format string.
:returns: A list of strings with formatting directives separated from surrounding text.
"""
return [t for t in self.tokenize_pattern.split(format_string) if t] | python | def get_tokens(self, format_string):
"""
Tokenize a logging format string.
:param format_string: The logging format string.
:returns: A list of strings with formatting directives separated from surrounding text.
"""
return [t for t in self.tokenize_pattern.split(format_string) if t] | [
"def",
"get_tokens",
"(",
"self",
",",
"format_string",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"tokenize_pattern",
".",
"split",
"(",
"format_string",
")",
"if",
"t",
"]"
] | Tokenize a logging format string.
:param format_string: The logging format string.
:returns: A list of strings with formatting directives separated from surrounding text. | [
"Tokenize",
"a",
"logging",
"format",
"string",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L1372-L1379 | train | 210,308 |
xolox/python-coloredlogs | coloredlogs/__init__.py | NameNormalizer.normalize_name | def normalize_name(self, name):
"""
Normalize a field or level name.
:param name: The field or level name (a string).
:returns: The normalized name (a string).
Transforms all strings to lowercase and resolves level name aliases
(refer to :func:`find_level_aliases()`) to their canonical name:
>>> from coloredlogs import NameNormalizer
>>> from humanfriendly import format_table
>>> nn = NameNormalizer()
>>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']
>>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))
-----------------------
| DEBUG | debug |
| INFO | info |
| WARN | warning |
| WARNING | warning |
| ERROR | error |
| FATAL | critical |
| CRITICAL | critical |
-----------------------
"""
name = name.lower()
if name in self.aliases:
name = self.aliases[name]
return name | python | def normalize_name(self, name):
"""
Normalize a field or level name.
:param name: The field or level name (a string).
:returns: The normalized name (a string).
Transforms all strings to lowercase and resolves level name aliases
(refer to :func:`find_level_aliases()`) to their canonical name:
>>> from coloredlogs import NameNormalizer
>>> from humanfriendly import format_table
>>> nn = NameNormalizer()
>>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']
>>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))
-----------------------
| DEBUG | debug |
| INFO | info |
| WARN | warning |
| WARNING | warning |
| ERROR | error |
| FATAL | critical |
| CRITICAL | critical |
-----------------------
"""
name = name.lower()
if name in self.aliases:
name = self.aliases[name]
return name | [
"def",
"normalize_name",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"self",
".",
"aliases",
":",
"name",
"=",
"self",
".",
"aliases",
"[",
"name",
"]",
"return",
"name"
] | Normalize a field or level name.
:param name: The field or level name (a string).
:returns: The normalized name (a string).
Transforms all strings to lowercase and resolves level name aliases
(refer to :func:`find_level_aliases()`) to their canonical name:
>>> from coloredlogs import NameNormalizer
>>> from humanfriendly import format_table
>>> nn = NameNormalizer()
>>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']
>>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))
-----------------------
| DEBUG | debug |
| INFO | info |
| WARN | warning |
| WARNING | warning |
| ERROR | error |
| FATAL | critical |
| CRITICAL | critical |
----------------------- | [
"Normalize",
"a",
"field",
"or",
"level",
"name",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L1406-L1434 | train | 210,309 |
xolox/python-coloredlogs | coloredlogs/cli.py | main | def main():
"""Command line interface for the ``coloredlogs`` program."""
actions = []
try:
# Parse the command line arguments.
options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
'convert', 'to-html', 'demo', 'help',
])
# Map command line options to actions.
for option, value in options:
if option in ('-c', '--convert', '--to-html'):
actions.append(functools.partial(convert_command_output, *arguments))
arguments = []
elif option in ('-d', '--demo'):
actions.append(demonstrate_colored_logging)
elif option in ('-h', '--help'):
usage(__doc__)
return
else:
assert False, "Programming error: Unhandled option!"
if not actions:
usage(__doc__)
return
except Exception as e:
warning("Error: %s", e)
sys.exit(1)
for function in actions:
function() | python | def main():
"""Command line interface for the ``coloredlogs`` program."""
actions = []
try:
# Parse the command line arguments.
options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
'convert', 'to-html', 'demo', 'help',
])
# Map command line options to actions.
for option, value in options:
if option in ('-c', '--convert', '--to-html'):
actions.append(functools.partial(convert_command_output, *arguments))
arguments = []
elif option in ('-d', '--demo'):
actions.append(demonstrate_colored_logging)
elif option in ('-h', '--help'):
usage(__doc__)
return
else:
assert False, "Programming error: Unhandled option!"
if not actions:
usage(__doc__)
return
except Exception as e:
warning("Error: %s", e)
sys.exit(1)
for function in actions:
function() | [
"def",
"main",
"(",
")",
":",
"actions",
"=",
"[",
"]",
"try",
":",
"# Parse the command line arguments.",
"options",
",",
"arguments",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'cdh'",
",",
"[",
"'convert'",
",",... | Command line interface for the ``coloredlogs`` program. | [
"Command",
"line",
"interface",
"for",
"the",
"coloredlogs",
"program",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/cli.py#L60-L87 | train | 210,310 |
xolox/python-coloredlogs | coloredlogs/converter/__init__.py | capture | def capture(command, encoding='UTF-8'):
"""
Capture the output of an external command as if it runs in an interactive terminal.
:param command: The command name and its arguments (a list of strings).
:param encoding: The encoding to use to decode the output (a string).
:returns: The output of the command.
This function runs an external command under ``script`` (emulating an
interactive terminal) to capture the output of the command as if it was
running in an interactive terminal (including ANSI escape sequences).
"""
with open(os.devnull, 'wb') as dev_null:
# We start by invoking the `script' program in a form that is supported
# by the Linux implementation [1] but fails command line validation on
# the MacOS (BSD) implementation [2]: The command is specified using
# the -c option and the typescript file is /dev/null.
#
# [1] http://man7.org/linux/man-pages/man1/script.1.html
# [2] https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/script.1.html
command_line = ['script', '-qc', ' '.join(map(pipes.quote, command)), '/dev/null']
script = subprocess.Popen(command_line, stdout=subprocess.PIPE, stderr=dev_null)
stdout, stderr = script.communicate()
if script.returncode == 0:
# If `script' succeeded we assume that it understood our command line
# invocation which means it's the Linux implementation (in this case
# we can use standard output instead of a temporary file).
output = stdout.decode(encoding)
else:
# If `script' failed we assume that it didn't understand our command
# line invocation which means it's the MacOS (BSD) implementation
# (in this case we need a temporary file because the command line
# interface requires it).
fd, temporary_file = tempfile.mkstemp(prefix='coloredlogs-', suffix='-capture.txt')
try:
command_line = ['script', '-q', temporary_file] + list(command)
subprocess.Popen(command_line, stdout=dev_null, stderr=dev_null).wait()
with codecs.open(temporary_file, 'r', encoding) as handle:
output = handle.read()
finally:
os.unlink(temporary_file)
# On MacOS when standard input is /dev/null I've observed
# the captured output starting with the characters '^D':
#
# $ script -q capture.txt echo example </dev/null
# example
# $ xxd capture.txt
# 00000000: 5e44 0808 6578 616d 706c 650d 0a ^D..example..
#
# I'm not sure why this is here, although I suppose it has to do
# with ^D in caret notation signifying end-of-file [1]. What I do
# know is that this is an implementation detail that callers of the
# capture() function shouldn't be bothered with, so we strip it.
#
# [1] https://en.wikipedia.org/wiki/End-of-file
if output.startswith(b'^D'):
output = output[2:]
# Clean up backspace and carriage return characters and the 'erase line'
# ANSI escape sequence and return the output as a Unicode string.
return u'\n'.join(clean_terminal_output(output)) | python | def capture(command, encoding='UTF-8'):
"""
Capture the output of an external command as if it runs in an interactive terminal.
:param command: The command name and its arguments (a list of strings).
:param encoding: The encoding to use to decode the output (a string).
:returns: The output of the command.
This function runs an external command under ``script`` (emulating an
interactive terminal) to capture the output of the command as if it was
running in an interactive terminal (including ANSI escape sequences).
"""
with open(os.devnull, 'wb') as dev_null:
# We start by invoking the `script' program in a form that is supported
# by the Linux implementation [1] but fails command line validation on
# the MacOS (BSD) implementation [2]: The command is specified using
# the -c option and the typescript file is /dev/null.
#
# [1] http://man7.org/linux/man-pages/man1/script.1.html
# [2] https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/script.1.html
command_line = ['script', '-qc', ' '.join(map(pipes.quote, command)), '/dev/null']
script = subprocess.Popen(command_line, stdout=subprocess.PIPE, stderr=dev_null)
stdout, stderr = script.communicate()
if script.returncode == 0:
# If `script' succeeded we assume that it understood our command line
# invocation which means it's the Linux implementation (in this case
# we can use standard output instead of a temporary file).
output = stdout.decode(encoding)
else:
# If `script' failed we assume that it didn't understand our command
# line invocation which means it's the MacOS (BSD) implementation
# (in this case we need a temporary file because the command line
# interface requires it).
fd, temporary_file = tempfile.mkstemp(prefix='coloredlogs-', suffix='-capture.txt')
try:
command_line = ['script', '-q', temporary_file] + list(command)
subprocess.Popen(command_line, stdout=dev_null, stderr=dev_null).wait()
with codecs.open(temporary_file, 'r', encoding) as handle:
output = handle.read()
finally:
os.unlink(temporary_file)
# On MacOS when standard input is /dev/null I've observed
# the captured output starting with the characters '^D':
#
# $ script -q capture.txt echo example </dev/null
# example
# $ xxd capture.txt
# 00000000: 5e44 0808 6578 616d 706c 650d 0a ^D..example..
#
# I'm not sure why this is here, although I suppose it has to do
# with ^D in caret notation signifying end-of-file [1]. What I do
# know is that this is an implementation detail that callers of the
# capture() function shouldn't be bothered with, so we strip it.
#
# [1] https://en.wikipedia.org/wiki/End-of-file
if output.startswith(b'^D'):
output = output[2:]
# Clean up backspace and carriage return characters and the 'erase line'
# ANSI escape sequence and return the output as a Unicode string.
return u'\n'.join(clean_terminal_output(output)) | [
"def",
"capture",
"(",
"command",
",",
"encoding",
"=",
"'UTF-8'",
")",
":",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'wb'",
")",
"as",
"dev_null",
":",
"# We start by invoking the `script' program in a form that is supported",
"# by the Linux implementation [1]... | Capture the output of an external command as if it runs in an interactive terminal.
:param command: The command name and its arguments (a list of strings).
:param encoding: The encoding to use to decode the output (a string).
:returns: The output of the command.
This function runs an external command under ``script`` (emulating an
interactive terminal) to capture the output of the command as if it was
running in an interactive terminal (including ANSI escape sequences). | [
"Capture",
"the",
"output",
"of",
"an",
"external",
"command",
"as",
"if",
"it",
"runs",
"in",
"an",
"interactive",
"terminal",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L58-L117 | train | 210,311 |
xolox/python-coloredlogs | coloredlogs/converter/__init__.py | convert | def convert(text, code=True, tabsize=4):
"""
Convert text with ANSI escape sequences to HTML.
:param text: The text with ANSI escape sequences (a string).
:param code: Whether to wrap the returned HTML fragment in a
``<code>...</code>`` element (a boolean, defaults
to :data:`True`).
:param tabsize: Refer to :func:`str.expandtabs()` for details.
:returns: The text converted to HTML (a string).
"""
output = []
in_span = False
compatible_text_styles = {
# The following ANSI text styles have an obvious mapping to CSS.
ANSI_TEXT_STYLES['bold']: {'font-weight': 'bold'},
ANSI_TEXT_STYLES['strike_through']: {'text-decoration': 'line-through'},
ANSI_TEXT_STYLES['underline']: {'text-decoration': 'underline'},
}
for token in TOKEN_PATTERN.split(text):
if token.startswith(('http://', 'https://', 'www.')):
url = token if '://' in token else ('http://' + token)
token = u'<a href="%s" style="color:inherit">%s</a>' % (html_encode(url), html_encode(token))
elif token.startswith(ANSI_CSI):
ansi_codes = token[len(ANSI_CSI):-1].split(';')
if all(c.isdigit() for c in ansi_codes):
ansi_codes = list(map(int, ansi_codes))
# First we check for a reset code to close the previous <span>
# element. As explained on Wikipedia [1] an absence of codes
# implies a reset code as well: "No parameters at all in ESC[m acts
# like a 0 reset code".
# [1] https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
if in_span and (0 in ansi_codes or not ansi_codes):
output.append('</span>')
in_span = False
# Now we're ready to generate the next <span> element (if any) in
# the knowledge that we're emitting opening <span> and closing
# </span> tags in the correct order.
styles = {}
is_faint = (ANSI_TEXT_STYLES['faint'] in ansi_codes)
is_inverse = (ANSI_TEXT_STYLES['inverse'] in ansi_codes)
while ansi_codes:
number = ansi_codes.pop(0)
# Try to match a compatible text style.
if number in compatible_text_styles:
styles.update(compatible_text_styles[number])
continue
# Try to extract a text and/or background color.
text_color = None
background_color = None
if 30 <= number <= 37:
# 30-37 sets the text color from the eight color palette.
text_color = EIGHT_COLOR_PALETTE[number - 30]
elif 40 <= number <= 47:
# 40-47 sets the background color from the eight color palette.
background_color = EIGHT_COLOR_PALETTE[number - 40]
elif 90 <= number <= 97:
# 90-97 sets the text color from the high-intensity eight color palette.
text_color = BRIGHT_COLOR_PALETTE[number - 90]
elif 100 <= number <= 107:
# 100-107 sets the background color from the high-intensity eight color palette.
background_color = BRIGHT_COLOR_PALETTE[number - 100]
elif number in (38, 39) and len(ansi_codes) >= 2 and ansi_codes[0] == 5:
# 38;5;N is a text color in the 256 color mode palette,
# 39;5;N is a background color in the 256 color mode palette.
try:
# Consume the 5 following 38 or 39.
ansi_codes.pop(0)
# Consume the 256 color mode color index.
color_index = ansi_codes.pop(0)
# Set the variable to the corresponding HTML/CSS color.
if number == 38:
text_color = EXTENDED_COLOR_PALETTE[color_index]
elif number == 39:
background_color = EXTENDED_COLOR_PALETTE[color_index]
except (ValueError, IndexError):
pass
# Apply the 'faint' or 'inverse' text style
# by manipulating the selected color(s).
if text_color and is_inverse:
# Use the text color as the background color and pick a
# text color that will be visible on the resulting
# background color.
background_color = text_color
text_color = select_text_color(*parse_hex_color(text_color))
if text_color and is_faint:
# Because I wasn't sure how to implement faint colors
# based on normal colors I looked at how gnome-terminal
# (my terminal of choice) handles this and it appears
# to just pick a somewhat darker color.
text_color = '#%02X%02X%02X' % tuple(
max(0, n - 40) for n in parse_hex_color(text_color)
)
if text_color:
styles['color'] = text_color
if background_color:
styles['background-color'] = background_color
if styles:
token = '<span style="%s">' % ';'.join(k + ':' + v for k, v in sorted(styles.items()))
in_span = True
else:
token = ''
else:
token = html_encode(token)
output.append(token)
html = ''.join(output)
html = encode_whitespace(html, tabsize)
if code:
html = '<code>%s</code>' % html
return html | python | def convert(text, code=True, tabsize=4):
"""
Convert text with ANSI escape sequences to HTML.
:param text: The text with ANSI escape sequences (a string).
:param code: Whether to wrap the returned HTML fragment in a
``<code>...</code>`` element (a boolean, defaults
to :data:`True`).
:param tabsize: Refer to :func:`str.expandtabs()` for details.
:returns: The text converted to HTML (a string).
"""
output = []
in_span = False
compatible_text_styles = {
# The following ANSI text styles have an obvious mapping to CSS.
ANSI_TEXT_STYLES['bold']: {'font-weight': 'bold'},
ANSI_TEXT_STYLES['strike_through']: {'text-decoration': 'line-through'},
ANSI_TEXT_STYLES['underline']: {'text-decoration': 'underline'},
}
for token in TOKEN_PATTERN.split(text):
if token.startswith(('http://', 'https://', 'www.')):
url = token if '://' in token else ('http://' + token)
token = u'<a href="%s" style="color:inherit">%s</a>' % (html_encode(url), html_encode(token))
elif token.startswith(ANSI_CSI):
ansi_codes = token[len(ANSI_CSI):-1].split(';')
if all(c.isdigit() for c in ansi_codes):
ansi_codes = list(map(int, ansi_codes))
# First we check for a reset code to close the previous <span>
# element. As explained on Wikipedia [1] an absence of codes
# implies a reset code as well: "No parameters at all in ESC[m acts
# like a 0 reset code".
# [1] https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
if in_span and (0 in ansi_codes or not ansi_codes):
output.append('</span>')
in_span = False
# Now we're ready to generate the next <span> element (if any) in
# the knowledge that we're emitting opening <span> and closing
# </span> tags in the correct order.
styles = {}
is_faint = (ANSI_TEXT_STYLES['faint'] in ansi_codes)
is_inverse = (ANSI_TEXT_STYLES['inverse'] in ansi_codes)
while ansi_codes:
number = ansi_codes.pop(0)
# Try to match a compatible text style.
if number in compatible_text_styles:
styles.update(compatible_text_styles[number])
continue
# Try to extract a text and/or background color.
text_color = None
background_color = None
if 30 <= number <= 37:
# 30-37 sets the text color from the eight color palette.
text_color = EIGHT_COLOR_PALETTE[number - 30]
elif 40 <= number <= 47:
# 40-47 sets the background color from the eight color palette.
background_color = EIGHT_COLOR_PALETTE[number - 40]
elif 90 <= number <= 97:
# 90-97 sets the text color from the high-intensity eight color palette.
text_color = BRIGHT_COLOR_PALETTE[number - 90]
elif 100 <= number <= 107:
# 100-107 sets the background color from the high-intensity eight color palette.
background_color = BRIGHT_COLOR_PALETTE[number - 100]
elif number in (38, 39) and len(ansi_codes) >= 2 and ansi_codes[0] == 5:
# 38;5;N is a text color in the 256 color mode palette,
# 39;5;N is a background color in the 256 color mode palette.
try:
# Consume the 5 following 38 or 39.
ansi_codes.pop(0)
# Consume the 256 color mode color index.
color_index = ansi_codes.pop(0)
# Set the variable to the corresponding HTML/CSS color.
if number == 38:
text_color = EXTENDED_COLOR_PALETTE[color_index]
elif number == 39:
background_color = EXTENDED_COLOR_PALETTE[color_index]
except (ValueError, IndexError):
pass
# Apply the 'faint' or 'inverse' text style
# by manipulating the selected color(s).
if text_color and is_inverse:
# Use the text color as the background color and pick a
# text color that will be visible on the resulting
# background color.
background_color = text_color
text_color = select_text_color(*parse_hex_color(text_color))
if text_color and is_faint:
# Because I wasn't sure how to implement faint colors
# based on normal colors I looked at how gnome-terminal
# (my terminal of choice) handles this and it appears
# to just pick a somewhat darker color.
text_color = '#%02X%02X%02X' % tuple(
max(0, n - 40) for n in parse_hex_color(text_color)
)
if text_color:
styles['color'] = text_color
if background_color:
styles['background-color'] = background_color
if styles:
token = '<span style="%s">' % ';'.join(k + ':' + v for k, v in sorted(styles.items()))
in_span = True
else:
token = ''
else:
token = html_encode(token)
output.append(token)
html = ''.join(output)
html = encode_whitespace(html, tabsize)
if code:
html = '<code>%s</code>' % html
return html | [
"def",
"convert",
"(",
"text",
",",
"code",
"=",
"True",
",",
"tabsize",
"=",
"4",
")",
":",
"output",
"=",
"[",
"]",
"in_span",
"=",
"False",
"compatible_text_styles",
"=",
"{",
"# The following ANSI text styles have an obvious mapping to CSS.",
"ANSI_TEXT_STYLES",... | Convert text with ANSI escape sequences to HTML.
:param text: The text with ANSI escape sequences (a string).
:param code: Whether to wrap the returned HTML fragment in a
``<code>...</code>`` element (a boolean, defaults
to :data:`True`).
:param tabsize: Refer to :func:`str.expandtabs()` for details.
:returns: The text converted to HTML (a string). | [
"Convert",
"text",
"with",
"ANSI",
"escape",
"sequences",
"to",
"HTML",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L120-L229 | train | 210,312 |
xolox/python-coloredlogs | coloredlogs/converter/__init__.py | encode_whitespace | def encode_whitespace(text, tabsize=4):
"""
Encode whitespace so that web browsers properly render it.
:param text: The plain text (a string).
:param tabsize: Refer to :func:`str.expandtabs()` for details.
:returns: The text converted to HTML (a string).
The purpose of this function is to encode whitespace in such a way that web
browsers render the same whitespace regardless of whether 'preformatted'
styling is used (by wrapping the text in a ``<pre>...</pre>`` element).
.. note:: While the string manipulation performed by this function is
specifically intended not to corrupt the HTML generated by
:func:`convert()` it definitely does have the potential to
corrupt HTML from other sources. You have been warned :-).
"""
# Convert Windows line endings (CR+LF) to UNIX line endings (LF).
text = text.replace('\r\n', '\n')
# Convert UNIX line endings (LF) to HTML line endings (<br>).
text = text.replace('\n', '<br>\n')
# Convert tabs to spaces.
text = text.expandtabs(tabsize)
# Convert leading spaces (that is to say spaces at the start of the string
# and/or directly after a line ending) into non-breaking spaces, otherwise
# HTML rendering engines will simply ignore these spaces.
text = re.sub(INDENT_PATTERN, encode_whitespace_cb, text)
# The conversion of leading spaces we just did misses a corner case where a
# line starts with an HTML tag but the first visible text is a space. Web
# browsers seem to ignore these spaces, so we need to convert them.
text = re.sub(TAG_INDENT_PATTERN, r'\1 ', text)
# Convert runs of multiple spaces into non-breaking spaces to avoid HTML
# rendering engines from visually collapsing runs of spaces into a single
# space. We specifically don't replace single spaces for several reasons:
# 1. We'd break the HTML emitted by convert() by replacing spaces
# inside HTML elements (for example the spaces that separate
# element names from attribute names).
# 2. If every single space is replaced by a non-breaking space,
# web browsers perform awkwardly unintuitive word wrapping.
# 3. The HTML output would be bloated for no good reason.
text = re.sub(' {2,}', encode_whitespace_cb, text)
return text | python | def encode_whitespace(text, tabsize=4):
"""
Encode whitespace so that web browsers properly render it.
:param text: The plain text (a string).
:param tabsize: Refer to :func:`str.expandtabs()` for details.
:returns: The text converted to HTML (a string).
The purpose of this function is to encode whitespace in such a way that web
browsers render the same whitespace regardless of whether 'preformatted'
styling is used (by wrapping the text in a ``<pre>...</pre>`` element).
.. note:: While the string manipulation performed by this function is
specifically intended not to corrupt the HTML generated by
:func:`convert()` it definitely does have the potential to
corrupt HTML from other sources. You have been warned :-).
"""
# Convert Windows line endings (CR+LF) to UNIX line endings (LF).
text = text.replace('\r\n', '\n')
# Convert UNIX line endings (LF) to HTML line endings (<br>).
text = text.replace('\n', '<br>\n')
# Convert tabs to spaces.
text = text.expandtabs(tabsize)
# Convert leading spaces (that is to say spaces at the start of the string
# and/or directly after a line ending) into non-breaking spaces, otherwise
# HTML rendering engines will simply ignore these spaces.
text = re.sub(INDENT_PATTERN, encode_whitespace_cb, text)
# The conversion of leading spaces we just did misses a corner case where a
# line starts with an HTML tag but the first visible text is a space. Web
# browsers seem to ignore these spaces, so we need to convert them.
text = re.sub(TAG_INDENT_PATTERN, r'\1 ', text)
# Convert runs of multiple spaces into non-breaking spaces to avoid HTML
# rendering engines from visually collapsing runs of spaces into a single
# space. We specifically don't replace single spaces for several reasons:
# 1. We'd break the HTML emitted by convert() by replacing spaces
# inside HTML elements (for example the spaces that separate
# element names from attribute names).
# 2. If every single space is replaced by a non-breaking space,
# web browsers perform awkwardly unintuitive word wrapping.
# 3. The HTML output would be bloated for no good reason.
text = re.sub(' {2,}', encode_whitespace_cb, text)
return text | [
"def",
"encode_whitespace",
"(",
"text",
",",
"tabsize",
"=",
"4",
")",
":",
"# Convert Windows line endings (CR+LF) to UNIX line endings (LF).",
"text",
"=",
"text",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"# Convert UNIX line endings (LF) to HTML line endings ... | Encode whitespace so that web browsers properly render it.
:param text: The plain text (a string).
:param tabsize: Refer to :func:`str.expandtabs()` for details.
:returns: The text converted to HTML (a string).
The purpose of this function is to encode whitespace in such a way that web
browsers render the same whitespace regardless of whether 'preformatted'
styling is used (by wrapping the text in a ``<pre>...</pre>`` element).
.. note:: While the string manipulation performed by this function is
specifically intended not to corrupt the HTML generated by
:func:`convert()` it definitely does have the potential to
corrupt HTML from other sources. You have been warned :-). | [
"Encode",
"whitespace",
"so",
"that",
"web",
"browsers",
"properly",
"render",
"it",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L232-L273 | train | 210,313 |
xolox/python-coloredlogs | coloredlogs/converter/__init__.py | html_encode | def html_encode(text):
"""
Encode characters with a special meaning as HTML.
:param text: The plain text (a string).
:returns: The text converted to HTML (a string).
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
return text | python | def html_encode(text):
"""
Encode characters with a special meaning as HTML.
:param text: The plain text (a string).
:returns: The text converted to HTML (a string).
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
return text | [
"def",
"html_encode",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"'<'",
",",
"'<'",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"'>'",
",",
"'>'",
... | Encode characters with a special meaning as HTML.
:param text: The plain text (a string).
:returns: The text converted to HTML (a string). | [
"Encode",
"characters",
"with",
"a",
"special",
"meaning",
"as",
"HTML",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L289-L300 | train | 210,314 |
xolox/python-coloredlogs | coloredlogs/converter/__init__.py | parse_hex_color | def parse_hex_color(value):
"""
Convert a CSS color in hexadecimal notation into its R, G, B components.
:param value: A CSS color in hexadecimal notation (a string like '#000000').
:return: A tuple with three integers (with values between 0 and 255)
corresponding to the R, G and B components of the color.
:raises: :exc:`~exceptions.ValueError` on values that can't be parsed.
"""
if value.startswith('#'):
value = value[1:]
if len(value) == 3:
return (
int(value[0] * 2, 16),
int(value[1] * 2, 16),
int(value[2] * 2, 16),
)
elif len(value) == 6:
return (
int(value[0:2], 16),
int(value[2:4], 16),
int(value[4:6], 16),
)
else:
raise ValueError() | python | def parse_hex_color(value):
"""
Convert a CSS color in hexadecimal notation into its R, G, B components.
:param value: A CSS color in hexadecimal notation (a string like '#000000').
:return: A tuple with three integers (with values between 0 and 255)
corresponding to the R, G and B components of the color.
:raises: :exc:`~exceptions.ValueError` on values that can't be parsed.
"""
if value.startswith('#'):
value = value[1:]
if len(value) == 3:
return (
int(value[0] * 2, 16),
int(value[1] * 2, 16),
int(value[2] * 2, 16),
)
elif len(value) == 6:
return (
int(value[0:2], 16),
int(value[2:4], 16),
int(value[4:6], 16),
)
else:
raise ValueError() | [
"def",
"parse_hex_color",
"(",
"value",
")",
":",
"if",
"value",
".",
"startswith",
"(",
"'#'",
")",
":",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"value",
")",
"==",
"3",
":",
"return",
"(",
"int",
"(",
"value",
"[",
"0",
"... | Convert a CSS color in hexadecimal notation into its R, G, B components.
:param value: A CSS color in hexadecimal notation (a string like '#000000').
:return: A tuple with three integers (with values between 0 and 255)
corresponding to the R, G and B components of the color.
:raises: :exc:`~exceptions.ValueError` on values that can't be parsed. | [
"Convert",
"a",
"CSS",
"color",
"in",
"hexadecimal",
"notation",
"into",
"its",
"R",
"G",
"B",
"components",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L303-L327 | train | 210,315 |
xolox/python-coloredlogs | coloredlogs/syslog.py | find_syslog_address | def find_syslog_address():
"""
Find the most suitable destination for system log messages.
:returns: The pathname of a log device (a string) or an address/port tuple as
supported by :class:`~logging.handlers.SysLogHandler`.
On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX`
is checked for existence. If both of these device files don't exist the default used
by :class:`~logging.handlers.SysLogHandler` is returned.
"""
if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX):
return LOG_DEVICE_MACOSX
elif os.path.exists(LOG_DEVICE_UNIX):
return LOG_DEVICE_UNIX
else:
return 'localhost', logging.handlers.SYSLOG_UDP_PORT | python | def find_syslog_address():
"""
Find the most suitable destination for system log messages.
:returns: The pathname of a log device (a string) or an address/port tuple as
supported by :class:`~logging.handlers.SysLogHandler`.
On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX`
is checked for existence. If both of these device files don't exist the default used
by :class:`~logging.handlers.SysLogHandler` is returned.
"""
if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX):
return LOG_DEVICE_MACOSX
elif os.path.exists(LOG_DEVICE_UNIX):
return LOG_DEVICE_UNIX
else:
return 'localhost', logging.handlers.SYSLOG_UDP_PORT | [
"def",
"find_syslog_address",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"LOG_DEVICE_MACOSX",
")",
":",
"return",
"LOG_DEVICE_MACOSX",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"LOG_DEV... | Find the most suitable destination for system log messages.
:returns: The pathname of a log device (a string) or an address/port tuple as
supported by :class:`~logging.handlers.SysLogHandler`.
On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX`
is checked for existence. If both of these device files don't exist the default used
by :class:`~logging.handlers.SysLogHandler` is returned. | [
"Find",
"the",
"most",
"suitable",
"destination",
"for",
"system",
"log",
"messages",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/syslog.py#L207-L223 | train | 210,316 |
xolox/python-coloredlogs | scripts/generate-screenshots.py | generate_screenshots | def generate_screenshots():
"""Generate screenshots from shell scripts."""
this_script = os.path.abspath(__file__)
this_directory = os.path.dirname(this_script)
repository = os.path.join(this_directory, os.pardir)
examples_directory = os.path.join(repository, 'docs', 'examples')
images_directory = os.path.join(repository, 'docs', 'images')
for shell_script in sorted(glob.glob(os.path.join(examples_directory, '*.sh'))):
basename, extension = os.path.splitext(os.path.basename(shell_script))
image_file = os.path.join(images_directory, '%s.png' % basename)
logger.info("Generating %s by running %s ..",
format_path(image_file),
format_path(shell_script))
command_line = [sys.executable, __file__, shell_script]
random_title = random_string(25)
# Generate the urxvt command line.
urxvt_command = [
'urxvt',
# Enforce a default geometry.
'-geometry', '98x30',
# Set the text and background color.
'-fg', TEXT_COLOR,
'-bg', BACKGROUND_COLOR,
# Set the font name and pixel size.
'-fn', 'xft:%s:pixelsize=%i' % (FONT_NAME, FONT_SIZE),
# Set the window title.
'-title', random_title,
# Hide scrollbars.
'+sb',
]
if which('qtile-run'):
# I've been using tiling window managers for years now, at the
# moment 'qtile' is my window manager of choice. It requires the
# following special handling to enable the 'urxvt' window to float,
# which in turn enables it to respect the '--geometry' option.
urxvt_command.insert(0, 'qtile-run')
urxvt_command.insert(1, '-f')
# Apply the Ubuntu color scheme to urxvt.
for index, css_color in enumerate(EIGHT_COLOR_PALETTE):
urxvt_command.extend(('--color%i' % index, css_color))
# Add the command that should run inside the terminal.
urxvt_command.extend(('-e', 'sh', '-c', 'setterm -cursor off; %s' % quote(command_line)))
# Launch urxvt.
execute(*urxvt_command, async=True)
# Make sure we close the urxvt window.
try:
# Wait for urxvt to start up. If I were to improve this I could
# instead wait for the creation of a file by interpret_script().
time.sleep(10)
# Take a screen shot of the window using ImageMagick.
execute('import', '-window', random_title, image_file)
# Auto-trim the screen shot, then give it a 5px border.
execute('convert', image_file, '-trim',
'-bordercolor', BACKGROUND_COLOR,
'-border', '5', image_file)
finally:
execute('wmctrl', '-c', random_title) | python | def generate_screenshots():
"""Generate screenshots from shell scripts."""
this_script = os.path.abspath(__file__)
this_directory = os.path.dirname(this_script)
repository = os.path.join(this_directory, os.pardir)
examples_directory = os.path.join(repository, 'docs', 'examples')
images_directory = os.path.join(repository, 'docs', 'images')
for shell_script in sorted(glob.glob(os.path.join(examples_directory, '*.sh'))):
basename, extension = os.path.splitext(os.path.basename(shell_script))
image_file = os.path.join(images_directory, '%s.png' % basename)
logger.info("Generating %s by running %s ..",
format_path(image_file),
format_path(shell_script))
command_line = [sys.executable, __file__, shell_script]
random_title = random_string(25)
# Generate the urxvt command line.
urxvt_command = [
'urxvt',
# Enforce a default geometry.
'-geometry', '98x30',
# Set the text and background color.
'-fg', TEXT_COLOR,
'-bg', BACKGROUND_COLOR,
# Set the font name and pixel size.
'-fn', 'xft:%s:pixelsize=%i' % (FONT_NAME, FONT_SIZE),
# Set the window title.
'-title', random_title,
# Hide scrollbars.
'+sb',
]
if which('qtile-run'):
# I've been using tiling window managers for years now, at the
# moment 'qtile' is my window manager of choice. It requires the
# following special handling to enable the 'urxvt' window to float,
# which in turn enables it to respect the '--geometry' option.
urxvt_command.insert(0, 'qtile-run')
urxvt_command.insert(1, '-f')
# Apply the Ubuntu color scheme to urxvt.
for index, css_color in enumerate(EIGHT_COLOR_PALETTE):
urxvt_command.extend(('--color%i' % index, css_color))
# Add the command that should run inside the terminal.
urxvt_command.extend(('-e', 'sh', '-c', 'setterm -cursor off; %s' % quote(command_line)))
# Launch urxvt.
execute(*urxvt_command, async=True)
# Make sure we close the urxvt window.
try:
# Wait for urxvt to start up. If I were to improve this I could
# instead wait for the creation of a file by interpret_script().
time.sleep(10)
# Take a screen shot of the window using ImageMagick.
execute('import', '-window', random_title, image_file)
# Auto-trim the screen shot, then give it a 5px border.
execute('convert', image_file, '-trim',
'-bordercolor', BACKGROUND_COLOR,
'-border', '5', image_file)
finally:
execute('wmctrl', '-c', random_title) | [
"def",
"generate_screenshots",
"(",
")",
":",
"this_script",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"this_directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"this_script",
")",
"repository",
"=",
"os",
".",
"path",
".",
"join... | Generate screenshots from shell scripts. | [
"Generate",
"screenshots",
"from",
"shell",
"scripts",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/scripts/generate-screenshots.py#L87-L143 | train | 210,317 |
xolox/python-coloredlogs | scripts/generate-screenshots.py | interpret_script | def interpret_script(shell_script):
"""Make it appear as if commands are typed into the terminal."""
with CaptureOutput() as capturer:
shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE)
with open(shell_script) as handle:
for line in handle:
sys.stdout.write(ansi_wrap('$', color='green') + ' ' + line)
sys.stdout.flush()
shell.stdin.write(line)
shell.stdin.flush()
shell.stdin.close()
time.sleep(12)
# Get the text that was shown in the terminal.
captured_output = capturer.get_text()
# Store the text that was shown in the terminal.
filename, extension = os.path.splitext(shell_script)
transcript_file = '%s.txt' % filename
logger.info("Updating %s ..", format_path(transcript_file))
with open(transcript_file, 'w') as handle:
handle.write(ansi_strip(captured_output)) | python | def interpret_script(shell_script):
"""Make it appear as if commands are typed into the terminal."""
with CaptureOutput() as capturer:
shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE)
with open(shell_script) as handle:
for line in handle:
sys.stdout.write(ansi_wrap('$', color='green') + ' ' + line)
sys.stdout.flush()
shell.stdin.write(line)
shell.stdin.flush()
shell.stdin.close()
time.sleep(12)
# Get the text that was shown in the terminal.
captured_output = capturer.get_text()
# Store the text that was shown in the terminal.
filename, extension = os.path.splitext(shell_script)
transcript_file = '%s.txt' % filename
logger.info("Updating %s ..", format_path(transcript_file))
with open(transcript_file, 'w') as handle:
handle.write(ansi_strip(captured_output)) | [
"def",
"interpret_script",
"(",
"shell_script",
")",
":",
"with",
"CaptureOutput",
"(",
")",
"as",
"capturer",
":",
"shell",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'bash'",
",",
"'-'",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"with",
... | Make it appear as if commands are typed into the terminal. | [
"Make",
"it",
"appear",
"as",
"if",
"commands",
"are",
"typed",
"into",
"the",
"terminal",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/scripts/generate-screenshots.py#L146-L165 | train | 210,318 |
xolox/python-coloredlogs | setup.py | get_version | def get_version(*args):
"""Extract the version number from a Python module."""
contents = get_contents(*args)
metadata = dict(re.findall('__([a-z]+)__ = [\'"]([^\'"]+)', contents))
return metadata['version'] | python | def get_version(*args):
"""Extract the version number from a Python module."""
contents = get_contents(*args)
metadata = dict(re.findall('__([a-z]+)__ = [\'"]([^\'"]+)', contents))
return metadata['version'] | [
"def",
"get_version",
"(",
"*",
"args",
")",
":",
"contents",
"=",
"get_contents",
"(",
"*",
"args",
")",
"metadata",
"=",
"dict",
"(",
"re",
".",
"findall",
"(",
"'__([a-z]+)__ = [\\'\"]([^\\'\"]+)'",
",",
"contents",
")",
")",
"return",
"metadata",
"[",
... | Extract the version number from a Python module. | [
"Extract",
"the",
"version",
"number",
"from",
"a",
"Python",
"module",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/setup.py#L39-L43 | train | 210,319 |
xolox/python-coloredlogs | setup.py | have_environment_marker_support | def have_environment_marker_support():
"""
Check whether setuptools has support for PEP-426 environment marker support.
Based on the ``setup.py`` script of the ``pytest`` package:
https://bitbucket.org/pytest-dev/pytest/src/default/setup.py
"""
try:
from pkg_resources import parse_version
from setuptools import __version__
return parse_version(__version__) >= parse_version('0.7.2')
except Exception:
return False | python | def have_environment_marker_support():
"""
Check whether setuptools has support for PEP-426 environment marker support.
Based on the ``setup.py`` script of the ``pytest`` package:
https://bitbucket.org/pytest-dev/pytest/src/default/setup.py
"""
try:
from pkg_resources import parse_version
from setuptools import __version__
return parse_version(__version__) >= parse_version('0.7.2')
except Exception:
return False | [
"def",
"have_environment_marker_support",
"(",
")",
":",
"try",
":",
"from",
"pkg_resources",
"import",
"parse_version",
"from",
"setuptools",
"import",
"__version__",
"return",
"parse_version",
"(",
"__version__",
")",
">=",
"parse_version",
"(",
"'0.7.2'",
")",
"e... | Check whether setuptools has support for PEP-426 environment marker support.
Based on the ``setup.py`` script of the ``pytest`` package:
https://bitbucket.org/pytest-dev/pytest/src/default/setup.py | [
"Check",
"whether",
"setuptools",
"has",
"support",
"for",
"PEP",
"-",
"426",
"environment",
"marker",
"support",
"."
] | 1cbf0c6bbee400c6ddbc43008143809934ec3e79 | https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/setup.py#L82-L94 | train | 210,320 |
Workable/flask-log-request-id | flask_log_request_id/request_id.py | RequestID._log_http_event | def _log_http_event(response):
"""
It will create a log event as werkzeug but at the end of request holding the request-id
Intended usage is a handler of Flask.after_request
:return: The same response object
"""
logger.info(
'{ip} - - "{method} {path} {status_code}"'.format(
ip=request.remote_addr,
method=request.method,
path=request.path,
status_code=response.status_code)
)
return response | python | def _log_http_event(response):
"""
It will create a log event as werkzeug but at the end of request holding the request-id
Intended usage is a handler of Flask.after_request
:return: The same response object
"""
logger.info(
'{ip} - - "{method} {path} {status_code}"'.format(
ip=request.remote_addr,
method=request.method,
path=request.path,
status_code=response.status_code)
)
return response | [
"def",
"_log_http_event",
"(",
"response",
")",
":",
"logger",
".",
"info",
"(",
"'{ip} - - \"{method} {path} {status_code}\"'",
".",
"format",
"(",
"ip",
"=",
"request",
".",
"remote_addr",
",",
"method",
"=",
"request",
".",
"method",
",",
"path",
"=",
"requ... | It will create a log event as werkzeug but at the end of request holding the request-id
Intended usage is a handler of Flask.after_request
:return: The same response object | [
"It",
"will",
"create",
"a",
"log",
"event",
"as",
"werkzeug",
"but",
"at",
"the",
"end",
"of",
"request",
"holding",
"the",
"request",
"-",
"id"
] | 3aaea86dfe2621ecc443a1e739ae6a27ae1187be | https://github.com/Workable/flask-log-request-id/blob/3aaea86dfe2621ecc443a1e739ae6a27ae1187be/flask_log_request_id/request_id.py#L88-L102 | train | 210,321 |
ecmwf/cfgrib | cfgrib/cfmessage.py | build_valid_time | def build_valid_time(time, step):
# type: (np.ndarray, np.ndarray) -> T.Tuple[T.Tuple[str, ...], np.ndarray]
"""
Return dimensions and data of the valid_time corresponding to the given ``time`` and ``step``.
The data is seconds from the same epoch as ``time`` and may have one or two dimensions.
:param time: given in seconds from an epoch, as returned by ``from_grib_date_time``
:param step: given in hours, as returned by ``from_grib_step``
"""
step_s = step * 3600
if len(time.shape) == 0 and len(step.shape) == 0:
data = time + step_s
dims = () # type: T.Tuple[str, ...]
elif len(time.shape) > 0 and len(step.shape) == 0:
data = time + step_s
dims = ('time',)
elif len(time.shape) == 0 and len(step.shape) > 0:
data = time + step_s
dims = ('step',)
else:
data = time[:, None] + step_s[None, :]
dims = ('time', 'step')
return dims, data | python | def build_valid_time(time, step):
# type: (np.ndarray, np.ndarray) -> T.Tuple[T.Tuple[str, ...], np.ndarray]
"""
Return dimensions and data of the valid_time corresponding to the given ``time`` and ``step``.
The data is seconds from the same epoch as ``time`` and may have one or two dimensions.
:param time: given in seconds from an epoch, as returned by ``from_grib_date_time``
:param step: given in hours, as returned by ``from_grib_step``
"""
step_s = step * 3600
if len(time.shape) == 0 and len(step.shape) == 0:
data = time + step_s
dims = () # type: T.Tuple[str, ...]
elif len(time.shape) > 0 and len(step.shape) == 0:
data = time + step_s
dims = ('time',)
elif len(time.shape) == 0 and len(step.shape) > 0:
data = time + step_s
dims = ('step',)
else:
data = time[:, None] + step_s[None, :]
dims = ('time', 'step')
return dims, data | [
"def",
"build_valid_time",
"(",
"time",
",",
"step",
")",
":",
"# type: (np.ndarray, np.ndarray) -> T.Tuple[T.Tuple[str, ...], np.ndarray]",
"step_s",
"=",
"step",
"*",
"3600",
"if",
"len",
"(",
"time",
".",
"shape",
")",
"==",
"0",
"and",
"len",
"(",
"step",
".... | Return dimensions and data of the valid_time corresponding to the given ``time`` and ``step``.
The data is seconds from the same epoch as ``time`` and may have one or two dimensions.
:param time: given in seconds from an epoch, as returned by ``from_grib_date_time``
:param step: given in hours, as returned by ``from_grib_step`` | [
"Return",
"dimensions",
"and",
"data",
"of",
"the",
"valid_time",
"corresponding",
"to",
"the",
"given",
"time",
"and",
"step",
".",
"The",
"data",
"is",
"seconds",
"from",
"the",
"same",
"epoch",
"as",
"time",
"and",
"may",
"have",
"one",
"or",
"two",
"... | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/cfmessage.py#L92-L114 | train | 210,322 |
ecmwf/cfgrib | cfgrib/dataset.py | open_file | def open_file(path, grib_errors='warn', **kwargs):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs:
warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning)
kwargs.pop('mode')
stream = messages.FileStream(path, message_class=cfmessage.CfMessage, errors=grib_errors)
return Dataset(*build_dataset_components(stream, **kwargs)) | python | def open_file(path, grib_errors='warn', **kwargs):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs:
warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning)
kwargs.pop('mode')
stream = messages.FileStream(path, message_class=cfmessage.CfMessage, errors=grib_errors)
return Dataset(*build_dataset_components(stream, **kwargs)) | [
"def",
"open_file",
"(",
"path",
",",
"grib_errors",
"=",
"'warn'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mode'",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"the `mode` keyword argument is ignored and deprecated\"",
",",
"FutureWarning",
")",
"kwa... | Open a GRIB file as a ``cfgrib.Dataset``. | [
"Open",
"a",
"GRIB",
"file",
"as",
"a",
"cfgrib",
".",
"Dataset",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/dataset.py#L502-L508 | train | 210,323 |
ecmwf/cfgrib | cfgrib/xarray_store.py | open_dataset | def open_dataset(path, **kwargs):
# type: (str, T.Any) -> xr.Dataset
"""
Return a ``xr.Dataset`` with the requested ``backend_kwargs`` from a GRIB file.
"""
if 'engine' in kwargs and kwargs['engine'] != 'cfgrib':
raise ValueError("only engine=='cfgrib' is supported")
kwargs['engine'] = 'cfgrib'
return xr.backends.api.open_dataset(path, **kwargs) | python | def open_dataset(path, **kwargs):
# type: (str, T.Any) -> xr.Dataset
"""
Return a ``xr.Dataset`` with the requested ``backend_kwargs`` from a GRIB file.
"""
if 'engine' in kwargs and kwargs['engine'] != 'cfgrib':
raise ValueError("only engine=='cfgrib' is supported")
kwargs['engine'] = 'cfgrib'
return xr.backends.api.open_dataset(path, **kwargs) | [
"def",
"open_dataset",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, T.Any) -> xr.Dataset",
"if",
"'engine'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'engine'",
"]",
"!=",
"'cfgrib'",
":",
"raise",
"ValueError",
"(",
"\"only engine=='cfgrib' is sup... | Return a ``xr.Dataset`` with the requested ``backend_kwargs`` from a GRIB file. | [
"Return",
"a",
"xr",
".",
"Dataset",
"with",
"the",
"requested",
"backend_kwargs",
"from",
"a",
"GRIB",
"file",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/xarray_store.py#L31-L39 | train | 210,324 |
ecmwf/cfgrib | cfgrib/xarray_store.py | open_datasets | def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs):
# type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset]
"""
Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics.
"""
if not no_warn:
warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning)
fbks = []
datasets = []
try:
datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs))
except DatasetBuildError as ex:
fbks.extend(ex.args[2])
# NOTE: the recursive call needs to stay out of the exception handler to avoid showing
# to the user a confusing error message due to exception chaining
for fbk in fbks:
bks = backend_kwargs.copy()
bks['filter_by_keys'] = fbk
datasets.extend(open_datasets(path, backend_kwargs=bks, no_warn=True, **kwargs))
return datasets | python | def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs):
# type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset]
"""
Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics.
"""
if not no_warn:
warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning)
fbks = []
datasets = []
try:
datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs))
except DatasetBuildError as ex:
fbks.extend(ex.args[2])
# NOTE: the recursive call needs to stay out of the exception handler to avoid showing
# to the user a confusing error message due to exception chaining
for fbk in fbks:
bks = backend_kwargs.copy()
bks['filter_by_keys'] = fbk
datasets.extend(open_datasets(path, backend_kwargs=bks, no_warn=True, **kwargs))
return datasets | [
"def",
"open_datasets",
"(",
"path",
",",
"backend_kwargs",
"=",
"{",
"}",
",",
"no_warn",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset]",
"if",
"not",
"no_warn",
":",
"warnings",
".",
"warn"... | Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics. | [
"Open",
"a",
"GRIB",
"file",
"groupping",
"incompatible",
"hypercubes",
"to",
"different",
"datasets",
"via",
"simple",
"heuristics",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/xarray_store.py#L42-L62 | train | 210,325 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_size | def codes_get_size(handle, key):
# type: (cffi.FFI.CData, str) -> int
"""
Get the number of coded value from a key.
If several keys of the same name are present, the total sum is returned.
:param bytes key: the keyword to get the size of
:rtype: int
"""
size = ffi.new('size_t *')
_codes_get_size(handle, key.encode(ENC), size)
return size[0] | python | def codes_get_size(handle, key):
# type: (cffi.FFI.CData, str) -> int
"""
Get the number of coded value from a key.
If several keys of the same name are present, the total sum is returned.
:param bytes key: the keyword to get the size of
:rtype: int
"""
size = ffi.new('size_t *')
_codes_get_size(handle, key.encode(ENC), size)
return size[0] | [
"def",
"codes_get_size",
"(",
"handle",
",",
"key",
")",
":",
"# type: (cffi.FFI.CData, str) -> int",
"size",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
")",
"_codes_get_size",
"(",
"handle",
",",
"key",
".",
"encode",
"(",
"ENC",
")",
",",
"size",
")",
"r... | Get the number of coded value from a key.
If several keys of the same name are present, the total sum is returned.
:param bytes key: the keyword to get the size of
:rtype: int | [
"Get",
"the",
"number",
"of",
"coded",
"value",
"from",
"a",
"key",
".",
"If",
"several",
"keys",
"of",
"the",
"same",
"name",
"are",
"present",
"the",
"total",
"sum",
"is",
"returned",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L212-L224 | train | 210,326 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_string_length | def codes_get_string_length(handle, key):
# type: (cffi.FFI.CData, str) -> int
"""
Get the length of the string representation of the key.
If several keys of the same name are present, the maximum length is returned.
:param bytes key: the keyword to get the string representation size of.
:rtype: int
"""
size = ffi.new('size_t *')
_codes_get_length(handle, key.encode(ENC), size)
return size[0] | python | def codes_get_string_length(handle, key):
# type: (cffi.FFI.CData, str) -> int
"""
Get the length of the string representation of the key.
If several keys of the same name are present, the maximum length is returned.
:param bytes key: the keyword to get the string representation size of.
:rtype: int
"""
size = ffi.new('size_t *')
_codes_get_length(handle, key.encode(ENC), size)
return size[0] | [
"def",
"codes_get_string_length",
"(",
"handle",
",",
"key",
")",
":",
"# type: (cffi.FFI.CData, str) -> int",
"size",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
")",
"_codes_get_length",
"(",
"handle",
",",
"key",
".",
"encode",
"(",
"ENC",
")",
",",
"size",
... | Get the length of the string representation of the key.
If several keys of the same name are present, the maximum length is returned.
:param bytes key: the keyword to get the string representation size of.
:rtype: int | [
"Get",
"the",
"length",
"of",
"the",
"string",
"representation",
"of",
"the",
"key",
".",
"If",
"several",
"keys",
"of",
"the",
"same",
"name",
"are",
"present",
"the",
"maximum",
"length",
"is",
"returned",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L230-L242 | train | 210,327 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_bytes_array | def codes_get_bytes_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[int]
"""
Get unsigned chars array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int)
"""
values = ffi.new('unsigned char[]', size)
size_p = ffi.new('size_t *', size)
_codes_get_bytes(handle, key.encode(ENC), values, size_p)
return list(values) | python | def codes_get_bytes_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[int]
"""
Get unsigned chars array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int)
"""
values = ffi.new('unsigned char[]', size)
size_p = ffi.new('size_t *', size)
_codes_get_bytes(handle, key.encode(ENC), values, size_p)
return list(values) | [
"def",
"codes_get_bytes_array",
"(",
"handle",
",",
"key",
",",
"size",
")",
":",
"# type: (cffi.FFI.CData, str, int) -> T.List[int]",
"values",
"=",
"ffi",
".",
"new",
"(",
"'unsigned char[]'",
",",
"size",
")",
"size_p",
"=",
"ffi",
".",
"new",
"(",
"'size_t *... | Get unsigned chars array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int) | [
"Get",
"unsigned",
"chars",
"array",
"values",
"from",
"a",
"key",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L248-L260 | train | 210,328 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_long_array | def codes_get_long_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[int]
"""
Get long array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int)
"""
values = ffi.new('long[]', size)
size_p = ffi.new('size_t *', size)
_codes_get_long_array(handle, key.encode(ENC), values, size_p)
return list(values) | python | def codes_get_long_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[int]
"""
Get long array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int)
"""
values = ffi.new('long[]', size)
size_p = ffi.new('size_t *', size)
_codes_get_long_array(handle, key.encode(ENC), values, size_p)
return list(values) | [
"def",
"codes_get_long_array",
"(",
"handle",
",",
"key",
",",
"size",
")",
":",
"# type: (cffi.FFI.CData, str, int) -> T.List[int]",
"values",
"=",
"ffi",
".",
"new",
"(",
"'long[]'",
",",
"size",
")",
"size_p",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
",",... | Get long array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int) | [
"Get",
"long",
"array",
"values",
"from",
"a",
"key",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L266-L278 | train | 210,329 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_double_array | def codes_get_double_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[float]
"""
Get double array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: T.List(float)
"""
values = ffi.new('double[]', size)
size_p = ffi.new('size_t *', size)
_codes_get_double_array(handle, key.encode(ENC), values, size_p)
return list(values) | python | def codes_get_double_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[float]
"""
Get double array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: T.List(float)
"""
values = ffi.new('double[]', size)
size_p = ffi.new('size_t *', size)
_codes_get_double_array(handle, key.encode(ENC), values, size_p)
return list(values) | [
"def",
"codes_get_double_array",
"(",
"handle",
",",
"key",
",",
"size",
")",
":",
"# type: (cffi.FFI.CData, str, int) -> T.List[float]",
"values",
"=",
"ffi",
".",
"new",
"(",
"'double[]'",
",",
"size",
")",
"size_p",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
... | Get double array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: T.List(float) | [
"Get",
"double",
"array",
"values",
"from",
"a",
"key",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L284-L296 | train | 210,330 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_string_array | def codes_get_string_array(handle, key, size, length=None):
# type: (cffi.FFI.CData, bytes, int, int) -> T.List[bytes]
"""
Get string array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: T.List[bytes]
"""
if length is None:
length = codes_get_string_length(handle, key)
values_keepalive = [ffi.new('char[]', length) for _ in range(size)]
values = ffi.new('char*[]', values_keepalive)
size_p = ffi.new('size_t *', size)
_codes_get_string_array(handle, key.encode(ENC), values, size_p)
return [ffi.string(values[i]).decode(ENC) for i in range(size_p[0])] | python | def codes_get_string_array(handle, key, size, length=None):
# type: (cffi.FFI.CData, bytes, int, int) -> T.List[bytes]
"""
Get string array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: T.List[bytes]
"""
if length is None:
length = codes_get_string_length(handle, key)
values_keepalive = [ffi.new('char[]', length) for _ in range(size)]
values = ffi.new('char*[]', values_keepalive)
size_p = ffi.new('size_t *', size)
_codes_get_string_array(handle, key.encode(ENC), values, size_p)
return [ffi.string(values[i]).decode(ENC) for i in range(size_p[0])] | [
"def",
"codes_get_string_array",
"(",
"handle",
",",
"key",
",",
"size",
",",
"length",
"=",
"None",
")",
":",
"# type: (cffi.FFI.CData, bytes, int, int) -> T.List[bytes]",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"codes_get_string_length",
"(",
"handle",
"... | Get string array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: T.List[bytes] | [
"Get",
"string",
"array",
"values",
"from",
"a",
"key",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L302-L317 | train | 210,331 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_string | def codes_get_string(handle, key, length=None):
# type: (cffi.FFI.CData, str, int) -> str
"""
Get string element from a key.
It may or may not fail in case there are more than one key in a message.
Outputs the last element.
:param bytes key: the keyword to select the value of
:param bool strict: flag to select if the method should fail in case of
more than one key in single message
:rtype: bytes
"""
if length is None:
length = codes_get_string_length(handle, key)
values = ffi.new('char[]', length)
length_p = ffi.new('size_t *', length)
_codes_get_string = check_return(lib.codes_get_string)
_codes_get_string(handle, key.encode(ENC), values, length_p)
return ffi.string(values, length_p[0]).decode(ENC) | python | def codes_get_string(handle, key, length=None):
# type: (cffi.FFI.CData, str, int) -> str
"""
Get string element from a key.
It may or may not fail in case there are more than one key in a message.
Outputs the last element.
:param bytes key: the keyword to select the value of
:param bool strict: flag to select if the method should fail in case of
more than one key in single message
:rtype: bytes
"""
if length is None:
length = codes_get_string_length(handle, key)
values = ffi.new('char[]', length)
length_p = ffi.new('size_t *', length)
_codes_get_string = check_return(lib.codes_get_string)
_codes_get_string(handle, key.encode(ENC), values, length_p)
return ffi.string(values, length_p[0]).decode(ENC) | [
"def",
"codes_get_string",
"(",
"handle",
",",
"key",
",",
"length",
"=",
"None",
")",
":",
"# type: (cffi.FFI.CData, str, int) -> str",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"codes_get_string_length",
"(",
"handle",
",",
"key",
")",
"values",
"=",
... | Get string element from a key.
It may or may not fail in case there are more than one key in a message.
Outputs the last element.
:param bytes key: the keyword to select the value of
:param bool strict: flag to select if the method should fail in case of
more than one key in single message
:rtype: bytes | [
"Get",
"string",
"element",
"from",
"a",
"key",
".",
"It",
"may",
"or",
"may",
"not",
"fail",
"in",
"case",
"there",
"are",
"more",
"than",
"one",
"key",
"in",
"a",
"message",
".",
"Outputs",
"the",
"last",
"element",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L336-L355 | train | 210,332 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_get_api_version | def codes_get_api_version():
"""
Get the API version.
Returns the version of the API as a string in the format "major.minor.revision".
"""
ver = lib.codes_get_api_version()
patch = ver % 100
ver = ver // 100
minor = ver % 100
major = ver // 100
return "%d.%d.%d" % (major, minor, patch) | python | def codes_get_api_version():
"""
Get the API version.
Returns the version of the API as a string in the format "major.minor.revision".
"""
ver = lib.codes_get_api_version()
patch = ver % 100
ver = ver // 100
minor = ver % 100
major = ver // 100
return "%d.%d.%d" % (major, minor, patch) | [
"def",
"codes_get_api_version",
"(",
")",
":",
"ver",
"=",
"lib",
".",
"codes_get_api_version",
"(",
")",
"patch",
"=",
"ver",
"%",
"100",
"ver",
"=",
"ver",
"//",
"100",
"minor",
"=",
"ver",
"%",
"100",
"major",
"=",
"ver",
"//",
"100",
"return",
"\... | Get the API version.
Returns the version of the API as a string in the format "major.minor.revision". | [
"Get",
"the",
"API",
"version",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L427-L439 | train | 210,333 |
ecmwf/cfgrib | cfgrib/bindings.py | codes_write | def codes_write(handle, outfile):
# type: (cffi.FFI.CData, T.BinaryIO) -> None
"""
Write a coded message to a file. If the file does not exist, it is created.
:param str path: (optional) the path to the GRIB file;
defaults to the one of the open index.
"""
mess = ffi.new('const void **')
mess_len = ffi.new('size_t*')
codes_get_message = check_return(lib.codes_get_message)
codes_get_message(handle, mess, mess_len)
message = ffi.buffer(mess[0], size=mess_len[0])
outfile.write(message) | python | def codes_write(handle, outfile):
# type: (cffi.FFI.CData, T.BinaryIO) -> None
"""
Write a coded message to a file. If the file does not exist, it is created.
:param str path: (optional) the path to the GRIB file;
defaults to the one of the open index.
"""
mess = ffi.new('const void **')
mess_len = ffi.new('size_t*')
codes_get_message = check_return(lib.codes_get_message)
codes_get_message(handle, mess, mess_len)
message = ffi.buffer(mess[0], size=mess_len[0])
outfile.write(message) | [
"def",
"codes_write",
"(",
"handle",
",",
"outfile",
")",
":",
"# type: (cffi.FFI.CData, T.BinaryIO) -> None",
"mess",
"=",
"ffi",
".",
"new",
"(",
"'const void **'",
")",
"mess_len",
"=",
"ffi",
".",
"new",
"(",
"'size_t*'",
")",
"codes_get_message",
"=",
"chec... | Write a coded message to a file. If the file does not exist, it is created.
:param str path: (optional) the path to the GRIB file;
defaults to the one of the open index. | [
"Write",
"a",
"coded",
"message",
"to",
"a",
"file",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"it",
"is",
"created",
"."
] | d6d533f49c1eebf78f2f16ed0671c666de08c666 | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L553-L566 | train | 210,334 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.update | def update(self, sequence):
"""
Update the set with the given iterable sequence, then return the index
of the last element inserted.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.update([3, 1, 5, 1, 4])
4
>>> print(oset)
OrderedSet([1, 2, 3, 5, 4])
"""
item_index = None
try:
for item in sequence:
item_index = self.add(item)
except TypeError:
raise ValueError(
"Argument needs to be an iterable, got %s" % type(sequence)
)
return item_index | python | def update(self, sequence):
"""
Update the set with the given iterable sequence, then return the index
of the last element inserted.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.update([3, 1, 5, 1, 4])
4
>>> print(oset)
OrderedSet([1, 2, 3, 5, 4])
"""
item_index = None
try:
for item in sequence:
item_index = self.add(item)
except TypeError:
raise ValueError(
"Argument needs to be an iterable, got %s" % type(sequence)
)
return item_index | [
"def",
"update",
"(",
"self",
",",
"sequence",
")",
":",
"item_index",
"=",
"None",
"try",
":",
"for",
"item",
"in",
"sequence",
":",
"item_index",
"=",
"self",
".",
"add",
"(",
"item",
")",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"\"Ar... | Update the set with the given iterable sequence, then return the index
of the last element inserted.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.update([3, 1, 5, 1, 4])
4
>>> print(oset)
OrderedSet([1, 2, 3, 5, 4]) | [
"Update",
"the",
"set",
"with",
"the",
"given",
"iterable",
"sequence",
"then",
"return",
"the",
"index",
"of",
"the",
"last",
"element",
"inserted",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L166-L186 | train | 210,335 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.pop | def pop(self):
"""
Remove and return the last element from the set.
Raises KeyError if the set is empty.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.pop()
3
"""
if not self.items:
raise KeyError("Set is empty")
elem = self.items[-1]
del self.items[-1]
del self.map[elem]
return elem | python | def pop(self):
"""
Remove and return the last element from the set.
Raises KeyError if the set is empty.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.pop()
3
"""
if not self.items:
raise KeyError("Set is empty")
elem = self.items[-1]
del self.items[-1]
del self.map[elem]
return elem | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"items",
":",
"raise",
"KeyError",
"(",
"\"Set is empty\"",
")",
"elem",
"=",
"self",
".",
"items",
"[",
"-",
"1",
"]",
"del",
"self",
".",
"items",
"[",
"-",
"1",
"]",
"del",
"self",... | Remove and return the last element from the set.
Raises KeyError if the set is empty.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.pop()
3 | [
"Remove",
"and",
"return",
"the",
"last",
"element",
"from",
"the",
"set",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L209-L226 | train | 210,336 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.union | def union(self, *sets):
"""
Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])
>>> oset | {10}
OrderedSet([3, 1, 4, 5, 2, 0, 10])
"""
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
containers = map(list, it.chain([self], sets))
items = it.chain.from_iterable(containers)
return cls(items) | python | def union(self, *sets):
"""
Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])
>>> oset | {10}
OrderedSet([3, 1, 4, 5, 2, 0, 10])
"""
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
containers = map(list, it.chain([self], sets))
items = it.chain.from_iterable(containers)
return cls(items) | [
"def",
"union",
"(",
"self",
",",
"*",
"sets",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"isinstance",
"(",
"self",
",",
"OrderedSet",
")",
"else",
"OrderedSet",
"containers",
"=",
"map",
"(",
"list",
",",
"it",
".",
"chain",
"(",
"[",
... | Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])
>>> oset | {10}
OrderedSet([3, 1, 4, 5, 2, 0, 10]) | [
"Combines",
"all",
"unique",
"items",
".",
"Each",
"items",
"order",
"is",
"defined",
"by",
"its",
"first",
"appearance",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L310-L327 | train | 210,337 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.intersection | def intersection(self, *sets):
"""
Returns elements in common between all sets. Order is defined only
by the first set.
Example:
>>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])
>>> print(oset)
OrderedSet([1, 2, 3])
>>> oset.intersection([2, 4, 5], [1, 2, 3, 4])
OrderedSet([2])
>>> oset.intersection()
OrderedSet([1, 2, 3])
"""
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
if sets:
common = set.intersection(*map(set, sets))
items = (item for item in self if item in common)
else:
items = self
return cls(items) | python | def intersection(self, *sets):
"""
Returns elements in common between all sets. Order is defined only
by the first set.
Example:
>>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])
>>> print(oset)
OrderedSet([1, 2, 3])
>>> oset.intersection([2, 4, 5], [1, 2, 3, 4])
OrderedSet([2])
>>> oset.intersection()
OrderedSet([1, 2, 3])
"""
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
if sets:
common = set.intersection(*map(set, sets))
items = (item for item in self if item in common)
else:
items = self
return cls(items) | [
"def",
"intersection",
"(",
"self",
",",
"*",
"sets",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"isinstance",
"(",
"self",
",",
"OrderedSet",
")",
"else",
"OrderedSet",
"if",
"sets",
":",
"common",
"=",
"set",
".",
"intersection",
"(",
"*",... | Returns elements in common between all sets. Order is defined only
by the first set.
Example:
>>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])
>>> print(oset)
OrderedSet([1, 2, 3])
>>> oset.intersection([2, 4, 5], [1, 2, 3, 4])
OrderedSet([2])
>>> oset.intersection()
OrderedSet([1, 2, 3]) | [
"Returns",
"elements",
"in",
"common",
"between",
"all",
"sets",
".",
"Order",
"is",
"defined",
"only",
"by",
"the",
"first",
"set",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L333-L353 | train | 210,338 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.difference | def difference(self, *sets):
"""
Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3])
"""
cls = self.__class__
if sets:
other = set.union(*map(set, sets))
items = (item for item in self if item not in other)
else:
items = self
return cls(items) | python | def difference(self, *sets):
"""
Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3])
"""
cls = self.__class__
if sets:
other = set.union(*map(set, sets))
items = (item for item in self if item not in other)
else:
items = self
return cls(items) | [
"def",
"difference",
"(",
"self",
",",
"*",
"sets",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"sets",
":",
"other",
"=",
"set",
".",
"union",
"(",
"*",
"map",
"(",
"set",
",",
"sets",
")",
")",
"items",
"=",
"(",
"item",
"for",
"ite... | Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3]) | [
"Returns",
"all",
"elements",
"that",
"are",
"in",
"this",
"set",
"but",
"not",
"the",
"others",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L355-L375 | train | 210,339 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.issubset | def issubset(self, other):
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
"""
if len(self) > len(other): # Fast check for obvious cases
return False
return all(item in other for item in self) | python | def issubset(self, other):
"""
Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False
"""
if len(self) > len(other): # Fast check for obvious cases
return False
return all(item in other for item in self) | [
"def",
"issubset",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"self",
")",
">",
"len",
"(",
"other",
")",
":",
"# Fast check for obvious cases",
"return",
"False",
"return",
"all",
"(",
"item",
"in",
"other",
"for",
"item",
"in",
"self",
")... | Report whether another set contains this set.
Example:
>>> OrderedSet([1, 2, 3]).issubset({1, 2})
False
>>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})
True
>>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})
False | [
"Report",
"whether",
"another",
"set",
"contains",
"this",
"set",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L377-L391 | train | 210,340 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.issuperset | def issuperset(self, other):
"""
Report whether this set contains another set.
Example:
>>> OrderedSet([1, 2]).issuperset([1, 2, 3])
False
>>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
True
>>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})
False
"""
if len(self) < len(other): # Fast check for obvious cases
return False
return all(item in self for item in other) | python | def issuperset(self, other):
"""
Report whether this set contains another set.
Example:
>>> OrderedSet([1, 2]).issuperset([1, 2, 3])
False
>>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
True
>>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})
False
"""
if len(self) < len(other): # Fast check for obvious cases
return False
return all(item in self for item in other) | [
"def",
"issuperset",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"len",
"(",
"other",
")",
":",
"# Fast check for obvious cases",
"return",
"False",
"return",
"all",
"(",
"item",
"in",
"self",
"for",
"item",
"in",
"other",
... | Report whether this set contains another set.
Example:
>>> OrderedSet([1, 2]).issuperset([1, 2, 3])
False
>>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
True
>>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})
False | [
"Report",
"whether",
"this",
"set",
"contains",
"another",
"set",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L393-L407 | train | 210,341 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.symmetric_difference | def symmetric_difference(self, other):
"""
Return the symmetric difference of two OrderedSets as a new set.
That is, the new set will contain all elements that are in exactly
one of the sets.
Their order will be preserved, with elements from `self` preceding
elements from `other`.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference(other)
OrderedSet([4, 5, 9, 2])
"""
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
diff1 = cls(self).difference(other)
diff2 = cls(other).difference(self)
return diff1.union(diff2) | python | def symmetric_difference(self, other):
"""
Return the symmetric difference of two OrderedSets as a new set.
That is, the new set will contain all elements that are in exactly
one of the sets.
Their order will be preserved, with elements from `self` preceding
elements from `other`.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference(other)
OrderedSet([4, 5, 9, 2])
"""
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet
diff1 = cls(self).difference(other)
diff2 = cls(other).difference(self)
return diff1.union(diff2) | [
"def",
"symmetric_difference",
"(",
"self",
",",
"other",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"isinstance",
"(",
"self",
",",
"OrderedSet",
")",
"else",
"OrderedSet",
"diff1",
"=",
"cls",
"(",
"self",
")",
".",
"difference",
"(",
"other... | Return the symmetric difference of two OrderedSets as a new set.
That is, the new set will contain all elements that are in exactly
one of the sets.
Their order will be preserved, with elements from `self` preceding
elements from `other`.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference(other)
OrderedSet([4, 5, 9, 2]) | [
"Return",
"the",
"symmetric",
"difference",
"of",
"two",
"OrderedSets",
"as",
"a",
"new",
"set",
".",
"That",
"is",
"the",
"new",
"set",
"will",
"contain",
"all",
"elements",
"that",
"are",
"in",
"exactly",
"one",
"of",
"the",
"sets",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L409-L427 | train | 210,342 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet._update_items | def _update_items(self, items):
"""
Replace the 'items' list of this OrderedSet with a new one, updating
self.map accordingly.
"""
self.items = items
self.map = {item: idx for (idx, item) in enumerate(items)} | python | def _update_items(self, items):
"""
Replace the 'items' list of this OrderedSet with a new one, updating
self.map accordingly.
"""
self.items = items
self.map = {item: idx for (idx, item) in enumerate(items)} | [
"def",
"_update_items",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"items",
"=",
"items",
"self",
".",
"map",
"=",
"{",
"item",
":",
"idx",
"for",
"(",
"idx",
",",
"item",
")",
"in",
"enumerate",
"(",
"items",
")",
"}"
] | Replace the 'items' list of this OrderedSet with a new one, updating
self.map accordingly. | [
"Replace",
"the",
"items",
"list",
"of",
"this",
"OrderedSet",
"with",
"a",
"new",
"one",
"updating",
"self",
".",
"map",
"accordingly",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L429-L435 | train | 210,343 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.difference_update | def difference_update(self, *sets):
"""
Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5])
"""
items_to_remove = set()
for other in sets:
items_to_remove |= set(other)
self._update_items([item for item in self.items if item not in items_to_remove]) | python | def difference_update(self, *sets):
"""
Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5])
"""
items_to_remove = set()
for other in sets:
items_to_remove |= set(other)
self._update_items([item for item in self.items if item not in items_to_remove]) | [
"def",
"difference_update",
"(",
"self",
",",
"*",
"sets",
")",
":",
"items_to_remove",
"=",
"set",
"(",
")",
"for",
"other",
"in",
"sets",
":",
"items_to_remove",
"|=",
"set",
"(",
"other",
")",
"self",
".",
"_update_items",
"(",
"[",
"item",
"for",
"... | Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5]) | [
"Update",
"this",
"OrderedSet",
"to",
"remove",
"items",
"from",
"one",
"or",
"more",
"other",
"sets",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L437-L455 | train | 210,344 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.intersection_update | def intersection_update(self, other):
"""
Update this OrderedSet to keep only items in another set, preserving
their order in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.intersection_update(other)
>>> print(this)
OrderedSet([1, 3, 7])
"""
other = set(other)
self._update_items([item for item in self.items if item in other]) | python | def intersection_update(self, other):
"""
Update this OrderedSet to keep only items in another set, preserving
their order in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.intersection_update(other)
>>> print(this)
OrderedSet([1, 3, 7])
"""
other = set(other)
self._update_items([item for item in self.items if item in other]) | [
"def",
"intersection_update",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"set",
"(",
"other",
")",
"self",
".",
"_update_items",
"(",
"[",
"item",
"for",
"item",
"in",
"self",
".",
"items",
"if",
"item",
"in",
"other",
"]",
")"
] | Update this OrderedSet to keep only items in another set, preserving
their order in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.intersection_update(other)
>>> print(this)
OrderedSet([1, 3, 7]) | [
"Update",
"this",
"OrderedSet",
"to",
"keep",
"only",
"items",
"in",
"another",
"set",
"preserving",
"their",
"order",
"in",
"this",
"set",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L457-L470 | train | 210,345 |
LuminosoInsight/ordered-set | ordered_set.py | OrderedSet.symmetric_difference_update | def symmetric_difference_update(self, other):
"""
Update this OrderedSet to remove items from another set, then
add items from the other set that were not present in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference_update(other)
>>> print(this)
OrderedSet([4, 5, 9, 2])
"""
items_to_add = [item for item in other if item not in self]
items_to_remove = set(other)
self._update_items(
[item for item in self.items if item not in items_to_remove] + items_to_add
) | python | def symmetric_difference_update(self, other):
"""
Update this OrderedSet to remove items from another set, then
add items from the other set that were not present in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference_update(other)
>>> print(this)
OrderedSet([4, 5, 9, 2])
"""
items_to_add = [item for item in other if item not in self]
items_to_remove = set(other)
self._update_items(
[item for item in self.items if item not in items_to_remove] + items_to_add
) | [
"def",
"symmetric_difference_update",
"(",
"self",
",",
"other",
")",
":",
"items_to_add",
"=",
"[",
"item",
"for",
"item",
"in",
"other",
"if",
"item",
"not",
"in",
"self",
"]",
"items_to_remove",
"=",
"set",
"(",
"other",
")",
"self",
".",
"_update_items... | Update this OrderedSet to remove items from another set, then
add items from the other set that were not present in this set.
Example:
>>> this = OrderedSet([1, 4, 3, 5, 7])
>>> other = OrderedSet([9, 7, 1, 3, 2])
>>> this.symmetric_difference_update(other)
>>> print(this)
OrderedSet([4, 5, 9, 2]) | [
"Update",
"this",
"OrderedSet",
"to",
"remove",
"items",
"from",
"another",
"set",
"then",
"add",
"items",
"from",
"the",
"other",
"set",
"that",
"were",
"not",
"present",
"in",
"this",
"set",
"."
] | a29eaedcedfe5072bcee11bdef61dea321d5e9f9 | https://github.com/LuminosoInsight/ordered-set/blob/a29eaedcedfe5072bcee11bdef61dea321d5e9f9/ordered_set.py#L472-L488 | train | 210,346 |
expo/expo-server-sdk-python | exponent_server_sdk/__init__.py | PushResponse.validate_response | def validate_response(self):
"""Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve.
"""
if self.is_success():
return
# Handle the error if we have any information
if self.details:
error = self.details.get('error', None)
if error == PushResponse.ERROR_DEVICE_NOT_REGISTERED:
raise DeviceNotRegisteredError(self)
elif error == PushResponse.ERROR_MESSAGE_TOO_BIG:
raise MessageTooBigError(self)
elif error == PushResponse.ERROR_MESSAGE_RATE_EXCEEDED:
raise MessageRateExceededError(self)
# No known error information, so let's raise a generic error.
raise PushResponseError(self) | python | def validate_response(self):
"""Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve.
"""
if self.is_success():
return
# Handle the error if we have any information
if self.details:
error = self.details.get('error', None)
if error == PushResponse.ERROR_DEVICE_NOT_REGISTERED:
raise DeviceNotRegisteredError(self)
elif error == PushResponse.ERROR_MESSAGE_TOO_BIG:
raise MessageTooBigError(self)
elif error == PushResponse.ERROR_MESSAGE_RATE_EXCEEDED:
raise MessageRateExceededError(self)
# No known error information, so let's raise a generic error.
raise PushResponseError(self) | [
"def",
"validate_response",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_success",
"(",
")",
":",
"return",
"# Handle the error if we have any information",
"if",
"self",
".",
"details",
":",
"error",
"=",
"self",
".",
"details",
".",
"get",
"(",
"'error'",
... | Raises an exception if there was an error. Otherwise, do nothing.
Clients should handle these errors, since these require custom handling
to properly resolve. | [
"Raises",
"an",
"exception",
"if",
"there",
"was",
"an",
"error",
".",
"Otherwise",
"do",
"nothing",
"."
] | 3d2969c7a674c48e1e46385fce09e9a7637d2fb6 | https://github.com/expo/expo-server-sdk-python/blob/3d2969c7a674c48e1e46385fce09e9a7637d2fb6/exponent_server_sdk/__init__.py#L159-L180 | train | 210,347 |
expo/expo-server-sdk-python | exponent_server_sdk/__init__.py | PushClient.is_exponent_push_token | def is_exponent_push_token(cls, token):
"""Returns `True` if the token is an Exponent push token"""
import six
return (
isinstance(token, six.string_types) and
token.startswith('ExponentPushToken')) | python | def is_exponent_push_token(cls, token):
"""Returns `True` if the token is an Exponent push token"""
import six
return (
isinstance(token, six.string_types) and
token.startswith('ExponentPushToken')) | [
"def",
"is_exponent_push_token",
"(",
"cls",
",",
"token",
")",
":",
"import",
"six",
"return",
"(",
"isinstance",
"(",
"token",
",",
"six",
".",
"string_types",
")",
"and",
"token",
".",
"startswith",
"(",
"'ExponentPushToken'",
")",
")"
] | Returns `True` if the token is an Exponent push token | [
"Returns",
"True",
"if",
"the",
"token",
"is",
"an",
"Exponent",
"push",
"token"
] | 3d2969c7a674c48e1e46385fce09e9a7637d2fb6 | https://github.com/expo/expo-server-sdk-python/blob/3d2969c7a674c48e1e46385fce09e9a7637d2fb6/exponent_server_sdk/__init__.py#L207-L213 | train | 210,348 |
expo/expo-server-sdk-python | exponent_server_sdk/__init__.py | PushClient._publish_internal | def _publish_internal(self, push_messages):
"""Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification',
'badge': 1,
'data': {'any': 'json object'},
}
Args:
push_messages: An array of PushMessage objects.
"""
# Delayed import because this file is immediately read on install, and
# the requests library may not be installed yet.
import requests
response = requests.post(
self.host + self.api_url + '/push/send',
data=json.dumps([pm.get_payload() for pm in push_messages]),
headers={
'accept': 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
}
)
# Let's validate the response format first.
try:
response_data = response.json()
except ValueError:
# The response isn't json. First, let's attempt to raise a normal
# http error. If it's a 200, then we'll raise our own error.
response.raise_for_status()
raise PushServerError('Invalid server response', response)
# If there are errors with the entire request, raise an error now.
if 'errors' in response_data:
raise PushServerError(
'Request failed',
response,
response_data=response_data,
errors=response_data['errors'])
# We expect the response to have a 'data' field with the responses.
if 'data' not in response_data:
raise PushServerError(
'Invalid server response',
response,
response_data=response_data)
# Use the requests library's built-in exceptions for any remaining 4xx
# and 5xx errors.
response.raise_for_status()
# Sanity check the response
if len(push_messages) != len(response_data['data']):
raise PushServerError(
('Mismatched response length. Expected %d %s but only '
'received %d' % (
len(push_messages),
'receipt' if len(push_messages) == 1 else 'receipts',
len(response_data['data']))),
response,
response_data=response_data)
# At this point, we know it's a 200 and the response format is correct.
# Now let's parse the responses per push notification.
receipts = []
for i, receipt in enumerate(response_data['data']):
receipts.append(PushResponse(
push_message=push_messages[i],
# If there is no status, assume error.
status=receipt.get('status', PushResponse.ERROR_STATUS),
message=receipt.get('message', ''),
details=receipt.get('details', None)))
return receipts | python | def _publish_internal(self, push_messages):
"""Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification',
'badge': 1,
'data': {'any': 'json object'},
}
Args:
push_messages: An array of PushMessage objects.
"""
# Delayed import because this file is immediately read on install, and
# the requests library may not be installed yet.
import requests
response = requests.post(
self.host + self.api_url + '/push/send',
data=json.dumps([pm.get_payload() for pm in push_messages]),
headers={
'accept': 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
}
)
# Let's validate the response format first.
try:
response_data = response.json()
except ValueError:
# The response isn't json. First, let's attempt to raise a normal
# http error. If it's a 200, then we'll raise our own error.
response.raise_for_status()
raise PushServerError('Invalid server response', response)
# If there are errors with the entire request, raise an error now.
if 'errors' in response_data:
raise PushServerError(
'Request failed',
response,
response_data=response_data,
errors=response_data['errors'])
# We expect the response to have a 'data' field with the responses.
if 'data' not in response_data:
raise PushServerError(
'Invalid server response',
response,
response_data=response_data)
# Use the requests library's built-in exceptions for any remaining 4xx
# and 5xx errors.
response.raise_for_status()
# Sanity check the response
if len(push_messages) != len(response_data['data']):
raise PushServerError(
('Mismatched response length. Expected %d %s but only '
'received %d' % (
len(push_messages),
'receipt' if len(push_messages) == 1 else 'receipts',
len(response_data['data']))),
response,
response_data=response_data)
# At this point, we know it's a 200 and the response format is correct.
# Now let's parse the responses per push notification.
receipts = []
for i, receipt in enumerate(response_data['data']):
receipts.append(PushResponse(
push_message=push_messages[i],
# If there is no status, assume error.
status=receipt.get('status', PushResponse.ERROR_STATUS),
message=receipt.get('message', ''),
details=receipt.get('details', None)))
return receipts | [
"def",
"_publish_internal",
"(",
"self",
",",
"push_messages",
")",
":",
"# Delayed import because this file is immediately read on install, and",
"# the requests library may not be installed yet.",
"import",
"requests",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".... | Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification',
'badge': 1,
'data': {'any': 'json object'},
}
Args:
push_messages: An array of PushMessage objects. | [
"Send",
"push",
"notifications"
] | 3d2969c7a674c48e1e46385fce09e9a7637d2fb6 | https://github.com/expo/expo-server-sdk-python/blob/3d2969c7a674c48e1e46385fce09e9a7637d2fb6/exponent_server_sdk/__init__.py#L215-L297 | train | 210,349 |
manodeep/Corrfunc | setup.py | get_dict_from_buffer | def get_dict_from_buffer(buf, keys=['DISTNAME', 'MAJOR',
'MINOR', 'PATCHLEVEL',
'PYTHON',
'MIN_PYTHON_MAJOR',
'MIN_PYTHON_MINOR',
'MIN_NUMPY_MAJOR',
'MIN_NUMPY_MINOR']):
"""
Parses a string buffer for key-val pairs for the supplied keys.
Returns: Python dictionary with all the keys (all keys in buffer
if None is passed for keys) with the values being a list
corresponding to each key.
Note: Return dict will contain all keys supplied (if not None).
If any key was not found in the buffer, then the value for
that key will be [] such that dict[key] does not produce
a KeyError.
Slightly modified from:
"http://stackoverflow.com/questions/5323703/regex-how-to-"\
"match-sequence-of-key-value-pairs-at-end-of-string
"""
pairs = dict()
if keys is None:
keys = "\S+"
regex = re.compile(r'''
\n # all key-value pairs are on separate lines
\s* # there might be some leading spaces
( # start group to return
(?:{0}\s*) # placeholder for tags to detect '\S+' == all
\s*:*=\s* # optional spaces, optional colon, = , optional spaces
.* # the value
) # end group to return
'''.format(keys), re.VERBOSE)
validate = False
else:
keys = [k.strip() for k in keys]
regex = re.compile(r'''
\n # all key-value pairs are on separate lines
\s* # there might be some leading spaces
( # start group to return
(?:{0}\s*) # placeholder for tags to detect '\S+' == all
\s*:*=\s* # optional spaces, optional colon, = , optional spaces
.* # the value
) # end group to return
'''.format('|'.join(keys)), re.VERBOSE)
validate = True
for k in keys:
pairs[k] = []
matches = regex.findall(buf)
for match in matches:
key, val = match.split('=', 1)
# remove colon and leading/trailing whitespace from key
key = (strip_line(key, ':')).strip()
# remove newline and leading/trailing whitespace from value
val = (strip_line(val)).strip()
if validate and key not in keys:
msg = "regex produced incorrect match. regex pattern = {0} "\
"claims key = [{1}] while original set of search keys "\
"= {2}".format(regex.pattern, key, '|'.join(keys))
raise AssertionError(msg)
pairs.setdefault(key, []).append(val)
return pairs | python | def get_dict_from_buffer(buf, keys=['DISTNAME', 'MAJOR',
'MINOR', 'PATCHLEVEL',
'PYTHON',
'MIN_PYTHON_MAJOR',
'MIN_PYTHON_MINOR',
'MIN_NUMPY_MAJOR',
'MIN_NUMPY_MINOR']):
"""
Parses a string buffer for key-val pairs for the supplied keys.
Returns: Python dictionary with all the keys (all keys in buffer
if None is passed for keys) with the values being a list
corresponding to each key.
Note: Return dict will contain all keys supplied (if not None).
If any key was not found in the buffer, then the value for
that key will be [] such that dict[key] does not produce
a KeyError.
Slightly modified from:
"http://stackoverflow.com/questions/5323703/regex-how-to-"\
"match-sequence-of-key-value-pairs-at-end-of-string
"""
pairs = dict()
if keys is None:
keys = "\S+"
regex = re.compile(r'''
\n # all key-value pairs are on separate lines
\s* # there might be some leading spaces
( # start group to return
(?:{0}\s*) # placeholder for tags to detect '\S+' == all
\s*:*=\s* # optional spaces, optional colon, = , optional spaces
.* # the value
) # end group to return
'''.format(keys), re.VERBOSE)
validate = False
else:
keys = [k.strip() for k in keys]
regex = re.compile(r'''
\n # all key-value pairs are on separate lines
\s* # there might be some leading spaces
( # start group to return
(?:{0}\s*) # placeholder for tags to detect '\S+' == all
\s*:*=\s* # optional spaces, optional colon, = , optional spaces
.* # the value
) # end group to return
'''.format('|'.join(keys)), re.VERBOSE)
validate = True
for k in keys:
pairs[k] = []
matches = regex.findall(buf)
for match in matches:
key, val = match.split('=', 1)
# remove colon and leading/trailing whitespace from key
key = (strip_line(key, ':')).strip()
# remove newline and leading/trailing whitespace from value
val = (strip_line(val)).strip()
if validate and key not in keys:
msg = "regex produced incorrect match. regex pattern = {0} "\
"claims key = [{1}] while original set of search keys "\
"= {2}".format(regex.pattern, key, '|'.join(keys))
raise AssertionError(msg)
pairs.setdefault(key, []).append(val)
return pairs | [
"def",
"get_dict_from_buffer",
"(",
"buf",
",",
"keys",
"=",
"[",
"'DISTNAME'",
",",
"'MAJOR'",
",",
"'MINOR'",
",",
"'PATCHLEVEL'",
",",
"'PYTHON'",
",",
"'MIN_PYTHON_MAJOR'",
",",
"'MIN_PYTHON_MINOR'",
",",
"'MIN_NUMPY_MAJOR'",
",",
"'MIN_NUMPY_MINOR'",
"]",
")"... | Parses a string buffer for key-val pairs for the supplied keys.
Returns: Python dictionary with all the keys (all keys in buffer
if None is passed for keys) with the values being a list
corresponding to each key.
Note: Return dict will contain all keys supplied (if not None).
If any key was not found in the buffer, then the value for
that key will be [] such that dict[key] does not produce
a KeyError.
Slightly modified from:
"http://stackoverflow.com/questions/5323703/regex-how-to-"\
"match-sequence-of-key-value-pairs-at-end-of-string | [
"Parses",
"a",
"string",
"buffer",
"for",
"key",
"-",
"val",
"pairs",
"for",
"the",
"supplied",
"keys",
"."
] | 753aa50b93eebfefc76a0b0cd61522536bd45d2a | https://github.com/manodeep/Corrfunc/blob/753aa50b93eebfefc76a0b0cd61522536bd45d2a/setup.py#L74-L144 | train | 210,350 |
manodeep/Corrfunc | setup.py | replace_first_key_in_makefile | def replace_first_key_in_makefile(buf, key, replacement, outfile=None):
'''
Replaces first line in 'buf' matching 'key' with 'replacement'.
Optionally, writes out this new buffer into 'outfile'.
Returns: Buffer after replacement has been done
'''
regexp = re.compile(r'''
\n\s* # there might be some leading spaces
( # start group to return
(?:{0}\s*) # placeholder for tags to detect '\S+' == all
\s*:*=\s* # optional spaces, optional colon, = , optional spaces
.* # the value
) # end group to return
'''.format(key), re.VERBOSE)
matches = regexp.findall(buf)
if matches is None:
msg = "Could not find key = {0} in the provided buffer. "\
"Pattern used = {1}".format(key, regexp.pattern)
raise ValueError(msg)
# Only replace the first occurence
newbuf = regexp.sub(replacement, buf, count=1)
if outfile is not None:
write_text_file(outfile, newbuf)
return newbuf | python | def replace_first_key_in_makefile(buf, key, replacement, outfile=None):
'''
Replaces first line in 'buf' matching 'key' with 'replacement'.
Optionally, writes out this new buffer into 'outfile'.
Returns: Buffer after replacement has been done
'''
regexp = re.compile(r'''
\n\s* # there might be some leading spaces
( # start group to return
(?:{0}\s*) # placeholder for tags to detect '\S+' == all
\s*:*=\s* # optional spaces, optional colon, = , optional spaces
.* # the value
) # end group to return
'''.format(key), re.VERBOSE)
matches = regexp.findall(buf)
if matches is None:
msg = "Could not find key = {0} in the provided buffer. "\
"Pattern used = {1}".format(key, regexp.pattern)
raise ValueError(msg)
# Only replace the first occurence
newbuf = regexp.sub(replacement, buf, count=1)
if outfile is not None:
write_text_file(outfile, newbuf)
return newbuf | [
"def",
"replace_first_key_in_makefile",
"(",
"buf",
",",
"key",
",",
"replacement",
",",
"outfile",
"=",
"None",
")",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r'''\n \\n\\s* # there might be some leading spaces\n ( # start group to return\... | Replaces first line in 'buf' matching 'key' with 'replacement'.
Optionally, writes out this new buffer into 'outfile'.
Returns: Buffer after replacement has been done | [
"Replaces",
"first",
"line",
"in",
"buf",
"matching",
"key",
"with",
"replacement",
".",
"Optionally",
"writes",
"out",
"this",
"new",
"buffer",
"into",
"outfile",
"."
] | 753aa50b93eebfefc76a0b0cd61522536bd45d2a | https://github.com/manodeep/Corrfunc/blob/753aa50b93eebfefc76a0b0cd61522536bd45d2a/setup.py#L147-L174 | train | 210,351 |
adamchainz/django-mysql | django_mysql/utils.py | settings_to_cmd_args | def settings_to_cmd_args(settings_dict):
"""
Copied from django 1.8 MySQL backend DatabaseClient - where the runshell
commandline creation has been extracted and made callable like so.
"""
args = ['mysql']
db = settings_dict['OPTIONS'].get('db', settings_dict['NAME'])
user = settings_dict['OPTIONS'].get('user', settings_dict['USER'])
passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD'])
host = settings_dict['OPTIONS'].get('host', settings_dict['HOST'])
port = settings_dict['OPTIONS'].get('port', settings_dict['PORT'])
cert = settings_dict['OPTIONS'].get('ssl', {}).get('ca')
defaults_file = settings_dict['OPTIONS'].get('read_default_file')
# Seems to be no good way to set sql_mode with CLI.
if defaults_file:
args += ["--defaults-file=%s" % defaults_file]
if user:
args += ["--user=%s" % user]
if passwd:
args += ["--password=%s" % passwd]
if host:
if '/' in host:
args += ["--socket=%s" % host]
else:
args += ["--host=%s" % host]
if port:
args += ["--port=%s" % port]
if cert:
args += ["--ssl-ca=%s" % cert]
if db:
args += [db]
return args | python | def settings_to_cmd_args(settings_dict):
"""
Copied from django 1.8 MySQL backend DatabaseClient - where the runshell
commandline creation has been extracted and made callable like so.
"""
args = ['mysql']
db = settings_dict['OPTIONS'].get('db', settings_dict['NAME'])
user = settings_dict['OPTIONS'].get('user', settings_dict['USER'])
passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD'])
host = settings_dict['OPTIONS'].get('host', settings_dict['HOST'])
port = settings_dict['OPTIONS'].get('port', settings_dict['PORT'])
cert = settings_dict['OPTIONS'].get('ssl', {}).get('ca')
defaults_file = settings_dict['OPTIONS'].get('read_default_file')
# Seems to be no good way to set sql_mode with CLI.
if defaults_file:
args += ["--defaults-file=%s" % defaults_file]
if user:
args += ["--user=%s" % user]
if passwd:
args += ["--password=%s" % passwd]
if host:
if '/' in host:
args += ["--socket=%s" % host]
else:
args += ["--host=%s" % host]
if port:
args += ["--port=%s" % port]
if cert:
args += ["--ssl-ca=%s" % cert]
if db:
args += [db]
return args | [
"def",
"settings_to_cmd_args",
"(",
"settings_dict",
")",
":",
"args",
"=",
"[",
"'mysql'",
"]",
"db",
"=",
"settings_dict",
"[",
"'OPTIONS'",
"]",
".",
"get",
"(",
"'db'",
",",
"settings_dict",
"[",
"'NAME'",
"]",
")",
"user",
"=",
"settings_dict",
"[",
... | Copied from django 1.8 MySQL backend DatabaseClient - where the runshell
commandline creation has been extracted and made callable like so. | [
"Copied",
"from",
"django",
"1",
".",
"8",
"MySQL",
"backend",
"DatabaseClient",
"-",
"where",
"the",
"runshell",
"commandline",
"creation",
"has",
"been",
"extracted",
"and",
"made",
"callable",
"like",
"so",
"."
] | 967daa4245cf55c9bc5dc018e560f417c528916a | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/utils.py#L114-L146 | train | 210,352 |
adamchainz/django-mysql | django_mysql/rewrite_query.py | modify_sql | def modify_sql(sql, add_comments, add_hints, add_index_hints):
"""
Parse the start of the SQL, injecting each string in add_comments in
individual SQL comments after the first keyword, and adding the named
SELECT hints from add_hints, taking the latest in the list in cases of
multiple mutually exclusive hints being given
"""
match = query_start_re.match(sql)
if not match:
# We don't understand what kind of query this is, don't rewrite it
return sql
tokens = [match.group('keyword')]
comments = match.group('comments').strip()
if comments:
tokens.append(comments)
# Inject comments after all existing comments
for comment in add_comments:
tokens.append('/*{}*/'.format(comment))
# Don't bother with SELECT rewrite rules on non-SELECT queries
if tokens[0] == "SELECT":
for group_name, hint_set in SELECT_HINTS.items():
try:
# Take the last hint we were told to add from this hint_set
to_add = [hint for hint in add_hints if hint in hint_set][-1]
tokens.append(to_add)
except IndexError:
# We weren't told to add any, so just add any hint from this
# set that was already there
existing = match.group(group_name)
if existing is not None:
tokens.append(existing.rstrip())
# Maybe rewrite the remainder of the statement for index hints
remainder = sql[match.end():]
if tokens[0] == "SELECT" and add_index_hints:
for index_hint in add_index_hints:
remainder = modify_sql_index_hints(remainder, *index_hint)
# Join everything
tokens.append(remainder)
return ' '.join(tokens) | python | def modify_sql(sql, add_comments, add_hints, add_index_hints):
"""
Parse the start of the SQL, injecting each string in add_comments in
individual SQL comments after the first keyword, and adding the named
SELECT hints from add_hints, taking the latest in the list in cases of
multiple mutually exclusive hints being given
"""
match = query_start_re.match(sql)
if not match:
# We don't understand what kind of query this is, don't rewrite it
return sql
tokens = [match.group('keyword')]
comments = match.group('comments').strip()
if comments:
tokens.append(comments)
# Inject comments after all existing comments
for comment in add_comments:
tokens.append('/*{}*/'.format(comment))
# Don't bother with SELECT rewrite rules on non-SELECT queries
if tokens[0] == "SELECT":
for group_name, hint_set in SELECT_HINTS.items():
try:
# Take the last hint we were told to add from this hint_set
to_add = [hint for hint in add_hints if hint in hint_set][-1]
tokens.append(to_add)
except IndexError:
# We weren't told to add any, so just add any hint from this
# set that was already there
existing = match.group(group_name)
if existing is not None:
tokens.append(existing.rstrip())
# Maybe rewrite the remainder of the statement for index hints
remainder = sql[match.end():]
if tokens[0] == "SELECT" and add_index_hints:
for index_hint in add_index_hints:
remainder = modify_sql_index_hints(remainder, *index_hint)
# Join everything
tokens.append(remainder)
return ' '.join(tokens) | [
"def",
"modify_sql",
"(",
"sql",
",",
"add_comments",
",",
"add_hints",
",",
"add_index_hints",
")",
":",
"match",
"=",
"query_start_re",
".",
"match",
"(",
"sql",
")",
"if",
"not",
"match",
":",
"# We don't understand what kind of query this is, don't rewrite it",
... | Parse the start of the SQL, injecting each string in add_comments in
individual SQL comments after the first keyword, and adding the named
SELECT hints from add_hints, taking the latest in the list in cases of
multiple mutually exclusive hints being given | [
"Parse",
"the",
"start",
"of",
"the",
"SQL",
"injecting",
"each",
"string",
"in",
"add_comments",
"in",
"individual",
"SQL",
"comments",
"after",
"the",
"first",
"keyword",
"and",
"adding",
"the",
"named",
"SELECT",
"hints",
"from",
"add_hints",
"taking",
"the... | 967daa4245cf55c9bc5dc018e560f417c528916a | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/rewrite_query.py#L115-L161 | train | 210,353 |
adamchainz/django-mysql | django_mysql/cache.py | MySQLCache.validate_key | def validate_key(self, key):
"""
Django normally warns about maximum key length, but we error on it.
"""
if len(key) > 250:
raise ValueError(
"Cache key is longer than the maxmimum 250 characters: {}"
.format(key),
)
return super(MySQLCache, self).validate_key(key) | python | def validate_key(self, key):
"""
Django normally warns about maximum key length, but we error on it.
"""
if len(key) > 250:
raise ValueError(
"Cache key is longer than the maxmimum 250 characters: {}"
.format(key),
)
return super(MySQLCache, self).validate_key(key) | [
"def",
"validate_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
">",
"250",
":",
"raise",
"ValueError",
"(",
"\"Cache key is longer than the maxmimum 250 characters: {}\"",
".",
"format",
"(",
"key",
")",
",",
")",
"return",
"super",
... | Django normally warns about maximum key length, but we error on it. | [
"Django",
"normally",
"warns",
"about",
"maximum",
"key",
"length",
"but",
"we",
"error",
"on",
"it",
"."
] | 967daa4245cf55c9bc5dc018e560f417c528916a | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/cache.py#L403-L412 | train | 210,354 |
adamchainz/django-mysql | django_mysql/cache.py | MySQLCache.decode | def decode(self, value, value_type):
"""
Take a value blob and its value_type one-char code and convert it back
to a python object
"""
if value_type == 'i':
return int(value)
if value_type == 'z':
value = zlib.decompress(value)
value_type = 'p'
if value_type == 'p':
return pickle.loads(force_bytes(value))
raise ValueError(
"Unknown value_type '{}' read from the cache table."
.format(value_type),
) | python | def decode(self, value, value_type):
"""
Take a value blob and its value_type one-char code and convert it back
to a python object
"""
if value_type == 'i':
return int(value)
if value_type == 'z':
value = zlib.decompress(value)
value_type = 'p'
if value_type == 'p':
return pickle.loads(force_bytes(value))
raise ValueError(
"Unknown value_type '{}' read from the cache table."
.format(value_type),
) | [
"def",
"decode",
"(",
"self",
",",
"value",
",",
"value_type",
")",
":",
"if",
"value_type",
"==",
"'i'",
":",
"return",
"int",
"(",
"value",
")",
"if",
"value_type",
"==",
"'z'",
":",
"value",
"=",
"zlib",
".",
"decompress",
"(",
"value",
")",
"valu... | Take a value blob and its value_type one-char code and convert it back
to a python object | [
"Take",
"a",
"value",
"blob",
"and",
"its",
"value_type",
"one",
"-",
"char",
"code",
"and",
"convert",
"it",
"back",
"to",
"a",
"python",
"object"
] | 967daa4245cf55c9bc5dc018e560f417c528916a | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/cache.py#L441-L459 | train | 210,355 |
adamchainz/django-mysql | django_mysql/models/handler.py | Handler._is_simple_query | def _is_simple_query(cls, query):
"""
Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement
"""
return (
not query.low_mark
and not query.high_mark
and not query.select
and not query.group_by
and not query.distinct
and not query.order_by
and len(query.alias_map) <= 1
) | python | def _is_simple_query(cls, query):
"""
Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement
"""
return (
not query.low_mark
and not query.high_mark
and not query.select
and not query.group_by
and not query.distinct
and not query.order_by
and len(query.alias_map) <= 1
) | [
"def",
"_is_simple_query",
"(",
"cls",
",",
"query",
")",
":",
"return",
"(",
"not",
"query",
".",
"low_mark",
"and",
"not",
"query",
".",
"high_mark",
"and",
"not",
"query",
".",
"select",
"and",
"not",
"query",
".",
"group_by",
"and",
"not",
"query",
... | Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement | [
"Inspect",
"the",
"internals",
"of",
"the",
"Query",
"and",
"say",
"if",
"we",
"think",
"its",
"WHERE",
"clause",
"can",
"be",
"used",
"in",
"a",
"HANDLER",
"statement"
] | 967daa4245cf55c9bc5dc018e560f417c528916a | https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/models/handler.py#L218-L231 | train | 210,356 |
rm-hull/luma.core | luma/core/sprite_system.py | spritesheet.animate | def animate(self, seq_name):
"""
Returns a generator which "executes" an animation sequence for the given
``seq_name``, inasmuch as the next frame for the given animation is
yielded when requested.
:param seq_name: The name of a previously defined animation sequence.
:type seq_name: str
:returns: A generator that yields all frames from the animation
sequence.
:raises AttributeError: If the ``seq_name`` is unknown.
"""
while True:
index = 0
anim = getattr(self.animations, seq_name)
speed = anim.speed if hasattr(anim, "speed") else 1
num_frames = len(anim.frames)
while index < num_frames:
frame = anim.frames[int(index)]
index += speed
if isinstance(frame, int):
yield self[frame]
else:
for subseq_frame in self.animate(frame):
yield subseq_frame
if not hasattr(anim, "next"):
break
seq_name = anim.next | python | def animate(self, seq_name):
"""
Returns a generator which "executes" an animation sequence for the given
``seq_name``, inasmuch as the next frame for the given animation is
yielded when requested.
:param seq_name: The name of a previously defined animation sequence.
:type seq_name: str
:returns: A generator that yields all frames from the animation
sequence.
:raises AttributeError: If the ``seq_name`` is unknown.
"""
while True:
index = 0
anim = getattr(self.animations, seq_name)
speed = anim.speed if hasattr(anim, "speed") else 1
num_frames = len(anim.frames)
while index < num_frames:
frame = anim.frames[int(index)]
index += speed
if isinstance(frame, int):
yield self[frame]
else:
for subseq_frame in self.animate(frame):
yield subseq_frame
if not hasattr(anim, "next"):
break
seq_name = anim.next | [
"def",
"animate",
"(",
"self",
",",
"seq_name",
")",
":",
"while",
"True",
":",
"index",
"=",
"0",
"anim",
"=",
"getattr",
"(",
"self",
".",
"animations",
",",
"seq_name",
")",
"speed",
"=",
"anim",
".",
"speed",
"if",
"hasattr",
"(",
"anim",
",",
... | Returns a generator which "executes" an animation sequence for the given
``seq_name``, inasmuch as the next frame for the given animation is
yielded when requested.
:param seq_name: The name of a previously defined animation sequence.
:type seq_name: str
:returns: A generator that yields all frames from the animation
sequence.
:raises AttributeError: If the ``seq_name`` is unknown. | [
"Returns",
"a",
"generator",
"which",
"executes",
"an",
"animation",
"sequence",
"for",
"the",
"given",
"seq_name",
"inasmuch",
"as",
"the",
"next",
"frame",
"for",
"the",
"given",
"animation",
"is",
"yielded",
"when",
"requested",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/sprite_system.py#L132-L162 | train | 210,357 |
rm-hull/luma.core | luma/core/sprite_system.py | framerate_regulator.effective_FPS | def effective_FPS(self):
"""
Calculates the effective frames-per-second - this should largely
correlate to the desired FPS supplied in the constructor, but no
guarantees are given.
:returns: The effective frame rate.
:rtype: float
"""
if self.start_time is None:
self.start_time = 0
elapsed = monotonic() - self.start_time
return self.called / elapsed | python | def effective_FPS(self):
"""
Calculates the effective frames-per-second - this should largely
correlate to the desired FPS supplied in the constructor, but no
guarantees are given.
:returns: The effective frame rate.
:rtype: float
"""
if self.start_time is None:
self.start_time = 0
elapsed = monotonic() - self.start_time
return self.called / elapsed | [
"def",
"effective_FPS",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_time",
"is",
"None",
":",
"self",
".",
"start_time",
"=",
"0",
"elapsed",
"=",
"monotonic",
"(",
")",
"-",
"self",
".",
"start_time",
"return",
"self",
".",
"called",
"/",
"elapse... | Calculates the effective frames-per-second - this should largely
correlate to the desired FPS supplied in the constructor, but no
guarantees are given.
:returns: The effective frame rate.
:rtype: float | [
"Calculates",
"the",
"effective",
"frames",
"-",
"per",
"-",
"second",
"-",
"this",
"should",
"largely",
"correlate",
"to",
"the",
"desired",
"FPS",
"supplied",
"in",
"the",
"constructor",
"but",
"no",
"guarantees",
"are",
"given",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/sprite_system.py#L216-L228 | train | 210,358 |
rm-hull/luma.core | luma/core/image_composition.py | ComposableImage._crop_box | def _crop_box(self, size):
"""
Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple
"""
(left, top) = self.offset
right = left + min(size[0], self.width)
bottom = top + min(size[1], self.height)
return (left, top, right, bottom) | python | def _crop_box(self, size):
"""
Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple
"""
(left, top) = self.offset
right = left + min(size[0], self.width)
bottom = top + min(size[1], self.height)
return (left, top, right, bottom) | [
"def",
"_crop_box",
"(",
"self",
",",
"size",
")",
":",
"(",
"left",
",",
"top",
")",
"=",
"self",
".",
"offset",
"right",
"=",
"left",
"+",
"min",
"(",
"size",
"[",
"0",
"]",
",",
"self",
".",
"width",
")",
"bottom",
"=",
"top",
"+",
"min",
... | Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple | [
"Helper",
"that",
"calculates",
"the",
"crop",
"box",
"for",
"the",
"offset",
"within",
"the",
"image",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/image_composition.py#L111-L124 | train | 210,359 |
rm-hull/luma.core | luma/core/image_composition.py | ImageComposition.refresh | def refresh(self):
"""
Clears the composition and renders all the images
taking into account their position and offset.
"""
self._clear()
for img in self.composed_images:
self._background_image.paste(img.image(self._device.size),
img.position)
self._background_image.crop(box=self._device.bounding_box) | python | def refresh(self):
"""
Clears the composition and renders all the images
taking into account their position and offset.
"""
self._clear()
for img in self.composed_images:
self._background_image.paste(img.image(self._device.size),
img.position)
self._background_image.crop(box=self._device.bounding_box) | [
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"_clear",
"(",
")",
"for",
"img",
"in",
"self",
".",
"composed_images",
":",
"self",
".",
"_background_image",
".",
"paste",
"(",
"img",
".",
"image",
"(",
"self",
".",
"_device",
".",
"size",
")"... | Clears the composition and renders all the images
taking into account their position and offset. | [
"Clears",
"the",
"composition",
"and",
"renders",
"all",
"the",
"images",
"taking",
"into",
"account",
"their",
"position",
"and",
"offset",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/image_composition.py#L171-L180 | train | 210,360 |
rm-hull/luma.core | luma/core/image_composition.py | ImageComposition._clear | def _clear(self):
"""
Helper that clears the composition.
"""
draw = ImageDraw.Draw(self._background_image)
draw.rectangle(self._device.bounding_box,
fill="black")
del draw | python | def _clear(self):
"""
Helper that clears the composition.
"""
draw = ImageDraw.Draw(self._background_image)
draw.rectangle(self._device.bounding_box,
fill="black")
del draw | [
"def",
"_clear",
"(",
"self",
")",
":",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"self",
".",
"_background_image",
")",
"draw",
".",
"rectangle",
"(",
"self",
".",
"_device",
".",
"bounding_box",
",",
"fill",
"=",
"\"black\"",
")",
"del",
"draw"
] | Helper that clears the composition. | [
"Helper",
"that",
"clears",
"the",
"composition",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/image_composition.py#L182-L189 | train | 210,361 |
rm-hull/luma.core | luma/core/framebuffer.py | diff_to_previous.inflate_bbox | def inflate_bbox(self):
"""
Realign the left and right edges of the bounding box such that they are
inflated to align modulo 4.
This method is optional, and used mainly to accommodate devices with
COM/SEG GDDRAM structures that store pixels in 4-bit nibbles.
"""
left, top, right, bottom = self.bounding_box
self.bounding_box = (
left & 0xFFFC,
top,
right if right % 4 == 0 else (right & 0xFFFC) + 0x04,
bottom)
return self.bounding_box | python | def inflate_bbox(self):
"""
Realign the left and right edges of the bounding box such that they are
inflated to align modulo 4.
This method is optional, and used mainly to accommodate devices with
COM/SEG GDDRAM structures that store pixels in 4-bit nibbles.
"""
left, top, right, bottom = self.bounding_box
self.bounding_box = (
left & 0xFFFC,
top,
right if right % 4 == 0 else (right & 0xFFFC) + 0x04,
bottom)
return self.bounding_box | [
"def",
"inflate_bbox",
"(",
"self",
")",
":",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"=",
"self",
".",
"bounding_box",
"self",
".",
"bounding_box",
"=",
"(",
"left",
"&",
"0xFFFC",
",",
"top",
",",
"right",
"if",
"right",
"%",
"4",
"==",
... | Realign the left and right edges of the bounding box such that they are
inflated to align modulo 4.
This method is optional, and used mainly to accommodate devices with
COM/SEG GDDRAM structures that store pixels in 4-bit nibbles. | [
"Realign",
"the",
"left",
"and",
"right",
"edges",
"of",
"the",
"bounding",
"box",
"such",
"that",
"they",
"are",
"inflated",
"to",
"align",
"modulo",
"4",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/framebuffer.py#L52-L67 | train | 210,362 |
rm-hull/luma.core | luma/core/virtual.py | terminal.println | def println(self, text=""):
"""
Prints the supplied text to the device, scrolling where necessary.
The text is always followed by a newline.
:param text: The text to print.
:type text: str
"""
if self.word_wrap:
# find directives in complete text
directives = ansi_color.find_directives(text, self)
# strip ansi from text
clean_text = ansi_color.strip_ansi_codes(text)
# wrap clean text
clean_lines = self.tw.wrap(clean_text)
# print wrapped text
index = 0
for line in clean_lines:
line_length = len(line)
y = 0
while y < line_length:
method, args = directives[index]
if method == self.putch:
y += 1
method(*args)
index += 1
self.newline()
else:
self.puts(text)
self.newline() | python | def println(self, text=""):
"""
Prints the supplied text to the device, scrolling where necessary.
The text is always followed by a newline.
:param text: The text to print.
:type text: str
"""
if self.word_wrap:
# find directives in complete text
directives = ansi_color.find_directives(text, self)
# strip ansi from text
clean_text = ansi_color.strip_ansi_codes(text)
# wrap clean text
clean_lines = self.tw.wrap(clean_text)
# print wrapped text
index = 0
for line in clean_lines:
line_length = len(line)
y = 0
while y < line_length:
method, args = directives[index]
if method == self.putch:
y += 1
method(*args)
index += 1
self.newline()
else:
self.puts(text)
self.newline() | [
"def",
"println",
"(",
"self",
",",
"text",
"=",
"\"\"",
")",
":",
"if",
"self",
".",
"word_wrap",
":",
"# find directives in complete text",
"directives",
"=",
"ansi_color",
".",
"find_directives",
"(",
"text",
",",
"self",
")",
"# strip ansi from text",
"clean... | Prints the supplied text to the device, scrolling where necessary.
The text is always followed by a newline.
:param text: The text to print.
:type text: str | [
"Prints",
"the",
"supplied",
"text",
"to",
"the",
"device",
"scrolling",
"where",
"necessary",
".",
"The",
"text",
"is",
"always",
"followed",
"by",
"a",
"newline",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L238-L270 | train | 210,363 |
rm-hull/luma.core | luma/core/virtual.py | terminal.newline | def newline(self):
"""
Advances the cursor position ot the left hand side, and to the next
line. If the cursor is on the lowest line, the displayed contents are
scrolled, causing the top line to be lost.
"""
self.carriage_return()
if self._cy + (2 * self._ch) >= self._device.height:
# Simulate a vertical scroll
copy = self._backing_image.crop((0, self._ch, self._device.width,
self._device.height))
self._backing_image.paste(copy, (0, 0))
self._canvas.rectangle((0, copy.height, self._device.width,
self._device.height), fill=self.default_bgcolor)
else:
self._cy += self._ch
self.flush()
if self.animate:
time.sleep(0.2) | python | def newline(self):
"""
Advances the cursor position ot the left hand side, and to the next
line. If the cursor is on the lowest line, the displayed contents are
scrolled, causing the top line to be lost.
"""
self.carriage_return()
if self._cy + (2 * self._ch) >= self._device.height:
# Simulate a vertical scroll
copy = self._backing_image.crop((0, self._ch, self._device.width,
self._device.height))
self._backing_image.paste(copy, (0, 0))
self._canvas.rectangle((0, copy.height, self._device.width,
self._device.height), fill=self.default_bgcolor)
else:
self._cy += self._ch
self.flush()
if self.animate:
time.sleep(0.2) | [
"def",
"newline",
"(",
"self",
")",
":",
"self",
".",
"carriage_return",
"(",
")",
"if",
"self",
".",
"_cy",
"+",
"(",
"2",
"*",
"self",
".",
"_ch",
")",
">=",
"self",
".",
"_device",
".",
"height",
":",
"# Simulate a vertical scroll",
"copy",
"=",
"... | Advances the cursor position ot the left hand side, and to the next
line. If the cursor is on the lowest line, the displayed contents are
scrolled, causing the top line to be lost. | [
"Advances",
"the",
"cursor",
"position",
"ot",
"the",
"left",
"hand",
"side",
"and",
"to",
"the",
"next",
"line",
".",
"If",
"the",
"cursor",
"is",
"on",
"the",
"lowest",
"line",
"the",
"displayed",
"contents",
"are",
"scrolled",
"causing",
"the",
"top",
... | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L337-L357 | train | 210,364 |
rm-hull/luma.core | luma/core/virtual.py | terminal.backspace | def backspace(self):
"""
Moves the cursor one place to the left, erasing the character at the
current position. Cannot move beyond column zero, nor onto the
previous line.
"""
if self._cx + self._cw >= 0:
self.erase()
self._cx -= self._cw
self.flush() | python | def backspace(self):
"""
Moves the cursor one place to the left, erasing the character at the
current position. Cannot move beyond column zero, nor onto the
previous line.
"""
if self._cx + self._cw >= 0:
self.erase()
self._cx -= self._cw
self.flush() | [
"def",
"backspace",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cx",
"+",
"self",
".",
"_cw",
">=",
"0",
":",
"self",
".",
"erase",
"(",
")",
"self",
".",
"_cx",
"-=",
"self",
".",
"_cw",
"self",
".",
"flush",
"(",
")"
] | Moves the cursor one place to the left, erasing the character at the
current position. Cannot move beyond column zero, nor onto the
previous line. | [
"Moves",
"the",
"cursor",
"one",
"place",
"to",
"the",
"left",
"erasing",
"the",
"character",
"at",
"the",
"current",
"position",
".",
"Cannot",
"move",
"beyond",
"column",
"zero",
"nor",
"onto",
"the",
"previous",
"line",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L359-L369 | train | 210,365 |
rm-hull/luma.core | luma/core/virtual.py | terminal.erase | def erase(self):
"""
Erase the contents of the cursor's current position without moving the
cursor's position.
"""
bounds = (self._cx, self._cy, self._cx + self._cw, self._cy + self._ch)
self._canvas.rectangle(bounds, fill=self._bgcolor) | python | def erase(self):
"""
Erase the contents of the cursor's current position without moving the
cursor's position.
"""
bounds = (self._cx, self._cy, self._cx + self._cw, self._cy + self._ch)
self._canvas.rectangle(bounds, fill=self._bgcolor) | [
"def",
"erase",
"(",
"self",
")",
":",
"bounds",
"=",
"(",
"self",
".",
"_cx",
",",
"self",
".",
"_cy",
",",
"self",
".",
"_cx",
"+",
"self",
".",
"_cw",
",",
"self",
".",
"_cy",
"+",
"self",
".",
"_ch",
")",
"self",
".",
"_canvas",
".",
"rec... | Erase the contents of the cursor's current position without moving the
cursor's position. | [
"Erase",
"the",
"contents",
"of",
"the",
"cursor",
"s",
"current",
"position",
"without",
"moving",
"the",
"cursor",
"s",
"position",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L371-L377 | train | 210,366 |
rm-hull/luma.core | luma/core/virtual.py | terminal.reset | def reset(self):
"""
Resets the foreground and background color value back to the original
when initialised.
"""
self._fgcolor = self.default_fgcolor
self._bgcolor = self.default_bgcolor | python | def reset(self):
"""
Resets the foreground and background color value back to the original
when initialised.
"""
self._fgcolor = self.default_fgcolor
self._bgcolor = self.default_bgcolor | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_fgcolor",
"=",
"self",
".",
"default_fgcolor",
"self",
".",
"_bgcolor",
"=",
"self",
".",
"default_bgcolor"
] | Resets the foreground and background color value back to the original
when initialised. | [
"Resets",
"the",
"foreground",
"and",
"background",
"color",
"value",
"back",
"to",
"the",
"original",
"when",
"initialised",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L403-L409 | train | 210,367 |
rm-hull/luma.core | luma/core/virtual.py | terminal.reverse_colors | def reverse_colors(self):
"""
Flips the foreground and background colors.
"""
self._bgcolor, self._fgcolor = self._fgcolor, self._bgcolor | python | def reverse_colors(self):
"""
Flips the foreground and background colors.
"""
self._bgcolor, self._fgcolor = self._fgcolor, self._bgcolor | [
"def",
"reverse_colors",
"(",
"self",
")",
":",
"self",
".",
"_bgcolor",
",",
"self",
".",
"_fgcolor",
"=",
"self",
".",
"_fgcolor",
",",
"self",
".",
"_bgcolor"
] | Flips the foreground and background colors. | [
"Flips",
"the",
"foreground",
"and",
"background",
"colors",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L411-L415 | train | 210,368 |
rm-hull/luma.core | luma/core/virtual.py | history.savepoint | def savepoint(self):
"""
Copies the last displayed image.
"""
if self._last_image:
self._savepoints.append(self._last_image)
self._last_image = None | python | def savepoint(self):
"""
Copies the last displayed image.
"""
if self._last_image:
self._savepoints.append(self._last_image)
self._last_image = None | [
"def",
"savepoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_image",
":",
"self",
".",
"_savepoints",
".",
"append",
"(",
"self",
".",
"_last_image",
")",
"self",
".",
"_last_image",
"=",
"None"
] | Copies the last displayed image. | [
"Copies",
"the",
"last",
"displayed",
"image",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L440-L446 | train | 210,369 |
rm-hull/luma.core | luma/core/virtual.py | history.restore | def restore(self, drop=0):
"""
Restores the last savepoint. If ``drop`` is supplied and greater than
zero, then that many savepoints are dropped, and the next savepoint is
restored.
:param drop:
:type drop: int
"""
assert(drop >= 0)
while drop > 0:
self._savepoints.pop()
drop -= 1
img = self._savepoints.pop()
self.display(img) | python | def restore(self, drop=0):
"""
Restores the last savepoint. If ``drop`` is supplied and greater than
zero, then that many savepoints are dropped, and the next savepoint is
restored.
:param drop:
:type drop: int
"""
assert(drop >= 0)
while drop > 0:
self._savepoints.pop()
drop -= 1
img = self._savepoints.pop()
self.display(img) | [
"def",
"restore",
"(",
"self",
",",
"drop",
"=",
"0",
")",
":",
"assert",
"(",
"drop",
">=",
"0",
")",
"while",
"drop",
">",
"0",
":",
"self",
".",
"_savepoints",
".",
"pop",
"(",
")",
"drop",
"-=",
"1",
"img",
"=",
"self",
".",
"_savepoints",
... | Restores the last savepoint. If ``drop`` is supplied and greater than
zero, then that many savepoints are dropped, and the next savepoint is
restored.
:param drop:
:type drop: int | [
"Restores",
"the",
"last",
"savepoint",
".",
"If",
"drop",
"is",
"supplied",
"and",
"greater",
"than",
"zero",
"then",
"that",
"many",
"savepoints",
"are",
"dropped",
"and",
"the",
"next",
"savepoint",
"is",
"restored",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L448-L463 | train | 210,370 |
rm-hull/luma.core | luma/core/virtual.py | sevensegment.text | def text(self, value):
"""
Updates the seven-segment display with the given value. If there is not
enough space to show the full text, an ``OverflowException`` is raised.
:param value: The value to render onto the device. Any characters which
cannot be rendered will be converted into the ``undefined``
character supplied in the constructor.
:type value: str
"""
self._text_buffer = observable(mutable_string(value),
observer=self._flush) | python | def text(self, value):
"""
Updates the seven-segment display with the given value. If there is not
enough space to show the full text, an ``OverflowException`` is raised.
:param value: The value to render onto the device. Any characters which
cannot be rendered will be converted into the ``undefined``
character supplied in the constructor.
:type value: str
"""
self._text_buffer = observable(mutable_string(value),
observer=self._flush) | [
"def",
"text",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_text_buffer",
"=",
"observable",
"(",
"mutable_string",
"(",
"value",
")",
",",
"observer",
"=",
"self",
".",
"_flush",
")"
] | Updates the seven-segment display with the given value. If there is not
enough space to show the full text, an ``OverflowException`` is raised.
:param value: The value to render onto the device. Any characters which
cannot be rendered will be converted into the ``undefined``
character supplied in the constructor.
:type value: str | [
"Updates",
"the",
"seven",
"-",
"segment",
"display",
"with",
"the",
"given",
"value",
".",
"If",
"there",
"is",
"not",
"enough",
"space",
"to",
"show",
"the",
"full",
"text",
"an",
"OverflowException",
"is",
"raised",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/virtual.py#L505-L516 | train | 210,371 |
rm-hull/luma.core | luma/core/threadpool.py | threadpool.add_task | def add_task(self, func, *args, **kargs):
"""
Add a task to the queue.
"""
self.tasks.put((func, args, kargs)) | python | def add_task(self, func, *args, **kargs):
"""
Add a task to the queue.
"""
self.tasks.put((func, args, kargs)) | [
"def",
"add_task",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"self",
".",
"tasks",
".",
"put",
"(",
"(",
"func",
",",
"args",
",",
"kargs",
")",
")"
] | Add a task to the queue. | [
"Add",
"a",
"task",
"to",
"the",
"queue",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/threadpool.py#L42-L46 | train | 210,372 |
rm-hull/luma.core | luma/core/mixin.py | capabilities.capabilities | def capabilities(self, width, height, rotate, mode="1"):
"""
Assigns attributes such as ``width``, ``height``, ``size`` and
``bounding_box`` correctly oriented from the supplied parameters.
:param width: The device width.
:type width: int
:param height: The device height.
:type height: int
:param rotate: An integer value of 0 (default), 1, 2 or 3 only, where 0 is
no rotation, 1 is rotate 90° clockwise, 2 is 180° rotation and 3
represents 270° rotation.
:type rotate: int
:param mode: The supported color model, one of ``"1"``, ``"RGB"`` or
``"RGBA"`` only.
:type mode: str
"""
assert mode in ("1", "RGB", "RGBA")
assert rotate in (0, 1, 2, 3)
self._w = width
self._h = height
self.width = width if rotate % 2 == 0 else height
self.height = height if rotate % 2 == 0 else width
self.size = (self.width, self.height)
self.bounding_box = (0, 0, self.width - 1, self.height - 1)
self.rotate = rotate
self.mode = mode
self.persist = False | python | def capabilities(self, width, height, rotate, mode="1"):
"""
Assigns attributes such as ``width``, ``height``, ``size`` and
``bounding_box`` correctly oriented from the supplied parameters.
:param width: The device width.
:type width: int
:param height: The device height.
:type height: int
:param rotate: An integer value of 0 (default), 1, 2 or 3 only, where 0 is
no rotation, 1 is rotate 90° clockwise, 2 is 180° rotation and 3
represents 270° rotation.
:type rotate: int
:param mode: The supported color model, one of ``"1"``, ``"RGB"`` or
``"RGBA"`` only.
:type mode: str
"""
assert mode in ("1", "RGB", "RGBA")
assert rotate in (0, 1, 2, 3)
self._w = width
self._h = height
self.width = width if rotate % 2 == 0 else height
self.height = height if rotate % 2 == 0 else width
self.size = (self.width, self.height)
self.bounding_box = (0, 0, self.width - 1, self.height - 1)
self.rotate = rotate
self.mode = mode
self.persist = False | [
"def",
"capabilities",
"(",
"self",
",",
"width",
",",
"height",
",",
"rotate",
",",
"mode",
"=",
"\"1\"",
")",
":",
"assert",
"mode",
"in",
"(",
"\"1\"",
",",
"\"RGB\"",
",",
"\"RGBA\"",
")",
"assert",
"rotate",
"in",
"(",
"0",
",",
"1",
",",
"2",... | Assigns attributes such as ``width``, ``height``, ``size`` and
``bounding_box`` correctly oriented from the supplied parameters.
:param width: The device width.
:type width: int
:param height: The device height.
:type height: int
:param rotate: An integer value of 0 (default), 1, 2 or 3 only, where 0 is
no rotation, 1 is rotate 90° clockwise, 2 is 180° rotation and 3
represents 270° rotation.
:type rotate: int
:param mode: The supported color model, one of ``"1"``, ``"RGB"`` or
``"RGBA"`` only.
:type mode: str | [
"Assigns",
"attributes",
"such",
"as",
"width",
"height",
"size",
"and",
"bounding_box",
"correctly",
"oriented",
"from",
"the",
"supplied",
"parameters",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/mixin.py#L13-L40 | train | 210,373 |
rm-hull/luma.core | luma/core/legacy/__init__.py | show_message | def show_message(device, msg, y_offset=0, fill=None, font=None,
scroll_delay=0.03):
"""
Scrolls a message right-to-left across the devices display.
:param device: The device to scroll across.
:param msg: The text message to display (must be ASCII only).
:type msg: str
:param y_offset: The row to use to display the text.
:type y_offset: int
:param fill: The fill color to use (standard Pillow color name or RGB
tuple).
:param font: The font (from :py:mod:`luma.core.legacy.font`) to use.
:param scroll_delay: The number of seconds to delay between scrolling.
:type scroll_delay: float
"""
fps = 0 if scroll_delay == 0 else 1.0 / scroll_delay
regulator = framerate_regulator(fps)
font = font or DEFAULT_FONT
with canvas(device) as draw:
w, h = textsize(msg, font)
x = device.width
virtual = viewport(device, width=w + x + x, height=device.height)
with canvas(virtual) as draw:
text(draw, (x, y_offset), msg, font=font, fill=fill)
i = 0
while i <= w + x:
with regulator:
virtual.set_position((i, 0))
i += 1 | python | def show_message(device, msg, y_offset=0, fill=None, font=None,
scroll_delay=0.03):
"""
Scrolls a message right-to-left across the devices display.
:param device: The device to scroll across.
:param msg: The text message to display (must be ASCII only).
:type msg: str
:param y_offset: The row to use to display the text.
:type y_offset: int
:param fill: The fill color to use (standard Pillow color name or RGB
tuple).
:param font: The font (from :py:mod:`luma.core.legacy.font`) to use.
:param scroll_delay: The number of seconds to delay between scrolling.
:type scroll_delay: float
"""
fps = 0 if scroll_delay == 0 else 1.0 / scroll_delay
regulator = framerate_regulator(fps)
font = font or DEFAULT_FONT
with canvas(device) as draw:
w, h = textsize(msg, font)
x = device.width
virtual = viewport(device, width=w + x + x, height=device.height)
with canvas(virtual) as draw:
text(draw, (x, y_offset), msg, font=font, fill=fill)
i = 0
while i <= w + x:
with regulator:
virtual.set_position((i, 0))
i += 1 | [
"def",
"show_message",
"(",
"device",
",",
"msg",
",",
"y_offset",
"=",
"0",
",",
"fill",
"=",
"None",
",",
"font",
"=",
"None",
",",
"scroll_delay",
"=",
"0.03",
")",
":",
"fps",
"=",
"0",
"if",
"scroll_delay",
"==",
"0",
"else",
"1.0",
"/",
"scro... | Scrolls a message right-to-left across the devices display.
:param device: The device to scroll across.
:param msg: The text message to display (must be ASCII only).
:type msg: str
:param y_offset: The row to use to display the text.
:type y_offset: int
:param fill: The fill color to use (standard Pillow color name or RGB
tuple).
:param font: The font (from :py:mod:`luma.core.legacy.font`) to use.
:param scroll_delay: The number of seconds to delay between scrolling.
:type scroll_delay: float | [
"Scrolls",
"a",
"message",
"right",
"-",
"to",
"-",
"left",
"across",
"the",
"devices",
"display",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/legacy/__init__.py#L61-L93 | train | 210,374 |
rm-hull/luma.core | luma/core/ansi_color.py | parse_str | def parse_str(text):
"""
Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes are translated into directives. For example ``\\033[42m``
would emit a directive of ``["background_color", "green"]``.
Note that unrecognised escape sequences are silently ignored: Only reset,
reverse colours and 8 foreground and background colours are supported.
It is up to the consumer to interpret the directives and update its state
accordingly.
:param text: An ASCII string which may or may not include valid ANSI Color
escape codes.
:type text: str
"""
prog = re.compile(r'^\033\[(\d+(;\d+)*)m', re.UNICODE)
while text != "":
result = prog.match(text)
if result:
for code in result.group(1).split(";"):
directive = valid_attributes.get(int(code), None)
if directive:
yield directive
n = len(result.group(0))
text = text[n:]
else:
yield ["putch", text[0]]
text = text[1:] | python | def parse_str(text):
"""
Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes are translated into directives. For example ``\\033[42m``
would emit a directive of ``["background_color", "green"]``.
Note that unrecognised escape sequences are silently ignored: Only reset,
reverse colours and 8 foreground and background colours are supported.
It is up to the consumer to interpret the directives and update its state
accordingly.
:param text: An ASCII string which may or may not include valid ANSI Color
escape codes.
:type text: str
"""
prog = re.compile(r'^\033\[(\d+(;\d+)*)m', re.UNICODE)
while text != "":
result = prog.match(text)
if result:
for code in result.group(1).split(";"):
directive = valid_attributes.get(int(code), None)
if directive:
yield directive
n = len(result.group(0))
text = text[n:]
else:
yield ["putch", text[0]]
text = text[1:] | [
"def",
"parse_str",
"(",
"text",
")",
":",
"prog",
"=",
"re",
".",
"compile",
"(",
"r'^\\033\\[(\\d+(;\\d+)*)m'",
",",
"re",
".",
"UNICODE",
")",
"while",
"text",
"!=",
"\"\"",
":",
"result",
"=",
"prog",
".",
"match",
"(",
"text",
")",
"if",
"result",... | Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes are translated into directives. For example ``\\033[42m``
would emit a directive of ``["background_color", "green"]``.
Note that unrecognised escape sequences are silently ignored: Only reset,
reverse colours and 8 foreground and background colours are supported.
It is up to the consumer to interpret the directives and update its state
accordingly.
:param text: An ASCII string which may or may not include valid ANSI Color
escape codes.
:type text: str | [
"Given",
"a",
"string",
"of",
"characters",
"for",
"each",
"normal",
"ASCII",
"character",
"yields",
"a",
"directive",
"consisting",
"of",
"a",
"putch",
"instruction",
"followed",
"by",
"the",
"character",
"itself",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/ansi_color.py#L41-L74 | train | 210,375 |
rm-hull/luma.core | luma/core/ansi_color.py | find_directives | def find_directives(text, klass):
"""
Find directives on class ``klass`` in string ``text``.
Returns list of ``(method, args)`` tuples.
.. versionadded:: 0.9.0
:param text: String containing directives.
:type text: str
:type klass: object
:rtype: list
"""
directives = []
for directive in parse_str(text):
method = klass.__getattribute__(directive[0])
args = directive[1:]
directives.append((method, args))
return directives | python | def find_directives(text, klass):
"""
Find directives on class ``klass`` in string ``text``.
Returns list of ``(method, args)`` tuples.
.. versionadded:: 0.9.0
:param text: String containing directives.
:type text: str
:type klass: object
:rtype: list
"""
directives = []
for directive in parse_str(text):
method = klass.__getattribute__(directive[0])
args = directive[1:]
directives.append((method, args))
return directives | [
"def",
"find_directives",
"(",
"text",
",",
"klass",
")",
":",
"directives",
"=",
"[",
"]",
"for",
"directive",
"in",
"parse_str",
"(",
"text",
")",
":",
"method",
"=",
"klass",
".",
"__getattribute__",
"(",
"directive",
"[",
"0",
"]",
")",
"args",
"="... | Find directives on class ``klass`` in string ``text``.
Returns list of ``(method, args)`` tuples.
.. versionadded:: 0.9.0
:param text: String containing directives.
:type text: str
:type klass: object
:rtype: list | [
"Find",
"directives",
"on",
"class",
"klass",
"in",
"string",
"text",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/ansi_color.py#L90-L108 | train | 210,376 |
rm-hull/luma.core | luma/core/cmdline.py | get_display_types | def get_display_types():
"""
Get ordered dict containing available display types from available luma
sub-projects.
:rtype: collections.OrderedDict
"""
display_types = OrderedDict()
for namespace in get_supported_libraries():
display_types[namespace] = get_choices('luma.{0}.device'.format(
namespace))
return display_types | python | def get_display_types():
"""
Get ordered dict containing available display types from available luma
sub-projects.
:rtype: collections.OrderedDict
"""
display_types = OrderedDict()
for namespace in get_supported_libraries():
display_types[namespace] = get_choices('luma.{0}.device'.format(
namespace))
return display_types | [
"def",
"get_display_types",
"(",
")",
":",
"display_types",
"=",
"OrderedDict",
"(",
")",
"for",
"namespace",
"in",
"get_supported_libraries",
"(",
")",
":",
"display_types",
"[",
"namespace",
"]",
"=",
"get_choices",
"(",
"'luma.{0}.device'",
".",
"format",
"("... | Get ordered dict containing available display types from available luma
sub-projects.
:rtype: collections.OrderedDict | [
"Get",
"ordered",
"dict",
"containing",
"available",
"display",
"types",
"from",
"available",
"luma",
"sub",
"-",
"projects",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/cmdline.py#L84-L96 | train | 210,377 |
rm-hull/luma.core | luma/core/cmdline.py | load_config | def load_config(path):
"""
Load device configuration from file path and return list with parsed lines.
:param path: Location of configuration file.
:type path: str
:rtype: list
"""
args = []
with open(path, 'r') as fp:
for line in fp.readlines():
if line.strip() and not line.startswith("#"):
args.append(line.replace("\n", ""))
return args | python | def load_config(path):
"""
Load device configuration from file path and return list with parsed lines.
:param path: Location of configuration file.
:type path: str
:rtype: list
"""
args = []
with open(path, 'r') as fp:
for line in fp.readlines():
if line.strip() and not line.startswith("#"):
args.append(line.replace("\n", ""))
return args | [
"def",
"load_config",
"(",
"path",
")",
":",
"args",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
"and",
"not",
... | Load device configuration from file path and return list with parsed lines.
:param path: Location of configuration file.
:type path: str
:rtype: list | [
"Load",
"device",
"configuration",
"from",
"file",
"path",
"and",
"return",
"list",
"with",
"parsed",
"lines",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/cmdline.py#L107-L121 | train | 210,378 |
rm-hull/luma.core | luma/core/cmdline.py | create_device | def create_device(args, display_types=None):
"""
Create and return device.
:type args: object
:type display_types: dict
"""
device = None
if display_types is None:
display_types = get_display_types()
if args.display in display_types.get('oled'):
import luma.oled.device
Device = getattr(luma.oled.device, args.display)
Serial = getattr(make_serial(args), args.interface)
device = Device(Serial(), **vars(args))
elif args.display in display_types.get('lcd'):
import luma.lcd.device
import luma.lcd.aux
Device = getattr(luma.lcd.device, args.display)
spi = make_serial(args).spi()
device = Device(spi, **vars(args))
luma.lcd.aux.backlight(gpio=spi._gpio, gpio_LIGHT=args.gpio_backlight, active_low=args.backlight_active == "low").enable(True)
elif args.display in display_types.get('led_matrix'):
import luma.led_matrix.device
from luma.core.interface.serial import noop
Device = getattr(luma.led_matrix.device, args.display)
spi = make_serial(args, gpio=noop()).spi()
device = Device(serial_interface=spi, **vars(args))
elif args.display in display_types.get('emulator'):
import luma.emulator.device
Device = getattr(luma.emulator.device, args.display)
device = Device(**vars(args))
return device | python | def create_device(args, display_types=None):
"""
Create and return device.
:type args: object
:type display_types: dict
"""
device = None
if display_types is None:
display_types = get_display_types()
if args.display in display_types.get('oled'):
import luma.oled.device
Device = getattr(luma.oled.device, args.display)
Serial = getattr(make_serial(args), args.interface)
device = Device(Serial(), **vars(args))
elif args.display in display_types.get('lcd'):
import luma.lcd.device
import luma.lcd.aux
Device = getattr(luma.lcd.device, args.display)
spi = make_serial(args).spi()
device = Device(spi, **vars(args))
luma.lcd.aux.backlight(gpio=spi._gpio, gpio_LIGHT=args.gpio_backlight, active_low=args.backlight_active == "low").enable(True)
elif args.display in display_types.get('led_matrix'):
import luma.led_matrix.device
from luma.core.interface.serial import noop
Device = getattr(luma.led_matrix.device, args.display)
spi = make_serial(args, gpio=noop()).spi()
device = Device(serial_interface=spi, **vars(args))
elif args.display in display_types.get('emulator'):
import luma.emulator.device
Device = getattr(luma.emulator.device, args.display)
device = Device(**vars(args))
return device | [
"def",
"create_device",
"(",
"args",
",",
"display_types",
"=",
"None",
")",
":",
"device",
"=",
"None",
"if",
"display_types",
"is",
"None",
":",
"display_types",
"=",
"get_display_types",
"(",
")",
"if",
"args",
".",
"display",
"in",
"display_types",
".",
... | Create and return device.
:type args: object
:type display_types: dict | [
"Create",
"and",
"return",
"device",
"."
] | 034b628fb304a01e77732a299c0b42e94d6443db | https://github.com/rm-hull/luma.core/blob/034b628fb304a01e77732a299c0b42e94d6443db/luma/core/cmdline.py#L164-L201 | train | 210,379 |
hmrc/service-manager | servicemanager/subprocess.py | check_output | def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output | python | def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output | [
"def",
"check_output",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'stdout'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'stdout argument not allowed, it will be overridden.'",
")",
"process",
"=",
"Popen",
"(",
"stdout",
"=",
"PIPE",... | r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n' | [
"r",
"Run",
"command",
"with",
"arguments",
"and",
"return",
"its",
"output",
"as",
"a",
"byte",
"string",
"."
] | 1d9d2ee38601ab2bdb1d817bc24ceda6321e673f | https://github.com/hmrc/service-manager/blob/1d9d2ee38601ab2bdb1d817bc24ceda6321e673f/servicemanager/subprocess.py#L544-L574 | train | 210,380 |
marcomusy/vtkplotter | examples/simulations/particle_simulator.py | ParticleSim.simulate | def simulate(self):
""" Runs the particle simulation. Simulates one time step, dt, of the particle motion.
Calculates the force between each pair of particles and updates particles' motion accordingly
"""
# Main simulation loop
for i in range(self.iterations):
for a in self.particles:
if a.fixed:
continue
ftot = vector(0, 0, 0) # total force acting on particle a
for b in self.particles:
if a.negligible and b.negligible or a == b:
continue
ab = a.pos - b.pos
ftot += ((K_COULOMB * a.charge * b.charge) / mag2(ab)) * versor(ab)
a.vel += ftot / a.mass * self.dt # update velocity and position of a
a.pos += a.vel * self.dt
a.vtk_actor.pos(a.pos)
if vp:
vp.show(zoom=1.2)
vp.camera.Azimuth(0.1) | python | def simulate(self):
""" Runs the particle simulation. Simulates one time step, dt, of the particle motion.
Calculates the force between each pair of particles and updates particles' motion accordingly
"""
# Main simulation loop
for i in range(self.iterations):
for a in self.particles:
if a.fixed:
continue
ftot = vector(0, 0, 0) # total force acting on particle a
for b in self.particles:
if a.negligible and b.negligible or a == b:
continue
ab = a.pos - b.pos
ftot += ((K_COULOMB * a.charge * b.charge) / mag2(ab)) * versor(ab)
a.vel += ftot / a.mass * self.dt # update velocity and position of a
a.pos += a.vel * self.dt
a.vtk_actor.pos(a.pos)
if vp:
vp.show(zoom=1.2)
vp.camera.Azimuth(0.1) | [
"def",
"simulate",
"(",
"self",
")",
":",
"# Main simulation loop",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"iterations",
")",
":",
"for",
"a",
"in",
"self",
".",
"particles",
":",
"if",
"a",
".",
"fixed",
":",
"continue",
"ftot",
"=",
"vector",
... | Runs the particle simulation. Simulates one time step, dt, of the particle motion.
Calculates the force between each pair of particles and updates particles' motion accordingly | [
"Runs",
"the",
"particle",
"simulation",
".",
"Simulates",
"one",
"time",
"step",
"dt",
"of",
"the",
"particle",
"motion",
".",
"Calculates",
"the",
"force",
"between",
"each",
"pair",
"of",
"particles",
"and",
"updates",
"particles",
"motion",
"accordingly"
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/examples/simulations/particle_simulator.py#L42-L62 | train | 210,381 |
marcomusy/vtkplotter | vtkplotter/addons.py | addCutterTool | def addCutterTool(actor):
"""Create handles to cut away parts of a mesh.
.. hint:: |cutter| |cutter.py|_
"""
if isinstance(actor, vtk.vtkVolume):
return _addVolumeCutterTool(actor)
elif isinstance(actor, vtk.vtkImageData):
from vtkplotter import Volume
return _addVolumeCutterTool(Volume(actor))
vp = settings.plotter_instance
if not vp.renderer:
save_int = vp.interactive
vp.show(interactive=0)
vp.interactive = save_int
vp.clickedActor = actor
if hasattr(actor, "polydata"):
apd = actor.polydata()
else:
apd = actor.GetMapper().GetInput()
planes = vtk.vtkPlanes()
planes.SetBounds(apd.GetBounds())
clipper = vtk.vtkClipPolyData()
clipper.GenerateClipScalarsOff()
clipper.SetInputData(apd)
clipper.SetClipFunction(planes)
clipper.InsideOutOn()
clipper.GenerateClippedOutputOn()
act0Mapper = vtk.vtkPolyDataMapper() # the part which stays
act0Mapper.SetInputConnection(clipper.GetOutputPort())
act0 = Actor()
act0.SetMapper(act0Mapper)
act0.GetProperty().SetColor(actor.GetProperty().GetColor())
act0.GetProperty().SetOpacity(1)
act1Mapper = vtk.vtkPolyDataMapper() # the part which is cut away
act1Mapper.SetInputConnection(clipper.GetClippedOutputPort())
act1 = vtk.vtkActor()
act1.SetMapper(act1Mapper)
act1.GetProperty().SetOpacity(0.02)
act1.GetProperty().SetRepresentationToWireframe()
act1.VisibilityOn()
vp.renderer.AddActor(act0)
vp.renderer.AddActor(act1)
vp.renderer.RemoveActor(actor)
def SelectPolygons(vobj, event):
vobj.GetPlanes(planes)
boxWidget = vtk.vtkBoxWidget()
boxWidget.OutlineCursorWiresOn()
boxWidget.GetSelectedOutlineProperty().SetColor(1, 0, 1)
boxWidget.GetOutlineProperty().SetColor(0.1, 0.1, 0.1)
boxWidget.GetOutlineProperty().SetOpacity(0.8)
boxWidget.SetPlaceFactor(1.05)
boxWidget.SetInteractor(vp.interactor)
boxWidget.SetInputData(apd)
boxWidget.PlaceWidget()
boxWidget.AddObserver("InteractionEvent", SelectPolygons)
boxWidget.On()
vp.cutterWidget = boxWidget
vp.clickedActor = act0
ia = vp.actors.index(actor)
vp.actors[ia] = act0
colors.printc("Mesh Cutter Tool:", c="m", invert=1)
colors.printc(" Move gray handles to cut away parts of the mesh", c="m")
colors.printc(" Press X to save file to: clipped.vtk", c="m")
vp.interactor.Start()
boxWidget.Off()
vp.widgets.append(boxWidget)
vp.interactor.Start() # allow extra interaction
return act0 | python | def addCutterTool(actor):
"""Create handles to cut away parts of a mesh.
.. hint:: |cutter| |cutter.py|_
"""
if isinstance(actor, vtk.vtkVolume):
return _addVolumeCutterTool(actor)
elif isinstance(actor, vtk.vtkImageData):
from vtkplotter import Volume
return _addVolumeCutterTool(Volume(actor))
vp = settings.plotter_instance
if not vp.renderer:
save_int = vp.interactive
vp.show(interactive=0)
vp.interactive = save_int
vp.clickedActor = actor
if hasattr(actor, "polydata"):
apd = actor.polydata()
else:
apd = actor.GetMapper().GetInput()
planes = vtk.vtkPlanes()
planes.SetBounds(apd.GetBounds())
clipper = vtk.vtkClipPolyData()
clipper.GenerateClipScalarsOff()
clipper.SetInputData(apd)
clipper.SetClipFunction(planes)
clipper.InsideOutOn()
clipper.GenerateClippedOutputOn()
act0Mapper = vtk.vtkPolyDataMapper() # the part which stays
act0Mapper.SetInputConnection(clipper.GetOutputPort())
act0 = Actor()
act0.SetMapper(act0Mapper)
act0.GetProperty().SetColor(actor.GetProperty().GetColor())
act0.GetProperty().SetOpacity(1)
act1Mapper = vtk.vtkPolyDataMapper() # the part which is cut away
act1Mapper.SetInputConnection(clipper.GetClippedOutputPort())
act1 = vtk.vtkActor()
act1.SetMapper(act1Mapper)
act1.GetProperty().SetOpacity(0.02)
act1.GetProperty().SetRepresentationToWireframe()
act1.VisibilityOn()
vp.renderer.AddActor(act0)
vp.renderer.AddActor(act1)
vp.renderer.RemoveActor(actor)
def SelectPolygons(vobj, event):
vobj.GetPlanes(planes)
boxWidget = vtk.vtkBoxWidget()
boxWidget.OutlineCursorWiresOn()
boxWidget.GetSelectedOutlineProperty().SetColor(1, 0, 1)
boxWidget.GetOutlineProperty().SetColor(0.1, 0.1, 0.1)
boxWidget.GetOutlineProperty().SetOpacity(0.8)
boxWidget.SetPlaceFactor(1.05)
boxWidget.SetInteractor(vp.interactor)
boxWidget.SetInputData(apd)
boxWidget.PlaceWidget()
boxWidget.AddObserver("InteractionEvent", SelectPolygons)
boxWidget.On()
vp.cutterWidget = boxWidget
vp.clickedActor = act0
ia = vp.actors.index(actor)
vp.actors[ia] = act0
colors.printc("Mesh Cutter Tool:", c="m", invert=1)
colors.printc(" Move gray handles to cut away parts of the mesh", c="m")
colors.printc(" Press X to save file to: clipped.vtk", c="m")
vp.interactor.Start()
boxWidget.Off()
vp.widgets.append(boxWidget)
vp.interactor.Start() # allow extra interaction
return act0 | [
"def",
"addCutterTool",
"(",
"actor",
")",
":",
"if",
"isinstance",
"(",
"actor",
",",
"vtk",
".",
"vtkVolume",
")",
":",
"return",
"_addVolumeCutterTool",
"(",
"actor",
")",
"elif",
"isinstance",
"(",
"actor",
",",
"vtk",
".",
"vtkImageData",
")",
":",
... | Create handles to cut away parts of a mesh.
.. hint:: |cutter| |cutter.py|_ | [
"Create",
"handles",
"to",
"cut",
"away",
"parts",
"of",
"a",
"mesh",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/addons.py#L484-L566 | train | 210,382 |
marcomusy/vtkplotter | vtkplotter/utils.py | isSequence | def isSequence(arg):
"""Check if input is iterable."""
if hasattr(arg, "strip"):
return False
if hasattr(arg, "__getslice__"):
return True
if hasattr(arg, "__iter__"):
return True
return False | python | def isSequence(arg):
"""Check if input is iterable."""
if hasattr(arg, "strip"):
return False
if hasattr(arg, "__getslice__"):
return True
if hasattr(arg, "__iter__"):
return True
return False | [
"def",
"isSequence",
"(",
"arg",
")",
":",
"if",
"hasattr",
"(",
"arg",
",",
"\"strip\"",
")",
":",
"return",
"False",
"if",
"hasattr",
"(",
"arg",
",",
"\"__getslice__\"",
")",
":",
"return",
"True",
"if",
"hasattr",
"(",
"arg",
",",
"\"__iter__\"",
"... | Check if input is iterable. | [
"Check",
"if",
"input",
"is",
"iterable",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L35-L43 | train | 210,383 |
marcomusy/vtkplotter | vtkplotter/utils.py | flatten | def flatten(list_to_flatten):
"""Flatten out a list."""
def genflatten(lst):
for elem in lst:
if isinstance(elem, (list, tuple)):
for x in flatten(elem):
yield x
else:
yield elem
return list(genflatten(list_to_flatten)) | python | def flatten(list_to_flatten):
"""Flatten out a list."""
def genflatten(lst):
for elem in lst:
if isinstance(elem, (list, tuple)):
for x in flatten(elem):
yield x
else:
yield elem
return list(genflatten(list_to_flatten)) | [
"def",
"flatten",
"(",
"list_to_flatten",
")",
":",
"def",
"genflatten",
"(",
"lst",
")",
":",
"for",
"elem",
"in",
"lst",
":",
"if",
"isinstance",
"(",
"elem",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"x",
"in",
"flatten",
"(",
"elem"... | Flatten out a list. | [
"Flatten",
"out",
"a",
"list",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L46-L57 | train | 210,384 |
marcomusy/vtkplotter | vtkplotter/utils.py | humansort | def humansort(l):
"""Sort in place a given list the way humans expect.
E.g. ['file11', 'file1'] -> ['file1', 'file11']
"""
import re
def alphanum_key(s):
# Turn a string into a list of string and number chunks.
# e.g. "z23a" -> ["z", 23, "a"]
def tryint(s):
if s.isdigit():
return int(s)
return s
return [tryint(c) for c in re.split("([0-9]+)", s)]
l.sort(key=alphanum_key)
return None | python | def humansort(l):
"""Sort in place a given list the way humans expect.
E.g. ['file11', 'file1'] -> ['file1', 'file11']
"""
import re
def alphanum_key(s):
# Turn a string into a list of string and number chunks.
# e.g. "z23a" -> ["z", 23, "a"]
def tryint(s):
if s.isdigit():
return int(s)
return s
return [tryint(c) for c in re.split("([0-9]+)", s)]
l.sort(key=alphanum_key)
return None | [
"def",
"humansort",
"(",
"l",
")",
":",
"import",
"re",
"def",
"alphanum_key",
"(",
"s",
")",
":",
"# Turn a string into a list of string and number chunks.",
"# e.g. \"z23a\" -> [\"z\", 23, \"a\"]",
"def",
"tryint",
"(",
"s",
")",
":",
"if",
"s",
".",
"isdigit",
... | Sort in place a given list the way humans expect.
E.g. ['file11', 'file1'] -> ['file1', 'file11'] | [
"Sort",
"in",
"place",
"a",
"given",
"list",
"the",
"way",
"humans",
"expect",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L60-L78 | train | 210,385 |
marcomusy/vtkplotter | vtkplotter/utils.py | lin_interp | def lin_interp(x, rangeX, rangeY):
"""
Interpolate linearly variable x in rangeX onto rangeY.
"""
s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])
y = rangeY[0] * (1 - s) + rangeY[1] * s
return y | python | def lin_interp(x, rangeX, rangeY):
"""
Interpolate linearly variable x in rangeX onto rangeY.
"""
s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])
y = rangeY[0] * (1 - s) + rangeY[1] * s
return y | [
"def",
"lin_interp",
"(",
"x",
",",
"rangeX",
",",
"rangeY",
")",
":",
"s",
"=",
"(",
"x",
"-",
"rangeX",
"[",
"0",
"]",
")",
"/",
"mag",
"(",
"rangeX",
"[",
"1",
"]",
"-",
"rangeX",
"[",
"0",
"]",
")",
"y",
"=",
"rangeY",
"[",
"0",
"]",
... | Interpolate linearly variable x in rangeX onto rangeY. | [
"Interpolate",
"linearly",
"variable",
"x",
"in",
"rangeX",
"onto",
"rangeY",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L81-L87 | train | 210,386 |
marcomusy/vtkplotter | vtkplotter/utils.py | versor | def versor(v):
"""Return the unit vector. Input can be a list of vectors."""
if isinstance(v[0], np.ndarray):
return np.divide(v, mag(v)[:, None])
else:
return v / mag(v) | python | def versor(v):
"""Return the unit vector. Input can be a list of vectors."""
if isinstance(v[0], np.ndarray):
return np.divide(v, mag(v)[:, None])
else:
return v / mag(v) | [
"def",
"versor",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
"[",
"0",
"]",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"np",
".",
"divide",
"(",
"v",
",",
"mag",
"(",
"v",
")",
"[",
":",
",",
"None",
"]",
")",
"else",
":",
"return... | Return the unit vector. Input can be a list of vectors. | [
"Return",
"the",
"unit",
"vector",
".",
"Input",
"can",
"be",
"a",
"list",
"of",
"vectors",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L100-L105 | train | 210,387 |
marcomusy/vtkplotter | vtkplotter/utils.py | mag | def mag(z):
"""Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray):
return np.array(list(map(np.linalg.norm, z)))
else:
return np.linalg.norm(z) | python | def mag(z):
"""Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray):
return np.array(list(map(np.linalg.norm, z)))
else:
return np.linalg.norm(z) | [
"def",
"mag",
"(",
"z",
")",
":",
"if",
"isinstance",
"(",
"z",
"[",
"0",
"]",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"np",
".",
"array",
"(",
"list",
"(",
"map",
"(",
"np",
".",
"linalg",
".",
"norm",
",",
"z",
")",
")",
")",
"else... | Get the magnitude of a vector. | [
"Get",
"the",
"magnitude",
"of",
"a",
"vector",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L108-L113 | train | 210,388 |
marcomusy/vtkplotter | vtkplotter/utils.py | precision | def precision(x, p):
"""
Returns a string representation of `x` formatted with precision `p`.
Based on the webkit javascript implementation taken
`from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
and implemented by `randlet <https://github.com/randlet/to-precision>`_.
"""
import math
x = float(x)
if x == 0.0:
return "0." + "0" * (p - 1)
out = []
if x < 0:
out.append("-")
x = -x
e = int(math.log10(x))
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if n < math.pow(10, p - 1):
e = e - 1
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if abs((n + 1.0) * tens - x) <= abs(n * tens - x):
n = n + 1
if n >= math.pow(10, p):
n = n / 10.0
e = e + 1
m = "%.*g" % (p, n)
if e < -2 or e >= p:
out.append(m[0])
if p > 1:
out.append(".")
out.extend(m[1:p])
out.append("e")
if e > 0:
out.append("+")
out.append(str(e))
elif e == (p - 1):
out.append(m)
elif e >= 0:
out.append(m[: e + 1])
if e + 1 < len(m):
out.append(".")
out.extend(m[e + 1 :])
else:
out.append("0.")
out.extend(["0"] * -(e + 1))
out.append(m)
return "".join(out) | python | def precision(x, p):
"""
Returns a string representation of `x` formatted with precision `p`.
Based on the webkit javascript implementation taken
`from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
and implemented by `randlet <https://github.com/randlet/to-precision>`_.
"""
import math
x = float(x)
if x == 0.0:
return "0." + "0" * (p - 1)
out = []
if x < 0:
out.append("-")
x = -x
e = int(math.log10(x))
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if n < math.pow(10, p - 1):
e = e - 1
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if abs((n + 1.0) * tens - x) <= abs(n * tens - x):
n = n + 1
if n >= math.pow(10, p):
n = n / 10.0
e = e + 1
m = "%.*g" % (p, n)
if e < -2 or e >= p:
out.append(m[0])
if p > 1:
out.append(".")
out.extend(m[1:p])
out.append("e")
if e > 0:
out.append("+")
out.append(str(e))
elif e == (p - 1):
out.append(m)
elif e >= 0:
out.append(m[: e + 1])
if e + 1 < len(m):
out.append(".")
out.extend(m[e + 1 :])
else:
out.append("0.")
out.extend(["0"] * -(e + 1))
out.append(m)
return "".join(out) | [
"def",
"precision",
"(",
"x",
",",
"p",
")",
":",
"import",
"math",
"x",
"=",
"float",
"(",
"x",
")",
"if",
"x",
"==",
"0.0",
":",
"return",
"\"0.\"",
"+",
"\"0\"",
"*",
"(",
"p",
"-",
"1",
")",
"out",
"=",
"[",
"]",
"if",
"x",
"<",
"0",
... | Returns a string representation of `x` formatted with precision `p`.
Based on the webkit javascript implementation taken
`from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
and implemented by `randlet <https://github.com/randlet/to-precision>`_. | [
"Returns",
"a",
"string",
"representation",
"of",
"x",
"formatted",
"with",
"precision",
"p",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L121-L178 | train | 210,389 |
marcomusy/vtkplotter | vtkplotter/utils.py | spher2cart | def spher2cart(rho, theta, phi):
"""Spherical to Cartesian coordinate conversion."""
st = np.sin(theta)
sp = np.sin(phi)
ct = np.cos(theta)
cp = np.cos(phi)
rhost = rho * st
x = rhost * cp
y = rhost * sp
z = rho * ct
return np.array([x, y, z]) | python | def spher2cart(rho, theta, phi):
"""Spherical to Cartesian coordinate conversion."""
st = np.sin(theta)
sp = np.sin(phi)
ct = np.cos(theta)
cp = np.cos(phi)
rhost = rho * st
x = rhost * cp
y = rhost * sp
z = rho * ct
return np.array([x, y, z]) | [
"def",
"spher2cart",
"(",
"rho",
",",
"theta",
",",
"phi",
")",
":",
"st",
"=",
"np",
".",
"sin",
"(",
"theta",
")",
"sp",
"=",
"np",
".",
"sin",
"(",
"phi",
")",
"ct",
"=",
"np",
".",
"cos",
"(",
"theta",
")",
"cp",
"=",
"np",
".",
"cos",
... | Spherical to Cartesian coordinate conversion. | [
"Spherical",
"to",
"Cartesian",
"coordinate",
"conversion",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L207-L217 | train | 210,390 |
marcomusy/vtkplotter | vtkplotter/utils.py | cart2spher | def cart2spher(x, y, z):
"""Cartesian to Spherical coordinate conversion."""
hxy = np.hypot(x, y)
r = np.hypot(hxy, z)
theta = np.arctan2(z, hxy)
phi = np.arctan2(y, x)
return r, theta, phi | python | def cart2spher(x, y, z):
"""Cartesian to Spherical coordinate conversion."""
hxy = np.hypot(x, y)
r = np.hypot(hxy, z)
theta = np.arctan2(z, hxy)
phi = np.arctan2(y, x)
return r, theta, phi | [
"def",
"cart2spher",
"(",
"x",
",",
"y",
",",
"z",
")",
":",
"hxy",
"=",
"np",
".",
"hypot",
"(",
"x",
",",
"y",
")",
"r",
"=",
"np",
".",
"hypot",
"(",
"hxy",
",",
"z",
")",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"z",
",",
"hxy",
")",
... | Cartesian to Spherical coordinate conversion. | [
"Cartesian",
"to",
"Spherical",
"coordinate",
"conversion",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L220-L226 | train | 210,391 |
marcomusy/vtkplotter | vtkplotter/utils.py | cart2pol | def cart2pol(x, y):
"""Cartesian to Polar coordinates conversion."""
theta = np.arctan2(y, x)
rho = np.hypot(x, y)
return theta, rho | python | def cart2pol(x, y):
"""Cartesian to Polar coordinates conversion."""
theta = np.arctan2(y, x)
rho = np.hypot(x, y)
return theta, rho | [
"def",
"cart2pol",
"(",
"x",
",",
"y",
")",
":",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"y",
",",
"x",
")",
"rho",
"=",
"np",
".",
"hypot",
"(",
"x",
",",
"y",
")",
"return",
"theta",
",",
"rho"
] | Cartesian to Polar coordinates conversion. | [
"Cartesian",
"to",
"Polar",
"coordinates",
"conversion",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L229-L233 | train | 210,392 |
marcomusy/vtkplotter | vtkplotter/utils.py | pol2cart | def pol2cart(theta, rho):
"""Polar to Cartesian coordinates conversion."""
x = rho * np.cos(theta)
y = rho * np.sin(theta)
return x, y | python | def pol2cart(theta, rho):
"""Polar to Cartesian coordinates conversion."""
x = rho * np.cos(theta)
y = rho * np.sin(theta)
return x, y | [
"def",
"pol2cart",
"(",
"theta",
",",
"rho",
")",
":",
"x",
"=",
"rho",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"y",
"=",
"rho",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"return",
"x",
",",
"y"
] | Polar to Cartesian coordinates conversion. | [
"Polar",
"to",
"Cartesian",
"coordinates",
"conversion",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L236-L240 | train | 210,393 |
marcomusy/vtkplotter | vtkplotter/utils.py | isIdentity | def isIdentity(M, tol=1e-06):
"""Check if vtkMatrix4x4 is Identity."""
for i in [0, 1, 2, 3]:
for j in [0, 1, 2, 3]:
e = M.GetElement(i, j)
if i == j:
if np.abs(e - 1) > tol:
return False
elif np.abs(e) > tol:
return False
return True | python | def isIdentity(M, tol=1e-06):
"""Check if vtkMatrix4x4 is Identity."""
for i in [0, 1, 2, 3]:
for j in [0, 1, 2, 3]:
e = M.GetElement(i, j)
if i == j:
if np.abs(e - 1) > tol:
return False
elif np.abs(e) > tol:
return False
return True | [
"def",
"isIdentity",
"(",
"M",
",",
"tol",
"=",
"1e-06",
")",
":",
"for",
"i",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
":",
"for",
"j",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
":",
"e",
"=",
"M",
".",
"GetElement",... | Check if vtkMatrix4x4 is Identity. | [
"Check",
"if",
"vtkMatrix4x4",
"is",
"Identity",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L243-L253 | train | 210,394 |
marcomusy/vtkplotter | vtkplotter/utils.py | grep | def grep(filename, tag, firstOccurrence=False):
"""Greps the line that starts with a specific `tag` string from inside a file."""
import re
try:
afile = open(filename, "r")
except:
print("Error in utils.grep(): cannot open file", filename)
exit()
content = None
for line in afile:
if re.search(tag, line):
content = line.split()
if firstOccurrence:
break
if content:
if len(content) == 2:
content = content[1]
else:
content = content[1:]
afile.close()
return content | python | def grep(filename, tag, firstOccurrence=False):
"""Greps the line that starts with a specific `tag` string from inside a file."""
import re
try:
afile = open(filename, "r")
except:
print("Error in utils.grep(): cannot open file", filename)
exit()
content = None
for line in afile:
if re.search(tag, line):
content = line.split()
if firstOccurrence:
break
if content:
if len(content) == 2:
content = content[1]
else:
content = content[1:]
afile.close()
return content | [
"def",
"grep",
"(",
"filename",
",",
"tag",
",",
"firstOccurrence",
"=",
"False",
")",
":",
"import",
"re",
"try",
":",
"afile",
"=",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"except",
":",
"print",
"(",
"\"Error in utils.grep(): cannot open file\"",
",",... | Greps the line that starts with a specific `tag` string from inside a file. | [
"Greps",
"the",
"line",
"that",
"starts",
"with",
"a",
"specific",
"tag",
"string",
"from",
"inside",
"a",
"file",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L256-L277 | train | 210,395 |
marcomusy/vtkplotter | vtkplotter/utils.py | makeBands | def makeBands(inputlist, numberOfBands):
"""
Group values of a list into bands of equal value.
:param int numberOfBands: number of bands, a positive integer > 2.
:return: a binned list of the same length as the input.
"""
if numberOfBands < 2:
return inputlist
vmin = np.min(inputlist)
vmax = np.max(inputlist)
bb = np.linspace(vmin, vmax, numberOfBands, endpoint=0)
dr = bb[1] - bb[0]
bb += dr / 2
tol = dr / 2 * 1.001
newlist = []
for s in inputlist:
for b in bb:
if abs(s - b) < tol:
newlist.append(b)
break
return np.array(newlist) | python | def makeBands(inputlist, numberOfBands):
"""
Group values of a list into bands of equal value.
:param int numberOfBands: number of bands, a positive integer > 2.
:return: a binned list of the same length as the input.
"""
if numberOfBands < 2:
return inputlist
vmin = np.min(inputlist)
vmax = np.max(inputlist)
bb = np.linspace(vmin, vmax, numberOfBands, endpoint=0)
dr = bb[1] - bb[0]
bb += dr / 2
tol = dr / 2 * 1.001
newlist = []
for s in inputlist:
for b in bb:
if abs(s - b) < tol:
newlist.append(b)
break
return np.array(newlist) | [
"def",
"makeBands",
"(",
"inputlist",
",",
"numberOfBands",
")",
":",
"if",
"numberOfBands",
"<",
"2",
":",
"return",
"inputlist",
"vmin",
"=",
"np",
".",
"min",
"(",
"inputlist",
")",
"vmax",
"=",
"np",
".",
"max",
"(",
"inputlist",
")",
"bb",
"=",
... | Group values of a list into bands of equal value.
:param int numberOfBands: number of bands, a positive integer > 2.
:return: a binned list of the same length as the input. | [
"Group",
"values",
"of",
"a",
"list",
"into",
"bands",
"of",
"equal",
"value",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L503-L526 | train | 210,396 |
marcomusy/vtkplotter | vtkplotter/plotter.py | clear | def clear(actor=()):
"""
Clear specific actor or list of actors from the current rendering window.
"""
if not settings.plotter_instance:
return
settings.plotter_instance.clear(actor)
return settings.plotter_instance | python | def clear(actor=()):
"""
Clear specific actor or list of actors from the current rendering window.
"""
if not settings.plotter_instance:
return
settings.plotter_instance.clear(actor)
return settings.plotter_instance | [
"def",
"clear",
"(",
"actor",
"=",
"(",
")",
")",
":",
"if",
"not",
"settings",
".",
"plotter_instance",
":",
"return",
"settings",
".",
"plotter_instance",
".",
"clear",
"(",
"actor",
")",
"return",
"settings",
".",
"plotter_instance"
] | Clear specific actor or list of actors from the current rendering window. | [
"Clear",
"specific",
"actor",
"or",
"list",
"of",
"actors",
"from",
"the",
"current",
"rendering",
"window",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L191-L198 | train | 210,397 |
marcomusy/vtkplotter | vtkplotter/plotter.py | Plotter.getVolumes | def getVolumes(self, obj=None, renderer=None):
"""
Return the list of the rendered Volumes.
"""
if renderer is None:
renderer = self.renderer
elif isinstance(renderer, int):
renderer = self.renderers.index(renderer)
else:
return []
if obj is None or isinstance(obj, int):
if obj is None:
acs = renderer.GetVolumes()
elif obj >= len(self.renderers):
colors.printc("~timesError in getVolumes: non existing renderer", obj, c=1)
return []
else:
acs = self.renderers[obj].GetVolumes()
vols = []
acs.InitTraversal()
for i in range(acs.GetNumberOfItems()):
a = acs.GetNextItem()
if a.GetPickable():
r = self.renderers.index(renderer)
if a == self.axes_exist[r]:
continue
vols.append(a)
return vols | python | def getVolumes(self, obj=None, renderer=None):
"""
Return the list of the rendered Volumes.
"""
if renderer is None:
renderer = self.renderer
elif isinstance(renderer, int):
renderer = self.renderers.index(renderer)
else:
return []
if obj is None or isinstance(obj, int):
if obj is None:
acs = renderer.GetVolumes()
elif obj >= len(self.renderers):
colors.printc("~timesError in getVolumes: non existing renderer", obj, c=1)
return []
else:
acs = self.renderers[obj].GetVolumes()
vols = []
acs.InitTraversal()
for i in range(acs.GetNumberOfItems()):
a = acs.GetNextItem()
if a.GetPickable():
r = self.renderers.index(renderer)
if a == self.axes_exist[r]:
continue
vols.append(a)
return vols | [
"def",
"getVolumes",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"renderer",
"=",
"None",
")",
":",
"if",
"renderer",
"is",
"None",
":",
"renderer",
"=",
"self",
".",
"renderer",
"elif",
"isinstance",
"(",
"renderer",
",",
"int",
")",
":",
"renderer",
... | Return the list of the rendered Volumes. | [
"Return",
"the",
"list",
"of",
"the",
"rendered",
"Volumes",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L550-L578 | train | 210,398 |
marcomusy/vtkplotter | vtkplotter/plotter.py | Plotter.getActors | def getActors(self, obj=None, renderer=None):
"""
Return an actors list.
If ``obj`` is:
``None``, return actors of current renderer
``int``, return actors in given renderer number
``vtkAssembly`` return the contained actors
``string``, return actors matching legend name
:param int,vtkRenderer renderer: specify which renederer to look into.
"""
if renderer is None:
renderer = self.renderer
elif isinstance(renderer, int):
renderer = self.renderers.index(renderer)
else:
return []
if obj is None or isinstance(obj, int):
if obj is None:
acs = renderer.GetActors()
elif obj >= len(self.renderers):
colors.printc("~timesError in getActors: non existing renderer", obj, c=1)
return []
else:
acs = self.renderers[obj].GetActors()
actors = []
acs.InitTraversal()
for i in range(acs.GetNumberOfItems()):
a = acs.GetNextItem()
if a.GetPickable():
r = self.renderers.index(renderer)
if a == self.axes_exist[r]:
continue
actors.append(a)
return actors
elif isinstance(obj, vtk.vtkAssembly):
cl = vtk.vtkPropCollection()
obj.GetActors(cl)
actors = []
cl.InitTraversal()
for i in range(obj.GetNumberOfPaths()):
act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
if act.GetPickable():
actors.append(act)
return actors
elif isinstance(obj, str): # search the actor by the legend name
actors = []
for a in self.actors:
if hasattr(a, "_legend") and obj in a._legend:
actors.append(a)
return actors
elif isinstance(obj, vtk.vtkActor):
return [obj]
if self.verbose:
colors.printc("~lightning Warning in getActors: unexpected input type", obj, c=1)
return [] | python | def getActors(self, obj=None, renderer=None):
"""
Return an actors list.
If ``obj`` is:
``None``, return actors of current renderer
``int``, return actors in given renderer number
``vtkAssembly`` return the contained actors
``string``, return actors matching legend name
:param int,vtkRenderer renderer: specify which renederer to look into.
"""
if renderer is None:
renderer = self.renderer
elif isinstance(renderer, int):
renderer = self.renderers.index(renderer)
else:
return []
if obj is None or isinstance(obj, int):
if obj is None:
acs = renderer.GetActors()
elif obj >= len(self.renderers):
colors.printc("~timesError in getActors: non existing renderer", obj, c=1)
return []
else:
acs = self.renderers[obj].GetActors()
actors = []
acs.InitTraversal()
for i in range(acs.GetNumberOfItems()):
a = acs.GetNextItem()
if a.GetPickable():
r = self.renderers.index(renderer)
if a == self.axes_exist[r]:
continue
actors.append(a)
return actors
elif isinstance(obj, vtk.vtkAssembly):
cl = vtk.vtkPropCollection()
obj.GetActors(cl)
actors = []
cl.InitTraversal()
for i in range(obj.GetNumberOfPaths()):
act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
if act.GetPickable():
actors.append(act)
return actors
elif isinstance(obj, str): # search the actor by the legend name
actors = []
for a in self.actors:
if hasattr(a, "_legend") and obj in a._legend:
actors.append(a)
return actors
elif isinstance(obj, vtk.vtkActor):
return [obj]
if self.verbose:
colors.printc("~lightning Warning in getActors: unexpected input type", obj, c=1)
return [] | [
"def",
"getActors",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"renderer",
"=",
"None",
")",
":",
"if",
"renderer",
"is",
"None",
":",
"renderer",
"=",
"self",
".",
"renderer",
"elif",
"isinstance",
"(",
"renderer",
",",
"int",
")",
":",
"renderer",
... | Return an actors list.
If ``obj`` is:
``None``, return actors of current renderer
``int``, return actors in given renderer number
``vtkAssembly`` return the contained actors
``string``, return actors matching legend name
:param int,vtkRenderer renderer: specify which renederer to look into. | [
"Return",
"an",
"actors",
"list",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L581-L645 | train | 210,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.