id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,100 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.add_source | def add_source(self, source):
"""Adds sources."""
if self._specific_sources:
return
try:
self._add_child(self.sources, self.sources_set, source)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | python | def add_source(self, source):
if self._specific_sources:
return
try:
self._add_child(self.sources, self.sources_set, source)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"def",
"add_source",
"(",
"self",
",",
"source",
")",
":",
"if",
"self",
".",
"_specific_sources",
":",
"return",
"try",
":",
"self",
".",
"_add_child",
"(",
"self",
".",
"sources",
",",
"self",
".",
"sources_set",
",",
"source",
")",
"except",
"TypeErro... | Adds sources. | [
"Adds",
"sources",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1263-L1275 |
23,101 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node._add_child | def _add_child(self, collection, set, child):
"""Adds 'child' to 'collection', first checking 'set' to see if it's
already present."""
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
if added:
self._children_reset() | python | def _add_child(self, collection, set, child):
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
if added:
self._children_reset() | [
"def",
"_add_child",
"(",
"self",
",",
"collection",
",",
"set",
",",
"child",
")",
":",
"added",
"=",
"None",
"for",
"c",
"in",
"child",
":",
"if",
"c",
"not",
"in",
"set",
":",
"set",
".",
"add",
"(",
"c",
")",
"collection",
".",
"append",
"(",... | Adds 'child' to 'collection', first checking 'set' to see if it's
already present. | [
"Adds",
"child",
"to",
"collection",
"first",
"checking",
"set",
"to",
"see",
"if",
"it",
"s",
"already",
"present",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1277-L1287 |
23,102 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.all_children | def all_children(self, scan=1):
"""Return a list of all the node's direct children."""
if scan:
self.scan()
# The return list may contain duplicate Nodes, especially in
# source trees where there are a lot of repeated #includes
# of a tangle of .h files. Profiling shows, however, that
# eliminating the duplicates with a brute-force approach that
# preserves the order (that is, something like:
#
# u = []
# for n in list:
# if n not in u:
# u.append(n)"
#
# takes more cycles than just letting the underlying methods
# hand back cached values if a Node's information is requested
# multiple times. (Other methods of removing duplicates, like
# using dictionary keys, lose the order, and the only ordered
# dictionary patterns I found all ended up using "not in"
# internally anyway...)
return list(chain.from_iterable([_f for _f in [self.sources, self.depends, self.implicit] if _f])) | python | def all_children(self, scan=1):
if scan:
self.scan()
# The return list may contain duplicate Nodes, especially in
# source trees where there are a lot of repeated #includes
# of a tangle of .h files. Profiling shows, however, that
# eliminating the duplicates with a brute-force approach that
# preserves the order (that is, something like:
#
# u = []
# for n in list:
# if n not in u:
# u.append(n)"
#
# takes more cycles than just letting the underlying methods
# hand back cached values if a Node's information is requested
# multiple times. (Other methods of removing duplicates, like
# using dictionary keys, lose the order, and the only ordered
# dictionary patterns I found all ended up using "not in"
# internally anyway...)
return list(chain.from_iterable([_f for _f in [self.sources, self.depends, self.implicit] if _f])) | [
"def",
"all_children",
"(",
"self",
",",
"scan",
"=",
"1",
")",
":",
"if",
"scan",
":",
"self",
".",
"scan",
"(",
")",
"# The return list may contain duplicate Nodes, especially in",
"# source trees where there are a lot of repeated #includes",
"# of a tangle of .h files. Pr... | Return a list of all the node's direct children. | [
"Return",
"a",
"list",
"of",
"all",
"the",
"node",
"s",
"direct",
"children",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1341-L1363 |
23,103 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.Tag | def Tag(self, key, value):
""" Add a user-defined tag. """
if not self._tags:
self._tags = {}
self._tags[key] = value | python | def Tag(self, key, value):
if not self._tags:
self._tags = {}
self._tags[key] = value | [
"def",
"Tag",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_tags",
":",
"self",
".",
"_tags",
"=",
"{",
"}",
"self",
".",
"_tags",
"[",
"key",
"]",
"=",
"value"
] | Add a user-defined tag. | [
"Add",
"a",
"user",
"-",
"defined",
"tag",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1396-L1400 |
23,104 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Node.render_include_tree | def render_include_tree(self):
"""
Return a text representation, suitable for displaying to the
user, of the include tree for the sources of this node.
"""
if self.is_derived():
env = self.get_build_env()
if env:
for s in self.sources:
scanner = self.get_source_scanner(s)
if scanner:
path = self.get_build_scanner_path(scanner)
else:
path = None
def f(node, env=env, scanner=scanner, path=path):
return node.get_found_includes(env, scanner, path)
return SCons.Util.render_tree(s, f, 1)
else:
return None | python | def render_include_tree(self):
if self.is_derived():
env = self.get_build_env()
if env:
for s in self.sources:
scanner = self.get_source_scanner(s)
if scanner:
path = self.get_build_scanner_path(scanner)
else:
path = None
def f(node, env=env, scanner=scanner, path=path):
return node.get_found_includes(env, scanner, path)
return SCons.Util.render_tree(s, f, 1)
else:
return None | [
"def",
"render_include_tree",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_derived",
"(",
")",
":",
"env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"if",
"env",
":",
"for",
"s",
"in",
"self",
".",
"sources",
":",
"scanner",
"=",
"self",
".",
"... | Return a text representation, suitable for displaying to the
user, of the include tree for the sources of this node. | [
"Return",
"a",
"text",
"representation",
"suitable",
"for",
"displaying",
"to",
"the",
"user",
"of",
"the",
"include",
"tree",
"for",
"the",
"sources",
"of",
"this",
"node",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1500-L1518 |
23,105 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py | Walker.get_next | def get_next(self):
"""Return the next node for this walk of the tree.
This function is intentionally iterative, not recursive,
to sidestep any issues of stack size limitations.
"""
while self.stack:
if self.stack[-1].wkids:
node = self.stack[-1].wkids.pop(0)
if not self.stack[-1].wkids:
self.stack[-1].wkids = None
if node in self.history:
self.cycle_func(node, self.stack)
else:
node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
self.stack.append(node)
self.history[node] = None
else:
node = self.stack.pop()
del self.history[node]
if node:
if self.stack:
parent = self.stack[-1]
else:
parent = None
self.eval_func(node, parent)
return node
return None | python | def get_next(self):
while self.stack:
if self.stack[-1].wkids:
node = self.stack[-1].wkids.pop(0)
if not self.stack[-1].wkids:
self.stack[-1].wkids = None
if node in self.history:
self.cycle_func(node, self.stack)
else:
node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
self.stack.append(node)
self.history[node] = None
else:
node = self.stack.pop()
del self.history[node]
if node:
if self.stack:
parent = self.stack[-1]
else:
parent = None
self.eval_func(node, parent)
return node
return None | [
"def",
"get_next",
"(",
"self",
")",
":",
"while",
"self",
".",
"stack",
":",
"if",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"wkids",
":",
"node",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"wkids",
".",
"pop",
"(",
"0",
")",
... | Return the next node for this walk of the tree.
This function is intentionally iterative, not recursive,
to sidestep any issues of stack size limitations. | [
"Return",
"the",
"next",
"node",
"for",
"this",
"walk",
"of",
"the",
"tree",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1693-L1721 |
23,106 | iotile/coretools | iotilecore/iotile/core/scripts/iotile_script.py | timeout_thread_handler | def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread if required during testing.
"""
stop_happened = stop_event.wait(timeout)
if stop_happened is False:
print("Killing program due to %f second timeout" % timeout)
os._exit(2) | python | def timeout_thread_handler(timeout, stop_event):
stop_happened = stop_event.wait(timeout)
if stop_happened is False:
print("Killing program due to %f second timeout" % timeout)
os._exit(2) | [
"def",
"timeout_thread_handler",
"(",
"timeout",
",",
"stop_event",
")",
":",
"stop_happened",
"=",
"stop_event",
".",
"wait",
"(",
"timeout",
")",
"if",
"stop_happened",
"is",
"False",
":",
"print",
"(",
"\"Killing program due to %f second timeout\"",
"%",
"timeout... | A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread if required during testing. | [
"A",
"background",
"thread",
"to",
"kill",
"the",
"process",
"if",
"it",
"takes",
"too",
"long",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/iotile_script.py#L39-L53 |
23,107 | iotile/coretools | iotilecore/iotile/core/scripts/iotile_script.py | create_parser | def create_parser():
"""Create the argument parser for iotile."""
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")
parser.add_argument('-l', '--logfile', help="The file where we should log all logging messages")
parser.add_argument('-i', '--include', action="append", default=[], help="Only include the specified loggers")
parser.add_argument('-e', '--exclude', action="append", default=[], help="Exclude the specified loggers, including all others")
parser.add_argument('-q', '--quit', action="store_true", help="Do not spawn a shell after executing any commands")
parser.add_argument('-t', '--timeout', type=float, help="Do not allow this process to run for more than a specified number of seconds.")
parser.add_argument('commands', nargs=argparse.REMAINDER, help="The command(s) to execute")
return parser | python | def create_parser():
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")
parser.add_argument('-l', '--logfile', help="The file where we should log all logging messages")
parser.add_argument('-i', '--include', action="append", default=[], help="Only include the specified loggers")
parser.add_argument('-e', '--exclude', action="append", default=[], help="Exclude the specified loggers, including all others")
parser.add_argument('-q', '--quit', action="store_true", help="Do not spawn a shell after executing any commands")
parser.add_argument('-t', '--timeout', type=float, help="Do not allow this process to run for more than a specified number of seconds.")
parser.add_argument('commands', nargs=argparse.REMAINDER, help="The command(s) to execute")
return parser | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'... | Create the argument parser for iotile. | [
"Create",
"the",
"argument",
"parser",
"for",
"iotile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/iotile_script.py#L56-L68 |
23,108 | iotile/coretools | iotilecore/iotile/core/scripts/iotile_script.py | parse_global_args | def parse_global_args(argv):
"""Parse all global iotile tool arguments.
Any flag based argument at the start of the command line is considered as
a global flag and parsed. The first non flag argument starts the commands
that are passed to the underlying hierarchical shell.
Args:
argv (list): The command line for this command
Returns:
Namespace: The parsed arguments, with all of the commands that should
be executed in an iotile shell as the attribute 'commands'
"""
parser = create_parser()
args = parser.parse_args(argv)
should_log = args.include or args.exclude or (args.verbose > 0)
verbosity = args.verbose
root = logging.getLogger()
if should_log:
formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',
'%y-%m-%d %H:%M:%S')
if args.logfile:
handler = logging.FileHandler(args.logfile)
else:
handler = logging.StreamHandler()
handler.setFormatter(formatter)
if args.include and args.exclude:
print("You cannot combine whitelisted (-i) and blacklisted (-e) loggers, you must use one or the other.")
sys.exit(1)
loglevels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if verbosity >= len(loglevels):
verbosity = len(loglevels) - 1
level = loglevels[verbosity]
if args.include:
for name in args.include:
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
root.addHandler(logging.NullHandler())
else:
# Disable propagation of log events from disabled loggers
for name in args.exclude:
logger = logging.getLogger(name)
logger.disabled = True
root.setLevel(level)
root.addHandler(handler)
else:
root.addHandler(logging.NullHandler())
return args | python | def parse_global_args(argv):
parser = create_parser()
args = parser.parse_args(argv)
should_log = args.include or args.exclude or (args.verbose > 0)
verbosity = args.verbose
root = logging.getLogger()
if should_log:
formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',
'%y-%m-%d %H:%M:%S')
if args.logfile:
handler = logging.FileHandler(args.logfile)
else:
handler = logging.StreamHandler()
handler.setFormatter(formatter)
if args.include and args.exclude:
print("You cannot combine whitelisted (-i) and blacklisted (-e) loggers, you must use one or the other.")
sys.exit(1)
loglevels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if verbosity >= len(loglevels):
verbosity = len(loglevels) - 1
level = loglevels[verbosity]
if args.include:
for name in args.include:
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
root.addHandler(logging.NullHandler())
else:
# Disable propagation of log events from disabled loggers
for name in args.exclude:
logger = logging.getLogger(name)
logger.disabled = True
root.setLevel(level)
root.addHandler(handler)
else:
root.addHandler(logging.NullHandler())
return args | [
"def",
"parse_global_args",
"(",
"argv",
")",
":",
"parser",
"=",
"create_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"should_log",
"=",
"args",
".",
"include",
"or",
"args",
".",
"exclude",
"or",
"(",
"args",
".",
"v... | Parse all global iotile tool arguments.
Any flag based argument at the start of the command line is considered as
a global flag and parsed. The first non flag argument starts the commands
that are passed to the underlying hierarchical shell.
Args:
argv (list): The command line for this command
Returns:
Namespace: The parsed arguments, with all of the commands that should
be executed in an iotile shell as the attribute 'commands' | [
"Parse",
"all",
"global",
"iotile",
"tool",
"arguments",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/iotile_script.py#L71-L132 |
23,109 | iotile/coretools | iotilecore/iotile/core/scripts/iotile_script.py | setup_completion | def setup_completion(shell):
"""Setup readline to tab complete in a cross platform way."""
# Handle special case of importing pyreadline on Windows
# See: http://stackoverflow.com/questions/6024952/readline-functionality-on-windows-with-python-2-7
import glob
try:
import readline
except ImportError:
import pyreadline as readline
def _complete(text, state):
buf = readline.get_line_buffer()
if buf.startswith('help ') or " " not in buf:
return [x for x in shell.valid_identifiers() if x.startswith(text)][state]
return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]
readline.set_completer_delims(' \t\n;')
# Handle Mac OS X special libedit based readline
# See: http://stackoverflow.com/questions/7116038/python-tab-completion-mac-osx-10-7-lion
if readline.__doc__ is not None and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
readline.set_completer(_complete) | python | def setup_completion(shell):
# Handle special case of importing pyreadline on Windows
# See: http://stackoverflow.com/questions/6024952/readline-functionality-on-windows-with-python-2-7
import glob
try:
import readline
except ImportError:
import pyreadline as readline
def _complete(text, state):
buf = readline.get_line_buffer()
if buf.startswith('help ') or " " not in buf:
return [x for x in shell.valid_identifiers() if x.startswith(text)][state]
return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]
readline.set_completer_delims(' \t\n;')
# Handle Mac OS X special libedit based readline
# See: http://stackoverflow.com/questions/7116038/python-tab-completion-mac-osx-10-7-lion
if readline.__doc__ is not None and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
readline.set_completer(_complete) | [
"def",
"setup_completion",
"(",
"shell",
")",
":",
"# Handle special case of importing pyreadline on Windows",
"# See: http://stackoverflow.com/questions/6024952/readline-functionality-on-windows-with-python-2-7",
"import",
"glob",
"try",
":",
"import",
"readline",
"except",
"ImportErr... | Setup readline to tab complete in a cross platform way. | [
"Setup",
"readline",
"to",
"tab",
"complete",
"in",
"a",
"cross",
"platform",
"way",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/iotile_script.py#L135-L161 |
23,110 | iotile/coretools | iotilecore/iotile/core/scripts/iotile_script.py | main | def main(argv=None):
"""Run the iotile shell tool.
You can optionally pass the arguments that should be run
in the argv parameter. If nothing is passed, the args
are pulled from sys.argv.
The return value of this function is the return value
of the shell command.
"""
if argv is None:
argv = sys.argv[1:]
args = parse_global_args(argv)
type_system.interactive = True
line = args.commands
timeout_thread = None
timeout_stop_event = threading.Event()
if args.timeout:
timeout_thread = threading.Thread(target=timeout_thread_handler, args=(args.timeout, timeout_stop_event))
timeout_thread.daemon = True
timeout_thread.start()
shell = HierarchicalShell('iotile')
shell.root_add("registry", "iotile.core.dev.annotated_registry,registry")
shell.root_add("config", "iotile.core.dev.config,ConfigManager")
shell.root_add('hw', "iotile.core.hw.hwmanager,HardwareManager")
reg = ComponentRegistry()
plugins = reg.list_plugins()
for key, val in plugins.items():
shell.root_add(key, val)
finished = False
try:
if len(line) > 0:
finished = shell.invoke(line)
except IOTileException as exc:
print(exc.format())
# if the command passed on the command line fails, then we should
# just exit rather than drop the user into a shell.
SharedLoop.stop()
return 1
except Exception: # pylint:disable=broad-except; We need to make sure we always call cmdstream.do_final_close()
# Catch all exceptions because otherwise we won't properly close cmdstreams
# since the program will be said to except 'abnormally'
traceback.print_exc()
SharedLoop.stop()
return 1
# If the user tells us to never spawn a shell, make sure we don't
# Also, if we finished our command and there is no context, quit now
if args.quit or finished:
SharedLoop.stop()
return 0
setup_completion(shell)
# We ended the initial command with a context, start a shell
try:
while True:
try:
linebuf = input("(%s) " % shell.context_name())
# Skip comments automatically
if len(linebuf) > 0 and linebuf[0] == '#':
continue
except KeyboardInterrupt:
print("")
continue
# Catch exception outside the loop so we stop invoking submethods if a parent
# fails because then the context and results would be unpredictable
try:
finished = shell.invoke_string(linebuf)
except KeyboardInterrupt:
print("")
if timeout_stop_event.is_set():
break
except IOTileException as exc:
print(exc.format())
except Exception: #pylint:disable=broad-except;
# We want to make sure the iotile tool never crashes when in interactive shell mode
traceback.print_exc()
if shell.finished():
break
# Make sure to catch ^C and ^D so that we can cleanly dispose of subprocess resources if
# there are any.
except EOFError:
print("")
except KeyboardInterrupt:
print("")
finally:
# Make sure we close any open CMDStream communication channels so that we don't lockup at exit
SharedLoop.stop()
# Make sure we cleanly join our timeout thread before exiting
if timeout_thread is not None:
timeout_stop_event.set()
timeout_thread.join() | python | def main(argv=None):
if argv is None:
argv = sys.argv[1:]
args = parse_global_args(argv)
type_system.interactive = True
line = args.commands
timeout_thread = None
timeout_stop_event = threading.Event()
if args.timeout:
timeout_thread = threading.Thread(target=timeout_thread_handler, args=(args.timeout, timeout_stop_event))
timeout_thread.daemon = True
timeout_thread.start()
shell = HierarchicalShell('iotile')
shell.root_add("registry", "iotile.core.dev.annotated_registry,registry")
shell.root_add("config", "iotile.core.dev.config,ConfigManager")
shell.root_add('hw', "iotile.core.hw.hwmanager,HardwareManager")
reg = ComponentRegistry()
plugins = reg.list_plugins()
for key, val in plugins.items():
shell.root_add(key, val)
finished = False
try:
if len(line) > 0:
finished = shell.invoke(line)
except IOTileException as exc:
print(exc.format())
# if the command passed on the command line fails, then we should
# just exit rather than drop the user into a shell.
SharedLoop.stop()
return 1
except Exception: # pylint:disable=broad-except; We need to make sure we always call cmdstream.do_final_close()
# Catch all exceptions because otherwise we won't properly close cmdstreams
# since the program will be said to except 'abnormally'
traceback.print_exc()
SharedLoop.stop()
return 1
# If the user tells us to never spawn a shell, make sure we don't
# Also, if we finished our command and there is no context, quit now
if args.quit or finished:
SharedLoop.stop()
return 0
setup_completion(shell)
# We ended the initial command with a context, start a shell
try:
while True:
try:
linebuf = input("(%s) " % shell.context_name())
# Skip comments automatically
if len(linebuf) > 0 and linebuf[0] == '#':
continue
except KeyboardInterrupt:
print("")
continue
# Catch exception outside the loop so we stop invoking submethods if a parent
# fails because then the context and results would be unpredictable
try:
finished = shell.invoke_string(linebuf)
except KeyboardInterrupt:
print("")
if timeout_stop_event.is_set():
break
except IOTileException as exc:
print(exc.format())
except Exception: #pylint:disable=broad-except;
# We want to make sure the iotile tool never crashes when in interactive shell mode
traceback.print_exc()
if shell.finished():
break
# Make sure to catch ^C and ^D so that we can cleanly dispose of subprocess resources if
# there are any.
except EOFError:
print("")
except KeyboardInterrupt:
print("")
finally:
# Make sure we close any open CMDStream communication channels so that we don't lockup at exit
SharedLoop.stop()
# Make sure we cleanly join our timeout thread before exiting
if timeout_thread is not None:
timeout_stop_event.set()
timeout_thread.join() | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"args",
"=",
"parse_global_args",
"(",
"argv",
")",
"type_system",
".",
"interactive",
"=",
"True",
"line",
"="... | Run the iotile shell tool.
You can optionally pass the arguments that should be run
in the argv parameter. If nothing is passed, the args
are pulled from sys.argv.
The return value of this function is the return value
of the shell command. | [
"Run",
"the",
"iotile",
"shell",
"tool",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/iotile_script.py#L164-L271 |
23,111 | iotile/coretools | iotilebuild/iotile/build/build/build.py | build | def build(args):
"""
Invoke the scons build system from the current directory, exactly as if
the scons tool had been invoked.
"""
# Do some sleuthing work to find scons if it's not installed into an importable
# place, as it is usually not.
scons_path = "Error"
try:
scons_path = resource_path('scons-local-{}'.format(SCONS_VERSION), expect='folder')
sys.path.insert(0, scons_path)
import SCons.Script
except ImportError:
raise BuildError("Couldn't find internal scons packaged w/ iotile-build. This is a bug that should be reported",
scons_path=scons_path)
site_path = resource_path('site_scons', expect='folder')
all_args = ['iotile', '--site-dir=%s' % site_path, '-Q']
sys.argv = all_args + list(args)
SCons.Script.main() | python | def build(args):
# Do some sleuthing work to find scons if it's not installed into an importable
# place, as it is usually not.
scons_path = "Error"
try:
scons_path = resource_path('scons-local-{}'.format(SCONS_VERSION), expect='folder')
sys.path.insert(0, scons_path)
import SCons.Script
except ImportError:
raise BuildError("Couldn't find internal scons packaged w/ iotile-build. This is a bug that should be reported",
scons_path=scons_path)
site_path = resource_path('site_scons', expect='folder')
all_args = ['iotile', '--site-dir=%s' % site_path, '-Q']
sys.argv = all_args + list(args)
SCons.Script.main() | [
"def",
"build",
"(",
"args",
")",
":",
"# Do some sleuthing work to find scons if it's not installed into an importable",
"# place, as it is usually not.",
"scons_path",
"=",
"\"Error\"",
"try",
":",
"scons_path",
"=",
"resource_path",
"(",
"'scons-local-{}'",
".",
"format",
... | Invoke the scons build system from the current directory, exactly as if
the scons tool had been invoked. | [
"Invoke",
"the",
"scons",
"build",
"system",
"from",
"the",
"current",
"directory",
"exactly",
"as",
"if",
"the",
"scons",
"tool",
"had",
"been",
"invoked",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L26-L47 |
23,112 | iotile/coretools | iotilebuild/iotile/build/build/build.py | TargetSettings.archs | def archs(self, as_list=False):
"""Return all of the architectures for this target.
Args:
as_list (bool): Return a list instead of the default set object.
Returns:
set or list: All of the architectures used in this TargetSettings object.
"""
archs = self.arch_list().split('/')
if as_list:
return archs
return set(archs) | python | def archs(self, as_list=False):
archs = self.arch_list().split('/')
if as_list:
return archs
return set(archs) | [
"def",
"archs",
"(",
"self",
",",
"as_list",
"=",
"False",
")",
":",
"archs",
"=",
"self",
".",
"arch_list",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"as_list",
":",
"return",
"archs",
"return",
"set",
"(",
"archs",
")"
] | Return all of the architectures for this target.
Args:
as_list (bool): Return a list instead of the default set object.
Returns:
set or list: All of the architectures used in this TargetSettings object. | [
"Return",
"all",
"of",
"the",
"architectures",
"for",
"this",
"target",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L92-L107 |
23,113 | iotile/coretools | iotilebuild/iotile/build/build/build.py | TargetSettings.retarget | def retarget(self, remove=[], add=[]):
"""Return a TargetSettings object for the same module but with some of the architectures
removed and others added.
"""
archs = self.arch_list().split('/')
for r in remove:
if r in archs:
archs.remove(r)
archs.extend(add)
archstr = "/".join(archs)
return self.family.find(archstr, self.module_name()) | python | def retarget(self, remove=[], add=[]):
archs = self.arch_list().split('/')
for r in remove:
if r in archs:
archs.remove(r)
archs.extend(add)
archstr = "/".join(archs)
return self.family.find(archstr, self.module_name()) | [
"def",
"retarget",
"(",
"self",
",",
"remove",
"=",
"[",
"]",
",",
"add",
"=",
"[",
"]",
")",
":",
"archs",
"=",
"self",
".",
"arch_list",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"for",
"r",
"in",
"remove",
":",
"if",
"r",
"in",
"archs",
":"... | Return a TargetSettings object for the same module but with some of the architectures
removed and others added. | [
"Return",
"a",
"TargetSettings",
"object",
"for",
"the",
"same",
"module",
"but",
"with",
"some",
"of",
"the",
"architectures",
"removed",
"and",
"others",
"added",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L115-L129 |
23,114 | iotile/coretools | iotilebuild/iotile/build/build/build.py | TargetSettings.property | def property(self, name, default=MISSING):
"""Get the value of the given property for this chip, using the default
value if not found and one is provided. If not found and default is None,
raise an Exception.
"""
if name in self.settings:
return self.settings[name]
if default is not MISSING:
return default
raise ArgumentError("property %s not found for target '%s' and no default given" % (name, self.name)) | python | def property(self, name, default=MISSING):
if name in self.settings:
return self.settings[name]
if default is not MISSING:
return default
raise ArgumentError("property %s not found for target '%s' and no default given" % (name, self.name)) | [
"def",
"property",
"(",
"self",
",",
"name",
",",
"default",
"=",
"MISSING",
")",
":",
"if",
"name",
"in",
"self",
".",
"settings",
":",
"return",
"self",
".",
"settings",
"[",
"name",
"]",
"if",
"default",
"is",
"not",
"MISSING",
":",
"return",
"def... | Get the value of the given property for this chip, using the default
value if not found and one is provided. If not found and default is None,
raise an Exception. | [
"Get",
"the",
"value",
"of",
"the",
"given",
"property",
"for",
"this",
"chip",
"using",
"the",
"default",
"value",
"if",
"not",
"found",
"and",
"one",
"is",
"provided",
".",
"If",
"not",
"found",
"and",
"default",
"is",
"None",
"raise",
"an",
"Exception... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L148-L160 |
23,115 | iotile/coretools | iotilebuild/iotile/build/build/build.py | TargetSettings.combined_properties | def combined_properties(self, suffix):
"""Get the value of all properties whose name ends with suffix and join them
together into a list.
"""
props = [y for x, y in self.settings.items() if x.endswith(suffix)]
properties = itertools.chain(*props)
processed_props = [x for x in properties]
return processed_props | python | def combined_properties(self, suffix):
props = [y for x, y in self.settings.items() if x.endswith(suffix)]
properties = itertools.chain(*props)
processed_props = [x for x in properties]
return processed_props | [
"def",
"combined_properties",
"(",
"self",
",",
"suffix",
")",
":",
"props",
"=",
"[",
"y",
"for",
"x",
",",
"y",
"in",
"self",
".",
"settings",
".",
"items",
"(",
")",
"if",
"x",
".",
"endswith",
"(",
"suffix",
")",
"]",
"properties",
"=",
"iterto... | Get the value of all properties whose name ends with suffix and join them
together into a list. | [
"Get",
"the",
"value",
"of",
"all",
"properties",
"whose",
"name",
"ends",
"with",
"suffix",
"and",
"join",
"them",
"together",
"into",
"a",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L162-L171 |
23,116 | iotile/coretools | iotilebuild/iotile/build/build/build.py | TargetSettings.includes | def includes(self):
"""Return all of the include directories for this chip as a list."""
incs = self.combined_properties('includes')
processed_incs = []
for prop in incs:
if isinstance(prop, str):
processed_incs.append(prop)
else:
processed_incs.append(os.path.join(*prop))
# All include paths are relative to base directory of the
fullpaths = [os.path.normpath(os.path.join('.', x)) for x in processed_incs]
fullpaths.append(os.path.normpath(os.path.abspath(self.build_dirs()['build'])))
return fullpaths | python | def includes(self):
incs = self.combined_properties('includes')
processed_incs = []
for prop in incs:
if isinstance(prop, str):
processed_incs.append(prop)
else:
processed_incs.append(os.path.join(*prop))
# All include paths are relative to base directory of the
fullpaths = [os.path.normpath(os.path.join('.', x)) for x in processed_incs]
fullpaths.append(os.path.normpath(os.path.abspath(self.build_dirs()['build'])))
return fullpaths | [
"def",
"includes",
"(",
"self",
")",
":",
"incs",
"=",
"self",
".",
"combined_properties",
"(",
"'includes'",
")",
"processed_incs",
"=",
"[",
"]",
"for",
"prop",
"in",
"incs",
":",
"if",
"isinstance",
"(",
"prop",
",",
"str",
")",
":",
"processed_incs",... | Return all of the include directories for this chip as a list. | [
"Return",
"all",
"of",
"the",
"include",
"directories",
"for",
"this",
"chip",
"as",
"a",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L173-L189 |
23,117 | iotile/coretools | iotilebuild/iotile/build/build/build.py | TargetSettings.arch_prefixes | def arch_prefixes(self):
"""Return the initial 1, 2, ..., N architectures as a prefix list
For arch1/arch2/arch3, this returns
[arch1],[arch1/arch2],[arch1/arch2/arch3]
"""
archs = self.archs(as_list=True)
prefixes = []
for i in range(1, len(archs)+1):
prefixes.append(archs[:i])
return prefixes | python | def arch_prefixes(self):
archs = self.archs(as_list=True)
prefixes = []
for i in range(1, len(archs)+1):
prefixes.append(archs[:i])
return prefixes | [
"def",
"arch_prefixes",
"(",
"self",
")",
":",
"archs",
"=",
"self",
".",
"archs",
"(",
"as_list",
"=",
"True",
")",
"prefixes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"archs",
")",
"+",
"1",
")",
":",
"prefixes",
... | Return the initial 1, 2, ..., N architectures as a prefix list
For arch1/arch2/arch3, this returns
[arch1],[arch1/arch2],[arch1/arch2/arch3] | [
"Return",
"the",
"initial",
"1",
"2",
"...",
"N",
"architectures",
"as",
"a",
"prefix",
"list"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L199-L212 |
23,118 | iotile/coretools | iotilebuild/iotile/build/build/build.py | ArchitectureGroup.targets | def targets(self, module):
"""Find the targets for a given module.
Returns:
list: A sequence of all of the targets for the specified module.
"""
if module not in self.module_targets:
raise BuildError("Could not find module in targets()", module=module)
return [self.find(x, module) for x in self.module_targets[module]] | python | def targets(self, module):
if module not in self.module_targets:
raise BuildError("Could not find module in targets()", module=module)
return [self.find(x, module) for x in self.module_targets[module]] | [
"def",
"targets",
"(",
"self",
",",
"module",
")",
":",
"if",
"module",
"not",
"in",
"self",
".",
"module_targets",
":",
"raise",
"BuildError",
"(",
"\"Could not find module in targets()\"",
",",
"module",
"=",
"module",
")",
"return",
"[",
"self",
".",
"fin... | Find the targets for a given module.
Returns:
list: A sequence of all of the targets for the specified module. | [
"Find",
"the",
"targets",
"for",
"a",
"given",
"module",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L283-L293 |
23,119 | iotile/coretools | iotilebuild/iotile/build/build/build.py | ArchitectureGroup.for_all_targets | def for_all_targets(self, module, func, filter_func=None):
"""Call func once for all of the targets of this module."""
for target in self.targets(module):
if filter_func is None or filter_func(target):
func(target) | python | def for_all_targets(self, module, func, filter_func=None):
for target in self.targets(module):
if filter_func is None or filter_func(target):
func(target) | [
"def",
"for_all_targets",
"(",
"self",
",",
"module",
",",
"func",
",",
"filter_func",
"=",
"None",
")",
":",
"for",
"target",
"in",
"self",
".",
"targets",
"(",
"module",
")",
":",
"if",
"filter_func",
"is",
"None",
"or",
"filter_func",
"(",
"target",
... | Call func once for all of the targets of this module. | [
"Call",
"func",
"once",
"for",
"all",
"of",
"the",
"targets",
"of",
"this",
"module",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L304-L309 |
23,120 | iotile/coretools | iotilebuild/iotile/build/build/build.py | ArchitectureGroup.validate_target | def validate_target(self, target):
"""Make sure that the specified target only contains architectures that we know about."""
archs = target.split('/')
for arch in archs:
if not arch in self.archs:
return False
return True | python | def validate_target(self, target):
archs = target.split('/')
for arch in archs:
if not arch in self.archs:
return False
return True | [
"def",
"validate_target",
"(",
"self",
",",
"target",
")",
":",
"archs",
"=",
"target",
".",
"split",
"(",
"'/'",
")",
"for",
"arch",
"in",
"archs",
":",
"if",
"not",
"arch",
"in",
"self",
".",
"archs",
":",
"return",
"False",
"return",
"True"
] | Make sure that the specified target only contains architectures that we know about. | [
"Make",
"sure",
"that",
"the",
"specified",
"target",
"only",
"contains",
"architectures",
"that",
"we",
"know",
"about",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L311-L320 |
23,121 | iotile/coretools | iotilebuild/iotile/build/build/build.py | ArchitectureGroup._load_architectures | def _load_architectures(self, family):
"""Load in all of the architectural overlays for this family. An architecture adds configuration
information that is used to build a common set of source code for a particular hardware and situation.
They are stackable so that you can specify a chip and a configuration for that chip, for example.
"""
if "architectures" not in family:
raise InternalError("required architectures key not in build_settings.json for desired family")
for key, val in family['architectures'].items():
if not isinstance(val, dict):
raise InternalError("All entries under chip_settings must be dictionaries")
self.archs[key] = deepcopy(val) | python | def _load_architectures(self, family):
if "architectures" not in family:
raise InternalError("required architectures key not in build_settings.json for desired family")
for key, val in family['architectures'].items():
if not isinstance(val, dict):
raise InternalError("All entries under chip_settings must be dictionaries")
self.archs[key] = deepcopy(val) | [
"def",
"_load_architectures",
"(",
"self",
",",
"family",
")",
":",
"if",
"\"architectures\"",
"not",
"in",
"family",
":",
"raise",
"InternalError",
"(",
"\"required architectures key not in build_settings.json for desired family\"",
")",
"for",
"key",
",",
"val",
"in",... | Load in all of the architectural overlays for this family. An architecture adds configuration
information that is used to build a common set of source code for a particular hardware and situation.
They are stackable so that you can specify a chip and a configuration for that chip, for example. | [
"Load",
"in",
"all",
"of",
"the",
"architectural",
"overlays",
"for",
"this",
"family",
".",
"An",
"architecture",
"adds",
"configuration",
"information",
"that",
"is",
"used",
"to",
"build",
"a",
"common",
"set",
"of",
"source",
"code",
"for",
"a",
"particu... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L380-L393 |
23,122 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/lex.py | generate | def generate(env):
"""Add Builders and construction variables for lex to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
# C
c_file.add_action(".l", LexAction)
c_file.add_emitter(".l", lexEmitter)
c_file.add_action(".lex", LexAction)
c_file.add_emitter(".lex", lexEmitter)
# Objective-C
cxx_file.add_action(".lm", LexAction)
cxx_file.add_emitter(".lm", lexEmitter)
# C++
cxx_file.add_action(".ll", LexAction)
cxx_file.add_emitter(".ll", lexEmitter)
env["LEX"] = env.Detect("flex") or "lex"
env["LEXFLAGS"] = SCons.Util.CLVar("")
env["LEXCOM"] = "$LEX $LEXFLAGS -t $SOURCES > $TARGET" | python | def generate(env):
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
# C
c_file.add_action(".l", LexAction)
c_file.add_emitter(".l", lexEmitter)
c_file.add_action(".lex", LexAction)
c_file.add_emitter(".lex", lexEmitter)
# Objective-C
cxx_file.add_action(".lm", LexAction)
cxx_file.add_emitter(".lm", lexEmitter)
# C++
cxx_file.add_action(".ll", LexAction)
cxx_file.add_emitter(".ll", lexEmitter)
env["LEX"] = env.Detect("flex") or "lex"
env["LEXFLAGS"] = SCons.Util.CLVar("")
env["LEXCOM"] = "$LEX $LEXFLAGS -t $SOURCES > $TARGET" | [
"def",
"generate",
"(",
"env",
")",
":",
"c_file",
",",
"cxx_file",
"=",
"SCons",
".",
"Tool",
".",
"createCFileBuilders",
"(",
"env",
")",
"# C",
"c_file",
".",
"add_action",
"(",
"\".l\"",
",",
"LexAction",
")",
"c_file",
".",
"add_emitter",
"(",
"\".l... | Add Builders and construction variables for lex to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"lex",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/lex.py#L67-L88 |
23,123 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerSubsystem.handle_tick | def handle_tick(self):
"""Internal callback every time 1 second has passed."""
self.uptime += 1
for name, interval in self.ticks.items():
if interval == 0:
continue
self.tick_counters[name] += 1
if self.tick_counters[name] == interval:
self.graph_input(self.TICK_STREAMS[name], self.uptime)
self.tick_counters[name] = 0 | python | def handle_tick(self):
self.uptime += 1
for name, interval in self.ticks.items():
if interval == 0:
continue
self.tick_counters[name] += 1
if self.tick_counters[name] == interval:
self.graph_input(self.TICK_STREAMS[name], self.uptime)
self.tick_counters[name] = 0 | [
"def",
"handle_tick",
"(",
"self",
")",
":",
"self",
".",
"uptime",
"+=",
"1",
"for",
"name",
",",
"interval",
"in",
"self",
".",
"ticks",
".",
"items",
"(",
")",
":",
"if",
"interval",
"==",
"0",
":",
"continue",
"self",
".",
"tick_counters",
"[",
... | Internal callback every time 1 second has passed. | [
"Internal",
"callback",
"every",
"time",
"1",
"second",
"has",
"passed",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L143-L155 |
23,124 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerSubsystem.set_tick | def set_tick(self, index, interval):
"""Update the a tick's interval.
Args:
index (int): The index of the tick that you want to fetch.
interval (int): The number of seconds between ticks.
Setting this to 0 will disable the tick.
Returns:
int: An error code.
"""
name = self.tick_name(index)
if name is None:
return pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY)
self.ticks[name] = interval
return Error.NO_ERROR | python | def set_tick(self, index, interval):
name = self.tick_name(index)
if name is None:
return pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY)
self.ticks[name] = interval
return Error.NO_ERROR | [
"def",
"set_tick",
"(",
"self",
",",
"index",
",",
"interval",
")",
":",
"name",
"=",
"self",
".",
"tick_name",
"(",
"index",
")",
"if",
"name",
"is",
"None",
":",
"return",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_GRAPH",
",",
"Error",
"."... | Update the a tick's interval.
Args:
index (int): The index of the tick that you want to fetch.
interval (int): The number of seconds between ticks.
Setting this to 0 will disable the tick.
Returns:
int: An error code. | [
"Update",
"the",
"a",
"tick",
"s",
"interval",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L157-L174 |
23,125 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerSubsystem.get_tick | def get_tick(self, index):
"""Get a tick's interval.
Args:
index (int): The index of the tick that you want to fetch.
Returns:
int, int: Error code and The tick's interval in seconds.
A value of 0 means that the tick is disabled.
"""
name = self.tick_name(index)
if name is None:
return [pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY), 0]
return [Error.NO_ERROR, self.ticks[name]] | python | def get_tick(self, index):
name = self.tick_name(index)
if name is None:
return [pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY), 0]
return [Error.NO_ERROR, self.ticks[name]] | [
"def",
"get_tick",
"(",
"self",
",",
"index",
")",
":",
"name",
"=",
"self",
".",
"tick_name",
"(",
"index",
")",
"if",
"name",
"is",
"None",
":",
"return",
"[",
"pack_error",
"(",
"ControllerSubsystem",
".",
"SENSOR_GRAPH",
",",
"Error",
".",
"INVALID_A... | Get a tick's interval.
Args:
index (int): The index of the tick that you want to fetch.
Returns:
int, int: Error code and The tick's interval in seconds.
A value of 0 means that the tick is disabled. | [
"Get",
"a",
"tick",
"s",
"interval",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L176-L192 |
23,126 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerSubsystem.get_time | def get_time(self, force_uptime=False):
"""Get the current UTC time or uptime.
By default, this method will return UTC time if possible and fall back
to uptime if not. If you specify, force_uptime=True, it will always
return uptime even if utc time is available.
Args:
force_uptime (bool): Always return uptime, defaults to False.
Returns:
int: The current uptime or encoded utc time.
"""
if force_uptime:
return self.uptime
time = self.uptime + self.time_offset
if self.is_utc:
time |= (1 << 31)
return time | python | def get_time(self, force_uptime=False):
if force_uptime:
return self.uptime
time = self.uptime + self.time_offset
if self.is_utc:
time |= (1 << 31)
return time | [
"def",
"get_time",
"(",
"self",
",",
"force_uptime",
"=",
"False",
")",
":",
"if",
"force_uptime",
":",
"return",
"self",
".",
"uptime",
"time",
"=",
"self",
".",
"uptime",
"+",
"self",
".",
"time_offset",
"if",
"self",
".",
"is_utc",
":",
"time",
"|="... | Get the current UTC time or uptime.
By default, this method will return UTC time if possible and fall back
to uptime if not. If you specify, force_uptime=True, it will always
return uptime even if utc time is available.
Args:
force_uptime (bool): Always return uptime, defaults to False.
Returns:
int: The current uptime or encoded utc time. | [
"Get",
"the",
"current",
"UTC",
"time",
"or",
"uptime",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L194-L216 |
23,127 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerSubsystem.synchronize_clock | def synchronize_clock(self, offset):
"""Persistently synchronize the clock to UTC time.
Args:
offset (int): The number of seconds since 1/1/2000 00:00Z
"""
self.time_offset = offset - self.uptime
self.is_utc = True
if self.has_rtc:
self.stored_offset = self.time_offset | python | def synchronize_clock(self, offset):
self.time_offset = offset - self.uptime
self.is_utc = True
if self.has_rtc:
self.stored_offset = self.time_offset | [
"def",
"synchronize_clock",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"time_offset",
"=",
"offset",
"-",
"self",
".",
"uptime",
"self",
".",
"is_utc",
"=",
"True",
"if",
"self",
".",
"has_rtc",
":",
"self",
".",
"stored_offset",
"=",
"self",
"... | Persistently synchronize the clock to UTC time.
Args:
offset (int): The number of seconds since 1/1/2000 00:00Z | [
"Persistently",
"synchronize",
"the",
"clock",
"to",
"UTC",
"time",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L218-L229 |
23,128 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerMixin.get_user_timer | def get_user_timer(self, index):
"""Get the current value of a user timer."""
err, tick = self.clock_manager.get_tick(index)
return [err, tick] | python | def get_user_timer(self, index):
err, tick = self.clock_manager.get_tick(index)
return [err, tick] | [
"def",
"get_user_timer",
"(",
"self",
",",
"index",
")",
":",
"err",
",",
"tick",
"=",
"self",
".",
"clock_manager",
".",
"get_tick",
"(",
"index",
")",
"return",
"[",
"err",
",",
"tick",
"]"
] | Get the current value of a user timer. | [
"Get",
"the",
"current",
"value",
"of",
"a",
"user",
"timer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L245-L249 |
23,129 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerMixin.set_user_timer | def set_user_timer(self, value, index):
"""Set the current value of a user timer."""
err = self.clock_manager.set_tick(index, value)
return [err] | python | def set_user_timer(self, value, index):
err = self.clock_manager.set_tick(index, value)
return [err] | [
"def",
"set_user_timer",
"(",
"self",
",",
"value",
",",
"index",
")",
":",
"err",
"=",
"self",
".",
"clock_manager",
".",
"set_tick",
"(",
"index",
",",
"value",
")",
"return",
"[",
"err",
"]"
] | Set the current value of a user timer. | [
"Set",
"the",
"current",
"value",
"of",
"a",
"user",
"timer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L252-L256 |
23,130 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | ClockManagerMixin.set_time_offset | def set_time_offset(self, offset, is_utc):
"""Temporarily set the current time offset."""
is_utc = bool(is_utc)
self.clock_manager.time_offset = offset
self.clock_manager.is_utc = is_utc
return [Error.NO_ERROR] | python | def set_time_offset(self, offset, is_utc):
is_utc = bool(is_utc)
self.clock_manager.time_offset = offset
self.clock_manager.is_utc = is_utc
return [Error.NO_ERROR] | [
"def",
"set_time_offset",
"(",
"self",
",",
"offset",
",",
"is_utc",
")",
":",
"is_utc",
"=",
"bool",
"(",
"is_utc",
")",
"self",
".",
"clock_manager",
".",
"time_offset",
"=",
"offset",
"self",
".",
"clock_manager",
".",
"is_utc",
"=",
"is_utc",
"return",... | Temporarily set the current time offset. | [
"Temporarily",
"set",
"the",
"current",
"time",
"offset",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L281-L288 |
23,131 | iotile/coretools | iotile_ext_cloud/iotile/cloud/utilities.py | device_id_to_slug | def device_id_to_slug(did):
""" Converts a device id into a correct device slug.
Args:
did (long) : A device id
did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX
Returns:
str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format
Raises:
ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string
"""
try:
device_slug = IOTileDeviceSlug(did, allow_64bits=False)
except ValueError:
raise ArgumentError("Unable to recognize {} as a device id".format(did))
return str(device_slug) | python | def device_id_to_slug(did):
try:
device_slug = IOTileDeviceSlug(did, allow_64bits=False)
except ValueError:
raise ArgumentError("Unable to recognize {} as a device id".format(did))
return str(device_slug) | [
"def",
"device_id_to_slug",
"(",
"did",
")",
":",
"try",
":",
"device_slug",
"=",
"IOTileDeviceSlug",
"(",
"did",
",",
"allow_64bits",
"=",
"False",
")",
"except",
"ValueError",
":",
"raise",
"ArgumentError",
"(",
"\"Unable to recognize {} as a device id\"",
".",
... | Converts a device id into a correct device slug.
Args:
did (long) : A device id
did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX
Returns:
str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format
Raises:
ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string | [
"Converts",
"a",
"device",
"id",
"into",
"a",
"correct",
"device",
"slug",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotile_ext_cloud/iotile/cloud/utilities.py#L31-L48 |
23,132 | iotile/coretools | iotile_ext_cloud/iotile/cloud/utilities.py | fleet_id_to_slug | def fleet_id_to_slug(did):
""" Converts a fleet id into a correct fleet slug.
Args:
did (long) : A fleet id
did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, g--XXXX, g--XXXX-XXXX-XXXX
Returns:
str: The device slug in the g--XXXX-XXXX-XXX format
Raises:
ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string
"""
try:
fleet_slug = IOTileFleetSlug(did)
except ValueError:
raise ArgumentError("Unable to recognize {} as a fleet id".format(did))
return str(fleet_slug) | python | def fleet_id_to_slug(did):
try:
fleet_slug = IOTileFleetSlug(did)
except ValueError:
raise ArgumentError("Unable to recognize {} as a fleet id".format(did))
return str(fleet_slug) | [
"def",
"fleet_id_to_slug",
"(",
"did",
")",
":",
"try",
":",
"fleet_slug",
"=",
"IOTileFleetSlug",
"(",
"did",
")",
"except",
"ValueError",
":",
"raise",
"ArgumentError",
"(",
"\"Unable to recognize {} as a fleet id\"",
".",
"format",
"(",
"did",
")",
")",
"retu... | Converts a fleet id into a correct fleet slug.
Args:
did (long) : A fleet id
did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, g--XXXX, g--XXXX-XXXX-XXXX
Returns:
str: The device slug in the g--XXXX-XXXX-XXX format
Raises:
ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string | [
"Converts",
"a",
"fleet",
"id",
"into",
"a",
"correct",
"fleet",
"slug",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotile_ext_cloud/iotile/cloud/utilities.py#L51-L68 |
23,133 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/win32.py | get_architecture | def get_architecture(arch=None):
"""Returns the definition for the specified architecture string.
If no string is specified, the system default is returned (as defined
by the PROCESSOR_ARCHITEW6432 or PROCESSOR_ARCHITECTURE environment
variables).
"""
if arch is None:
arch = os.environ.get('PROCESSOR_ARCHITEW6432')
if not arch:
arch = os.environ.get('PROCESSOR_ARCHITECTURE')
return SupportedArchitectureMap.get(arch, ArchDefinition('', [''])) | python | def get_architecture(arch=None):
if arch is None:
arch = os.environ.get('PROCESSOR_ARCHITEW6432')
if not arch:
arch = os.environ.get('PROCESSOR_ARCHITECTURE')
return SupportedArchitectureMap.get(arch, ArchDefinition('', [''])) | [
"def",
"get_architecture",
"(",
"arch",
"=",
"None",
")",
":",
"if",
"arch",
"is",
"None",
":",
"arch",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PROCESSOR_ARCHITEW6432'",
")",
"if",
"not",
"arch",
":",
"arch",
"=",
"os",
".",
"environ",
".",
"ge... | Returns the definition for the specified architecture string.
If no string is specified, the system default is returned (as defined
by the PROCESSOR_ARCHITEW6432 or PROCESSOR_ARCHITECTURE environment
variables). | [
"Returns",
"the",
"definition",
"for",
"the",
"specified",
"architecture",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/win32.py#L358-L369 |
23,134 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rpm.py | generate | def generate(env):
"""Add Builders and construction variables for rpm to an Environment."""
try:
bld = env['BUILDERS']['Rpm']
except KeyError:
bld = RpmBuilder
env['BUILDERS']['Rpm'] = bld
env.SetDefault(RPM = 'LC_ALL=C rpmbuild')
env.SetDefault(RPMFLAGS = SCons.Util.CLVar('-ta'))
env.SetDefault(RPMCOM = rpmAction)
env.SetDefault(RPMSUFFIX = '.rpm') | python | def generate(env):
try:
bld = env['BUILDERS']['Rpm']
except KeyError:
bld = RpmBuilder
env['BUILDERS']['Rpm'] = bld
env.SetDefault(RPM = 'LC_ALL=C rpmbuild')
env.SetDefault(RPMFLAGS = SCons.Util.CLVar('-ta'))
env.SetDefault(RPMCOM = rpmAction)
env.SetDefault(RPMSUFFIX = '.rpm') | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Rpm'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"RpmBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Rpm'",
"]",
"=",
"bld",
"env",
".",
"SetDe... | Add Builders and construction variables for rpm to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"rpm",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/rpm.py#L112-L123 |
23,135 | iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/topic_sequencer.py | TopicSequencer.next_id | def next_id(self, channel):
"""Get the next sequence number for a named channel or topic
If channel has not been sent to next_id before, 0 is returned
otherwise next_id returns the last id returned + 1.
Args:
channel (string): The name of the channel to get a sequential
id for.
Returns:
int: The next id for this channel
"""
if channel not in self.topics:
self.topics[channel] = 0
return 0
self.topics[channel] += 1
return self.topics[channel] | python | def next_id(self, channel):
if channel not in self.topics:
self.topics[channel] = 0
return 0
self.topics[channel] += 1
return self.topics[channel] | [
"def",
"next_id",
"(",
"self",
",",
"channel",
")",
":",
"if",
"channel",
"not",
"in",
"self",
".",
"topics",
":",
"self",
".",
"topics",
"[",
"channel",
"]",
"=",
"0",
"return",
"0",
"self",
".",
"topics",
"[",
"channel",
"]",
"+=",
"1",
"return",... | Get the next sequence number for a named channel or topic
If channel has not been sent to next_id before, 0 is returned
otherwise next_id returns the last id returned + 1.
Args:
channel (string): The name of the channel to get a sequential
id for.
Returns:
int: The next id for this channel | [
"Get",
"the",
"next",
"sequence",
"number",
"for",
"a",
"named",
"channel",
"or",
"topic"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/topic_sequencer.py#L16-L35 |
23,136 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/posix.py | escape | def escape(arg):
"escape shell special characters"
slash = '\\'
special = '"$'
arg = arg.replace(slash, slash+slash)
for c in special:
arg = arg.replace(c, slash+c)
# print("ESCAPE RESULT: %s" % arg)
return '"' + arg + '"' | python | def escape(arg):
"escape shell special characters"
slash = '\\'
special = '"$'
arg = arg.replace(slash, slash+slash)
for c in special:
arg = arg.replace(c, slash+c)
# print("ESCAPE RESULT: %s" % arg)
return '"' + arg + '"' | [
"def",
"escape",
"(",
"arg",
")",
":",
"slash",
"=",
"'\\\\'",
"special",
"=",
"'\"$'",
"arg",
"=",
"arg",
".",
"replace",
"(",
"slash",
",",
"slash",
"+",
"slash",
")",
"for",
"c",
"in",
"special",
":",
"arg",
"=",
"arg",
".",
"replace",
"(",
"c... | escape shell special characters | [
"escape",
"shell",
"special",
"characters"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/posix.py#L50-L60 |
23,137 | iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/stream_manager.py | BasicStreamingSubsystem.process_streamer | def process_streamer(self, streamer, callback=None):
"""Start streaming a streamer.
Args:
streamer (DataStreamer): The streamer itself.
callback (callable): An optional callable that will be called as:
callable(index, success, highest_id_received_from_other_side)
"""
index = streamer.index
if index in self._in_progress_streamers:
raise InternalError("You cannot add a streamer again until it has finished streaming.")
queue_item = QueuedStreamer(streamer, callback)
self._in_progress_streamers.add(index)
self._logger.debug("Streamer %d: queued to send %d readings", index, queue_item.initial_count)
self._queue.put_nowait(queue_item) | python | def process_streamer(self, streamer, callback=None):
index = streamer.index
if index in self._in_progress_streamers:
raise InternalError("You cannot add a streamer again until it has finished streaming.")
queue_item = QueuedStreamer(streamer, callback)
self._in_progress_streamers.add(index)
self._logger.debug("Streamer %d: queued to send %d readings", index, queue_item.initial_count)
self._queue.put_nowait(queue_item) | [
"def",
"process_streamer",
"(",
"self",
",",
"streamer",
",",
"callback",
"=",
"None",
")",
":",
"index",
"=",
"streamer",
".",
"index",
"if",
"index",
"in",
"self",
".",
"_in_progress_streamers",
":",
"raise",
"InternalError",
"(",
"\"You cannot add a streamer ... | Start streaming a streamer.
Args:
streamer (DataStreamer): The streamer itself.
callback (callable): An optional callable that will be called as:
callable(index, success, highest_id_received_from_other_side) | [
"Start",
"streaming",
"a",
"streamer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/stream_manager.py#L107-L125 |
23,138 | iotile/coretools | iotilecore/iotile/core/hw/virtual/common_types.py | pack_rpc_response | def pack_rpc_response(response=None, exception=None):
"""Convert a response payload or exception to a status code and payload.
This function will convert an Exception raised by an RPC implementation
to the corresponding status code.
"""
if response is None:
response = bytes()
if exception is None:
status = (1 << 6)
if len(response) > 0:
status |= (1 << 7)
elif isinstance(exception, (RPCInvalidIDError, RPCNotFoundError)):
status = 2
elif isinstance(exception, BusyRPCResponse):
status = 0
elif isinstance(exception, TileNotFoundError):
status = 0xFF
elif isinstance(exception, RPCErrorCode):
status = (1 << 6) | (exception.params['code'] & ((1 << 6) - 1))
else:
status = 3
return status, response | python | def pack_rpc_response(response=None, exception=None):
if response is None:
response = bytes()
if exception is None:
status = (1 << 6)
if len(response) > 0:
status |= (1 << 7)
elif isinstance(exception, (RPCInvalidIDError, RPCNotFoundError)):
status = 2
elif isinstance(exception, BusyRPCResponse):
status = 0
elif isinstance(exception, TileNotFoundError):
status = 0xFF
elif isinstance(exception, RPCErrorCode):
status = (1 << 6) | (exception.params['code'] & ((1 << 6) - 1))
else:
status = 3
return status, response | [
"def",
"pack_rpc_response",
"(",
"response",
"=",
"None",
",",
"exception",
"=",
"None",
")",
":",
"if",
"response",
"is",
"None",
":",
"response",
"=",
"bytes",
"(",
")",
"if",
"exception",
"is",
"None",
":",
"status",
"=",
"(",
"1",
"<<",
"6",
")",... | Convert a response payload or exception to a status code and payload.
This function will convert an Exception raised by an RPC implementation
to the corresponding status code. | [
"Convert",
"a",
"response",
"payload",
"or",
"exception",
"to",
"a",
"status",
"code",
"and",
"payload",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/common_types.py#L45-L70 |
23,139 | iotile/coretools | iotilecore/iotile/core/hw/virtual/common_types.py | unpack_rpc_response | def unpack_rpc_response(status, response=None, rpc_id=0, address=0):
"""Unpack an RPC status back in to payload or exception."""
status_code = status & ((1 << 6) - 1)
if address == 8:
status_code &= ~(1 << 7)
if status == 0:
raise BusyRPCResponse()
elif status == 2:
raise RPCNotFoundError("rpc %d:%04X not found" % (address, rpc_id))
elif status == 3:
raise RPCErrorCode(status_code)
elif status == 0xFF:
raise TileNotFoundError("tile %d not found" % address)
elif status_code != 0:
raise RPCErrorCode(status_code)
if response is None:
response = b''
return response | python | def unpack_rpc_response(status, response=None, rpc_id=0, address=0):
status_code = status & ((1 << 6) - 1)
if address == 8:
status_code &= ~(1 << 7)
if status == 0:
raise BusyRPCResponse()
elif status == 2:
raise RPCNotFoundError("rpc %d:%04X not found" % (address, rpc_id))
elif status == 3:
raise RPCErrorCode(status_code)
elif status == 0xFF:
raise TileNotFoundError("tile %d not found" % address)
elif status_code != 0:
raise RPCErrorCode(status_code)
if response is None:
response = b''
return response | [
"def",
"unpack_rpc_response",
"(",
"status",
",",
"response",
"=",
"None",
",",
"rpc_id",
"=",
"0",
",",
"address",
"=",
"0",
")",
":",
"status_code",
"=",
"status",
"&",
"(",
"(",
"1",
"<<",
"6",
")",
"-",
"1",
")",
"if",
"address",
"==",
"8",
"... | Unpack an RPC status back in to payload or exception. | [
"Unpack",
"an",
"RPC",
"status",
"back",
"in",
"to",
"payload",
"or",
"exception",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/common_types.py#L73-L95 |
23,140 | iotile/coretools | iotilecore/iotile/core/hw/virtual/common_types.py | pack_rpc_payload | def pack_rpc_payload(arg_format, args):
"""Pack an RPC payload according to arg_format.
Args:
arg_format (str): a struct format code (without the <) for the
parameter format for this RPC. This format code may include the final
character V, which means that it expects a variable length bytearray.
args (list): A list of arguments to pack according to arg_format.
Returns:
bytes: The packed argument buffer.
"""
code = _create_respcode(arg_format, args)
packed_result = struct.pack(code, *args)
unpacked_validation = struct.unpack(code, packed_result)
if tuple(args) != unpacked_validation:
raise RPCInvalidArgumentsError("Passed values would be truncated, please validate the size of your string",
code=code, args=args)
return packed_result | python | def pack_rpc_payload(arg_format, args):
code = _create_respcode(arg_format, args)
packed_result = struct.pack(code, *args)
unpacked_validation = struct.unpack(code, packed_result)
if tuple(args) != unpacked_validation:
raise RPCInvalidArgumentsError("Passed values would be truncated, please validate the size of your string",
code=code, args=args)
return packed_result | [
"def",
"pack_rpc_payload",
"(",
"arg_format",
",",
"args",
")",
":",
"code",
"=",
"_create_respcode",
"(",
"arg_format",
",",
"args",
")",
"packed_result",
"=",
"struct",
".",
"pack",
"(",
"code",
",",
"*",
"args",
")",
"unpacked_validation",
"=",
"struct",
... | Pack an RPC payload according to arg_format.
Args:
arg_format (str): a struct format code (without the <) for the
parameter format for this RPC. This format code may include the final
character V, which means that it expects a variable length bytearray.
args (list): A list of arguments to pack according to arg_format.
Returns:
bytes: The packed argument buffer. | [
"Pack",
"an",
"RPC",
"payload",
"according",
"to",
"arg_format",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/common_types.py#L98-L118 |
23,141 | iotile/coretools | iotilecore/iotile/core/hw/virtual/common_types.py | unpack_rpc_payload | def unpack_rpc_payload(resp_format, payload):
"""Unpack an RPC payload according to resp_format.
Args:
resp_format (str): a struct format code (without the <) for the
parameter format for this RPC. This format code may include the final
character V, which means that it expects a variable length bytearray.
payload (bytes): The binary payload that should be unpacked.
Returns:
list: A list of the unpacked payload items.
"""
code = _create_argcode(resp_format, payload)
return struct.unpack(code, payload) | python | def unpack_rpc_payload(resp_format, payload):
code = _create_argcode(resp_format, payload)
return struct.unpack(code, payload) | [
"def",
"unpack_rpc_payload",
"(",
"resp_format",
",",
"payload",
")",
":",
"code",
"=",
"_create_argcode",
"(",
"resp_format",
",",
"payload",
")",
"return",
"struct",
".",
"unpack",
"(",
"code",
",",
"payload",
")"
] | Unpack an RPC payload according to resp_format.
Args:
resp_format (str): a struct format code (without the <) for the
parameter format for this RPC. This format code may include the final
character V, which means that it expects a variable length bytearray.
payload (bytes): The binary payload that should be unpacked.
Returns:
list: A list of the unpacked payload items. | [
"Unpack",
"an",
"RPC",
"payload",
"according",
"to",
"resp_format",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/common_types.py#L121-L135 |
23,142 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | isfortran | def isfortran(env, source):
"""Return 1 if any of code in source has fortran files in it, 0
otherwise."""
try:
fsuffixes = env['FORTRANSUFFIXES']
except KeyError:
# If no FORTRANSUFFIXES, no fortran tool, so there is no need to look
# for fortran sources.
return 0
if not source:
# Source might be None for unusual cases like SConf.
return 0
for s in source:
if s.sources:
ext = os.path.splitext(str(s.sources[0]))[1]
if ext in fsuffixes:
return 1
return 0 | python | def isfortran(env, source):
try:
fsuffixes = env['FORTRANSUFFIXES']
except KeyError:
# If no FORTRANSUFFIXES, no fortran tool, so there is no need to look
# for fortran sources.
return 0
if not source:
# Source might be None for unusual cases like SConf.
return 0
for s in source:
if s.sources:
ext = os.path.splitext(str(s.sources[0]))[1]
if ext in fsuffixes:
return 1
return 0 | [
"def",
"isfortran",
"(",
"env",
",",
"source",
")",
":",
"try",
":",
"fsuffixes",
"=",
"env",
"[",
"'FORTRANSUFFIXES'",
"]",
"except",
"KeyError",
":",
"# If no FORTRANSUFFIXES, no fortran tool, so there is no need to look",
"# for fortran sources.",
"return",
"0",
"if"... | Return 1 if any of code in source has fortran files in it, 0
otherwise. | [
"Return",
"1",
"if",
"any",
"of",
"code",
"in",
"source",
"has",
"fortran",
"files",
"in",
"it",
"0",
"otherwise",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L41-L59 |
23,143 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | ComputeFortranSuffixes | def ComputeFortranSuffixes(suffixes, ppsuffixes):
"""suffixes are fortran source files, and ppsuffixes the ones to be
pre-processed. Both should be sequences, not strings."""
assert len(suffixes) > 0
s = suffixes[0]
sup = s.upper()
upper_suffixes = [_.upper() for _ in suffixes]
if SCons.Util.case_sensitive_suffixes(s, sup):
ppsuffixes.extend(upper_suffixes)
else:
suffixes.extend(upper_suffixes) | python | def ComputeFortranSuffixes(suffixes, ppsuffixes):
assert len(suffixes) > 0
s = suffixes[0]
sup = s.upper()
upper_suffixes = [_.upper() for _ in suffixes]
if SCons.Util.case_sensitive_suffixes(s, sup):
ppsuffixes.extend(upper_suffixes)
else:
suffixes.extend(upper_suffixes) | [
"def",
"ComputeFortranSuffixes",
"(",
"suffixes",
",",
"ppsuffixes",
")",
":",
"assert",
"len",
"(",
"suffixes",
")",
">",
"0",
"s",
"=",
"suffixes",
"[",
"0",
"]",
"sup",
"=",
"s",
".",
"upper",
"(",
")",
"upper_suffixes",
"=",
"[",
"_",
".",
"upper... | suffixes are fortran source files, and ppsuffixes the ones to be
pre-processed. Both should be sequences, not strings. | [
"suffixes",
"are",
"fortran",
"source",
"files",
"and",
"ppsuffixes",
"the",
"ones",
"to",
"be",
"pre",
"-",
"processed",
".",
"Both",
"should",
"be",
"sequences",
"not",
"strings",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L88-L98 |
23,144 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | CreateDialectActions | def CreateDialectActions(dialect):
"""Create dialect specific actions."""
CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect)
CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect)
ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR' % dialect)
ShCompPPAction = SCons.Action.Action('$SH%sPPCOM ' % dialect, '$SH%sPPCOMSTR' % dialect)
return CompAction, CompPPAction, ShCompAction, ShCompPPAction | python | def CreateDialectActions(dialect):
CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect)
CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect)
ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR' % dialect)
ShCompPPAction = SCons.Action.Action('$SH%sPPCOM ' % dialect, '$SH%sPPCOMSTR' % dialect)
return CompAction, CompPPAction, ShCompAction, ShCompPPAction | [
"def",
"CreateDialectActions",
"(",
"dialect",
")",
":",
"CompAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$%sCOM '",
"%",
"dialect",
",",
"'$%sCOMSTR'",
"%",
"dialect",
")",
"CompPPAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"... | Create dialect specific actions. | [
"Create",
"dialect",
"specific",
"actions",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L100-L107 |
23,145 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | DialectAddToEnv | def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0):
"""Add dialect specific construction variables."""
ComputeFortranSuffixes(suffixes, ppsuffixes)
fscan = SCons.Scanner.Fortran.FortranScan("%sPATH" % dialect)
for suffix in suffixes + ppsuffixes:
SCons.Tool.SourceFileScanner.add_scanner(suffix, fscan)
env.AppendUnique(FORTRANSUFFIXES = suffixes + ppsuffixes)
compaction, compppaction, shcompaction, shcompppaction = \
CreateDialectActions(dialect)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in suffixes:
static_obj.add_action(suffix, compaction)
shared_obj.add_action(suffix, shcompaction)
static_obj.add_emitter(suffix, FortranEmitter)
shared_obj.add_emitter(suffix, ShFortranEmitter)
for suffix in ppsuffixes:
static_obj.add_action(suffix, compppaction)
shared_obj.add_action(suffix, shcompppaction)
static_obj.add_emitter(suffix, FortranEmitter)
shared_obj.add_emitter(suffix, ShFortranEmitter)
if '%sFLAGS' % dialect not in env:
env['%sFLAGS' % dialect] = SCons.Util.CLVar('')
if 'SH%sFLAGS' % dialect not in env:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
# If a tool does not define fortran prefix/suffix for include path, use C ones
if 'INC%sPREFIX' % dialect not in env:
env['INC%sPREFIX' % dialect] = '$INCPREFIX'
if 'INC%sSUFFIX' % dialect not in env:
env['INC%sSUFFIX' % dialect] = '$INCSUFFIX'
env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect)
if support_module == 1:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
else:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) | python | def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0):
ComputeFortranSuffixes(suffixes, ppsuffixes)
fscan = SCons.Scanner.Fortran.FortranScan("%sPATH" % dialect)
for suffix in suffixes + ppsuffixes:
SCons.Tool.SourceFileScanner.add_scanner(suffix, fscan)
env.AppendUnique(FORTRANSUFFIXES = suffixes + ppsuffixes)
compaction, compppaction, shcompaction, shcompppaction = \
CreateDialectActions(dialect)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in suffixes:
static_obj.add_action(suffix, compaction)
shared_obj.add_action(suffix, shcompaction)
static_obj.add_emitter(suffix, FortranEmitter)
shared_obj.add_emitter(suffix, ShFortranEmitter)
for suffix in ppsuffixes:
static_obj.add_action(suffix, compppaction)
shared_obj.add_action(suffix, shcompppaction)
static_obj.add_emitter(suffix, FortranEmitter)
shared_obj.add_emitter(suffix, ShFortranEmitter)
if '%sFLAGS' % dialect not in env:
env['%sFLAGS' % dialect] = SCons.Util.CLVar('')
if 'SH%sFLAGS' % dialect not in env:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
# If a tool does not define fortran prefix/suffix for include path, use C ones
if 'INC%sPREFIX' % dialect not in env:
env['INC%sPREFIX' % dialect] = '$INCPREFIX'
if 'INC%sSUFFIX' % dialect not in env:
env['INC%sSUFFIX' % dialect] = '$INCSUFFIX'
env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect)
if support_module == 1:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
else:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) | [
"def",
"DialectAddToEnv",
"(",
"env",
",",
"dialect",
",",
"suffixes",
",",
"ppsuffixes",
",",
"support_module",
"=",
"0",
")",
":",
"ComputeFortranSuffixes",
"(",
"suffixes",
",",
"ppsuffixes",
")",
"fscan",
"=",
"SCons",
".",
"Scanner",
".",
"Fortran",
"."... | Add dialect specific construction variables. | [
"Add",
"dialect",
"specific",
"construction",
"variables",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L109-L161 |
23,146 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_fortran_to_env | def add_fortran_to_env(env):
"""Add Builders and construction variables for Fortran to an Environment."""
try:
FortranSuffixes = env['FORTRANFILESUFFIXES']
except KeyError:
FortranSuffixes = ['.f', '.for', '.ftn']
#print("Adding %s to fortran suffixes" % FortranSuffixes)
try:
FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
except KeyError:
FortranPPSuffixes = ['.fpp', '.FPP']
DialectAddToEnv(env, "FORTRAN", FortranSuffixes,
FortranPPSuffixes, support_module = 1)
env['FORTRANMODPREFIX'] = '' # like $LIBPREFIX
env['FORTRANMODSUFFIX'] = '.mod' # like $LIBSUFFIX
env['FORTRANMODDIR'] = '' # where the compiler should place .mod files
env['FORTRANMODDIRPREFIX'] = '' # some prefix to $FORTRANMODDIR - similar to $INCPREFIX
env['FORTRANMODDIRSUFFIX'] = '' # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX
env['_FORTRANMODFLAG'] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' | python | def add_fortran_to_env(env):
try:
FortranSuffixes = env['FORTRANFILESUFFIXES']
except KeyError:
FortranSuffixes = ['.f', '.for', '.ftn']
#print("Adding %s to fortran suffixes" % FortranSuffixes)
try:
FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
except KeyError:
FortranPPSuffixes = ['.fpp', '.FPP']
DialectAddToEnv(env, "FORTRAN", FortranSuffixes,
FortranPPSuffixes, support_module = 1)
env['FORTRANMODPREFIX'] = '' # like $LIBPREFIX
env['FORTRANMODSUFFIX'] = '.mod' # like $LIBSUFFIX
env['FORTRANMODDIR'] = '' # where the compiler should place .mod files
env['FORTRANMODDIRPREFIX'] = '' # some prefix to $FORTRANMODDIR - similar to $INCPREFIX
env['FORTRANMODDIRSUFFIX'] = '' # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX
env['_FORTRANMODFLAG'] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' | [
"def",
"add_fortran_to_env",
"(",
"env",
")",
":",
"try",
":",
"FortranSuffixes",
"=",
"env",
"[",
"'FORTRANFILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"FortranSuffixes",
"=",
"[",
"'.f'",
",",
"'.for'",
",",
"'.ftn'",
"]",
"#print(\"Adding %s to fortran suffi... | Add Builders and construction variables for Fortran to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Fortran",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L163-L185 |
23,147 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_f77_to_env | def add_f77_to_env(env):
"""Add Builders and construction variables for f77 to an Environment."""
try:
F77Suffixes = env['F77FILESUFFIXES']
except KeyError:
F77Suffixes = ['.f77']
#print("Adding %s to f77 suffixes" % F77Suffixes)
try:
F77PPSuffixes = env['F77PPFILESUFFIXES']
except KeyError:
F77PPSuffixes = []
DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes) | python | def add_f77_to_env(env):
try:
F77Suffixes = env['F77FILESUFFIXES']
except KeyError:
F77Suffixes = ['.f77']
#print("Adding %s to f77 suffixes" % F77Suffixes)
try:
F77PPSuffixes = env['F77PPFILESUFFIXES']
except KeyError:
F77PPSuffixes = []
DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes) | [
"def",
"add_f77_to_env",
"(",
"env",
")",
":",
"try",
":",
"F77Suffixes",
"=",
"env",
"[",
"'F77FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F77Suffixes",
"=",
"[",
"'.f77'",
"]",
"#print(\"Adding %s to f77 suffixes\" % F77Suffixes)",
"try",
":",
"F77PPSuffixes"... | Add Builders and construction variables for f77 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f77",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L187-L200 |
23,148 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_f90_to_env | def add_f90_to_env(env):
"""Add Builders and construction variables for f90 to an Environment."""
try:
F90Suffixes = env['F90FILESUFFIXES']
except KeyError:
F90Suffixes = ['.f90']
#print("Adding %s to f90 suffixes" % F90Suffixes)
try:
F90PPSuffixes = env['F90PPFILESUFFIXES']
except KeyError:
F90PPSuffixes = []
DialectAddToEnv(env, "F90", F90Suffixes, F90PPSuffixes,
support_module = 1) | python | def add_f90_to_env(env):
try:
F90Suffixes = env['F90FILESUFFIXES']
except KeyError:
F90Suffixes = ['.f90']
#print("Adding %s to f90 suffixes" % F90Suffixes)
try:
F90PPSuffixes = env['F90PPFILESUFFIXES']
except KeyError:
F90PPSuffixes = []
DialectAddToEnv(env, "F90", F90Suffixes, F90PPSuffixes,
support_module = 1) | [
"def",
"add_f90_to_env",
"(",
"env",
")",
":",
"try",
":",
"F90Suffixes",
"=",
"env",
"[",
"'F90FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F90Suffixes",
"=",
"[",
"'.f90'",
"]",
"#print(\"Adding %s to f90 suffixes\" % F90Suffixes)",
"try",
":",
"F90PPSuffixes"... | Add Builders and construction variables for f90 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f90",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L202-L216 |
23,149 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_f95_to_env | def add_f95_to_env(env):
"""Add Builders and construction variables for f95 to an Environment."""
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']
except KeyError:
F95PPSuffixes = []
DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes,
support_module = 1) | python | def add_f95_to_env(env):
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']
except KeyError:
F95PPSuffixes = []
DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes,
support_module = 1) | [
"def",
"add_f95_to_env",
"(",
"env",
")",
":",
"try",
":",
"F95Suffixes",
"=",
"env",
"[",
"'F95FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F95Suffixes",
"=",
"[",
"'.f95'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F95PPSuffixes"... | Add Builders and construction variables for f95 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f95",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L218-L232 |
23,150 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_f03_to_env | def add_f03_to_env(env):
"""Add Builders and construction variables for f03 to an Environment."""
try:
F03Suffixes = env['F03FILESUFFIXES']
except KeyError:
F03Suffixes = ['.f03']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F03PPSuffixes = env['F03PPFILESUFFIXES']
except KeyError:
F03PPSuffixes = []
DialectAddToEnv(env, "F03", F03Suffixes, F03PPSuffixes,
support_module = 1) | python | def add_f03_to_env(env):
try:
F03Suffixes = env['F03FILESUFFIXES']
except KeyError:
F03Suffixes = ['.f03']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F03PPSuffixes = env['F03PPFILESUFFIXES']
except KeyError:
F03PPSuffixes = []
DialectAddToEnv(env, "F03", F03Suffixes, F03PPSuffixes,
support_module = 1) | [
"def",
"add_f03_to_env",
"(",
"env",
")",
":",
"try",
":",
"F03Suffixes",
"=",
"env",
"[",
"'F03FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F03Suffixes",
"=",
"[",
"'.f03'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F03PPSuffixes"... | Add Builders and construction variables for f03 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f03",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L234-L248 |
23,151 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_f08_to_env | def add_f08_to_env(env):
"""Add Builders and construction variables for f08 to an Environment."""
try:
F08Suffixes = env['F08FILESUFFIXES']
except KeyError:
F08Suffixes = ['.f08']
try:
F08PPSuffixes = env['F08PPFILESUFFIXES']
except KeyError:
F08PPSuffixes = []
DialectAddToEnv(env, "F08", F08Suffixes, F08PPSuffixes,
support_module = 1) | python | def add_f08_to_env(env):
try:
F08Suffixes = env['F08FILESUFFIXES']
except KeyError:
F08Suffixes = ['.f08']
try:
F08PPSuffixes = env['F08PPFILESUFFIXES']
except KeyError:
F08PPSuffixes = []
DialectAddToEnv(env, "F08", F08Suffixes, F08PPSuffixes,
support_module = 1) | [
"def",
"add_f08_to_env",
"(",
"env",
")",
":",
"try",
":",
"F08Suffixes",
"=",
"env",
"[",
"'F08FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F08Suffixes",
"=",
"[",
"'.f08'",
"]",
"try",
":",
"F08PPSuffixes",
"=",
"env",
"[",
"'F08PPFILESUFFIXES'",
"]",
... | Add Builders and construction variables for f08 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f08",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L250-L263 |
23,152 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | add_all_to_env | def add_all_to_env(env):
"""Add builders and construction variables for all supported fortran
dialects."""
add_fortran_to_env(env)
add_f77_to_env(env)
add_f90_to_env(env)
add_f95_to_env(env)
add_f03_to_env(env)
add_f08_to_env(env) | python | def add_all_to_env(env):
add_fortran_to_env(env)
add_f77_to_env(env)
add_f90_to_env(env)
add_f95_to_env(env)
add_f03_to_env(env)
add_f08_to_env(env) | [
"def",
"add_all_to_env",
"(",
"env",
")",
":",
"add_fortran_to_env",
"(",
"env",
")",
"add_f77_to_env",
"(",
"env",
")",
"add_f90_to_env",
"(",
"env",
")",
"add_f95_to_env",
"(",
"env",
")",
"add_f03_to_env",
"(",
"env",
")",
"add_f08_to_env",
"(",
"env",
")... | Add builders and construction variables for all supported fortran
dialects. | [
"Add",
"builders",
"and",
"construction",
"variables",
"for",
"all",
"supported",
"fortran",
"dialects",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L265-L273 |
23,153 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | _delete_duplicates | def _delete_duplicates(l, keep_last):
"""Delete duplicates from a sequence, keeping the first or last."""
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
seen.add(i)
except TypeError:
# probably unhashable. Just keep it.
result.append(i)
if keep_last:
result.reverse()
return result | python | def _delete_duplicates(l, keep_last):
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
seen.add(i)
except TypeError:
# probably unhashable. Just keep it.
result.append(i)
if keep_last:
result.reverse()
return result | [
"def",
"_delete_duplicates",
"(",
"l",
",",
"keep_last",
")",
":",
"seen",
"=",
"set",
"(",
")",
"result",
"=",
"[",
"]",
"if",
"keep_last",
":",
"# reverse in & out, then keep first",
"l",
".",
"reverse",
"(",
")",
"for",
"i",
"in",
"l",
":",
"try",
"... | Delete duplicates from a sequence, keeping the first or last. | [
"Delete",
"duplicates",
"from",
"a",
"sequence",
"keeping",
"the",
"first",
"or",
"last",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L168-L184 |
23,154 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | MethodWrapper.clone | def clone(self, new_object):
"""
Returns an object that re-binds the underlying "method" to
the specified new object.
"""
return self.__class__(new_object, self.method, self.name) | python | def clone(self, new_object):
return self.__class__(new_object, self.method, self.name) | [
"def",
"clone",
"(",
"self",
",",
"new_object",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"new_object",
",",
"self",
".",
"method",
",",
"self",
".",
"name",
")"
] | Returns an object that re-binds the underlying "method" to
the specified new object. | [
"Returns",
"an",
"object",
"that",
"re",
"-",
"binds",
"the",
"underlying",
"method",
"to",
"the",
"specified",
"new",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L226-L231 |
23,155 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | SubstitutionEnvironment._init_special | def _init_special(self):
"""Initial the dispatch tables for special handling of
special construction variables."""
self._special_del = {}
self._special_del['SCANNERS'] = _del_SCANNERS
self._special_set = {}
for key in reserved_construction_var_names:
self._special_set[key] = _set_reserved
for key in future_reserved_construction_var_names:
self._special_set[key] = _set_future_reserved
self._special_set['BUILDERS'] = _set_BUILDERS
self._special_set['SCANNERS'] = _set_SCANNERS
# Freeze the keys of self._special_set in a list for use by
# methods that need to check. (Empirically, list scanning has
# gotten better than dict.has_key() in Python 2.5.)
self._special_set_keys = list(self._special_set.keys()) | python | def _init_special(self):
self._special_del = {}
self._special_del['SCANNERS'] = _del_SCANNERS
self._special_set = {}
for key in reserved_construction_var_names:
self._special_set[key] = _set_reserved
for key in future_reserved_construction_var_names:
self._special_set[key] = _set_future_reserved
self._special_set['BUILDERS'] = _set_BUILDERS
self._special_set['SCANNERS'] = _set_SCANNERS
# Freeze the keys of self._special_set in a list for use by
# methods that need to check. (Empirically, list scanning has
# gotten better than dict.has_key() in Python 2.5.)
self._special_set_keys = list(self._special_set.keys()) | [
"def",
"_init_special",
"(",
"self",
")",
":",
"self",
".",
"_special_del",
"=",
"{",
"}",
"self",
".",
"_special_del",
"[",
"'SCANNERS'",
"]",
"=",
"_del_SCANNERS",
"self",
".",
"_special_set",
"=",
"{",
"}",
"for",
"key",
"in",
"reserved_construction_var_n... | Initial the dispatch tables for special handling of
special construction variables. | [
"Initial",
"the",
"dispatch",
"tables",
"for",
"special",
"handling",
"of",
"special",
"construction",
"variables",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L380-L397 |
23,156 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | SubstitutionEnvironment.AddMethod | def AddMethod(self, function, name=None):
"""
Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself.
"""
method = MethodWrapper(self, function, name)
self.added_methods.append(method) | python | def AddMethod(self, function, name=None):
method = MethodWrapper(self, function, name)
self.added_methods.append(method) | [
"def",
"AddMethod",
"(",
"self",
",",
"function",
",",
"name",
"=",
"None",
")",
":",
"method",
"=",
"MethodWrapper",
"(",
"self",
",",
"function",
",",
"name",
")",
"self",
".",
"added_methods",
".",
"append",
"(",
"method",
")"
] | Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself. | [
"Adds",
"the",
"specified",
"function",
"as",
"a",
"method",
"of",
"this",
"construction",
"environment",
"with",
"the",
"specified",
"name",
".",
"If",
"the",
"name",
"is",
"omitted",
"the",
"default",
"name",
"is",
"the",
"name",
"of",
"the",
"function",
... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L597-L604 |
23,157 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | SubstitutionEnvironment.RemoveMethod | def RemoveMethod(self, function):
"""
Removes the specified function's MethodWrapper from the
added_methods list, so we don't re-bind it when making a clone.
"""
self.added_methods = [dm for dm in self.added_methods if not dm.method is function] | python | def RemoveMethod(self, function):
self.added_methods = [dm for dm in self.added_methods if not dm.method is function] | [
"def",
"RemoveMethod",
"(",
"self",
",",
"function",
")",
":",
"self",
".",
"added_methods",
"=",
"[",
"dm",
"for",
"dm",
"in",
"self",
".",
"added_methods",
"if",
"not",
"dm",
".",
"method",
"is",
"function",
"]"
] | Removes the specified function's MethodWrapper from the
added_methods list, so we don't re-bind it when making a clone. | [
"Removes",
"the",
"specified",
"function",
"s",
"MethodWrapper",
"from",
"the",
"added_methods",
"list",
"so",
"we",
"don",
"t",
"re",
"-",
"bind",
"it",
"when",
"making",
"a",
"clone",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L606-L611 |
23,158 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | SubstitutionEnvironment.Override | def Override(self, overrides):
"""
Produce a modified environment whose variables are overridden by
the overrides dictionaries. "overrides" is a dictionary that
will override the variables of this environment.
This function is much more efficient than Clone() or creating
a new Environment because it doesn't copy the construction
environment dictionary, it just wraps the underlying construction
environment, and doesn't even create a wrapper object if there
are no overrides.
"""
if not overrides: return self
o = copy_non_reserved_keywords(overrides)
if not o: return self
overrides = {}
merges = None
for key, value in o.items():
if key == 'parse_flags':
merges = value
else:
overrides[key] = SCons.Subst.scons_subst_once(value, self, key)
env = OverrideEnvironment(self, overrides)
if merges: env.MergeFlags(merges)
return env | python | def Override(self, overrides):
if not overrides: return self
o = copy_non_reserved_keywords(overrides)
if not o: return self
overrides = {}
merges = None
for key, value in o.items():
if key == 'parse_flags':
merges = value
else:
overrides[key] = SCons.Subst.scons_subst_once(value, self, key)
env = OverrideEnvironment(self, overrides)
if merges: env.MergeFlags(merges)
return env | [
"def",
"Override",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"not",
"overrides",
":",
"return",
"self",
"o",
"=",
"copy_non_reserved_keywords",
"(",
"overrides",
")",
"if",
"not",
"o",
":",
"return",
"self",
"overrides",
"=",
"{",
"}",
"merges",
"="... | Produce a modified environment whose variables are overridden by
the overrides dictionaries. "overrides" is a dictionary that
will override the variables of this environment.
This function is much more efficient than Clone() or creating
a new Environment because it doesn't copy the construction
environment dictionary, it just wraps the underlying construction
environment, and doesn't even create a wrapper object if there
are no overrides. | [
"Produce",
"a",
"modified",
"environment",
"whose",
"variables",
"are",
"overridden",
"by",
"the",
"overrides",
"dictionaries",
".",
"overrides",
"is",
"a",
"dictionary",
"that",
"will",
"override",
"the",
"variables",
"of",
"this",
"environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L613-L637 |
23,159 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | SubstitutionEnvironment.MergeFlags | def MergeFlags(self, args, unique=1, dict=None):
"""
Merge the dict in args into the construction variables of this
env, or the passed-in dict. If args is not a dict, it is
converted into a dict using ParseFlags. If unique is not set,
the flags are appended rather than merged.
"""
if dict is None:
dict = self
if not SCons.Util.is_Dict(args):
args = self.ParseFlags(args)
if not unique:
self.Append(**args)
return self
for key, value in args.items():
if not value:
continue
try:
orig = self[key]
except KeyError:
orig = value
else:
if not orig:
orig = value
elif value:
# Add orig and value. The logic here was lifted from
# part of env.Append() (see there for a lot of comments
# about the order in which things are tried) and is
# used mainly to handle coercion of strings to CLVar to
# "do the right thing" given (e.g.) an original CCFLAGS
# string variable like '-pipe -Wall'.
try:
orig = orig + value
except (KeyError, TypeError):
try:
add_to_orig = orig.append
except AttributeError:
value.insert(0, orig)
orig = value
else:
add_to_orig(value)
t = []
if key[-4:] == 'PATH':
### keep left-most occurence
for v in orig:
if v not in t:
t.append(v)
else:
### keep right-most occurence
orig.reverse()
for v in orig:
if v not in t:
t.insert(0, v)
self[key] = t
return self | python | def MergeFlags(self, args, unique=1, dict=None):
if dict is None:
dict = self
if not SCons.Util.is_Dict(args):
args = self.ParseFlags(args)
if not unique:
self.Append(**args)
return self
for key, value in args.items():
if not value:
continue
try:
orig = self[key]
except KeyError:
orig = value
else:
if not orig:
orig = value
elif value:
# Add orig and value. The logic here was lifted from
# part of env.Append() (see there for a lot of comments
# about the order in which things are tried) and is
# used mainly to handle coercion of strings to CLVar to
# "do the right thing" given (e.g.) an original CCFLAGS
# string variable like '-pipe -Wall'.
try:
orig = orig + value
except (KeyError, TypeError):
try:
add_to_orig = orig.append
except AttributeError:
value.insert(0, orig)
orig = value
else:
add_to_orig(value)
t = []
if key[-4:] == 'PATH':
### keep left-most occurence
for v in orig:
if v not in t:
t.append(v)
else:
### keep right-most occurence
orig.reverse()
for v in orig:
if v not in t:
t.insert(0, v)
self[key] = t
return self | [
"def",
"MergeFlags",
"(",
"self",
",",
"args",
",",
"unique",
"=",
"1",
",",
"dict",
"=",
"None",
")",
":",
"if",
"dict",
"is",
"None",
":",
"dict",
"=",
"self",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_Dict",
"(",
"args",
")",
":",
"args",
... | Merge the dict in args into the construction variables of this
env, or the passed-in dict. If args is not a dict, it is
converted into a dict using ParseFlags. If unique is not set,
the flags are appended rather than merged. | [
"Merge",
"the",
"dict",
"in",
"args",
"into",
"the",
"construction",
"variables",
"of",
"this",
"env",
"or",
"the",
"passed",
"-",
"in",
"dict",
".",
"If",
"args",
"is",
"not",
"a",
"dict",
"it",
"is",
"converted",
"into",
"a",
"dict",
"using",
"ParseF... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L803-L858 |
23,160 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.get_factory | def get_factory(self, factory, default='File'):
"""Return a factory function for creating Nodes for this
construction environment.
"""
name = default
try:
is_node = issubclass(factory, SCons.Node.FS.Base)
except TypeError:
# The specified factory isn't a Node itself--it's
# most likely None, or possibly a callable.
pass
else:
if is_node:
# The specified factory is a Node (sub)class. Try to
# return the FS method that corresponds to the Node's
# name--that is, we return self.fs.Dir if they want a Dir,
# self.fs.File for a File, etc.
try: name = factory.__name__
except AttributeError: pass
else: factory = None
if not factory:
# They passed us None, or we picked up a name from a specified
# class, so return the FS method. (Note that we *don't*
# use our own self.{Dir,File} methods because that would
# cause env.subst() to be called twice on the file name,
# interfering with files that have $$ in them.)
factory = getattr(self.fs, name)
return factory | python | def get_factory(self, factory, default='File'):
name = default
try:
is_node = issubclass(factory, SCons.Node.FS.Base)
except TypeError:
# The specified factory isn't a Node itself--it's
# most likely None, or possibly a callable.
pass
else:
if is_node:
# The specified factory is a Node (sub)class. Try to
# return the FS method that corresponds to the Node's
# name--that is, we return self.fs.Dir if they want a Dir,
# self.fs.File for a File, etc.
try: name = factory.__name__
except AttributeError: pass
else: factory = None
if not factory:
# They passed us None, or we picked up a name from a specified
# class, so return the FS method. (Note that we *don't*
# use our own self.{Dir,File} methods because that would
# cause env.subst() to be called twice on the file name,
# interfering with files that have $$ in them.)
factory = getattr(self.fs, name)
return factory | [
"def",
"get_factory",
"(",
"self",
",",
"factory",
",",
"default",
"=",
"'File'",
")",
":",
"name",
"=",
"default",
"try",
":",
"is_node",
"=",
"issubclass",
"(",
"factory",
",",
"SCons",
".",
"Node",
".",
"FS",
".",
"Base",
")",
"except",
"TypeError",... | Return a factory function for creating Nodes for this
construction environment. | [
"Return",
"a",
"factory",
"function",
"for",
"creating",
"Nodes",
"for",
"this",
"construction",
"environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1021-L1048 |
23,161 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Append | def Append(self, **kw):
"""Append values to existing construction variables
in an Environment.
"""
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
# within try:-except: blocks, so we have to nest our code.
try:
if key == 'CPPDEFINES' and SCons.Util.is_String(self._dict[key]):
self._dict[key] = [self._dict[key]]
orig = self._dict[key]
except KeyError:
# No existing variable in the environment, so just set
# it to the new value.
if key == 'CPPDEFINES' and SCons.Util.is_String(val):
self._dict[key] = [val]
else:
self._dict[key] = val
else:
try:
# Check if the original looks like a dictionary.
# If it is, we can't just try adding the value because
# dictionaries don't have __add__() methods, and
# things like UserList will incorrectly coerce the
# original dict to a list (which we don't want).
update_dict = orig.update
except AttributeError:
try:
# Most straightforward: just try to add them
# together. This will work in most cases, when the
# original and new values are of compatible types.
self._dict[key] = orig + val
except (KeyError, TypeError):
try:
# Check if the original is a list.
add_to_orig = orig.append
except AttributeError:
# The original isn't a list, but the new
# value is (by process of elimination),
# so insert the original in the new value
# (if there's one to insert) and replace
# the variable with it.
if orig:
val.insert(0, orig)
self._dict[key] = val
else:
# The original is a list, so append the new
# value to it (if there's a value to append).
if val:
add_to_orig(val)
else:
# The original looks like a dictionary, so update it
# based on what we think the value looks like.
if SCons.Util.is_List(val):
if key == 'CPPDEFINES':
tmp = []
for (k, v) in orig.items():
if v is not None:
tmp.append((k, v))
else:
tmp.append((k,))
orig = tmp
orig += val
self._dict[key] = orig
else:
for v in val:
orig[v] = None
else:
try:
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
for k, v in val.items():
orig[k] = v
else:
orig[val] = None
self.scanner_map_delete(kw) | python | def Append(self, **kw):
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
# within try:-except: blocks, so we have to nest our code.
try:
if key == 'CPPDEFINES' and SCons.Util.is_String(self._dict[key]):
self._dict[key] = [self._dict[key]]
orig = self._dict[key]
except KeyError:
# No existing variable in the environment, so just set
# it to the new value.
if key == 'CPPDEFINES' and SCons.Util.is_String(val):
self._dict[key] = [val]
else:
self._dict[key] = val
else:
try:
# Check if the original looks like a dictionary.
# If it is, we can't just try adding the value because
# dictionaries don't have __add__() methods, and
# things like UserList will incorrectly coerce the
# original dict to a list (which we don't want).
update_dict = orig.update
except AttributeError:
try:
# Most straightforward: just try to add them
# together. This will work in most cases, when the
# original and new values are of compatible types.
self._dict[key] = orig + val
except (KeyError, TypeError):
try:
# Check if the original is a list.
add_to_orig = orig.append
except AttributeError:
# The original isn't a list, but the new
# value is (by process of elimination),
# so insert the original in the new value
# (if there's one to insert) and replace
# the variable with it.
if orig:
val.insert(0, orig)
self._dict[key] = val
else:
# The original is a list, so append the new
# value to it (if there's a value to append).
if val:
add_to_orig(val)
else:
# The original looks like a dictionary, so update it
# based on what we think the value looks like.
if SCons.Util.is_List(val):
if key == 'CPPDEFINES':
tmp = []
for (k, v) in orig.items():
if v is not None:
tmp.append((k, v))
else:
tmp.append((k,))
orig = tmp
orig += val
self._dict[key] = orig
else:
for v in val:
orig[v] = None
else:
try:
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
for k, v in val.items():
orig[k] = v
else:
orig[val] = None
self.scanner_map_delete(kw) | [
"def",
"Append",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"=",
"copy_non_reserved_keywords",
"(",
"kw",
")",
"for",
"key",
",",
"val",
"in",
"kw",
".",
"items",
"(",
")",
":",
"# It would be easier on the eyes to write this using",
"# \"continue\" sta... | Append values to existing construction variables
in an Environment. | [
"Append",
"values",
"to",
"existing",
"construction",
"variables",
"in",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1129-L1208 |
23,162 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.AppendENVPath | def AppendENVPath(self, name, newpath, envname = 'ENV',
sep = os.pathsep, delete_existing=1):
"""Append path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the end (it will be left where it is).
"""
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | python | def AppendENVPath(self, name, newpath, envname = 'ENV',
sep = os.pathsep, delete_existing=1):
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | [
"def",
"AppendENVPath",
"(",
"self",
",",
"name",
",",
"newpath",
",",
"envname",
"=",
"'ENV'",
",",
"sep",
"=",
"os",
".",
"pathsep",
",",
"delete_existing",
"=",
"1",
")",
":",
"orig",
"=",
"''",
"if",
"envname",
"in",
"self",
".",
"_dict",
"and",
... | Append path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the end (it will be left where it is). | [
"Append",
"path",
"elements",
"to",
"the",
"path",
"name",
"in",
"the",
"ENV",
"dictionary",
"for",
"this",
"environment",
".",
"Will",
"only",
"add",
"any",
"particular",
"path",
"once",
"and",
"will",
"normpath",
"and",
"normcase",
"all",
"paths",
"to",
... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1219-L1241 |
23,163 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Detect | def Detect(self, progs):
"""Return the first available program in progs.
"""
if not SCons.Util.is_List(progs):
progs = [ progs ]
for prog in progs:
path = self.WhereIs(prog)
if path: return prog
return None | python | def Detect(self, progs):
if not SCons.Util.is_List(progs):
progs = [ progs ]
for prog in progs:
path = self.WhereIs(prog)
if path: return prog
return None | [
"def",
"Detect",
"(",
"self",
",",
"progs",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"progs",
")",
":",
"progs",
"=",
"[",
"progs",
"]",
"for",
"prog",
"in",
"progs",
":",
"path",
"=",
"self",
".",
"WhereIs",
"(",
"prog",... | Return the first available program in progs. | [
"Return",
"the",
"first",
"available",
"program",
"in",
"progs",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1486-L1494 |
23,164 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Dump | def Dump(self, key = None):
"""
Using the standard Python pretty printer, return the contents of the
scons build environment as a string.
If the key passed in is anything other than None, then that will
be used as an index into the build environment dictionary and
whatever is found there will be fed into the pretty printer. Note
that this key is case sensitive.
"""
import pprint
pp = pprint.PrettyPrinter(indent=2)
if key:
dict = self.Dictionary(key)
else:
dict = self.Dictionary()
return pp.pformat(dict) | python | def Dump(self, key = None):
import pprint
pp = pprint.PrettyPrinter(indent=2)
if key:
dict = self.Dictionary(key)
else:
dict = self.Dictionary()
return pp.pformat(dict) | [
"def",
"Dump",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"import",
"pprint",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"2",
")",
"if",
"key",
":",
"dict",
"=",
"self",
".",
"Dictionary",
"(",
"key",
")",
"else",
":",
"d... | Using the standard Python pretty printer, return the contents of the
scons build environment as a string.
If the key passed in is anything other than None, then that will
be used as an index into the build environment dictionary and
whatever is found there will be fed into the pretty printer. Note
that this key is case sensitive. | [
"Using",
"the",
"standard",
"Python",
"pretty",
"printer",
"return",
"the",
"contents",
"of",
"the",
"scons",
"build",
"environment",
"as",
"a",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1504-L1520 |
23,165 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.FindIxes | def FindIxes(self, paths, prefix, suffix):
"""
Search a list of paths for something that matches the prefix and suffix.
paths - the list of paths or nodes.
prefix - construction variable for the prefix.
suffix - construction variable for the suffix.
"""
suffix = self.subst('$'+suffix)
prefix = self.subst('$'+prefix)
for path in paths:
dir,name = os.path.split(str(path))
if name[:len(prefix)] == prefix and name[-len(suffix):] == suffix:
return path | python | def FindIxes(self, paths, prefix, suffix):
suffix = self.subst('$'+suffix)
prefix = self.subst('$'+prefix)
for path in paths:
dir,name = os.path.split(str(path))
if name[:len(prefix)] == prefix and name[-len(suffix):] == suffix:
return path | [
"def",
"FindIxes",
"(",
"self",
",",
"paths",
",",
"prefix",
",",
"suffix",
")",
":",
"suffix",
"=",
"self",
".",
"subst",
"(",
"'$'",
"+",
"suffix",
")",
"prefix",
"=",
"self",
".",
"subst",
"(",
"'$'",
"+",
"prefix",
")",
"for",
"path",
"in",
"... | Search a list of paths for something that matches the prefix and suffix.
paths - the list of paths or nodes.
prefix - construction variable for the prefix.
suffix - construction variable for the suffix. | [
"Search",
"a",
"list",
"of",
"paths",
"for",
"something",
"that",
"matches",
"the",
"prefix",
"and",
"suffix",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1522-L1537 |
23,166 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.ParseDepends | def ParseDepends(self, filename, must_exist=None, only_one=0):
"""
Parse a mkdep-style file for explicit dependencies. This is
completely abusable, and should be unnecessary in the "normal"
case of proper SCons configuration, but it may help make
the transition from a Make hierarchy easier for some people
to swallow. It can also be genuinely useful when using a tool
that can write a .d file, but for which writing a scanner would
be too complicated.
"""
filename = self.subst(filename)
try:
fp = open(filename, 'r')
except IOError:
if must_exist:
raise
return
lines = SCons.Util.LogicalLines(fp).readlines()
lines = [l for l in lines if l[0] != '#']
tdlist = []
for line in lines:
try:
target, depends = line.split(':', 1)
except (AttributeError, ValueError):
# Throws AttributeError if line isn't a string. Can throw
# ValueError if line doesn't split into two or more elements.
pass
else:
tdlist.append((target.split(), depends.split()))
if only_one:
targets = []
for td in tdlist:
targets.extend(td[0])
if len(targets) > 1:
raise SCons.Errors.UserError(
"More than one dependency target found in `%s': %s"
% (filename, targets))
for target, depends in tdlist:
self.Depends(target, depends) | python | def ParseDepends(self, filename, must_exist=None, only_one=0):
filename = self.subst(filename)
try:
fp = open(filename, 'r')
except IOError:
if must_exist:
raise
return
lines = SCons.Util.LogicalLines(fp).readlines()
lines = [l for l in lines if l[0] != '#']
tdlist = []
for line in lines:
try:
target, depends = line.split(':', 1)
except (AttributeError, ValueError):
# Throws AttributeError if line isn't a string. Can throw
# ValueError if line doesn't split into two or more elements.
pass
else:
tdlist.append((target.split(), depends.split()))
if only_one:
targets = []
for td in tdlist:
targets.extend(td[0])
if len(targets) > 1:
raise SCons.Errors.UserError(
"More than one dependency target found in `%s': %s"
% (filename, targets))
for target, depends in tdlist:
self.Depends(target, depends) | [
"def",
"ParseDepends",
"(",
"self",
",",
"filename",
",",
"must_exist",
"=",
"None",
",",
"only_one",
"=",
"0",
")",
":",
"filename",
"=",
"self",
".",
"subst",
"(",
"filename",
")",
"try",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
... | Parse a mkdep-style file for explicit dependencies. This is
completely abusable, and should be unnecessary in the "normal"
case of proper SCons configuration, but it may help make
the transition from a Make hierarchy easier for some people
to swallow. It can also be genuinely useful when using a tool
that can write a .d file, but for which writing a scanner would
be too complicated. | [
"Parse",
"a",
"mkdep",
"-",
"style",
"file",
"for",
"explicit",
"dependencies",
".",
"This",
"is",
"completely",
"abusable",
"and",
"should",
"be",
"unnecessary",
"in",
"the",
"normal",
"case",
"of",
"proper",
"SCons",
"configuration",
"but",
"it",
"may",
"h... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1559-L1597 |
23,167 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Prepend | def Prepend(self, **kw):
"""Prepend values to existing construction variables
in an Environment.
"""
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
# within try:-except: blocks, so we have to nest our code.
try:
orig = self._dict[key]
except KeyError:
# No existing variable in the environment, so just set
# it to the new value.
self._dict[key] = val
else:
try:
# Check if the original looks like a dictionary.
# If it is, we can't just try adding the value because
# dictionaries don't have __add__() methods, and
# things like UserList will incorrectly coerce the
# original dict to a list (which we don't want).
update_dict = orig.update
except AttributeError:
try:
# Most straightforward: just try to add them
# together. This will work in most cases, when the
# original and new values are of compatible types.
self._dict[key] = val + orig
except (KeyError, TypeError):
try:
# Check if the added value is a list.
add_to_val = val.append
except AttributeError:
# The added value isn't a list, but the
# original is (by process of elimination),
# so insert the the new value in the original
# (if there's one to insert).
if val:
orig.insert(0, val)
else:
# The added value is a list, so append
# the original to it (if there's a value
# to append).
if orig:
add_to_val(orig)
self._dict[key] = val
else:
# The original looks like a dictionary, so update it
# based on what we think the value looks like.
if SCons.Util.is_List(val):
for v in val:
orig[v] = None
else:
try:
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
for k, v in val.items():
orig[k] = v
else:
orig[val] = None
self.scanner_map_delete(kw) | python | def Prepend(self, **kw):
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
# within try:-except: blocks, so we have to nest our code.
try:
orig = self._dict[key]
except KeyError:
# No existing variable in the environment, so just set
# it to the new value.
self._dict[key] = val
else:
try:
# Check if the original looks like a dictionary.
# If it is, we can't just try adding the value because
# dictionaries don't have __add__() methods, and
# things like UserList will incorrectly coerce the
# original dict to a list (which we don't want).
update_dict = orig.update
except AttributeError:
try:
# Most straightforward: just try to add them
# together. This will work in most cases, when the
# original and new values are of compatible types.
self._dict[key] = val + orig
except (KeyError, TypeError):
try:
# Check if the added value is a list.
add_to_val = val.append
except AttributeError:
# The added value isn't a list, but the
# original is (by process of elimination),
# so insert the the new value in the original
# (if there's one to insert).
if val:
orig.insert(0, val)
else:
# The added value is a list, so append
# the original to it (if there's a value
# to append).
if orig:
add_to_val(orig)
self._dict[key] = val
else:
# The original looks like a dictionary, so update it
# based on what we think the value looks like.
if SCons.Util.is_List(val):
for v in val:
orig[v] = None
else:
try:
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
for k, v in val.items():
orig[k] = v
else:
orig[val] = None
self.scanner_map_delete(kw) | [
"def",
"Prepend",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"=",
"copy_non_reserved_keywords",
"(",
"kw",
")",
"for",
"key",
",",
"val",
"in",
"kw",
".",
"items",
"(",
")",
":",
"# It would be easier on the eyes to write this using",
"# \"continue\" st... | Prepend values to existing construction variables
in an Environment. | [
"Prepend",
"values",
"to",
"existing",
"construction",
"variables",
"in",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1603-L1666 |
23,168 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.PrependENVPath | def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep,
delete_existing=1):
"""Prepend path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the front (it will be left where it is).
"""
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = SCons.Util.PrependPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | python | def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep,
delete_existing=1):
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = SCons.Util.PrependPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | [
"def",
"PrependENVPath",
"(",
"self",
",",
"name",
",",
"newpath",
",",
"envname",
"=",
"'ENV'",
",",
"sep",
"=",
"os",
".",
"pathsep",
",",
"delete_existing",
"=",
"1",
")",
":",
"orig",
"=",
"''",
"if",
"envname",
"in",
"self",
".",
"_dict",
"and",... | Prepend path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the front (it will be left where it is). | [
"Prepend",
"path",
"elements",
"to",
"the",
"path",
"name",
"in",
"the",
"ENV",
"dictionary",
"for",
"this",
"environment",
".",
"Will",
"only",
"add",
"any",
"particular",
"path",
"once",
"and",
"will",
"normpath",
"and",
"normcase",
"all",
"paths",
"to",
... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1668-L1690 |
23,169 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.PrependUnique | def PrependUnique(self, delete_existing=0, **kw):
"""Prepend values to existing construction variables
in an Environment, if they're not already there.
If delete_existing is 1, removes existing values first, so
values move to front.
"""
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
if SCons.Util.is_List(val):
val = _delete_duplicates(val, not delete_existing)
if key not in self._dict or self._dict[key] in ('', None):
self._dict[key] = val
elif SCons.Util.is_Dict(self._dict[key]) and \
SCons.Util.is_Dict(val):
self._dict[key].update(val)
elif SCons.Util.is_List(val):
dk = self._dict[key]
if not SCons.Util.is_List(dk):
dk = [dk]
if delete_existing:
dk = [x for x in dk if x not in val]
else:
val = [x for x in val if x not in dk]
self._dict[key] = val + dk
else:
dk = self._dict[key]
if SCons.Util.is_List(dk):
# By elimination, val is not a list. Since dk is a
# list, wrap val in a list first.
if delete_existing:
dk = [x for x in dk if x not in val]
self._dict[key] = [val] + dk
else:
if not val in dk:
self._dict[key] = [val] + dk
else:
if delete_existing:
dk = [x for x in dk if x not in val]
self._dict[key] = val + dk
self.scanner_map_delete(kw) | python | def PrependUnique(self, delete_existing=0, **kw):
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
if SCons.Util.is_List(val):
val = _delete_duplicates(val, not delete_existing)
if key not in self._dict or self._dict[key] in ('', None):
self._dict[key] = val
elif SCons.Util.is_Dict(self._dict[key]) and \
SCons.Util.is_Dict(val):
self._dict[key].update(val)
elif SCons.Util.is_List(val):
dk = self._dict[key]
if not SCons.Util.is_List(dk):
dk = [dk]
if delete_existing:
dk = [x for x in dk if x not in val]
else:
val = [x for x in val if x not in dk]
self._dict[key] = val + dk
else:
dk = self._dict[key]
if SCons.Util.is_List(dk):
# By elimination, val is not a list. Since dk is a
# list, wrap val in a list first.
if delete_existing:
dk = [x for x in dk if x not in val]
self._dict[key] = [val] + dk
else:
if not val in dk:
self._dict[key] = [val] + dk
else:
if delete_existing:
dk = [x for x in dk if x not in val]
self._dict[key] = val + dk
self.scanner_map_delete(kw) | [
"def",
"PrependUnique",
"(",
"self",
",",
"delete_existing",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"=",
"copy_non_reserved_keywords",
"(",
"kw",
")",
"for",
"key",
",",
"val",
"in",
"kw",
".",
"items",
"(",
")",
":",
"if",
"SCons",
".",
"U... | Prepend values to existing construction variables
in an Environment, if they're not already there.
If delete_existing is 1, removes existing values first, so
values move to front. | [
"Prepend",
"values",
"to",
"existing",
"construction",
"variables",
"in",
"an",
"Environment",
"if",
"they",
"re",
"not",
"already",
"there",
".",
"If",
"delete_existing",
"is",
"1",
"removes",
"existing",
"values",
"first",
"so",
"values",
"move",
"to",
"fron... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1692-L1731 |
23,170 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.ReplaceIxes | def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix):
"""
Replace old_prefix with new_prefix and old_suffix with new_suffix.
env - Environment used to interpolate variables.
path - the path that will be modified.
old_prefix - construction variable for the old prefix.
old_suffix - construction variable for the old suffix.
new_prefix - construction variable for the new prefix.
new_suffix - construction variable for the new suffix.
"""
old_prefix = self.subst('$'+old_prefix)
old_suffix = self.subst('$'+old_suffix)
new_prefix = self.subst('$'+new_prefix)
new_suffix = self.subst('$'+new_suffix)
dir,name = os.path.split(str(path))
if name[:len(old_prefix)] == old_prefix:
name = name[len(old_prefix):]
if name[-len(old_suffix):] == old_suffix:
name = name[:-len(old_suffix)]
return os.path.join(dir, new_prefix+name+new_suffix) | python | def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix):
old_prefix = self.subst('$'+old_prefix)
old_suffix = self.subst('$'+old_suffix)
new_prefix = self.subst('$'+new_prefix)
new_suffix = self.subst('$'+new_suffix)
dir,name = os.path.split(str(path))
if name[:len(old_prefix)] == old_prefix:
name = name[len(old_prefix):]
if name[-len(old_suffix):] == old_suffix:
name = name[:-len(old_suffix)]
return os.path.join(dir, new_prefix+name+new_suffix) | [
"def",
"ReplaceIxes",
"(",
"self",
",",
"path",
",",
"old_prefix",
",",
"old_suffix",
",",
"new_prefix",
",",
"new_suffix",
")",
":",
"old_prefix",
"=",
"self",
".",
"subst",
"(",
"'$'",
"+",
"old_prefix",
")",
"old_suffix",
"=",
"self",
".",
"subst",
"(... | Replace old_prefix with new_prefix and old_suffix with new_suffix.
env - Environment used to interpolate variables.
path - the path that will be modified.
old_prefix - construction variable for the old prefix.
old_suffix - construction variable for the old suffix.
new_prefix - construction variable for the new prefix.
new_suffix - construction variable for the new suffix. | [
"Replace",
"old_prefix",
"with",
"new_prefix",
"and",
"old_suffix",
"with",
"new_suffix",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1749-L1771 |
23,171 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.WhereIs | def WhereIs(self, prog, path=None, pathext=None, reject=[]):
"""Find prog in the path.
"""
if path is None:
try:
path = self['ENV']['PATH']
except KeyError:
pass
elif SCons.Util.is_String(path):
path = self.subst(path)
if pathext is None:
try:
pathext = self['ENV']['PATHEXT']
except KeyError:
pass
elif SCons.Util.is_String(pathext):
pathext = self.subst(pathext)
prog = SCons.Util.CLVar(self.subst(prog)) # support "program --with-args"
path = SCons.Util.WhereIs(prog[0], path, pathext, reject)
if path: return path
return None | python | def WhereIs(self, prog, path=None, pathext=None, reject=[]):
if path is None:
try:
path = self['ENV']['PATH']
except KeyError:
pass
elif SCons.Util.is_String(path):
path = self.subst(path)
if pathext is None:
try:
pathext = self['ENV']['PATHEXT']
except KeyError:
pass
elif SCons.Util.is_String(pathext):
pathext = self.subst(pathext)
prog = SCons.Util.CLVar(self.subst(prog)) # support "program --with-args"
path = SCons.Util.WhereIs(prog[0], path, pathext, reject)
if path: return path
return None | [
"def",
"WhereIs",
"(",
"self",
",",
"prog",
",",
"path",
"=",
"None",
",",
"pathext",
"=",
"None",
",",
"reject",
"=",
"[",
"]",
")",
":",
"if",
"path",
"is",
"None",
":",
"try",
":",
"path",
"=",
"self",
"[",
"'ENV'",
"]",
"[",
"'PATH'",
"]",
... | Find prog in the path. | [
"Find",
"prog",
"in",
"the",
"path",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1791-L1811 |
23,172 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Command | def Command(self, target, source, action, **kw):
"""Builds the supplied target files from the supplied
source files using the supplied action. Action may
be any type that the Builder constructor will accept
for an action."""
bkw = {
'action' : action,
'target_factory' : self.fs.Entry,
'source_factory' : self.fs.Entry,
}
try: bkw['source_scanner'] = kw['source_scanner']
except KeyError: pass
else: del kw['source_scanner']
bld = SCons.Builder.Builder(**bkw)
return bld(self, target, source, **kw) | python | def Command(self, target, source, action, **kw):
bkw = {
'action' : action,
'target_factory' : self.fs.Entry,
'source_factory' : self.fs.Entry,
}
try: bkw['source_scanner'] = kw['source_scanner']
except KeyError: pass
else: del kw['source_scanner']
bld = SCons.Builder.Builder(**bkw)
return bld(self, target, source, **kw) | [
"def",
"Command",
"(",
"self",
",",
"target",
",",
"source",
",",
"action",
",",
"*",
"*",
"kw",
")",
":",
"bkw",
"=",
"{",
"'action'",
":",
"action",
",",
"'target_factory'",
":",
"self",
".",
"fs",
".",
"Entry",
",",
"'source_factory'",
":",
"self"... | Builds the supplied target files from the supplied
source files using the supplied action. Action may
be any type that the Builder constructor will accept
for an action. | [
"Builds",
"the",
"supplied",
"target",
"files",
"from",
"the",
"supplied",
"source",
"files",
"using",
"the",
"supplied",
"action",
".",
"Action",
"may",
"be",
"any",
"type",
"that",
"the",
"Builder",
"constructor",
"will",
"accept",
"for",
"an",
"action",
"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1951-L1965 |
23,173 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Depends | def Depends(self, target, dependency):
"""Explicity specify that 'target's depend on 'dependency'."""
tlist = self.arg2nodes(target, self.fs.Entry)
dlist = self.arg2nodes(dependency, self.fs.Entry)
for t in tlist:
t.add_dependency(dlist)
return tlist | python | def Depends(self, target, dependency):
tlist = self.arg2nodes(target, self.fs.Entry)
dlist = self.arg2nodes(dependency, self.fs.Entry)
for t in tlist:
t.add_dependency(dlist)
return tlist | [
"def",
"Depends",
"(",
"self",
",",
"target",
",",
"dependency",
")",
":",
"tlist",
"=",
"self",
".",
"arg2nodes",
"(",
"target",
",",
"self",
".",
"fs",
".",
"Entry",
")",
"dlist",
"=",
"self",
".",
"arg2nodes",
"(",
"dependency",
",",
"self",
".",
... | Explicity specify that 'target's depend on 'dependency'. | [
"Explicity",
"specify",
"that",
"target",
"s",
"depend",
"on",
"dependency",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1967-L1973 |
23,174 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.NoClean | def NoClean(self, *targets):
"""Tags a target so that it will not be cleaned by -c"""
tlist = []
for t in targets:
tlist.extend(self.arg2nodes(t, self.fs.Entry))
for t in tlist:
t.set_noclean()
return tlist | python | def NoClean(self, *targets):
tlist = []
for t in targets:
tlist.extend(self.arg2nodes(t, self.fs.Entry))
for t in tlist:
t.set_noclean()
return tlist | [
"def",
"NoClean",
"(",
"self",
",",
"*",
"targets",
")",
":",
"tlist",
"=",
"[",
"]",
"for",
"t",
"in",
"targets",
":",
"tlist",
".",
"extend",
"(",
"self",
".",
"arg2nodes",
"(",
"t",
",",
"self",
".",
"fs",
".",
"Entry",
")",
")",
"for",
"t",... | Tags a target so that it will not be cleaned by -c | [
"Tags",
"a",
"target",
"so",
"that",
"it",
"will",
"not",
"be",
"cleaned",
"by",
"-",
"c"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L1995-L2002 |
23,175 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.NoCache | def NoCache(self, *targets):
"""Tags a target so that it will not be cached"""
tlist = []
for t in targets:
tlist.extend(self.arg2nodes(t, self.fs.Entry))
for t in tlist:
t.set_nocache()
return tlist | python | def NoCache(self, *targets):
tlist = []
for t in targets:
tlist.extend(self.arg2nodes(t, self.fs.Entry))
for t in tlist:
t.set_nocache()
return tlist | [
"def",
"NoCache",
"(",
"self",
",",
"*",
"targets",
")",
":",
"tlist",
"=",
"[",
"]",
"for",
"t",
"in",
"targets",
":",
"tlist",
".",
"extend",
"(",
"self",
".",
"arg2nodes",
"(",
"t",
",",
"self",
".",
"fs",
".",
"Entry",
")",
")",
"for",
"t",... | Tags a target so that it will not be cached | [
"Tags",
"a",
"target",
"so",
"that",
"it",
"will",
"not",
"be",
"cached"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2004-L2011 |
23,176 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Execute | def Execute(self, action, *args, **kw):
"""Directly execute an action through an Environment
"""
action = self.Action(action, *args, **kw)
result = action([], [], self)
if isinstance(result, SCons.Errors.BuildError):
errstr = result.errstr
if result.filename:
errstr = result.filename + ': ' + errstr
sys.stderr.write("scons: *** %s\n" % errstr)
return result.status
else:
return result | python | def Execute(self, action, *args, **kw):
action = self.Action(action, *args, **kw)
result = action([], [], self)
if isinstance(result, SCons.Errors.BuildError):
errstr = result.errstr
if result.filename:
errstr = result.filename + ': ' + errstr
sys.stderr.write("scons: *** %s\n" % errstr)
return result.status
else:
return result | [
"def",
"Execute",
"(",
"self",
",",
"action",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"action",
"=",
"self",
".",
"Action",
"(",
"action",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"result",
"=",
"action",
"(",
"[",
"]",
",",
"[",
... | Directly execute an action through an Environment | [
"Directly",
"execute",
"an",
"action",
"through",
"an",
"Environment"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2027-L2039 |
23,177 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Ignore | def Ignore(self, target, dependency):
"""Ignore a dependency."""
tlist = self.arg2nodes(target, self.fs.Entry)
dlist = self.arg2nodes(dependency, self.fs.Entry)
for t in tlist:
t.add_ignore(dlist)
return tlist | python | def Ignore(self, target, dependency):
tlist = self.arg2nodes(target, self.fs.Entry)
dlist = self.arg2nodes(dependency, self.fs.Entry)
for t in tlist:
t.add_ignore(dlist)
return tlist | [
"def",
"Ignore",
"(",
"self",
",",
"target",
",",
"dependency",
")",
":",
"tlist",
"=",
"self",
".",
"arg2nodes",
"(",
"target",
",",
"self",
".",
"fs",
".",
"Entry",
")",
"dlist",
"=",
"self",
".",
"arg2nodes",
"(",
"dependency",
",",
"self",
".",
... | Ignore a dependency. | [
"Ignore",
"a",
"dependency",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2070-L2076 |
23,178 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.SideEffect | def SideEffect(self, side_effect, target):
"""Tell scons that side_effects are built as side
effects of building targets."""
side_effects = self.arg2nodes(side_effect, self.fs.Entry)
targets = self.arg2nodes(target, self.fs.Entry)
for side_effect in side_effects:
if side_effect.multiple_side_effect_has_builder():
raise SCons.Errors.UserError("Multiple ways to build the same target were specified for: %s" % str(side_effect))
side_effect.add_source(targets)
side_effect.side_effect = 1
self.Precious(side_effect)
for target in targets:
target.side_effects.append(side_effect)
return side_effects | python | def SideEffect(self, side_effect, target):
side_effects = self.arg2nodes(side_effect, self.fs.Entry)
targets = self.arg2nodes(target, self.fs.Entry)
for side_effect in side_effects:
if side_effect.multiple_side_effect_has_builder():
raise SCons.Errors.UserError("Multiple ways to build the same target were specified for: %s" % str(side_effect))
side_effect.add_source(targets)
side_effect.side_effect = 1
self.Precious(side_effect)
for target in targets:
target.side_effects.append(side_effect)
return side_effects | [
"def",
"SideEffect",
"(",
"self",
",",
"side_effect",
",",
"target",
")",
":",
"side_effects",
"=",
"self",
".",
"arg2nodes",
"(",
"side_effect",
",",
"self",
".",
"fs",
".",
"Entry",
")",
"targets",
"=",
"self",
".",
"arg2nodes",
"(",
"target",
",",
"... | Tell scons that side_effects are built as side
effects of building targets. | [
"Tell",
"scons",
"that",
"side_effects",
"are",
"built",
"as",
"side",
"effects",
"of",
"building",
"targets",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2144-L2158 |
23,179 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.Split | def Split(self, arg):
"""This function converts a string or list into a list of strings
or Nodes. This makes things easier for users by allowing files to
be specified as a white-space separated list to be split.
The input rules are:
- A single string containing names separated by spaces. These will be
split apart at the spaces.
- A single Node instance
- A list containing either strings or Node instances. Any strings
in the list are not split at spaces.
In all cases, the function returns a list of Nodes and strings."""
if SCons.Util.is_List(arg):
return list(map(self.subst, arg))
elif SCons.Util.is_String(arg):
return self.subst(arg).split()
else:
return [self.subst(arg)] | python | def Split(self, arg):
if SCons.Util.is_List(arg):
return list(map(self.subst, arg))
elif SCons.Util.is_String(arg):
return self.subst(arg).split()
else:
return [self.subst(arg)] | [
"def",
"Split",
"(",
"self",
",",
"arg",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"arg",
")",
":",
"return",
"list",
"(",
"map",
"(",
"self",
".",
"subst",
",",
"arg",
")",
")",
"elif",
"SCons",
".",
"Util",
".",
"is_String",
... | This function converts a string or list into a list of strings
or Nodes. This makes things easier for users by allowing files to
be specified as a white-space separated list to be split.
The input rules are:
- A single string containing names separated by spaces. These will be
split apart at the spaces.
- A single Node instance
- A list containing either strings or Node instances. Any strings
in the list are not split at spaces.
In all cases, the function returns a list of Nodes and strings. | [
"This",
"function",
"converts",
"a",
"string",
"or",
"list",
"into",
"a",
"list",
"of",
"strings",
"or",
"Nodes",
".",
"This",
"makes",
"things",
"easier",
"for",
"users",
"by",
"allowing",
"files",
"to",
"be",
"specified",
"as",
"a",
"white",
"-",
"spac... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2188-L2207 |
23,180 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.FindSourceFiles | def FindSourceFiles(self, node='.'):
""" returns a list of all source files.
"""
node = self.arg2nodes(node, self.fs.Entry)[0]
sources = []
def build_source(ss):
for s in ss:
if isinstance(s, SCons.Node.FS.Dir):
build_source(s.all_children())
elif s.has_builder():
build_source(s.sources)
elif isinstance(s.disambiguate(), SCons.Node.FS.File):
sources.append(s)
build_source(node.all_children())
def final_source(node):
while (node != node.srcnode()):
node = node.srcnode()
return node
sources = list(map( final_source, sources ));
# remove duplicates
return list(set(sources)) | python | def FindSourceFiles(self, node='.'):
node = self.arg2nodes(node, self.fs.Entry)[0]
sources = []
def build_source(ss):
for s in ss:
if isinstance(s, SCons.Node.FS.Dir):
build_source(s.all_children())
elif s.has_builder():
build_source(s.sources)
elif isinstance(s.disambiguate(), SCons.Node.FS.File):
sources.append(s)
build_source(node.all_children())
def final_source(node):
while (node != node.srcnode()):
node = node.srcnode()
return node
sources = list(map( final_source, sources ));
# remove duplicates
return list(set(sources)) | [
"def",
"FindSourceFiles",
"(",
"self",
",",
"node",
"=",
"'.'",
")",
":",
"node",
"=",
"self",
".",
"arg2nodes",
"(",
"node",
",",
"self",
".",
"fs",
".",
"Entry",
")",
"[",
"0",
"]",
"sources",
"=",
"[",
"]",
"def",
"build_source",
"(",
"ss",
")... | returns a list of all source files. | [
"returns",
"a",
"list",
"of",
"all",
"source",
"files",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2241-L2263 |
23,181 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | Base.FindInstalledFiles | def FindInstalledFiles(self):
""" returns the list of all targets of the Install and InstallAs Builder.
"""
from SCons.Tool import install
if install._UNIQUE_INSTALLED_FILES is None:
install._UNIQUE_INSTALLED_FILES = SCons.Util.uniquer_hashables(install._INSTALLED_FILES)
return install._UNIQUE_INSTALLED_FILES | python | def FindInstalledFiles(self):
from SCons.Tool import install
if install._UNIQUE_INSTALLED_FILES is None:
install._UNIQUE_INSTALLED_FILES = SCons.Util.uniquer_hashables(install._INSTALLED_FILES)
return install._UNIQUE_INSTALLED_FILES | [
"def",
"FindInstalledFiles",
"(",
"self",
")",
":",
"from",
"SCons",
".",
"Tool",
"import",
"install",
"if",
"install",
".",
"_UNIQUE_INSTALLED_FILES",
"is",
"None",
":",
"install",
".",
"_UNIQUE_INSTALLED_FILES",
"=",
"SCons",
".",
"Util",
".",
"uniquer_hashabl... | returns the list of all targets of the Install and InstallAs Builder. | [
"returns",
"the",
"list",
"of",
"all",
"targets",
"of",
"the",
"Install",
"and",
"InstallAs",
"Builder",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L2265-L2271 |
23,182 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/pdflatex.py | generate | def generate(env):
"""Add Builders and construction variables for pdflatex to an Environment."""
global PDFLaTeXAction
if PDFLaTeXAction is None:
PDFLaTeXAction = SCons.Action.Action('$PDFLATEXCOM', '$PDFLATEXCOMSTR')
global PDFLaTeXAuxAction
if PDFLaTeXAuxAction is None:
PDFLaTeXAuxAction = SCons.Action.Action(PDFLaTeXAuxFunction,
strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ltx', PDFLaTeXAuxAction)
bld.add_action('.latex', PDFLaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_pdf_emitter)
bld.add_emitter('.latex', SCons.Tool.tex.tex_pdf_emitter)
SCons.Tool.tex.generate_common(env) | python | def generate(env):
global PDFLaTeXAction
if PDFLaTeXAction is None:
PDFLaTeXAction = SCons.Action.Action('$PDFLATEXCOM', '$PDFLATEXCOMSTR')
global PDFLaTeXAuxAction
if PDFLaTeXAuxAction is None:
PDFLaTeXAuxAction = SCons.Action.Action(PDFLaTeXAuxFunction,
strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ltx', PDFLaTeXAuxAction)
bld.add_action('.latex', PDFLaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_pdf_emitter)
bld.add_emitter('.latex', SCons.Tool.tex.tex_pdf_emitter)
SCons.Tool.tex.generate_common(env) | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"PDFLaTeXAction",
"if",
"PDFLaTeXAction",
"is",
"None",
":",
"PDFLaTeXAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$PDFLATEXCOM'",
",",
"'$PDFLATEXCOMSTR'",
")",
"global",
"PDFLaTeXAuxAction",
"if... | Add Builders and construction variables for pdflatex to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"pdflatex",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/pdflatex.py#L52-L74 |
23,183 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py | installShlibLinks | def installShlibLinks(dest, source, env):
"""If we are installing a versioned shared library create the required links."""
Verbose = False
symlinks = listShlibLinksToInstall(dest, source, env)
if Verbose:
print('installShlibLinks: symlinks={:r}'.format(SCons.Tool.StringizeLibSymlinks(symlinks)))
if symlinks:
SCons.Tool.CreateLibSymlinks(env, symlinks)
return | python | def installShlibLinks(dest, source, env):
Verbose = False
symlinks = listShlibLinksToInstall(dest, source, env)
if Verbose:
print('installShlibLinks: symlinks={:r}'.format(SCons.Tool.StringizeLibSymlinks(symlinks)))
if symlinks:
SCons.Tool.CreateLibSymlinks(env, symlinks)
return | [
"def",
"installShlibLinks",
"(",
"dest",
",",
"source",
",",
"env",
")",
":",
"Verbose",
"=",
"False",
"symlinks",
"=",
"listShlibLinksToInstall",
"(",
"dest",
",",
"source",
",",
"env",
")",
"if",
"Verbose",
":",
"print",
"(",
"'installShlibLinks: symlinks={:... | If we are installing a versioned shared library create the required links. | [
"If",
"we",
"are",
"installing",
"a",
"versioned",
"shared",
"library",
"create",
"the",
"required",
"links",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py#L165-L173 |
23,184 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py | installFunc | def installFunc(target, source, env):
"""Install a source file into a target using the function specified
as the INSTALL construction variable."""
try:
install = env['INSTALL']
except KeyError:
raise SCons.Errors.UserError('Missing INSTALL construction variable.')
assert len(target)==len(source), \
"Installing source %s into target %s: target and source lists must have same length."%(list(map(str, source)), list(map(str, target)))
for t,s in zip(target,source):
if install(t.get_path(),s.get_path(),env):
return 1
return 0 | python | def installFunc(target, source, env):
try:
install = env['INSTALL']
except KeyError:
raise SCons.Errors.UserError('Missing INSTALL construction variable.')
assert len(target)==len(source), \
"Installing source %s into target %s: target and source lists must have same length."%(list(map(str, source)), list(map(str, target)))
for t,s in zip(target,source):
if install(t.get_path(),s.get_path(),env):
return 1
return 0 | [
"def",
"installFunc",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"try",
":",
"install",
"=",
"env",
"[",
"'INSTALL'",
"]",
"except",
"KeyError",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"'Missing INSTALL construction variable.'",
... | Install a source file into a target using the function specified
as the INSTALL construction variable. | [
"Install",
"a",
"source",
"file",
"into",
"a",
"target",
"using",
"the",
"function",
"specified",
"as",
"the",
"INSTALL",
"construction",
"variable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py#L175-L189 |
23,185 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py | installFuncVersionedLib | def installFuncVersionedLib(target, source, env):
"""Install a versioned library into a target using the function specified
as the INSTALLVERSIONEDLIB construction variable."""
try:
install = env['INSTALLVERSIONEDLIB']
except KeyError:
raise SCons.Errors.UserError('Missing INSTALLVERSIONEDLIB construction variable.')
assert len(target)==len(source), \
"Installing source %s into target %s: target and source lists must have same length."%(list(map(str, source)), list(map(str, target)))
for t,s in zip(target,source):
if hasattr(t.attributes, 'shlibname'):
tpath = os.path.join(t.get_dir(), t.attributes.shlibname)
else:
tpath = t.get_path()
if install(tpath,s.get_path(),env):
return 1
return 0 | python | def installFuncVersionedLib(target, source, env):
try:
install = env['INSTALLVERSIONEDLIB']
except KeyError:
raise SCons.Errors.UserError('Missing INSTALLVERSIONEDLIB construction variable.')
assert len(target)==len(source), \
"Installing source %s into target %s: target and source lists must have same length."%(list(map(str, source)), list(map(str, target)))
for t,s in zip(target,source):
if hasattr(t.attributes, 'shlibname'):
tpath = os.path.join(t.get_dir(), t.attributes.shlibname)
else:
tpath = t.get_path()
if install(tpath,s.get_path(),env):
return 1
return 0 | [
"def",
"installFuncVersionedLib",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"try",
":",
"install",
"=",
"env",
"[",
"'INSTALLVERSIONEDLIB'",
"]",
"except",
"KeyError",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"'Missing INSTALLVERS... | Install a versioned library into a target using the function specified
as the INSTALLVERSIONEDLIB construction variable. | [
"Install",
"a",
"versioned",
"library",
"into",
"a",
"target",
"using",
"the",
"function",
"specified",
"as",
"the",
"INSTALLVERSIONEDLIB",
"construction",
"variable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py#L191-L209 |
23,186 | iotile/coretools | iotilecore/iotile/core/hw/update/records/send_rpc.py | SendErrorCheckingRPCRecord.parse_multiple_rpcs | def parse_multiple_rpcs(cls, record_data):
"""Parse record_data into multiple error checking rpcs."""
rpcs = []
while len(record_data) > 0:
total_length, record_type = struct.unpack_from("<LB3x", record_data)
if record_type != SendErrorCheckingRPCRecord.RecordType:
raise ArgumentError("Record set contains a record that is not an error checking RPC",
record_type=record_type)
record_contents = record_data[8: total_length]
parsed_rpc = cls._parse_rpc_info(record_contents)
rpcs.append(parsed_rpc)
record_data = record_data[total_length:]
return rpcs | python | def parse_multiple_rpcs(cls, record_data):
rpcs = []
while len(record_data) > 0:
total_length, record_type = struct.unpack_from("<LB3x", record_data)
if record_type != SendErrorCheckingRPCRecord.RecordType:
raise ArgumentError("Record set contains a record that is not an error checking RPC",
record_type=record_type)
record_contents = record_data[8: total_length]
parsed_rpc = cls._parse_rpc_info(record_contents)
rpcs.append(parsed_rpc)
record_data = record_data[total_length:]
return rpcs | [
"def",
"parse_multiple_rpcs",
"(",
"cls",
",",
"record_data",
")",
":",
"rpcs",
"=",
"[",
"]",
"while",
"len",
"(",
"record_data",
")",
">",
"0",
":",
"total_length",
",",
"record_type",
"=",
"struct",
".",
"unpack_from",
"(",
"\"<LB3x\"",
",",
"record_dat... | Parse record_data into multiple error checking rpcs. | [
"Parse",
"record_data",
"into",
"multiple",
"error",
"checking",
"rpcs",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/records/send_rpc.py#L195-L212 |
23,187 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/clang.py | generate | def generate(env):
"""Add Builders and construction variables for clang to an Environment."""
SCons.Tool.cc.generate(env)
env['CC'] = env.Detect(compilers) or 'clang'
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
else:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC')
# determine compiler version
if env['CC']:
#pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'],
pipe = SCons.Action._subproc(env, [env['CC'], '--version'],
stdin='devnull',
stderr='devnull',
stdout=subprocess.PIPE)
if pipe.wait() != 0: return
# clang -dumpversion is of no use
line = pipe.stdout.readline()
if sys.version_info[0] > 2:
line = line.decode()
match = re.search(r'clang +version +([0-9]+(?:\.[0-9]+)+)', line)
if match:
env['CCVERSION'] = match.group(1) | python | def generate(env):
SCons.Tool.cc.generate(env)
env['CC'] = env.Detect(compilers) or 'clang'
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
else:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC')
# determine compiler version
if env['CC']:
#pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'],
pipe = SCons.Action._subproc(env, [env['CC'], '--version'],
stdin='devnull',
stderr='devnull',
stdout=subprocess.PIPE)
if pipe.wait() != 0: return
# clang -dumpversion is of no use
line = pipe.stdout.readline()
if sys.version_info[0] > 2:
line = line.decode()
match = re.search(r'clang +version +([0-9]+(?:\.[0-9]+)+)', line)
if match:
env['CCVERSION'] = match.group(1) | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"cc",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'CC'",
"]",
"=",
"env",
".",
"Detect",
"(",
"compilers",
")",
"or",
"'clang'",
"if",
"env",
"[",
"'PLATFORM'",
"]",
"in",
"["... | Add Builders and construction variables for clang to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"clang",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/clang.py#L51-L74 |
23,188 | iotile/coretools | iotilecore/iotile/core/utilities/stoppable_thread.py | StoppableWorkerThread.wait_running | def wait_running(self, timeout=None):
"""Wait for the thread to pass control to its routine.
Args:
timeout (float): The maximum amount of time to wait
"""
flag = self._running.wait(timeout)
if flag is False:
raise TimeoutExpiredError("Timeout waiting for thread to start running") | python | def wait_running(self, timeout=None):
flag = self._running.wait(timeout)
if flag is False:
raise TimeoutExpiredError("Timeout waiting for thread to start running") | [
"def",
"wait_running",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"flag",
"=",
"self",
".",
"_running",
".",
"wait",
"(",
"timeout",
")",
"if",
"flag",
"is",
"False",
":",
"raise",
"TimeoutExpiredError",
"(",
"\"Timeout waiting for thread to start run... | Wait for the thread to pass control to its routine.
Args:
timeout (float): The maximum amount of time to wait | [
"Wait",
"for",
"the",
"thread",
"to",
"pass",
"control",
"to",
"its",
"routine",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/stoppable_thread.py#L120-L130 |
23,189 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.create_event | def create_event(self, register=False):
"""Create an asyncio.Event inside the emulation loop.
This method exists as a convenience to create an Event object that is
associated with the correct EventLoop(). If you pass register=True,
then the event will be registered as an event that must be set for the
EmulationLoop to be considered idle. This means that whenever
wait_idle() is called, it will block until this event is set.
Examples of when you may want this behavior is when the event is
signaling whether a tile has completed restarting itself. The reset()
rpc cannot block until the tile has initialized since it may need to
send its own rpcs as part of the initialization process. However, we
want to retain the behavior that once the reset() rpc returns the tile
has been completely reset.
The cleanest way of achieving this is to have the tile set its
self.initialized Event when it has finished rebooting and register
that event so that wait_idle() nicely blocks until the reset process
is complete.
Args:
register (bool): Whether to register the event so that wait_idle
blocks until it is set.
Returns:
asyncio.Event: The Event object.
"""
event = asyncio.Event(loop=self._loop)
if register:
self._events.add(event)
return event | python | def create_event(self, register=False):
event = asyncio.Event(loop=self._loop)
if register:
self._events.add(event)
return event | [
"def",
"create_event",
"(",
"self",
",",
"register",
"=",
"False",
")",
":",
"event",
"=",
"asyncio",
".",
"Event",
"(",
"loop",
"=",
"self",
".",
"_loop",
")",
"if",
"register",
":",
"self",
".",
"_events",
".",
"add",
"(",
"event",
")",
"return",
... | Create an asyncio.Event inside the emulation loop.
This method exists as a convenience to create an Event object that is
associated with the correct EventLoop(). If you pass register=True,
then the event will be registered as an event that must be set for the
EmulationLoop to be considered idle. This means that whenever
wait_idle() is called, it will block until this event is set.
Examples of when you may want this behavior is when the event is
signaling whether a tile has completed restarting itself. The reset()
rpc cannot block until the tile has initialized since it may need to
send its own rpcs as part of the initialization process. However, we
want to retain the behavior that once the reset() rpc returns the tile
has been completely reset.
The cleanest way of achieving this is to have the tile set its
self.initialized Event when it has finished rebooting and register
that event so that wait_idle() nicely blocks until the reset process
is complete.
Args:
register (bool): Whether to register the event so that wait_idle
blocks until it is set.
Returns:
asyncio.Event: The Event object. | [
"Create",
"an",
"asyncio",
".",
"Event",
"inside",
"the",
"emulation",
"loop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L70-L103 |
23,190 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.create_queue | def create_queue(self, register=False):
"""Create a new work queue and optionally register it.
This will make sure the queue is attached to the correct event loop.
You can optionally choose to automatically register it so that
wait_idle() will block until the queue is empty.
Args:
register (bool): Whether to call register_workqueue() automatically.
Returns:
asyncio.Queue: The newly created queue.
"""
queue = asyncio.Queue(loop=self._loop)
if register:
self._work_queues.add(queue)
return queue | python | def create_queue(self, register=False):
queue = asyncio.Queue(loop=self._loop)
if register:
self._work_queues.add(queue)
return queue | [
"def",
"create_queue",
"(",
"self",
",",
"register",
"=",
"False",
")",
":",
"queue",
"=",
"asyncio",
".",
"Queue",
"(",
"loop",
"=",
"self",
".",
"_loop",
")",
"if",
"register",
":",
"self",
".",
"_work_queues",
".",
"add",
"(",
"queue",
")",
"retur... | Create a new work queue and optionally register it.
This will make sure the queue is attached to the correct event loop.
You can optionally choose to automatically register it so that
wait_idle() will block until the queue is empty.
Args:
register (bool): Whether to call register_workqueue() automatically.
Returns:
asyncio.Queue: The newly created queue. | [
"Create",
"a",
"new",
"work",
"queue",
"and",
"optionally",
"register",
"it",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L105-L123 |
23,191 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.start | def start(self):
"""Start the background emulation loop."""
if self._started is True:
raise ArgumentError("EmulationLoop.start() called multiple times")
self._thread = threading.Thread(target=self._loop_thread_main)
self._thread.start()
self._started = True | python | def start(self):
if self._started is True:
raise ArgumentError("EmulationLoop.start() called multiple times")
self._thread = threading.Thread(target=self._loop_thread_main)
self._thread.start()
self._started = True | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_started",
"is",
"True",
":",
"raise",
"ArgumentError",
"(",
"\"EmulationLoop.start() called multiple times\"",
")",
"self",
".",
"_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",... | Start the background emulation loop. | [
"Start",
"the",
"background",
"emulation",
"loop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L189-L197 |
23,192 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.stop | def stop(self):
"""Stop the background emulation loop."""
if self._started is False:
raise ArgumentError("EmulationLoop.stop() called without calling start()")
self.verify_calling_thread(False, "Cannot call EmulationLoop.stop() from inside the event loop")
if self._thread.is_alive():
self._loop.call_soon_threadsafe(self._loop.create_task, self._clean_shutdown())
self._thread.join() | python | def stop(self):
if self._started is False:
raise ArgumentError("EmulationLoop.stop() called without calling start()")
self.verify_calling_thread(False, "Cannot call EmulationLoop.stop() from inside the event loop")
if self._thread.is_alive():
self._loop.call_soon_threadsafe(self._loop.create_task, self._clean_shutdown())
self._thread.join() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_started",
"is",
"False",
":",
"raise",
"ArgumentError",
"(",
"\"EmulationLoop.stop() called without calling start()\"",
")",
"self",
".",
"verify_calling_thread",
"(",
"False",
",",
"\"Cannot call EmulationLoo... | Stop the background emulation loop. | [
"Stop",
"the",
"background",
"emulation",
"loop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L199-L209 |
23,193 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.wait_idle | def wait_idle(self, timeout=1.0):
"""Wait until the rpc queue is empty.
This method may be called either from within the event loop or from
outside of it. If it is called outside of the event loop it will
block the calling thread until the rpc queue is temporarily empty.
If it is called from within the event loop it will return an awaitable
object that can be used to wait for the same condition.
The awaitable object will already have a timeout if the timeout
parameter is passed.
Args:
timeout (float): The maximum number of seconds to wait.
"""
async def _awaiter():
background_work = {x.join() for x in self._work_queues}
for event in self._events:
if not event.is_set():
background_work.add(event.wait())
_done, pending = await asyncio.wait(background_work, timeout=timeout)
if len(pending) > 0:
raise TimeoutExpiredError("Timeout waiting for event loop to become idle", pending=pending)
if self._on_emulation_thread():
return asyncio.wait_for(_awaiter(), timeout=timeout)
self.run_task_external(_awaiter())
return None | python | def wait_idle(self, timeout=1.0):
async def _awaiter():
background_work = {x.join() for x in self._work_queues}
for event in self._events:
if not event.is_set():
background_work.add(event.wait())
_done, pending = await asyncio.wait(background_work, timeout=timeout)
if len(pending) > 0:
raise TimeoutExpiredError("Timeout waiting for event loop to become idle", pending=pending)
if self._on_emulation_thread():
return asyncio.wait_for(_awaiter(), timeout=timeout)
self.run_task_external(_awaiter())
return None | [
"def",
"wait_idle",
"(",
"self",
",",
"timeout",
"=",
"1.0",
")",
":",
"async",
"def",
"_awaiter",
"(",
")",
":",
"background_work",
"=",
"{",
"x",
".",
"join",
"(",
")",
"for",
"x",
"in",
"self",
".",
"_work_queues",
"}",
"for",
"event",
"in",
"se... | Wait until the rpc queue is empty.
This method may be called either from within the event loop or from
outside of it. If it is called outside of the event loop it will
block the calling thread until the rpc queue is temporarily empty.
If it is called from within the event loop it will return an awaitable
object that can be used to wait for the same condition.
The awaitable object will already have a timeout if the timeout
parameter is passed.
Args:
timeout (float): The maximum number of seconds to wait. | [
"Wait",
"until",
"the",
"rpc",
"queue",
"is",
"empty",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L211-L242 |
23,194 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.run_task_external | def run_task_external(self, coroutine):
"""Inject a task into the emulation loop and wait for it to finish.
The coroutine parameter is run as a Task inside the EmulationLoop
until it completes and the return value (or any raised Exception) is
pased back into the caller's thread.
Args:
coroutine (coroutine): The task to inject into the event loop.
Returns:
object: Whatever the coroutine returned.
"""
self.verify_calling_thread(False, 'run_task_external must not be called from the emulation thread')
future = asyncio.run_coroutine_threadsafe(coroutine, self._loop)
return future.result() | python | def run_task_external(self, coroutine):
self.verify_calling_thread(False, 'run_task_external must not be called from the emulation thread')
future = asyncio.run_coroutine_threadsafe(coroutine, self._loop)
return future.result() | [
"def",
"run_task_external",
"(",
"self",
",",
"coroutine",
")",
":",
"self",
".",
"verify_calling_thread",
"(",
"False",
",",
"'run_task_external must not be called from the emulation thread'",
")",
"future",
"=",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"coroutin... | Inject a task into the emulation loop and wait for it to finish.
The coroutine parameter is run as a Task inside the EmulationLoop
until it completes and the return value (or any raised Exception) is
pased back into the caller's thread.
Args:
coroutine (coroutine): The task to inject into the event loop.
Returns:
object: Whatever the coroutine returned. | [
"Inject",
"a",
"task",
"into",
"the",
"emulation",
"loop",
"and",
"wait",
"for",
"it",
"to",
"finish",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L244-L261 |
23,195 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.call_rpc_external | def call_rpc_external(self, address, rpc_id, arg_payload, timeout=10.0):
"""Call an RPC from outside of the event loop and block until it finishes.
This is the main method by which a caller outside of the EmulationLoop
can inject an RPC into the EmulationLoop and wait for it to complete.
This method is synchronous so it blocks until the RPC completes or the
timeout expires.
Args:
address (int): The address of the mock tile this RPC is for
rpc_id (int): The number of the RPC
payload (bytes): A byte string of payload parameters up to 20 bytes
timeout (float): The maximum time to wait for the RPC to finish.
Returns:
bytes: The response payload from the RPC
"""
self.verify_calling_thread(False, "call_rpc_external is for use **outside** of the event loop")
response = CrossThreadResponse()
self._loop.call_soon_threadsafe(self._rpc_queue.put_rpc, address, rpc_id, arg_payload, response)
try:
return response.wait(timeout)
except RPCRuntimeError as err:
return err.binary_error | python | def call_rpc_external(self, address, rpc_id, arg_payload, timeout=10.0):
self.verify_calling_thread(False, "call_rpc_external is for use **outside** of the event loop")
response = CrossThreadResponse()
self._loop.call_soon_threadsafe(self._rpc_queue.put_rpc, address, rpc_id, arg_payload, response)
try:
return response.wait(timeout)
except RPCRuntimeError as err:
return err.binary_error | [
"def",
"call_rpc_external",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"arg_payload",
",",
"timeout",
"=",
"10.0",
")",
":",
"self",
".",
"verify_calling_thread",
"(",
"False",
",",
"\"call_rpc_external is for use **outside** of the event loop\"",
")",
"response... | Call an RPC from outside of the event loop and block until it finishes.
This is the main method by which a caller outside of the EmulationLoop
can inject an RPC into the EmulationLoop and wait for it to complete.
This method is synchronous so it blocks until the RPC completes or the
timeout expires.
Args:
address (int): The address of the mock tile this RPC is for
rpc_id (int): The number of the RPC
payload (bytes): A byte string of payload parameters up to 20 bytes
timeout (float): The maximum time to wait for the RPC to finish.
Returns:
bytes: The response payload from the RPC | [
"Call",
"an",
"RPC",
"from",
"outside",
"of",
"the",
"event",
"loop",
"and",
"block",
"until",
"it",
"finishes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L263-L290 |
23,196 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.await_rpc | async def await_rpc(self, address, rpc_id, *args, **kwargs):
"""Send an RPC from inside the EmulationLoop.
This is the primary method by which tasks running inside the
EmulationLoop dispatch RPCs. The RPC is added to the queue of waiting
RPCs to be drained by the RPC dispatch task and this coroutine will
block until it finishes.
**This method must only be called from inside the EmulationLoop**
Args:
address (int): The address of the tile that has the RPC.
rpc_id (int): The 16-bit id of the rpc we want to call
*args: Any required arguments for the RPC as python objects.
**kwargs: Only two keyword arguments are supported:
- arg_format: A format specifier for the argument list
- result_format: A format specifier for the result
Returns:
list: A list of the decoded response members from the RPC.
"""
self.verify_calling_thread(True, "await_rpc must be called from **inside** the event loop")
if isinstance(rpc_id, RPCDeclaration):
arg_format = rpc_id.arg_format
resp_format = rpc_id.resp_format
rpc_id = rpc_id.rpc_id
else:
arg_format = kwargs.get('arg_format', None)
resp_format = kwargs.get('resp_format', None)
arg_payload = b''
if arg_format is not None:
arg_payload = pack_rpc_payload(arg_format, args)
self._logger.debug("Sending rpc to %d:%04X, payload=%s", address, rpc_id, args)
response = AwaitableResponse()
self._rpc_queue.put_rpc(address, rpc_id, arg_payload, response)
try:
resp_payload = await response.wait(1.0)
except RPCRuntimeError as err:
resp_payload = err.binary_error
if resp_format is None:
return []
resp = unpack_rpc_payload(resp_format, resp_payload)
return resp | python | async def await_rpc(self, address, rpc_id, *args, **kwargs):
self.verify_calling_thread(True, "await_rpc must be called from **inside** the event loop")
if isinstance(rpc_id, RPCDeclaration):
arg_format = rpc_id.arg_format
resp_format = rpc_id.resp_format
rpc_id = rpc_id.rpc_id
else:
arg_format = kwargs.get('arg_format', None)
resp_format = kwargs.get('resp_format', None)
arg_payload = b''
if arg_format is not None:
arg_payload = pack_rpc_payload(arg_format, args)
self._logger.debug("Sending rpc to %d:%04X, payload=%s", address, rpc_id, args)
response = AwaitableResponse()
self._rpc_queue.put_rpc(address, rpc_id, arg_payload, response)
try:
resp_payload = await response.wait(1.0)
except RPCRuntimeError as err:
resp_payload = err.binary_error
if resp_format is None:
return []
resp = unpack_rpc_payload(resp_format, resp_payload)
return resp | [
"async",
"def",
"await_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"verify_calling_thread",
"(",
"True",
",",
"\"await_rpc must be called from **inside** the event loop\"",
")",
"if",
"isins... | Send an RPC from inside the EmulationLoop.
This is the primary method by which tasks running inside the
EmulationLoop dispatch RPCs. The RPC is added to the queue of waiting
RPCs to be drained by the RPC dispatch task and this coroutine will
block until it finishes.
**This method must only be called from inside the EmulationLoop**
Args:
address (int): The address of the tile that has the RPC.
rpc_id (int): The 16-bit id of the rpc we want to call
*args: Any required arguments for the RPC as python objects.
**kwargs: Only two keyword arguments are supported:
- arg_format: A format specifier for the argument list
- result_format: A format specifier for the result
Returns:
list: A list of the decoded response members from the RPC. | [
"Send",
"an",
"RPC",
"from",
"inside",
"the",
"EmulationLoop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L292-L343 |
23,197 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.verify_calling_thread | def verify_calling_thread(self, should_be_emulation, message=None):
"""Verify if the calling thread is or is not the emulation thread.
This method can be called to make sure that an action is being taken
in the appropriate context such as not blocking the event loop thread
or modifying an emulate state outside of the event loop thread.
If the verification fails an InternalError exception is raised,
allowing this method to be used to protect other methods from being
called in a context that could deadlock or cause race conditions.
Args:
should_be_emulation (bool): True if this call should be taking place
on the emulation, thread, False if it must not take place on
the emulation thread.
message (str): Optional message to include when raising the exception.
Otherwise a generic message is used.
Raises:
InternalError: When called from the wrong thread.
"""
if should_be_emulation == self._on_emulation_thread():
return
if message is None:
message = "Operation performed on invalid thread"
raise InternalError(message) | python | def verify_calling_thread(self, should_be_emulation, message=None):
if should_be_emulation == self._on_emulation_thread():
return
if message is None:
message = "Operation performed on invalid thread"
raise InternalError(message) | [
"def",
"verify_calling_thread",
"(",
"self",
",",
"should_be_emulation",
",",
"message",
"=",
"None",
")",
":",
"if",
"should_be_emulation",
"==",
"self",
".",
"_on_emulation_thread",
"(",
")",
":",
"return",
"if",
"message",
"is",
"None",
":",
"message",
"=",... | Verify if the calling thread is or is not the emulation thread.
This method can be called to make sure that an action is being taken
in the appropriate context such as not blocking the event loop thread
or modifying an emulate state outside of the event loop thread.
If the verification fails an InternalError exception is raised,
allowing this method to be used to protect other methods from being
called in a context that could deadlock or cause race conditions.
Args:
should_be_emulation (bool): True if this call should be taking place
on the emulation, thread, False if it must not take place on
the emulation thread.
message (str): Optional message to include when raising the exception.
Otherwise a generic message is used.
Raises:
InternalError: When called from the wrong thread. | [
"Verify",
"if",
"the",
"calling",
"thread",
"is",
"or",
"is",
"not",
"the",
"emulation",
"thread",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L345-L373 |
23,198 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.add_task | def add_task(self, tile_address, coroutine):
"""Add a task into the event loop.
This is the main entry point for registering background tasks that are
associated with a tile. The tasks are added to the EmulationLoop and
the tile they are a part of is recorded. When the tile is reset, all
of its background tasks are canceled as part of the reset process.
If you have a task that should not be associated with any tile, you
may pass `None` for tile_address and the task will not be cancelled
when any tile is reset.
Args:
tile_address (int): The address of the tile running
the task.
coroutine (coroutine): A coroutine that will be added
to the event loop.
"""
self._loop.call_soon_threadsafe(self._add_task, tile_address, coroutine) | python | def add_task(self, tile_address, coroutine):
self._loop.call_soon_threadsafe(self._add_task, tile_address, coroutine) | [
"def",
"add_task",
"(",
"self",
",",
"tile_address",
",",
"coroutine",
")",
":",
"self",
".",
"_loop",
".",
"call_soon_threadsafe",
"(",
"self",
".",
"_add_task",
",",
"tile_address",
",",
"coroutine",
")"
] | Add a task into the event loop.
This is the main entry point for registering background tasks that are
associated with a tile. The tasks are added to the EmulationLoop and
the tile they are a part of is recorded. When the tile is reset, all
of its background tasks are canceled as part of the reset process.
If you have a task that should not be associated with any tile, you
may pass `None` for tile_address and the task will not be cancelled
when any tile is reset.
Args:
tile_address (int): The address of the tile running
the task.
coroutine (coroutine): A coroutine that will be added
to the event loop. | [
"Add",
"a",
"task",
"into",
"the",
"event",
"loop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L375-L394 |
23,199 | iotile/coretools | iotileemulate/iotile/emulate/internal/emulation_loop.py | EmulationLoop.stop_tasks | async def stop_tasks(self, address):
"""Clear all tasks pertaining to a tile.
This coroutine will synchronously cancel all running tasks that were
attached to the given tile and wait for them to stop before returning.
Args:
address (int): The address of the tile we should stop.
"""
tasks = self._tasks.get(address, [])
for task in tasks:
task.cancel()
asyncio.gather(*tasks, return_exceptions=True)
self._tasks[address] = [] | python | async def stop_tasks(self, address):
tasks = self._tasks.get(address, [])
for task in tasks:
task.cancel()
asyncio.gather(*tasks, return_exceptions=True)
self._tasks[address] = [] | [
"async",
"def",
"stop_tasks",
"(",
"self",
",",
"address",
")",
":",
"tasks",
"=",
"self",
".",
"_tasks",
".",
"get",
"(",
"address",
",",
"[",
"]",
")",
"for",
"task",
"in",
"tasks",
":",
"task",
".",
"cancel",
"(",
")",
"asyncio",
".",
"gather",
... | Clear all tasks pertaining to a tile.
This coroutine will synchronously cancel all running tasks that were
attached to the given tile and wait for them to stop before returning.
Args:
address (int): The address of the tile we should stop. | [
"Clear",
"all",
"tasks",
"pertaining",
"to",
"a",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L434-L449 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.