repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
iotile/coretools
iotilecore/iotile/core/hw/auth/auth_provider.py
AuthProvider.DeriveReportKey
def DeriveReportKey(cls, root_key, report_id, sent_timestamp): """Derive a standard one time use report signing key. The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp) where MAGIC_NUMBER is 0x00000002 and all integers are in little endian. """ signed_data = struct.pack("<LLL", AuthProvider.ReportKeyMagic, report_id, sent_timestamp) hmac_calc = hmac.new(root_key, signed_data, hashlib.sha256) return bytearray(hmac_calc.digest())
python
def DeriveReportKey(cls, root_key, report_id, sent_timestamp): """Derive a standard one time use report signing key. The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp) where MAGIC_NUMBER is 0x00000002 and all integers are in little endian. """ signed_data = struct.pack("<LLL", AuthProvider.ReportKeyMagic, report_id, sent_timestamp) hmac_calc = hmac.new(root_key, signed_data, hashlib.sha256) return bytearray(hmac_calc.digest())
[ "def", "DeriveReportKey", "(", "cls", ",", "root_key", ",", "report_id", ",", "sent_timestamp", ")", ":", "signed_data", "=", "struct", ".", "pack", "(", "\"<LLL\"", ",", "AuthProvider", ".", "ReportKeyMagic", ",", "report_id", ",", "sent_timestamp", ")", "hmac_calc", "=", "hmac", ".", "new", "(", "root_key", ",", "signed_data", ",", "hashlib", ".", "sha256", ")", "return", "bytearray", "(", "hmac_calc", ".", "digest", "(", ")", ")" ]
Derive a standard one time use report signing key. The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp) where MAGIC_NUMBER is 0x00000002 and all integers are in little endian.
[ "Derive", "a", "standard", "one", "time", "use", "report", "signing", "key", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/auth/auth_provider.py#L72-L82
train
iotile/coretools
iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py
AwaitableDict.declare
def declare(self, name): """Declare that a key will be set in the future. This will create a future for the key that is used to hold its result and allow awaiting it. Args: name (str): The unique key that will be used. """ if name in self._data: raise KeyError("Declared name {} that already existed".format(name)) self._data[name] = self._loop.create_future()
python
def declare(self, name): """Declare that a key will be set in the future. This will create a future for the key that is used to hold its result and allow awaiting it. Args: name (str): The unique key that will be used. """ if name in self._data: raise KeyError("Declared name {} that already existed".format(name)) self._data[name] = self._loop.create_future()
[ "def", "declare", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_data", ":", "raise", "KeyError", "(", "\"Declared name {} that already existed\"", ".", "format", "(", "name", ")", ")", "self", ".", "_data", "[", "name", "]", "=", "self", ".", "_loop", ".", "create_future", "(", ")" ]
Declare that a key will be set in the future. This will create a future for the key that is used to hold its result and allow awaiting it. Args: name (str): The unique key that will be used.
[ "Declare", "that", "a", "key", "will", "be", "set", "in", "the", "future", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L39-L52
train
iotile/coretools
iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py
AwaitableDict.get
async def get(self, name, timeout=None, autoremove=True): """Wait for a value to be set for a key. This is the primary way to receive values from AwaitableDict. You pass in the name of the key you want to wait for, the maximum amount of time you want to wait and then you can await the result and it will resolve to value from the call to set or an asyncio.TimeoutError. You should generally leave autoremove as the default True value. This causes the key to be removed from the dictionary after get returns. Normally you have a single user calling ``get`` and another calling ``set`` so you want to automatically clean up after the getter returns, no matter what. If the key has not already been declared, it will be declared automatically inside this function so it is not necessary to call :meth:`declare` manually in most use cases. Args: name (str): The name of the key to wait on. timeout (float): The maximum timeout to wait. autoremove (bool): Whether to automatically remove the key when get() returns. Returns: object: Whatever was set in the key by :meth:`set`. Raises: asyncio.TimeoutError: The key was not set within the timeout. """ self._ensure_declared(name) try: await asyncio.wait_for(self._data[name], timeout, loop=self._loop.get_loop()) return self._data[name].result() finally: if autoremove: self._data[name].cancel() del self._data[name]
python
async def get(self, name, timeout=None, autoremove=True): """Wait for a value to be set for a key. This is the primary way to receive values from AwaitableDict. You pass in the name of the key you want to wait for, the maximum amount of time you want to wait and then you can await the result and it will resolve to value from the call to set or an asyncio.TimeoutError. You should generally leave autoremove as the default True value. This causes the key to be removed from the dictionary after get returns. Normally you have a single user calling ``get`` and another calling ``set`` so you want to automatically clean up after the getter returns, no matter what. If the key has not already been declared, it will be declared automatically inside this function so it is not necessary to call :meth:`declare` manually in most use cases. Args: name (str): The name of the key to wait on. timeout (float): The maximum timeout to wait. autoremove (bool): Whether to automatically remove the key when get() returns. Returns: object: Whatever was set in the key by :meth:`set`. Raises: asyncio.TimeoutError: The key was not set within the timeout. """ self._ensure_declared(name) try: await asyncio.wait_for(self._data[name], timeout, loop=self._loop.get_loop()) return self._data[name].result() finally: if autoremove: self._data[name].cancel() del self._data[name]
[ "async", "def", "get", "(", "self", ",", "name", ",", "timeout", "=", "None", ",", "autoremove", "=", "True", ")", ":", "self", ".", "_ensure_declared", "(", "name", ")", "try", ":", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_data", "[", "name", "]", ",", "timeout", ",", "loop", "=", "self", ".", "_loop", ".", "get_loop", "(", ")", ")", "return", "self", ".", "_data", "[", "name", "]", ".", "result", "(", ")", "finally", ":", "if", "autoremove", ":", "self", ".", "_data", "[", "name", "]", ".", "cancel", "(", ")", "del", "self", ".", "_data", "[", "name", "]" ]
Wait for a value to be set for a key. This is the primary way to receive values from AwaitableDict. You pass in the name of the key you want to wait for, the maximum amount of time you want to wait and then you can await the result and it will resolve to value from the call to set or an asyncio.TimeoutError. You should generally leave autoremove as the default True value. This causes the key to be removed from the dictionary after get returns. Normally you have a single user calling ``get`` and another calling ``set`` so you want to automatically clean up after the getter returns, no matter what. If the key has not already been declared, it will be declared automatically inside this function so it is not necessary to call :meth:`declare` manually in most use cases. Args: name (str): The name of the key to wait on. timeout (float): The maximum timeout to wait. autoremove (bool): Whether to automatically remove the key when get() returns. Returns: object: Whatever was set in the key by :meth:`set`. Raises: asyncio.TimeoutError: The key was not set within the timeout.
[ "Wait", "for", "a", "value", "to", "be", "set", "for", "a", "key", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L54-L94
train
iotile/coretools
iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py
AwaitableDict.get_nowait
def get_nowait(self, name, default=_MISSING, autoremove=False): """Get the value of a key if it is already set. This method allows you to check if a key has already been set without blocking. If the key has not been set you will get the default value you pass in or KeyError() if no default is passed. When this method returns the key is automatically removed unless you pass ``autoremove=False``. This method is not a coroutine and does not block. Args: name (str): The name of the key to wait on. default (object): The default value to return if the key has not yet been set. Defaults to raising KeyError(). autoremove (bool): Whether to automatically remove the key when get() returns. Returns: object: Whatever was set in the key by :meth:`set`. """ self._ensure_declared(name) try: future = self._data[name] if future.done(): return future.result() if default is _MISSING: raise KeyError("Key {} has not been assigned a value and no default given".format(name)) return default finally: if autoremove: self._data[name].cancel() del self._data[name]
python
def get_nowait(self, name, default=_MISSING, autoremove=False): """Get the value of a key if it is already set. This method allows you to check if a key has already been set without blocking. If the key has not been set you will get the default value you pass in or KeyError() if no default is passed. When this method returns the key is automatically removed unless you pass ``autoremove=False``. This method is not a coroutine and does not block. Args: name (str): The name of the key to wait on. default (object): The default value to return if the key has not yet been set. Defaults to raising KeyError(). autoremove (bool): Whether to automatically remove the key when get() returns. Returns: object: Whatever was set in the key by :meth:`set`. """ self._ensure_declared(name) try: future = self._data[name] if future.done(): return future.result() if default is _MISSING: raise KeyError("Key {} has not been assigned a value and no default given".format(name)) return default finally: if autoremove: self._data[name].cancel() del self._data[name]
[ "def", "get_nowait", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ",", "autoremove", "=", "False", ")", ":", "self", ".", "_ensure_declared", "(", "name", ")", "try", ":", "future", "=", "self", ".", "_data", "[", "name", "]", "if", "future", ".", "done", "(", ")", ":", "return", "future", ".", "result", "(", ")", "if", "default", "is", "_MISSING", ":", "raise", "KeyError", "(", "\"Key {} has not been assigned a value and no default given\"", ".", "format", "(", "name", ")", ")", "return", "default", "finally", ":", "if", "autoremove", ":", "self", ".", "_data", "[", "name", "]", ".", "cancel", "(", ")", "del", "self", ".", "_data", "[", "name", "]" ]
Get the value of a key if it is already set. This method allows you to check if a key has already been set without blocking. If the key has not been set you will get the default value you pass in or KeyError() if no default is passed. When this method returns the key is automatically removed unless you pass ``autoremove=False``. This method is not a coroutine and does not block. Args: name (str): The name of the key to wait on. default (object): The default value to return if the key has not yet been set. Defaults to raising KeyError(). autoremove (bool): Whether to automatically remove the key when get() returns. Returns: object: Whatever was set in the key by :meth:`set`.
[ "Get", "the", "value", "of", "a", "key", "if", "it", "is", "already", "set", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L96-L133
train
iotile/coretools
iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py
AwaitableDict.set
def set(self, name, value, autodeclare=False): """Set the value of a key. This method will cause anyone waiting on a key (and any future waiters) to unblock and be returned the value you pass here. If the key has not been declared previously, a KeyError() is raised unless you pass ``autodeclare=True`` which will cause the key to be declared. Normally you don't want to autodeclare. This method is not a coroutine and does not block. Args: name (str): The key to set value (object): The value to set autodeclare (bool): Whether to automatically declare the key if is has not already been declared. Defaults to False. """ if not autodeclare and name not in self._data: raise KeyError("Key {} has not been declared and autodeclare=False".format(name)) self._ensure_declared(name) self._data[name].set_result(value)
python
def set(self, name, value, autodeclare=False): """Set the value of a key. This method will cause anyone waiting on a key (and any future waiters) to unblock and be returned the value you pass here. If the key has not been declared previously, a KeyError() is raised unless you pass ``autodeclare=True`` which will cause the key to be declared. Normally you don't want to autodeclare. This method is not a coroutine and does not block. Args: name (str): The key to set value (object): The value to set autodeclare (bool): Whether to automatically declare the key if is has not already been declared. Defaults to False. """ if not autodeclare and name not in self._data: raise KeyError("Key {} has not been declared and autodeclare=False".format(name)) self._ensure_declared(name) self._data[name].set_result(value)
[ "def", "set", "(", "self", ",", "name", ",", "value", ",", "autodeclare", "=", "False", ")", ":", "if", "not", "autodeclare", "and", "name", "not", "in", "self", ".", "_data", ":", "raise", "KeyError", "(", "\"Key {} has not been declared and autodeclare=False\"", ".", "format", "(", "name", ")", ")", "self", ".", "_ensure_declared", "(", "name", ")", "self", ".", "_data", "[", "name", "]", ".", "set_result", "(", "value", ")" ]
Set the value of a key. This method will cause anyone waiting on a key (and any future waiters) to unblock and be returned the value you pass here. If the key has not been declared previously, a KeyError() is raised unless you pass ``autodeclare=True`` which will cause the key to be declared. Normally you don't want to autodeclare. This method is not a coroutine and does not block. Args: name (str): The key to set value (object): The value to set autodeclare (bool): Whether to automatically declare the key if is has not already been declared. Defaults to False.
[ "Set", "the", "value", "of", "a", "key", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/awaitable_dict.py#L135-L159
train
iotile/coretools
iotilesensorgraph/iotile/sg/parser/parser_v1.py
SensorGraphFileParser.dump_tree
def dump_tree(self, statement=None, indent_level=0): """Dump the AST for this parsed file. Args: statement (SensorGraphStatement): the statement to print if this function is called recursively. indent_level (int): The number of spaces to indent this statement. Used for recursively printing blocks of statements. Returns: str: The AST for this parsed sg file as a nested tree with one node per line and blocks indented. """ out = u"" indent = u" "*indent_level if statement is None: for root_statement in self.statements: out += self.dump_tree(root_statement, indent_level) else: out += indent + str(statement) + u'\n' if len(statement.children) > 0: for child in statement.children: out += self.dump_tree(child, indent_level=indent_level+4) return out
python
def dump_tree(self, statement=None, indent_level=0): """Dump the AST for this parsed file. Args: statement (SensorGraphStatement): the statement to print if this function is called recursively. indent_level (int): The number of spaces to indent this statement. Used for recursively printing blocks of statements. Returns: str: The AST for this parsed sg file as a nested tree with one node per line and blocks indented. """ out = u"" indent = u" "*indent_level if statement is None: for root_statement in self.statements: out += self.dump_tree(root_statement, indent_level) else: out += indent + str(statement) + u'\n' if len(statement.children) > 0: for child in statement.children: out += self.dump_tree(child, indent_level=indent_level+4) return out
[ "def", "dump_tree", "(", "self", ",", "statement", "=", "None", ",", "indent_level", "=", "0", ")", ":", "out", "=", "u\"\"", "indent", "=", "u\" \"", "*", "indent_level", "if", "statement", "is", "None", ":", "for", "root_statement", "in", "self", ".", "statements", ":", "out", "+=", "self", ".", "dump_tree", "(", "root_statement", ",", "indent_level", ")", "else", ":", "out", "+=", "indent", "+", "str", "(", "statement", ")", "+", "u'\\n'", "if", "len", "(", "statement", ".", "children", ")", ">", "0", ":", "for", "child", "in", "statement", ".", "children", ":", "out", "+=", "self", ".", "dump_tree", "(", "child", ",", "indent_level", "=", "indent_level", "+", "4", ")", "return", "out" ]
Dump the AST for this parsed file. Args: statement (SensorGraphStatement): the statement to print if this function is called recursively. indent_level (int): The number of spaces to indent this statement. Used for recursively printing blocks of statements. Returns: str: The AST for this parsed sg file as a nested tree with one node per line and blocks indented.
[ "Dump", "the", "AST", "for", "this", "parsed", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L23-L51
train
iotile/coretools
iotilesensorgraph/iotile/sg/parser/parser_v1.py
SensorGraphFileParser.parse_file
def parse_file(self, sg_file=None, data=None): """Parse a sensor graph file into an AST describing the file. This function builds the statements list for this parser. If you pass ``sg_file``, it will be interpreted as the path to a file to parse. If you pass ``data`` it will be directly interpreted as the string to parse. """ if sg_file is not None and data is not None: raise ArgumentError("You must pass either a path to an sgf file or the sgf contents but not both") if sg_file is None and data is None: raise ArgumentError("You must pass either a path to an sgf file or the sgf contents, neither passed") if sg_file is not None: try: with open(sg_file, "r") as inf: data = inf.read() except IOError: raise ArgumentError("Could not read sensor graph file", path=sg_file) # convert tabs to spaces so our line numbers match correctly data = data.replace(u'\t', u' ') lang = get_language() result = lang.parseString(data) for statement in result: parsed = self.parse_statement(statement, orig_contents=data) self.statements.append(parsed)
python
def parse_file(self, sg_file=None, data=None): """Parse a sensor graph file into an AST describing the file. This function builds the statements list for this parser. If you pass ``sg_file``, it will be interpreted as the path to a file to parse. If you pass ``data`` it will be directly interpreted as the string to parse. """ if sg_file is not None and data is not None: raise ArgumentError("You must pass either a path to an sgf file or the sgf contents but not both") if sg_file is None and data is None: raise ArgumentError("You must pass either a path to an sgf file or the sgf contents, neither passed") if sg_file is not None: try: with open(sg_file, "r") as inf: data = inf.read() except IOError: raise ArgumentError("Could not read sensor graph file", path=sg_file) # convert tabs to spaces so our line numbers match correctly data = data.replace(u'\t', u' ') lang = get_language() result = lang.parseString(data) for statement in result: parsed = self.parse_statement(statement, orig_contents=data) self.statements.append(parsed)
[ "def", "parse_file", "(", "self", ",", "sg_file", "=", "None", ",", "data", "=", "None", ")", ":", "if", "sg_file", "is", "not", "None", "and", "data", "is", "not", "None", ":", "raise", "ArgumentError", "(", "\"You must pass either a path to an sgf file or the sgf contents but not both\"", ")", "if", "sg_file", "is", "None", "and", "data", "is", "None", ":", "raise", "ArgumentError", "(", "\"You must pass either a path to an sgf file or the sgf contents, neither passed\"", ")", "if", "sg_file", "is", "not", "None", ":", "try", ":", "with", "open", "(", "sg_file", ",", "\"r\"", ")", "as", "inf", ":", "data", "=", "inf", ".", "read", "(", ")", "except", "IOError", ":", "raise", "ArgumentError", "(", "\"Could not read sensor graph file\"", ",", "path", "=", "sg_file", ")", "# convert tabs to spaces so our line numbers match correctly", "data", "=", "data", ".", "replace", "(", "u'\\t'", ",", "u' '", ")", "lang", "=", "get_language", "(", ")", "result", "=", "lang", ".", "parseString", "(", "data", ")", "for", "statement", "in", "result", ":", "parsed", "=", "self", ".", "parse_statement", "(", "statement", ",", "orig_contents", "=", "data", ")", "self", ".", "statements", ".", "append", "(", "parsed", ")" ]
Parse a sensor graph file into an AST describing the file. This function builds the statements list for this parser. If you pass ``sg_file``, it will be interpreted as the path to a file to parse. If you pass ``data`` it will be directly interpreted as the string to parse.
[ "Parse", "a", "sensor", "graph", "file", "into", "an", "AST", "describing", "the", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L53-L83
train
iotile/coretools
iotilesensorgraph/iotile/sg/parser/parser_v1.py
SensorGraphFileParser.compile
def compile(self, model): """Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for. """ log = SensorLog(InMemoryStorageEngine(model), model) self.sensor_graph = SensorGraph(log, model) allocator = StreamAllocator(self.sensor_graph, model) self._scope_stack = [] # Create a root scope root = RootScope(self.sensor_graph, allocator) self._scope_stack.append(root) for statement in self.statements: statement.execute(self.sensor_graph, self._scope_stack) self.sensor_graph.initialize_remaining_constants() self.sensor_graph.sort_nodes()
python
def compile(self, model): """Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for. """ log = SensorLog(InMemoryStorageEngine(model), model) self.sensor_graph = SensorGraph(log, model) allocator = StreamAllocator(self.sensor_graph, model) self._scope_stack = [] # Create a root scope root = RootScope(self.sensor_graph, allocator) self._scope_stack.append(root) for statement in self.statements: statement.execute(self.sensor_graph, self._scope_stack) self.sensor_graph.initialize_remaining_constants() self.sensor_graph.sort_nodes()
[ "def", "compile", "(", "self", ",", "model", ")", ":", "log", "=", "SensorLog", "(", "InMemoryStorageEngine", "(", "model", ")", ",", "model", ")", "self", ".", "sensor_graph", "=", "SensorGraph", "(", "log", ",", "model", ")", "allocator", "=", "StreamAllocator", "(", "self", ".", "sensor_graph", ",", "model", ")", "self", ".", "_scope_stack", "=", "[", "]", "# Create a root scope", "root", "=", "RootScope", "(", "self", ".", "sensor_graph", ",", "allocator", ")", "self", ".", "_scope_stack", ".", "append", "(", "root", ")", "for", "statement", "in", "self", ".", "statements", ":", "statement", ".", "execute", "(", "self", ".", "sensor_graph", ",", "self", ".", "_scope_stack", ")", "self", ".", "sensor_graph", ".", "initialize_remaining_constants", "(", ")", "self", ".", "sensor_graph", ".", "sort_nodes", "(", ")" ]
Compile this file into a SensorGraph. You must have preivously called parse_file to parse a sensor graph file into statements that are then executed by this command to build a sensor graph. The results are stored in self.sensor_graph and can be inspected before running optimization passes. Args: model (DeviceModel): The device model that we should compile this sensor graph for.
[ "Compile", "this", "file", "into", "a", "SensorGraph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L85-L115
train
iotile/coretools
iotilesensorgraph/iotile/sg/parser/parser_v1.py
SensorGraphFileParser.parse_statement
def parse_statement(self, statement, orig_contents): """Parse a statement, possibly called recursively. Args: statement (int, ParseResult): The pyparsing parse result that contains one statement prepended with the match location orig_contents (str): The original contents of the file that we're parsing in case we need to convert an index into a line, column pair. Returns: SensorGraphStatement: The parsed statement. """ children = [] is_block = False name = statement.getName() # Recursively parse all children statements in a block # before parsing the block itself. # If this is a non-block statement, parse it using the statement # parser to figure out what specific statement it is before # processing it further. # This two step process produces better syntax error messsages if name == 'block': children_statements = statement[1] for child in children_statements: parsed = self.parse_statement(child, orig_contents=orig_contents) children.append(parsed) locn = statement[0]['location'] statement = statement[0][1] name = statement.getName() is_block = True else: stmt_language = get_statement() locn = statement['location'] statement = statement['match'] statement_string = str(u"".join(statement.asList())) # Try to parse this generic statement into an actual statement. # Do this here in a separate step so we have good error messages when there # is a problem parsing a step. try: statement = stmt_language.parseString(statement_string)[0] except (pyparsing.ParseException, pyparsing.ParseSyntaxException) as exc: raise SensorGraphSyntaxError("Error parsing statement in sensor graph file", message=exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), column=pyparsing.col(locn, orig_contents)) except SensorGraphSemanticError as exc: # Reraise semantic errors with line information raise SensorGraphSemanticError(exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), **exc.params) name = statement.getName() if name not in statement_map: raise ArgumentError("Unknown statement in sensor graph file", parsed_statement=statement, name=name) # Save off our location information so we can give good error and warning information line = pyparsing.line(locn, orig_contents).strip() line_number = pyparsing.lineno(locn, orig_contents) column = pyparsing.col(locn, orig_contents) location_info = LocationInfo(line, line_number, column) if is_block: return statement_map[name](statement, children=children, location=location_info) return statement_map[name](statement, location_info)
python
def parse_statement(self, statement, orig_contents): """Parse a statement, possibly called recursively. Args: statement (int, ParseResult): The pyparsing parse result that contains one statement prepended with the match location orig_contents (str): The original contents of the file that we're parsing in case we need to convert an index into a line, column pair. Returns: SensorGraphStatement: The parsed statement. """ children = [] is_block = False name = statement.getName() # Recursively parse all children statements in a block # before parsing the block itself. # If this is a non-block statement, parse it using the statement # parser to figure out what specific statement it is before # processing it further. # This two step process produces better syntax error messsages if name == 'block': children_statements = statement[1] for child in children_statements: parsed = self.parse_statement(child, orig_contents=orig_contents) children.append(parsed) locn = statement[0]['location'] statement = statement[0][1] name = statement.getName() is_block = True else: stmt_language = get_statement() locn = statement['location'] statement = statement['match'] statement_string = str(u"".join(statement.asList())) # Try to parse this generic statement into an actual statement. # Do this here in a separate step so we have good error messages when there # is a problem parsing a step. try: statement = stmt_language.parseString(statement_string)[0] except (pyparsing.ParseException, pyparsing.ParseSyntaxException) as exc: raise SensorGraphSyntaxError("Error parsing statement in sensor graph file", message=exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), column=pyparsing.col(locn, orig_contents)) except SensorGraphSemanticError as exc: # Reraise semantic errors with line information raise SensorGraphSemanticError(exc.msg, line=pyparsing.line(locn, orig_contents).strip(), line_number=pyparsing.lineno(locn, orig_contents), **exc.params) name = statement.getName() if name not in statement_map: raise ArgumentError("Unknown statement in sensor graph file", parsed_statement=statement, name=name) # Save off our location information so we can give good error and warning information line = pyparsing.line(locn, orig_contents).strip() line_number = pyparsing.lineno(locn, orig_contents) column = pyparsing.col(locn, orig_contents) location_info = LocationInfo(line, line_number, column) if is_block: return statement_map[name](statement, children=children, location=location_info) return statement_map[name](statement, location_info)
[ "def", "parse_statement", "(", "self", ",", "statement", ",", "orig_contents", ")", ":", "children", "=", "[", "]", "is_block", "=", "False", "name", "=", "statement", ".", "getName", "(", ")", "# Recursively parse all children statements in a block", "# before parsing the block itself.", "# If this is a non-block statement, parse it using the statement", "# parser to figure out what specific statement it is before", "# processing it further.", "# This two step process produces better syntax error messsages", "if", "name", "==", "'block'", ":", "children_statements", "=", "statement", "[", "1", "]", "for", "child", "in", "children_statements", ":", "parsed", "=", "self", ".", "parse_statement", "(", "child", ",", "orig_contents", "=", "orig_contents", ")", "children", ".", "append", "(", "parsed", ")", "locn", "=", "statement", "[", "0", "]", "[", "'location'", "]", "statement", "=", "statement", "[", "0", "]", "[", "1", "]", "name", "=", "statement", ".", "getName", "(", ")", "is_block", "=", "True", "else", ":", "stmt_language", "=", "get_statement", "(", ")", "locn", "=", "statement", "[", "'location'", "]", "statement", "=", "statement", "[", "'match'", "]", "statement_string", "=", "str", "(", "u\"\"", ".", "join", "(", "statement", ".", "asList", "(", ")", ")", ")", "# Try to parse this generic statement into an actual statement.", "# Do this here in a separate step so we have good error messages when there", "# is a problem parsing a step.", "try", ":", "statement", "=", "stmt_language", ".", "parseString", "(", "statement_string", ")", "[", "0", "]", "except", "(", "pyparsing", ".", "ParseException", ",", "pyparsing", ".", "ParseSyntaxException", ")", "as", "exc", ":", "raise", "SensorGraphSyntaxError", "(", "\"Error parsing statement in sensor graph file\"", ",", "message", "=", "exc", ".", "msg", ",", "line", "=", "pyparsing", ".", "line", "(", "locn", ",", "orig_contents", ")", ".", "strip", "(", ")", ",", "line_number", "=", "pyparsing", ".", "lineno", "(", "locn", ",", "orig_contents", ")", ",", "column", "=", "pyparsing", ".", "col", "(", "locn", ",", "orig_contents", ")", ")", "except", "SensorGraphSemanticError", "as", "exc", ":", "# Reraise semantic errors with line information", "raise", "SensorGraphSemanticError", "(", "exc", ".", "msg", ",", "line", "=", "pyparsing", ".", "line", "(", "locn", ",", "orig_contents", ")", ".", "strip", "(", ")", ",", "line_number", "=", "pyparsing", ".", "lineno", "(", "locn", ",", "orig_contents", ")", ",", "*", "*", "exc", ".", "params", ")", "name", "=", "statement", ".", "getName", "(", ")", "if", "name", "not", "in", "statement_map", ":", "raise", "ArgumentError", "(", "\"Unknown statement in sensor graph file\"", ",", "parsed_statement", "=", "statement", ",", "name", "=", "name", ")", "# Save off our location information so we can give good error and warning information", "line", "=", "pyparsing", ".", "line", "(", "locn", ",", "orig_contents", ")", ".", "strip", "(", ")", "line_number", "=", "pyparsing", ".", "lineno", "(", "locn", ",", "orig_contents", ")", "column", "=", "pyparsing", ".", "col", "(", "locn", ",", "orig_contents", ")", "location_info", "=", "LocationInfo", "(", "line", ",", "line_number", ",", "column", ")", "if", "is_block", ":", "return", "statement_map", "[", "name", "]", "(", "statement", ",", "children", "=", "children", ",", "location", "=", "location_info", ")", "return", "statement_map", "[", "name", "]", "(", "statement", ",", "location_info", ")" ]
Parse a statement, possibly called recursively. Args: statement (int, ParseResult): The pyparsing parse result that contains one statement prepended with the match location orig_contents (str): The original contents of the file that we're parsing in case we need to convert an index into a line, column pair. Returns: SensorGraphStatement: The parsed statement.
[ "Parse", "a", "statement", "possibly", "called", "recursively", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/parser_v1.py#L117-L182
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/virtualdevice.py
VirtualIOTileDevice.stream
def stream(self, report, callback=None): """Stream a report asynchronously. If no one is listening for the report, the report may be dropped, otherwise it will be queued for sending Args: report (IOTileReport): The report that should be streamed callback (callable): Optional callback to get notified when this report is actually sent. """ if self._push_channel is None: return self._push_channel.stream(report, callback=callback)
python
def stream(self, report, callback=None): """Stream a report asynchronously. If no one is listening for the report, the report may be dropped, otherwise it will be queued for sending Args: report (IOTileReport): The report that should be streamed callback (callable): Optional callback to get notified when this report is actually sent. """ if self._push_channel is None: return self._push_channel.stream(report, callback=callback)
[ "def", "stream", "(", "self", ",", "report", ",", "callback", "=", "None", ")", ":", "if", "self", ".", "_push_channel", "is", "None", ":", "return", "self", ".", "_push_channel", ".", "stream", "(", "report", ",", "callback", "=", "callback", ")" ]
Stream a report asynchronously. If no one is listening for the report, the report may be dropped, otherwise it will be queued for sending Args: report (IOTileReport): The report that should be streamed callback (callable): Optional callback to get notified when this report is actually sent.
[ "Stream", "a", "report", "asynchronously", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L121-L136
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/virtualdevice.py
VirtualIOTileDevice.stream_realtime
def stream_realtime(self, stream, value): """Stream a realtime value as an IndividualReadingReport. If the streaming interface of the VirtualInterface this VirtualDevice is attached to is not opened, the realtime reading may be dropped. Args: stream (int): The stream id to send value (int): The stream value to send """ if not self.stream_iface_open: return reading = IOTileReading(0, stream, value) report = IndividualReadingReport.FromReadings(self.iotile_id, [reading]) self.stream(report)
python
def stream_realtime(self, stream, value): """Stream a realtime value as an IndividualReadingReport. If the streaming interface of the VirtualInterface this VirtualDevice is attached to is not opened, the realtime reading may be dropped. Args: stream (int): The stream id to send value (int): The stream value to send """ if not self.stream_iface_open: return reading = IOTileReading(0, stream, value) report = IndividualReadingReport.FromReadings(self.iotile_id, [reading]) self.stream(report)
[ "def", "stream_realtime", "(", "self", ",", "stream", ",", "value", ")", ":", "if", "not", "self", ".", "stream_iface_open", ":", "return", "reading", "=", "IOTileReading", "(", "0", ",", "stream", ",", "value", ")", "report", "=", "IndividualReadingReport", ".", "FromReadings", "(", "self", ".", "iotile_id", ",", "[", "reading", "]", ")", "self", ".", "stream", "(", "report", ")" ]
Stream a realtime value as an IndividualReadingReport. If the streaming interface of the VirtualInterface this VirtualDevice is attached to is not opened, the realtime reading may be dropped. Args: stream (int): The stream id to send value (int): The stream value to send
[ "Stream", "a", "realtime", "value", "as", "an", "IndividualReadingReport", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L138-L156
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/virtualdevice.py
VirtualIOTileDevice.trace
def trace(self, data, callback=None): """Trace data asynchronously. If no one is listening for traced data, it will be dropped otherwise it will be queued for sending. Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): Optional callback to get notified when this data is actually sent. """ if self._push_channel is None: return self._push_channel.trace(data, callback=callback)
python
def trace(self, data, callback=None): """Trace data asynchronously. If no one is listening for traced data, it will be dropped otherwise it will be queued for sending. Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): Optional callback to get notified when this data is actually sent. """ if self._push_channel is None: return self._push_channel.trace(data, callback=callback)
[ "def", "trace", "(", "self", ",", "data", ",", "callback", "=", "None", ")", ":", "if", "self", ".", "_push_channel", "is", "None", ":", "return", "self", ".", "_push_channel", ".", "trace", "(", "data", ",", "callback", "=", "callback", ")" ]
Trace data asynchronously. If no one is listening for traced data, it will be dropped otherwise it will be queued for sending. Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): Optional callback to get notified when this data is actually sent.
[ "Trace", "data", "asynchronously", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L158-L174
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/virtualdevice.py
VirtualIOTileDevice.register_rpc
def register_rpc(self, address, rpc_id, func): """Register a single RPC handler with the given info. This function can be used to directly register individual RPCs, rather than delegating all RPCs at a given address to a virtual Tile. If calls to this function are mixed with calls to add_tile for the same address, these RPCs will take precedence over what is defined in the tiles. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC func (callable): The function that should be called to handle the RPC. func is called as func(payload) and must return a single string object of up to 20 bytes with its response """ if rpc_id < 0 or rpc_id > 0xFFFF: raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id)) if address not in self._rpc_overlays: self._rpc_overlays[address] = RPCDispatcher() self._rpc_overlays[address].add_rpc(rpc_id, func)
python
def register_rpc(self, address, rpc_id, func): """Register a single RPC handler with the given info. This function can be used to directly register individual RPCs, rather than delegating all RPCs at a given address to a virtual Tile. If calls to this function are mixed with calls to add_tile for the same address, these RPCs will take precedence over what is defined in the tiles. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC func (callable): The function that should be called to handle the RPC. func is called as func(payload) and must return a single string object of up to 20 bytes with its response """ if rpc_id < 0 or rpc_id > 0xFFFF: raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id)) if address not in self._rpc_overlays: self._rpc_overlays[address] = RPCDispatcher() self._rpc_overlays[address].add_rpc(rpc_id, func)
[ "def", "register_rpc", "(", "self", ",", "address", ",", "rpc_id", ",", "func", ")", ":", "if", "rpc_id", "<", "0", "or", "rpc_id", ">", "0xFFFF", ":", "raise", "RPCInvalidIDError", "(", "\"Invalid RPC ID: {}\"", ".", "format", "(", "rpc_id", ")", ")", "if", "address", "not", "in", "self", ".", "_rpc_overlays", ":", "self", ".", "_rpc_overlays", "[", "address", "]", "=", "RPCDispatcher", "(", ")", "self", ".", "_rpc_overlays", "[", "address", "]", ".", "add_rpc", "(", "rpc_id", ",", "func", ")" ]
Register a single RPC handler with the given info. This function can be used to directly register individual RPCs, rather than delegating all RPCs at a given address to a virtual Tile. If calls to this function are mixed with calls to add_tile for the same address, these RPCs will take precedence over what is defined in the tiles. Args: address (int): The address of the mock tile this RPC is for rpc_id (int): The number of the RPC func (callable): The function that should be called to handle the RPC. func is called as func(payload) and must return a single string object of up to 20 bytes with its response
[ "Register", "a", "single", "RPC", "handler", "with", "the", "given", "info", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L176-L201
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/virtualdevice.py
VirtualIOTileDevice.add_tile
def add_tile(self, address, tile): """Add a tile to handle all RPCs at a given address. Args: address (int): The address of the tile tile (RPCDispatcher): A tile object that inherits from RPCDispatcher """ if address in self._tiles: raise ArgumentError("Tried to add two tiles at the same address", address=address) self._tiles[address] = tile
python
def add_tile(self, address, tile): """Add a tile to handle all RPCs at a given address. Args: address (int): The address of the tile tile (RPCDispatcher): A tile object that inherits from RPCDispatcher """ if address in self._tiles: raise ArgumentError("Tried to add two tiles at the same address", address=address) self._tiles[address] = tile
[ "def", "add_tile", "(", "self", ",", "address", ",", "tile", ")", ":", "if", "address", "in", "self", ".", "_tiles", ":", "raise", "ArgumentError", "(", "\"Tried to add two tiles at the same address\"", ",", "address", "=", "address", ")", "self", ".", "_tiles", "[", "address", "]", "=", "tile" ]
Add a tile to handle all RPCs at a given address. Args: address (int): The address of the tile tile (RPCDispatcher): A tile object that inherits from RPCDispatcher
[ "Add", "a", "tile", "to", "handle", "all", "RPCs", "at", "a", "given", "address", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/virtualdevice.py#L230-L241
train
iotile/coretools
iotileemulate/iotile/emulate/reference/reference_device.py
ReferenceDevice.iter_tiles
def iter_tiles(self, include_controller=True): """Iterate over all tiles in this device in order. The ordering is by tile address which places the controller tile first in the list. Args: include_controller (bool): Include the controller tile in the results. Yields: int, EmulatedTile: A tuple with the tile address and tile object. """ for address, tile in sorted(self._tiles.items()): if address == 8 and not include_controller: continue yield address, tile
python
def iter_tiles(self, include_controller=True): """Iterate over all tiles in this device in order. The ordering is by tile address which places the controller tile first in the list. Args: include_controller (bool): Include the controller tile in the results. Yields: int, EmulatedTile: A tuple with the tile address and tile object. """ for address, tile in sorted(self._tiles.items()): if address == 8 and not include_controller: continue yield address, tile
[ "def", "iter_tiles", "(", "self", ",", "include_controller", "=", "True", ")", ":", "for", "address", ",", "tile", "in", "sorted", "(", "self", ".", "_tiles", ".", "items", "(", ")", ")", ":", "if", "address", "==", "8", "and", "not", "include_controller", ":", "continue", "yield", "address", ",", "tile" ]
Iterate over all tiles in this device in order. The ordering is by tile address which places the controller tile first in the list. Args: include_controller (bool): Include the controller tile in the results. Yields: int, EmulatedTile: A tuple with the tile address and tile object.
[ "Iterate", "over", "all", "tiles", "in", "this", "device", "in", "order", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L69-L87
train
iotile/coretools
iotileemulate/iotile/emulate/reference/reference_device.py
ReferenceDevice.open_streaming_interface
def open_streaming_interface(self): """Called when someone opens a streaming interface to the device. This method will automatically notify sensor_graph that there is a streaming interface opened. Returns: list: A list of IOTileReport objects that should be sent out the streaming interface. """ super(ReferenceDevice, self).open_streaming_interface() self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_OPEN) return []
python
def open_streaming_interface(self): """Called when someone opens a streaming interface to the device. This method will automatically notify sensor_graph that there is a streaming interface opened. Returns: list: A list of IOTileReport objects that should be sent out the streaming interface. """ super(ReferenceDevice, self).open_streaming_interface() self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_OPEN) return []
[ "def", "open_streaming_interface", "(", "self", ")", ":", "super", "(", "ReferenceDevice", ",", "self", ")", ".", "open_streaming_interface", "(", ")", "self", ".", "rpc", "(", "8", ",", "rpcs", ".", "SG_GRAPH_INPUT", ",", "8", ",", "streams", ".", "COMM_TILE_OPEN", ")", "return", "[", "]" ]
Called when someone opens a streaming interface to the device. This method will automatically notify sensor_graph that there is a streaming interface opened. Returns: list: A list of IOTileReport objects that should be sent out the streaming interface.
[ "Called", "when", "someone", "opens", "a", "streaming", "interface", "to", "the", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L144-L158
train
iotile/coretools
iotileemulate/iotile/emulate/reference/reference_device.py
ReferenceDevice.close_streaming_interface
def close_streaming_interface(self): """Called when someone closes the streaming interface to the device. This method will automatically notify sensor_graph that there is a no longer a streaming interface opened. """ super(ReferenceDevice, self).close_streaming_interface() self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_CLOSED)
python
def close_streaming_interface(self): """Called when someone closes the streaming interface to the device. This method will automatically notify sensor_graph that there is a no longer a streaming interface opened. """ super(ReferenceDevice, self).close_streaming_interface() self.rpc(8, rpcs.SG_GRAPH_INPUT, 8, streams.COMM_TILE_CLOSED)
[ "def", "close_streaming_interface", "(", "self", ")", ":", "super", "(", "ReferenceDevice", ",", "self", ")", ".", "close_streaming_interface", "(", ")", "self", ".", "rpc", "(", "8", ",", "rpcs", ".", "SG_GRAPH_INPUT", ",", "8", ",", "streams", ".", "COMM_TILE_CLOSED", ")" ]
Called when someone closes the streaming interface to the device. This method will automatically notify sensor_graph that there is a no longer a streaming interface opened.
[ "Called", "when", "someone", "closes", "the", "streaming", "interface", "to", "the", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_device.py#L160-L169
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/main.py
build_parser
def build_parser(): """Build the script's argument parser.""" parser = argparse.ArgumentParser(description="The IOTile task supervisor") parser.add_argument('-c', '--config', help="config json with options") parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging verbosity") return parser
python
def build_parser(): """Build the script's argument parser.""" parser = argparse.ArgumentParser(description="The IOTile task supervisor") parser.add_argument('-c', '--config', help="config json with options") parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging verbosity") return parser
[ "def", "build_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"The IOTile task supervisor\"", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--config'", ",", "help", "=", "\"config json with options\"", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "action", "=", "\"count\"", ",", "default", "=", "0", ",", "help", "=", "\"Increase logging verbosity\"", ")", "return", "parser" ]
Build the script's argument parser.
[ "Build", "the", "script", "s", "argument", "parser", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/main.py#L20-L27
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/main.py
configure_logging
def configure_logging(verbosity): """Set up the global logging level. Args: verbosity (int): The logging verbosity """ root = logging.getLogger() formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s', '%y-%m-%d %H:%M:%S') handler = logging.StreamHandler() handler.setFormatter(formatter) loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] if verbosity >= len(loglevels): verbosity = len(loglevels) - 1 level = loglevels[verbosity] root.setLevel(level) root.addHandler(handler)
python
def configure_logging(verbosity): """Set up the global logging level. Args: verbosity (int): The logging verbosity """ root = logging.getLogger() formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s', '%y-%m-%d %H:%M:%S') handler = logging.StreamHandler() handler.setFormatter(formatter) loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] if verbosity >= len(loglevels): verbosity = len(loglevels) - 1 level = loglevels[verbosity] root.setLevel(level) root.addHandler(handler)
[ "def", "configure_logging", "(", "verbosity", ")", ":", "root", "=", "logging", ".", "getLogger", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s'", ",", "'%y-%m-%d %H:%M:%S'", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "formatter", ")", "loglevels", "=", "[", "logging", ".", "CRITICAL", ",", "logging", ".", "ERROR", ",", "logging", ".", "WARNING", ",", "logging", ".", "INFO", ",", "logging", ".", "DEBUG", "]", "if", "verbosity", ">=", "len", "(", "loglevels", ")", ":", "verbosity", "=", "len", "(", "loglevels", ")", "-", "1", "level", "=", "loglevels", "[", "verbosity", "]", "root", ".", "setLevel", "(", "level", ")", "root", ".", "addHandler", "(", "handler", ")" ]
Set up the global logging level. Args: verbosity (int): The logging verbosity
[ "Set", "up", "the", "global", "logging", "level", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/main.py#L30-L51
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
createProgBuilder
def createProgBuilder(env): """This is a utility function that creates the Program Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: program = env['BUILDERS']['Program'] except KeyError: import SCons.Defaults program = SCons.Builder.Builder(action = SCons.Defaults.LinkAction, emitter = '$PROGEMITTER', prefix = '$PROGPREFIX', suffix = '$PROGSUFFIX', src_suffix = '$OBJSUFFIX', src_builder = 'Object', target_scanner = ProgramScanner) env['BUILDERS']['Program'] = program return program
python
def createProgBuilder(env): """This is a utility function that creates the Program Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: program = env['BUILDERS']['Program'] except KeyError: import SCons.Defaults program = SCons.Builder.Builder(action = SCons.Defaults.LinkAction, emitter = '$PROGEMITTER', prefix = '$PROGPREFIX', suffix = '$PROGSUFFIX', src_suffix = '$OBJSUFFIX', src_builder = 'Object', target_scanner = ProgramScanner) env['BUILDERS']['Program'] = program return program
[ "def", "createProgBuilder", "(", "env", ")", ":", "try", ":", "program", "=", "env", "[", "'BUILDERS'", "]", "[", "'Program'", "]", "except", "KeyError", ":", "import", "SCons", ".", "Defaults", "program", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "SCons", ".", "Defaults", ".", "LinkAction", ",", "emitter", "=", "'$PROGEMITTER'", ",", "prefix", "=", "'$PROGPREFIX'", ",", "suffix", "=", "'$PROGSUFFIX'", ",", "src_suffix", "=", "'$OBJSUFFIX'", ",", "src_builder", "=", "'Object'", ",", "target_scanner", "=", "ProgramScanner", ")", "env", "[", "'BUILDERS'", "]", "[", "'Program'", "]", "=", "program", "return", "program" ]
This is a utility function that creates the Program Builder in an Environment if it is not there already. If it is already there, we return the existing one.
[ "This", "is", "a", "utility", "function", "that", "creates", "the", "Program", "Builder", "in", "an", "Environment", "if", "it", "is", "not", "there", "already", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L306-L326
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
createStaticLibBuilder
def createStaticLibBuilder(env): """This is a utility function that creates the StaticLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: static_lib = env['BUILDERS']['StaticLibrary'] except KeyError: action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ] if env.get('RANLIB',False) or env.Detect('ranlib'): ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR") action_list.append(ranlib_action) static_lib = SCons.Builder.Builder(action = action_list, emitter = '$LIBEMITTER', prefix = '$LIBPREFIX', suffix = '$LIBSUFFIX', src_suffix = '$OBJSUFFIX', src_builder = 'StaticObject') env['BUILDERS']['StaticLibrary'] = static_lib env['BUILDERS']['Library'] = static_lib return static_lib
python
def createStaticLibBuilder(env): """This is a utility function that creates the StaticLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: static_lib = env['BUILDERS']['StaticLibrary'] except KeyError: action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ] if env.get('RANLIB',False) or env.Detect('ranlib'): ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR") action_list.append(ranlib_action) static_lib = SCons.Builder.Builder(action = action_list, emitter = '$LIBEMITTER', prefix = '$LIBPREFIX', suffix = '$LIBSUFFIX', src_suffix = '$OBJSUFFIX', src_builder = 'StaticObject') env['BUILDERS']['StaticLibrary'] = static_lib env['BUILDERS']['Library'] = static_lib return static_lib
[ "def", "createStaticLibBuilder", "(", "env", ")", ":", "try", ":", "static_lib", "=", "env", "[", "'BUILDERS'", "]", "[", "'StaticLibrary'", "]", "except", "KeyError", ":", "action_list", "=", "[", "SCons", ".", "Action", ".", "Action", "(", "\"$ARCOM\"", ",", "\"$ARCOMSTR\"", ")", "]", "if", "env", ".", "get", "(", "'RANLIB'", ",", "False", ")", "or", "env", ".", "Detect", "(", "'ranlib'", ")", ":", "ranlib_action", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$RANLIBCOM\"", ",", "\"$RANLIBCOMSTR\"", ")", "action_list", ".", "append", "(", "ranlib_action", ")", "static_lib", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "action_list", ",", "emitter", "=", "'$LIBEMITTER'", ",", "prefix", "=", "'$LIBPREFIX'", ",", "suffix", "=", "'$LIBSUFFIX'", ",", "src_suffix", "=", "'$OBJSUFFIX'", ",", "src_builder", "=", "'StaticObject'", ")", "env", "[", "'BUILDERS'", "]", "[", "'StaticLibrary'", "]", "=", "static_lib", "env", "[", "'BUILDERS'", "]", "[", "'Library'", "]", "=", "static_lib", "return", "static_lib" ]
This is a utility function that creates the StaticLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one.
[ "This", "is", "a", "utility", "function", "that", "creates", "the", "StaticLibrary", "Builder", "in", "an", "Environment", "if", "it", "is", "not", "there", "already", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L329-L353
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
createSharedLibBuilder
def createSharedLibBuilder(env): """This is a utility function that creates the SharedLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: shared_lib = env['BUILDERS']['SharedLibrary'] except KeyError: import SCons.Defaults action_list = [ SCons.Defaults.SharedCheck, SCons.Defaults.ShLinkAction, LibSymlinksAction ] shared_lib = SCons.Builder.Builder(action = action_list, emitter = "$SHLIBEMITTER", prefix = ShLibPrefixGenerator, suffix = ShLibSuffixGenerator, target_scanner = ProgramScanner, src_suffix = '$SHOBJSUFFIX', src_builder = 'SharedObject') env['BUILDERS']['SharedLibrary'] = shared_lib return shared_lib
python
def createSharedLibBuilder(env): """This is a utility function that creates the SharedLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: shared_lib = env['BUILDERS']['SharedLibrary'] except KeyError: import SCons.Defaults action_list = [ SCons.Defaults.SharedCheck, SCons.Defaults.ShLinkAction, LibSymlinksAction ] shared_lib = SCons.Builder.Builder(action = action_list, emitter = "$SHLIBEMITTER", prefix = ShLibPrefixGenerator, suffix = ShLibSuffixGenerator, target_scanner = ProgramScanner, src_suffix = '$SHOBJSUFFIX', src_builder = 'SharedObject') env['BUILDERS']['SharedLibrary'] = shared_lib return shared_lib
[ "def", "createSharedLibBuilder", "(", "env", ")", ":", "try", ":", "shared_lib", "=", "env", "[", "'BUILDERS'", "]", "[", "'SharedLibrary'", "]", "except", "KeyError", ":", "import", "SCons", ".", "Defaults", "action_list", "=", "[", "SCons", ".", "Defaults", ".", "SharedCheck", ",", "SCons", ".", "Defaults", ".", "ShLinkAction", ",", "LibSymlinksAction", "]", "shared_lib", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "action_list", ",", "emitter", "=", "\"$SHLIBEMITTER\"", ",", "prefix", "=", "ShLibPrefixGenerator", ",", "suffix", "=", "ShLibSuffixGenerator", ",", "target_scanner", "=", "ProgramScanner", ",", "src_suffix", "=", "'$SHOBJSUFFIX'", ",", "src_builder", "=", "'SharedObject'", ")", "env", "[", "'BUILDERS'", "]", "[", "'SharedLibrary'", "]", "=", "shared_lib", "return", "shared_lib" ]
This is a utility function that creates the SharedLibrary Builder in an Environment if it is not there already. If it is already there, we return the existing one.
[ "This", "is", "a", "utility", "function", "that", "creates", "the", "SharedLibrary", "Builder", "in", "an", "Environment", "if", "it", "is", "not", "there", "already", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L787-L810
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
createLoadableModuleBuilder
def createLoadableModuleBuilder(env): """This is a utility function that creates the LoadableModule Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: ld_module = env['BUILDERS']['LoadableModule'] except KeyError: import SCons.Defaults action_list = [ SCons.Defaults.SharedCheck, SCons.Defaults.LdModuleLinkAction, LibSymlinksAction ] ld_module = SCons.Builder.Builder(action = action_list, emitter = "$LDMODULEEMITTER", prefix = LdModPrefixGenerator, suffix = LdModSuffixGenerator, target_scanner = ProgramScanner, src_suffix = '$SHOBJSUFFIX', src_builder = 'SharedObject') env['BUILDERS']['LoadableModule'] = ld_module return ld_module
python
def createLoadableModuleBuilder(env): """This is a utility function that creates the LoadableModule Builder in an Environment if it is not there already. If it is already there, we return the existing one. """ try: ld_module = env['BUILDERS']['LoadableModule'] except KeyError: import SCons.Defaults action_list = [ SCons.Defaults.SharedCheck, SCons.Defaults.LdModuleLinkAction, LibSymlinksAction ] ld_module = SCons.Builder.Builder(action = action_list, emitter = "$LDMODULEEMITTER", prefix = LdModPrefixGenerator, suffix = LdModSuffixGenerator, target_scanner = ProgramScanner, src_suffix = '$SHOBJSUFFIX', src_builder = 'SharedObject') env['BUILDERS']['LoadableModule'] = ld_module return ld_module
[ "def", "createLoadableModuleBuilder", "(", "env", ")", ":", "try", ":", "ld_module", "=", "env", "[", "'BUILDERS'", "]", "[", "'LoadableModule'", "]", "except", "KeyError", ":", "import", "SCons", ".", "Defaults", "action_list", "=", "[", "SCons", ".", "Defaults", ".", "SharedCheck", ",", "SCons", ".", "Defaults", ".", "LdModuleLinkAction", ",", "LibSymlinksAction", "]", "ld_module", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "action_list", ",", "emitter", "=", "\"$LDMODULEEMITTER\"", ",", "prefix", "=", "LdModPrefixGenerator", ",", "suffix", "=", "LdModSuffixGenerator", ",", "target_scanner", "=", "ProgramScanner", ",", "src_suffix", "=", "'$SHOBJSUFFIX'", ",", "src_builder", "=", "'SharedObject'", ")", "env", "[", "'BUILDERS'", "]", "[", "'LoadableModule'", "]", "=", "ld_module", "return", "ld_module" ]
This is a utility function that creates the LoadableModule Builder in an Environment if it is not there already. If it is already there, we return the existing one.
[ "This", "is", "a", "utility", "function", "that", "creates", "the", "LoadableModule", "Builder", "in", "an", "Environment", "if", "it", "is", "not", "there", "already", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L812-L835
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
createObjBuilders
def createObjBuilders(env): """This is a utility function that creates the StaticObject and SharedObject Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The return is a 2-tuple of (StaticObject, SharedObject) """ try: static_obj = env['BUILDERS']['StaticObject'] except KeyError: static_obj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$OBJPREFIX', suffix = '$OBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['StaticObject'] = static_obj env['BUILDERS']['Object'] = static_obj try: shared_obj = env['BUILDERS']['SharedObject'] except KeyError: shared_obj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$SHOBJPREFIX', suffix = '$SHOBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['SharedObject'] = shared_obj return (static_obj, shared_obj)
python
def createObjBuilders(env): """This is a utility function that creates the StaticObject and SharedObject Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The return is a 2-tuple of (StaticObject, SharedObject) """ try: static_obj = env['BUILDERS']['StaticObject'] except KeyError: static_obj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$OBJPREFIX', suffix = '$OBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['StaticObject'] = static_obj env['BUILDERS']['Object'] = static_obj try: shared_obj = env['BUILDERS']['SharedObject'] except KeyError: shared_obj = SCons.Builder.Builder(action = {}, emitter = {}, prefix = '$SHOBJPREFIX', suffix = '$SHOBJSUFFIX', src_builder = ['CFile', 'CXXFile'], source_scanner = SourceFileScanner, single_source = 1) env['BUILDERS']['SharedObject'] = shared_obj return (static_obj, shared_obj)
[ "def", "createObjBuilders", "(", "env", ")", ":", "try", ":", "static_obj", "=", "env", "[", "'BUILDERS'", "]", "[", "'StaticObject'", "]", "except", "KeyError", ":", "static_obj", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "{", "}", ",", "emitter", "=", "{", "}", ",", "prefix", "=", "'$OBJPREFIX'", ",", "suffix", "=", "'$OBJSUFFIX'", ",", "src_builder", "=", "[", "'CFile'", ",", "'CXXFile'", "]", ",", "source_scanner", "=", "SourceFileScanner", ",", "single_source", "=", "1", ")", "env", "[", "'BUILDERS'", "]", "[", "'StaticObject'", "]", "=", "static_obj", "env", "[", "'BUILDERS'", "]", "[", "'Object'", "]", "=", "static_obj", "try", ":", "shared_obj", "=", "env", "[", "'BUILDERS'", "]", "[", "'SharedObject'", "]", "except", "KeyError", ":", "shared_obj", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "{", "}", ",", "emitter", "=", "{", "}", ",", "prefix", "=", "'$SHOBJPREFIX'", ",", "suffix", "=", "'$SHOBJSUFFIX'", ",", "src_builder", "=", "[", "'CFile'", ",", "'CXXFile'", "]", ",", "source_scanner", "=", "SourceFileScanner", ",", "single_source", "=", "1", ")", "env", "[", "'BUILDERS'", "]", "[", "'SharedObject'", "]", "=", "shared_obj", "return", "(", "static_obj", ",", "shared_obj", ")" ]
This is a utility function that creates the StaticObject and SharedObject Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The return is a 2-tuple of (StaticObject, SharedObject)
[ "This", "is", "a", "utility", "function", "that", "creates", "the", "StaticObject", "and", "SharedObject", "Builders", "in", "an", "Environment", "if", "they", "are", "not", "there", "already", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L837-L876
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
CreateJarBuilder
def CreateJarBuilder(env): """The Jar builder expects a list of class files which it can package into a jar file. The jar tool provides an interface for passing other types of java files such as .java, directories or swig interfaces and will build them to class files in which it can package into the jar. """ try: java_jar = env['BUILDERS']['JarFile'] except KeyError: fs = SCons.Node.FS.get_default_fs() jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR') java_jar = SCons.Builder.Builder(action = jar_com, suffix = '$JARSUFFIX', src_suffix = '$JAVACLASSSUFFIX', src_builder = 'JavaClassFile', source_factory = fs.Entry) env['BUILDERS']['JarFile'] = java_jar return java_jar
python
def CreateJarBuilder(env): """The Jar builder expects a list of class files which it can package into a jar file. The jar tool provides an interface for passing other types of java files such as .java, directories or swig interfaces and will build them to class files in which it can package into the jar. """ try: java_jar = env['BUILDERS']['JarFile'] except KeyError: fs = SCons.Node.FS.get_default_fs() jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR') java_jar = SCons.Builder.Builder(action = jar_com, suffix = '$JARSUFFIX', src_suffix = '$JAVACLASSSUFFIX', src_builder = 'JavaClassFile', source_factory = fs.Entry) env['BUILDERS']['JarFile'] = java_jar return java_jar
[ "def", "CreateJarBuilder", "(", "env", ")", ":", "try", ":", "java_jar", "=", "env", "[", "'BUILDERS'", "]", "[", "'JarFile'", "]", "except", "KeyError", ":", "fs", "=", "SCons", ".", "Node", ".", "FS", ".", "get_default_fs", "(", ")", "jar_com", "=", "SCons", ".", "Action", ".", "Action", "(", "'$JARCOM'", ",", "'$JARCOMSTR'", ")", "java_jar", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "jar_com", ",", "suffix", "=", "'$JARSUFFIX'", ",", "src_suffix", "=", "'$JAVACLASSSUFFIX'", ",", "src_builder", "=", "'JavaClassFile'", ",", "source_factory", "=", "fs", ".", "Entry", ")", "env", "[", "'BUILDERS'", "]", "[", "'JarFile'", "]", "=", "java_jar", "return", "java_jar" ]
The Jar builder expects a list of class files which it can package into a jar file. The jar tool provides an interface for passing other types of java files such as .java, directories or swig interfaces and will build them to class files in which it can package into the jar.
[ "The", "Jar", "builder", "expects", "a", "list", "of", "class", "files", "which", "it", "can", "package", "into", "a", "jar", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L915-L935
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
ToolInitializerMethod.get_builder
def get_builder(self, env): """ Returns the appropriate real Builder for this method name after having the associated ToolInitializer object apply the appropriate Tool module. """ builder = getattr(env, self.__name__) self.initializer.apply_tools(env) builder = getattr(env, self.__name__) if builder is self: # There was no Builder added, which means no valid Tool # for this name was found (or possibly there's a mismatch # between the name we were called by and the Builder name # added by the Tool module). return None self.initializer.remove_methods(env) return builder
python
def get_builder(self, env): """ Returns the appropriate real Builder for this method name after having the associated ToolInitializer object apply the appropriate Tool module. """ builder = getattr(env, self.__name__) self.initializer.apply_tools(env) builder = getattr(env, self.__name__) if builder is self: # There was no Builder added, which means no valid Tool # for this name was found (or possibly there's a mismatch # between the name we were called by and the Builder name # added by the Tool module). return None self.initializer.remove_methods(env) return builder
[ "def", "get_builder", "(", "self", ",", "env", ")", ":", "builder", "=", "getattr", "(", "env", ",", "self", ".", "__name__", ")", "self", ".", "initializer", ".", "apply_tools", "(", "env", ")", "builder", "=", "getattr", "(", "env", ",", "self", ".", "__name__", ")", "if", "builder", "is", "self", ":", "# There was no Builder added, which means no valid Tool", "# for this name was found (or possibly there's a mismatch", "# between the name we were called by and the Builder name", "# added by the Tool module).", "return", "None", "self", ".", "initializer", ".", "remove_methods", "(", "env", ")", "return", "builder" ]
Returns the appropriate real Builder for this method name after having the associated ToolInitializer object apply the appropriate Tool module.
[ "Returns", "the", "appropriate", "real", "Builder", "for", "this", "method", "name", "after", "having", "the", "associated", "ToolInitializer", "object", "apply", "the", "appropriate", "Tool", "module", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L1009-L1029
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
ToolInitializer.remove_methods
def remove_methods(self, env): """ Removes the methods that were added by the tool initialization so we no longer copy and re-bind them when the construction environment gets cloned. """ for method in list(self.methods.values()): env.RemoveMethod(method)
python
def remove_methods(self, env): """ Removes the methods that were added by the tool initialization so we no longer copy and re-bind them when the construction environment gets cloned. """ for method in list(self.methods.values()): env.RemoveMethod(method)
[ "def", "remove_methods", "(", "self", ",", "env", ")", ":", "for", "method", "in", "list", "(", "self", ".", "methods", ".", "values", "(", ")", ")", ":", "env", ".", "RemoveMethod", "(", "method", ")" ]
Removes the methods that were added by the tool initialization so we no longer copy and re-bind them when the construction environment gets cloned.
[ "Removes", "the", "methods", "that", "were", "added", "by", "the", "tool", "initialization", "so", "we", "no", "longer", "copy", "and", "re", "-", "bind", "them", "when", "the", "construction", "environment", "gets", "cloned", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L1064-L1071
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
ToolInitializer.apply_tools
def apply_tools(self, env): """ Searches the list of associated Tool modules for one that exists, and applies that to the construction environment. """ for t in self.tools: tool = SCons.Tool.Tool(t) if tool.exists(env): env.Tool(tool) return
python
def apply_tools(self, env): """ Searches the list of associated Tool modules for one that exists, and applies that to the construction environment. """ for t in self.tools: tool = SCons.Tool.Tool(t) if tool.exists(env): env.Tool(tool) return
[ "def", "apply_tools", "(", "self", ",", "env", ")", ":", "for", "t", "in", "self", ".", "tools", ":", "tool", "=", "SCons", ".", "Tool", ".", "Tool", "(", "t", ")", "if", "tool", ".", "exists", "(", "env", ")", ":", "env", ".", "Tool", "(", "tool", ")", "return" ]
Searches the list of associated Tool modules for one that exists, and applies that to the construction environment.
[ "Searches", "the", "list", "of", "associated", "Tool", "modules", "for", "one", "that", "exists", "and", "applies", "that", "to", "the", "construction", "environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L1073-L1082
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
get_contents_entry
def get_contents_entry(node): """Fetch the contents of the entry. Returns the exact binary contents of the file.""" try: node = node.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_contents() in emitters and the # like (e.g. in qt.py) don't have to disambiguate by hand # or catch the exception. return '' else: return _get_contents_map[node._func_get_contents](node)
python
def get_contents_entry(node): """Fetch the contents of the entry. Returns the exact binary contents of the file.""" try: node = node.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_contents() in emitters and the # like (e.g. in qt.py) don't have to disambiguate by hand # or catch the exception. return '' else: return _get_contents_map[node._func_get_contents](node)
[ "def", "get_contents_entry", "(", "node", ")", ":", "try", ":", "node", "=", "node", ".", "disambiguate", "(", "must_exist", "=", "1", ")", "except", "SCons", ".", "Errors", ".", "UserError", ":", "# There was nothing on disk with which to disambiguate", "# this entry. Leave it as an Entry, but return a null", "# string so calls to get_contents() in emitters and the", "# like (e.g. in qt.py) don't have to disambiguate by hand", "# or catch the exception.", "return", "''", "else", ":", "return", "_get_contents_map", "[", "node", ".", "_func_get_contents", "]", "(", "node", ")" ]
Fetch the contents of the entry. Returns the exact binary contents of the file.
[ "Fetch", "the", "contents", "of", "the", "entry", ".", "Returns", "the", "exact", "binary", "contents", "of", "the", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L188-L201
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
get_contents_dir
def get_contents_dir(node): """Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.""" contents = [] for n in sorted(node.children(), key=lambda t: t.name): contents.append('%s %s\n' % (n.get_csig(), n.name)) return ''.join(contents)
python
def get_contents_dir(node): """Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.""" contents = [] for n in sorted(node.children(), key=lambda t: t.name): contents.append('%s %s\n' % (n.get_csig(), n.name)) return ''.join(contents)
[ "def", "get_contents_dir", "(", "node", ")", ":", "contents", "=", "[", "]", "for", "n", "in", "sorted", "(", "node", ".", "children", "(", ")", ",", "key", "=", "lambda", "t", ":", "t", ".", "name", ")", ":", "contents", ".", "append", "(", "'%s %s\\n'", "%", "(", "n", ".", "get_csig", "(", ")", ",", "n", ".", "name", ")", ")", "return", "''", ".", "join", "(", "contents", ")" ]
Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.
[ "Return", "content", "signatures", "and", "names", "of", "all", "our", "children", "separated", "by", "new", "-", "lines", ".", "Ensure", "that", "the", "nodes", "are", "sorted", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L203-L209
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.get_build_env
def get_build_env(self): """Fetch the appropriate Environment to build this node. """ try: return self._memo['get_build_env'] except KeyError: pass result = self.get_executor().get_build_env() self._memo['get_build_env'] = result return result
python
def get_build_env(self): """Fetch the appropriate Environment to build this node. """ try: return self._memo['get_build_env'] except KeyError: pass result = self.get_executor().get_build_env() self._memo['get_build_env'] = result return result
[ "def", "get_build_env", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_memo", "[", "'get_build_env'", "]", "except", "KeyError", ":", "pass", "result", "=", "self", ".", "get_executor", "(", ")", ".", "get_build_env", "(", ")", "self", ".", "_memo", "[", "'get_build_env'", "]", "=", "result", "return", "result" ]
Fetch the appropriate Environment to build this node.
[ "Fetch", "the", "appropriate", "Environment", "to", "build", "this", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L616-L625
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.get_executor
def get_executor(self, create=1): """Fetch the action executor for this node. Create one if there isn't already one, and requested to do so.""" try: executor = self.executor except AttributeError: if not create: raise try: act = self.builder.action except AttributeError: executor = SCons.Executor.Null(targets=[self]) else: executor = SCons.Executor.Executor(act, self.env or self.builder.env, [self.builder.overrides], [self], self.sources) self.executor = executor return executor
python
def get_executor(self, create=1): """Fetch the action executor for this node. Create one if there isn't already one, and requested to do so.""" try: executor = self.executor except AttributeError: if not create: raise try: act = self.builder.action except AttributeError: executor = SCons.Executor.Null(targets=[self]) else: executor = SCons.Executor.Executor(act, self.env or self.builder.env, [self.builder.overrides], [self], self.sources) self.executor = executor return executor
[ "def", "get_executor", "(", "self", ",", "create", "=", "1", ")", ":", "try", ":", "executor", "=", "self", ".", "executor", "except", "AttributeError", ":", "if", "not", "create", ":", "raise", "try", ":", "act", "=", "self", ".", "builder", ".", "action", "except", "AttributeError", ":", "executor", "=", "SCons", ".", "Executor", ".", "Null", "(", "targets", "=", "[", "self", "]", ")", "else", ":", "executor", "=", "SCons", ".", "Executor", ".", "Executor", "(", "act", ",", "self", ".", "env", "or", "self", ".", "builder", ".", "env", ",", "[", "self", ".", "builder", ".", "overrides", "]", ",", "[", "self", "]", ",", "self", ".", "sources", ")", "self", ".", "executor", "=", "executor", "return", "executor" ]
Fetch the action executor for this node. Create one if there isn't already one, and requested to do so.
[ "Fetch", "the", "action", "executor", "for", "this", "node", ".", "Create", "one", "if", "there", "isn", "t", "already", "one", "and", "requested", "to", "do", "so", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L635-L654
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.executor_cleanup
def executor_cleanup(self): """Let the executor clean up any cached information.""" try: executor = self.get_executor(create=None) except AttributeError: pass else: if executor is not None: executor.cleanup()
python
def executor_cleanup(self): """Let the executor clean up any cached information.""" try: executor = self.get_executor(create=None) except AttributeError: pass else: if executor is not None: executor.cleanup()
[ "def", "executor_cleanup", "(", "self", ")", ":", "try", ":", "executor", "=", "self", ".", "get_executor", "(", "create", "=", "None", ")", "except", "AttributeError", ":", "pass", "else", ":", "if", "executor", "is", "not", "None", ":", "executor", ".", "cleanup", "(", ")" ]
Let the executor clean up any cached information.
[ "Let", "the", "executor", "clean", "up", "any", "cached", "information", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L656-L664
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.prepare
def prepare(self): """Prepare for this Node to be built. This is called after the Taskmaster has decided that the Node is out-of-date and must be rebuilt, but before actually calling the method to build the Node. This default implementation checks that explicit or implicit dependencies either exist or are derived, and initializes the BuildInfo structure that will hold the information about how this node is, uh, built. (The existence of source files is checked separately by the Executor, which aggregates checks for all of the targets built by a specific action.) Overriding this method allows for for a Node subclass to remove the underlying file from the file system. Note that subclass methods should call this base class method to get the child check and the BuildInfo structure. """ if self.depends is not None: for d in self.depends: if d.missing(): msg = "Explicit dependency `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (d, self)) if self.implicit is not None: for i in self.implicit: if i.missing(): msg = "Implicit dependency `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (i, self)) self.binfo = self.get_binfo()
python
def prepare(self): """Prepare for this Node to be built. This is called after the Taskmaster has decided that the Node is out-of-date and must be rebuilt, but before actually calling the method to build the Node. This default implementation checks that explicit or implicit dependencies either exist or are derived, and initializes the BuildInfo structure that will hold the information about how this node is, uh, built. (The existence of source files is checked separately by the Executor, which aggregates checks for all of the targets built by a specific action.) Overriding this method allows for for a Node subclass to remove the underlying file from the file system. Note that subclass methods should call this base class method to get the child check and the BuildInfo structure. """ if self.depends is not None: for d in self.depends: if d.missing(): msg = "Explicit dependency `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (d, self)) if self.implicit is not None: for i in self.implicit: if i.missing(): msg = "Implicit dependency `%s' not found, needed by target `%s'." raise SCons.Errors.StopError(msg % (i, self)) self.binfo = self.get_binfo()
[ "def", "prepare", "(", "self", ")", ":", "if", "self", ".", "depends", "is", "not", "None", ":", "for", "d", "in", "self", ".", "depends", ":", "if", "d", ".", "missing", "(", ")", ":", "msg", "=", "\"Explicit dependency `%s' not found, needed by target `%s'.\"", "raise", "SCons", ".", "Errors", ".", "StopError", "(", "msg", "%", "(", "d", ",", "self", ")", ")", "if", "self", ".", "implicit", "is", "not", "None", ":", "for", "i", "in", "self", ".", "implicit", ":", "if", "i", ".", "missing", "(", ")", ":", "msg", "=", "\"Implicit dependency `%s' not found, needed by target `%s'.\"", "raise", "SCons", ".", "Errors", ".", "StopError", "(", "msg", "%", "(", "i", ",", "self", ")", ")", "self", ".", "binfo", "=", "self", ".", "get_binfo", "(", ")" ]
Prepare for this Node to be built. This is called after the Taskmaster has decided that the Node is out-of-date and must be rebuilt, but before actually calling the method to build the Node. This default implementation checks that explicit or implicit dependencies either exist or are derived, and initializes the BuildInfo structure that will hold the information about how this node is, uh, built. (The existence of source files is checked separately by the Executor, which aggregates checks for all of the targets built by a specific action.) Overriding this method allows for for a Node subclass to remove the underlying file from the file system. Note that subclass methods should call this base class method to get the child check and the BuildInfo structure.
[ "Prepare", "for", "this", "Node", "to", "be", "built", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L703-L734
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.build
def build(self, **kw): """Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). """ try: self.get_executor()(self, **kw) except SCons.Errors.BuildError as e: e.node = self raise
python
def build(self, **kw): """Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). """ try: self.get_executor()(self, **kw) except SCons.Errors.BuildError as e: e.node = self raise
[ "def", "build", "(", "self", ",", "*", "*", "kw", ")", ":", "try", ":", "self", ".", "get_executor", "(", ")", "(", "self", ",", "*", "*", "kw", ")", "except", "SCons", ".", "Errors", ".", "BuildError", "as", "e", ":", "e", ".", "node", "=", "self", "raise" ]
Actually build the node. This is called by the Taskmaster after it's decided that the Node is out-of-date and must be rebuilt, and after the prepare() method has gotten everything, uh, prepared. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built().
[ "Actually", "build", "the", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L736-L752
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.built
def built(self): """Called just after this node is successfully built.""" # Clear the implicit dependency caches of any Nodes # waiting for this Node to be built. for parent in self.waiting_parents: parent.implicit = None self.clear() if self.pseudo: if self.exists(): raise SCons.Errors.UserError("Pseudo target " + str(self) + " must not exist") else: if not self.exists() and do_store_info: SCons.Warnings.warn(SCons.Warnings.TargetNotBuiltWarning, "Cannot find target " + str(self) + " after building") self.ninfo.update(self)
python
def built(self): """Called just after this node is successfully built.""" # Clear the implicit dependency caches of any Nodes # waiting for this Node to be built. for parent in self.waiting_parents: parent.implicit = None self.clear() if self.pseudo: if self.exists(): raise SCons.Errors.UserError("Pseudo target " + str(self) + " must not exist") else: if not self.exists() and do_store_info: SCons.Warnings.warn(SCons.Warnings.TargetNotBuiltWarning, "Cannot find target " + str(self) + " after building") self.ninfo.update(self)
[ "def", "built", "(", "self", ")", ":", "# Clear the implicit dependency caches of any Nodes", "# waiting for this Node to be built.", "for", "parent", "in", "self", ".", "waiting_parents", ":", "parent", ".", "implicit", "=", "None", "self", ".", "clear", "(", ")", "if", "self", ".", "pseudo", ":", "if", "self", ".", "exists", "(", ")", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"Pseudo target \"", "+", "str", "(", "self", ")", "+", "\" must not exist\"", ")", "else", ":", "if", "not", "self", ".", "exists", "(", ")", "and", "do_store_info", ":", "SCons", ".", "Warnings", ".", "warn", "(", "SCons", ".", "Warnings", ".", "TargetNotBuiltWarning", ",", "\"Cannot find target \"", "+", "str", "(", "self", ")", "+", "\" after building\"", ")", "self", ".", "ninfo", ".", "update", "(", "self", ")" ]
Called just after this node is successfully built.
[ "Called", "just", "after", "this", "node", "is", "successfully", "built", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L754-L771
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.has_builder
def has_builder(self): """Return whether this Node has a builder or not. In Boolean tests, this turns out to be a *lot* more efficient than simply examining the builder attribute directly ("if node.builder: ..."). When the builder attribute is examined directly, it ends up calling __getattr__ for both the __len__ and __nonzero__ attributes on instances of our Builder Proxy class(es), generating a bazillion extra calls and slowing things down immensely. """ try: b = self.builder except AttributeError: # There was no explicit builder for this Node, so initialize # the self.builder attribute to None now. b = self.builder = None return b is not None
python
def has_builder(self): """Return whether this Node has a builder or not. In Boolean tests, this turns out to be a *lot* more efficient than simply examining the builder attribute directly ("if node.builder: ..."). When the builder attribute is examined directly, it ends up calling __getattr__ for both the __len__ and __nonzero__ attributes on instances of our Builder Proxy class(es), generating a bazillion extra calls and slowing things down immensely. """ try: b = self.builder except AttributeError: # There was no explicit builder for this Node, so initialize # the self.builder attribute to None now. b = self.builder = None return b is not None
[ "def", "has_builder", "(", "self", ")", ":", "try", ":", "b", "=", "self", ".", "builder", "except", "AttributeError", ":", "# There was no explicit builder for this Node, so initialize", "# the self.builder attribute to None now.", "b", "=", "self", ".", "builder", "=", "None", "return", "b", "is", "not", "None" ]
Return whether this Node has a builder or not. In Boolean tests, this turns out to be a *lot* more efficient than simply examining the builder attribute directly ("if node.builder: ..."). When the builder attribute is examined directly, it ends up calling __getattr__ for both the __len__ and __nonzero__ attributes on instances of our Builder Proxy class(es), generating a bazillion extra calls and slowing things down immensely.
[ "Return", "whether", "this", "Node", "has", "a", "builder", "or", "not", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L858-L875
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.get_implicit_deps
def get_implicit_deps(self, env, initial_scanner, path_func, kw = {}): """Return a list of implicit dependencies for this node. This method exists to handle recursive invocation of the scanner on the implicit dependencies returned by the scanner, if the scanner's recursive flag says that we should. """ nodes = [self] seen = set(nodes) dependencies = [] path_memo = {} root_node_scanner = self._get_scanner(env, initial_scanner, None, kw) while nodes: node = nodes.pop(0) scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw) if not scanner: continue try: path = path_memo[scanner] except KeyError: path = path_func(scanner) path_memo[scanner] = path included_deps = [x for x in node.get_found_includes(env, scanner, path) if x not in seen] if included_deps: dependencies.extend(included_deps) seen.update(included_deps) nodes.extend(scanner.recurse_nodes(included_deps)) return dependencies
python
def get_implicit_deps(self, env, initial_scanner, path_func, kw = {}): """Return a list of implicit dependencies for this node. This method exists to handle recursive invocation of the scanner on the implicit dependencies returned by the scanner, if the scanner's recursive flag says that we should. """ nodes = [self] seen = set(nodes) dependencies = [] path_memo = {} root_node_scanner = self._get_scanner(env, initial_scanner, None, kw) while nodes: node = nodes.pop(0) scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw) if not scanner: continue try: path = path_memo[scanner] except KeyError: path = path_func(scanner) path_memo[scanner] = path included_deps = [x for x in node.get_found_includes(env, scanner, path) if x not in seen] if included_deps: dependencies.extend(included_deps) seen.update(included_deps) nodes.extend(scanner.recurse_nodes(included_deps)) return dependencies
[ "def", "get_implicit_deps", "(", "self", ",", "env", ",", "initial_scanner", ",", "path_func", ",", "kw", "=", "{", "}", ")", ":", "nodes", "=", "[", "self", "]", "seen", "=", "set", "(", "nodes", ")", "dependencies", "=", "[", "]", "path_memo", "=", "{", "}", "root_node_scanner", "=", "self", ".", "_get_scanner", "(", "env", ",", "initial_scanner", ",", "None", ",", "kw", ")", "while", "nodes", ":", "node", "=", "nodes", ".", "pop", "(", "0", ")", "scanner", "=", "node", ".", "_get_scanner", "(", "env", ",", "initial_scanner", ",", "root_node_scanner", ",", "kw", ")", "if", "not", "scanner", ":", "continue", "try", ":", "path", "=", "path_memo", "[", "scanner", "]", "except", "KeyError", ":", "path", "=", "path_func", "(", "scanner", ")", "path_memo", "[", "scanner", "]", "=", "path", "included_deps", "=", "[", "x", "for", "x", "in", "node", ".", "get_found_includes", "(", "env", ",", "scanner", ",", "path", ")", "if", "x", "not", "in", "seen", "]", "if", "included_deps", ":", "dependencies", ".", "extend", "(", "included_deps", ")", "seen", ".", "update", "(", "included_deps", ")", "nodes", ".", "extend", "(", "scanner", ".", "recurse_nodes", "(", "included_deps", ")", ")", "return", "dependencies" ]
Return a list of implicit dependencies for this node. This method exists to handle recursive invocation of the scanner on the implicit dependencies returned by the scanner, if the scanner's recursive flag says that we should.
[ "Return", "a", "list", "of", "implicit", "dependencies", "for", "this", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L929-L962
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.get_source_scanner
def get_source_scanner(self, node): """Fetch the source scanner for the specified node NOTE: "self" is the target being built, "node" is the source file for which we want to fetch the scanner. Implies self.has_builder() is true; again, expect to only be called from locations where this is already verified. This function may be called very often; it attempts to cache the scanner found to improve performance. """ scanner = None try: scanner = self.builder.source_scanner except AttributeError: pass if not scanner: # The builder didn't have an explicit scanner, so go look up # a scanner from env['SCANNERS'] based on the node's scanner # key (usually the file extension). scanner = self.get_env_scanner(self.get_build_env()) if scanner: scanner = scanner.select(node) return scanner
python
def get_source_scanner(self, node): """Fetch the source scanner for the specified node NOTE: "self" is the target being built, "node" is the source file for which we want to fetch the scanner. Implies self.has_builder() is true; again, expect to only be called from locations where this is already verified. This function may be called very often; it attempts to cache the scanner found to improve performance. """ scanner = None try: scanner = self.builder.source_scanner except AttributeError: pass if not scanner: # The builder didn't have an explicit scanner, so go look up # a scanner from env['SCANNERS'] based on the node's scanner # key (usually the file extension). scanner = self.get_env_scanner(self.get_build_env()) if scanner: scanner = scanner.select(node) return scanner
[ "def", "get_source_scanner", "(", "self", ",", "node", ")", ":", "scanner", "=", "None", "try", ":", "scanner", "=", "self", ".", "builder", ".", "source_scanner", "except", "AttributeError", ":", "pass", "if", "not", "scanner", ":", "# The builder didn't have an explicit scanner, so go look up", "# a scanner from env['SCANNERS'] based on the node's scanner", "# key (usually the file extension).", "scanner", "=", "self", ".", "get_env_scanner", "(", "self", ".", "get_build_env", "(", ")", ")", "if", "scanner", ":", "scanner", "=", "scanner", ".", "select", "(", "node", ")", "return", "scanner" ]
Fetch the source scanner for the specified node NOTE: "self" is the target being built, "node" is the source file for which we want to fetch the scanner. Implies self.has_builder() is true; again, expect to only be called from locations where this is already verified. This function may be called very often; it attempts to cache the scanner found to improve performance.
[ "Fetch", "the", "source", "scanner", "for", "the", "specified", "node" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L987-L1011
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.scan
def scan(self): """Scan this node's dependents for implicit dependencies.""" # Don't bother scanning non-derived files, because we don't # care what their dependencies are. # Don't scan again, if we already have scanned. if self.implicit is not None: return self.implicit = [] self.implicit_set = set() self._children_reset() if not self.has_builder(): return build_env = self.get_build_env() executor = self.get_executor() # Here's where we implement --implicit-cache. if implicit_cache and not implicit_deps_changed: implicit = self.get_stored_implicit() if implicit is not None: # We now add the implicit dependencies returned from the # stored .sconsign entry to have already been converted # to Nodes for us. (We used to run them through a # source_factory function here.) # Update all of the targets with them. This # essentially short-circuits an N*M scan of the # sources for each individual target, which is a hell # of a lot more efficient. for tgt in executor.get_all_targets(): tgt.add_to_implicit(implicit) if implicit_deps_unchanged or self.is_up_to_date(): return # one of this node's sources has changed, # so we must recalculate the implicit deps for all targets for tgt in executor.get_all_targets(): tgt.implicit = [] tgt.implicit_set = set() # Have the executor scan the sources. executor.scan_sources(self.builder.source_scanner) # If there's a target scanner, have the executor scan the target # node itself and associated targets that might be built. scanner = self.get_target_scanner() if scanner: executor.scan_targets(scanner)
python
def scan(self): """Scan this node's dependents for implicit dependencies.""" # Don't bother scanning non-derived files, because we don't # care what their dependencies are. # Don't scan again, if we already have scanned. if self.implicit is not None: return self.implicit = [] self.implicit_set = set() self._children_reset() if not self.has_builder(): return build_env = self.get_build_env() executor = self.get_executor() # Here's where we implement --implicit-cache. if implicit_cache and not implicit_deps_changed: implicit = self.get_stored_implicit() if implicit is not None: # We now add the implicit dependencies returned from the # stored .sconsign entry to have already been converted # to Nodes for us. (We used to run them through a # source_factory function here.) # Update all of the targets with them. This # essentially short-circuits an N*M scan of the # sources for each individual target, which is a hell # of a lot more efficient. for tgt in executor.get_all_targets(): tgt.add_to_implicit(implicit) if implicit_deps_unchanged or self.is_up_to_date(): return # one of this node's sources has changed, # so we must recalculate the implicit deps for all targets for tgt in executor.get_all_targets(): tgt.implicit = [] tgt.implicit_set = set() # Have the executor scan the sources. executor.scan_sources(self.builder.source_scanner) # If there's a target scanner, have the executor scan the target # node itself and associated targets that might be built. scanner = self.get_target_scanner() if scanner: executor.scan_targets(scanner)
[ "def", "scan", "(", "self", ")", ":", "# Don't bother scanning non-derived files, because we don't", "# care what their dependencies are.", "# Don't scan again, if we already have scanned.", "if", "self", ".", "implicit", "is", "not", "None", ":", "return", "self", ".", "implicit", "=", "[", "]", "self", ".", "implicit_set", "=", "set", "(", ")", "self", ".", "_children_reset", "(", ")", "if", "not", "self", ".", "has_builder", "(", ")", ":", "return", "build_env", "=", "self", ".", "get_build_env", "(", ")", "executor", "=", "self", ".", "get_executor", "(", ")", "# Here's where we implement --implicit-cache.", "if", "implicit_cache", "and", "not", "implicit_deps_changed", ":", "implicit", "=", "self", ".", "get_stored_implicit", "(", ")", "if", "implicit", "is", "not", "None", ":", "# We now add the implicit dependencies returned from the", "# stored .sconsign entry to have already been converted", "# to Nodes for us. (We used to run them through a", "# source_factory function here.)", "# Update all of the targets with them. This", "# essentially short-circuits an N*M scan of the", "# sources for each individual target, which is a hell", "# of a lot more efficient.", "for", "tgt", "in", "executor", ".", "get_all_targets", "(", ")", ":", "tgt", ".", "add_to_implicit", "(", "implicit", ")", "if", "implicit_deps_unchanged", "or", "self", ".", "is_up_to_date", "(", ")", ":", "return", "# one of this node's sources has changed,", "# so we must recalculate the implicit deps for all targets", "for", "tgt", "in", "executor", ".", "get_all_targets", "(", ")", ":", "tgt", ".", "implicit", "=", "[", "]", "tgt", ".", "implicit_set", "=", "set", "(", ")", "# Have the executor scan the sources.", "executor", ".", "scan_sources", "(", "self", ".", "builder", ".", "source_scanner", ")", "# If there's a target scanner, have the executor scan the target", "# node itself and associated targets that might be built.", "scanner", "=", "self", ".", "get_target_scanner", "(", ")", "if", "scanner", ":", "executor", ".", "scan_targets", "(", "scanner", ")" ]
Scan this node's dependents for implicit dependencies.
[ "Scan", "this", "node", "s", "dependents", "for", "implicit", "dependencies", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1020-L1067
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.get_binfo
def get_binfo(self): """ Fetch a node's build information. node - the node whose sources will be collected cache - alternate node to use for the signature cache returns - the build signature This no longer handles the recursive descent of the node's children's signatures. We expect that they're already built and updated by someone else, if that's what's wanted. """ try: return self.binfo except AttributeError: pass binfo = self.new_binfo() self.binfo = binfo executor = self.get_executor() ignore_set = self.ignore_set if self.has_builder(): binfo.bact = str(executor) binfo.bactsig = SCons.Util.MD5signature(executor.get_contents()) if self._specific_sources: sources = [ s for s in self.sources if not s in ignore_set] else: sources = executor.get_unignored_sources(self, self.ignore) seen = set() binfo.bsources = [s for s in sources if s not in seen and not seen.add(s)] binfo.bsourcesigs = [s.get_ninfo() for s in binfo.bsources] binfo.bdepends = self.depends binfo.bdependsigs = [d.get_ninfo() for d in self.depends if d not in ignore_set] binfo.bimplicit = self.implicit or [] binfo.bimplicitsigs = [i.get_ninfo() for i in binfo.bimplicit if i not in ignore_set] return binfo
python
def get_binfo(self): """ Fetch a node's build information. node - the node whose sources will be collected cache - alternate node to use for the signature cache returns - the build signature This no longer handles the recursive descent of the node's children's signatures. We expect that they're already built and updated by someone else, if that's what's wanted. """ try: return self.binfo except AttributeError: pass binfo = self.new_binfo() self.binfo = binfo executor = self.get_executor() ignore_set = self.ignore_set if self.has_builder(): binfo.bact = str(executor) binfo.bactsig = SCons.Util.MD5signature(executor.get_contents()) if self._specific_sources: sources = [ s for s in self.sources if not s in ignore_set] else: sources = executor.get_unignored_sources(self, self.ignore) seen = set() binfo.bsources = [s for s in sources if s not in seen and not seen.add(s)] binfo.bsourcesigs = [s.get_ninfo() for s in binfo.bsources] binfo.bdepends = self.depends binfo.bdependsigs = [d.get_ninfo() for d in self.depends if d not in ignore_set] binfo.bimplicit = self.implicit or [] binfo.bimplicitsigs = [i.get_ninfo() for i in binfo.bimplicit if i not in ignore_set] return binfo
[ "def", "get_binfo", "(", "self", ")", ":", "try", ":", "return", "self", ".", "binfo", "except", "AttributeError", ":", "pass", "binfo", "=", "self", ".", "new_binfo", "(", ")", "self", ".", "binfo", "=", "binfo", "executor", "=", "self", ".", "get_executor", "(", ")", "ignore_set", "=", "self", ".", "ignore_set", "if", "self", ".", "has_builder", "(", ")", ":", "binfo", ".", "bact", "=", "str", "(", "executor", ")", "binfo", ".", "bactsig", "=", "SCons", ".", "Util", ".", "MD5signature", "(", "executor", ".", "get_contents", "(", ")", ")", "if", "self", ".", "_specific_sources", ":", "sources", "=", "[", "s", "for", "s", "in", "self", ".", "sources", "if", "not", "s", "in", "ignore_set", "]", "else", ":", "sources", "=", "executor", ".", "get_unignored_sources", "(", "self", ",", "self", ".", "ignore", ")", "seen", "=", "set", "(", ")", "binfo", ".", "bsources", "=", "[", "s", "for", "s", "in", "sources", "if", "s", "not", "in", "seen", "and", "not", "seen", ".", "add", "(", "s", ")", "]", "binfo", ".", "bsourcesigs", "=", "[", "s", ".", "get_ninfo", "(", ")", "for", "s", "in", "binfo", ".", "bsources", "]", "binfo", ".", "bdepends", "=", "self", ".", "depends", "binfo", ".", "bdependsigs", "=", "[", "d", ".", "get_ninfo", "(", ")", "for", "d", "in", "self", ".", "depends", "if", "d", "not", "in", "ignore_set", "]", "binfo", ".", "bimplicit", "=", "self", ".", "implicit", "or", "[", "]", "binfo", ".", "bimplicitsigs", "=", "[", "i", ".", "get_ninfo", "(", ")", "for", "i", "in", "binfo", ".", "bimplicit", "if", "i", "not", "in", "ignore_set", "]", "return", "binfo" ]
Fetch a node's build information. node - the node whose sources will be collected cache - alternate node to use for the signature cache returns - the build signature This no longer handles the recursive descent of the node's children's signatures. We expect that they're already built and updated by someone else, if that's what's wanted.
[ "Fetch", "a", "node", "s", "build", "information", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1109-L1155
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.add_dependency
def add_dependency(self, depend): """Adds dependencies.""" try: self._add_child(self.depends, self.depends_set, depend) 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 dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
python
def add_dependency(self, depend): """Adds dependencies.""" try: self._add_child(self.depends, self.depends_set, depend) 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 dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
[ "def", "add_dependency", "(", "self", ",", "depend", ")", ":", "try", ":", "self", ".", "_add_child", "(", "self", ".", "depends", ",", "self", ".", "depends_set", ",", "depend", ")", "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 dependency to %s:\\n\\t%s is a %s, not a Node\"", "%", "(", "str", "(", "self", ")", ",", "s", ",", "type", "(", "e", ")", ")", ")" ]
Adds dependencies.
[ "Adds", "dependencies", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1232-L1242
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
Node.add_ignore
def add_ignore(self, depend): """Adds dependencies to ignore.""" try: self._add_child(self.ignore, self.ignore_set, depend) 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 ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
python
def add_ignore(self, depend): """Adds dependencies to ignore.""" try: self._add_child(self.ignore, self.ignore_set, depend) 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 ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
[ "def", "add_ignore", "(", "self", ",", "depend", ")", ":", "try", ":", "self", ".", "_add_child", "(", "self", ".", "ignore", ",", "self", ".", "ignore_set", ",", "depend", ")", "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 ignore a non-Node dependency of %s:\\n\\t%s is a %s, not a Node\"", "%", "(", "str", "(", "self", ")", ",", "s", ",", "type", "(", "e", ")", ")", ")" ]
Adds dependencies to ignore.
[ "Adds", "dependencies", "to", "ignore", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1251-L1261
train
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): """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)))
[ "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", ")", ")", ")" ]
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
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """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]))
[ "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", "]", ")", ")" ]
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
train
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): """ Add a user-defined tag. """ 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
train
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): """ 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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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(): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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()
[ "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", "(", ")" ]
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
train
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): """ 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()
[ "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", "(", ")" ]
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
train
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): """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)
[ "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
train
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=[]): """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())
[ "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", "(", ")", ")" ]
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
train
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): """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))
[ "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", ")", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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]]
[ "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", "]", "]" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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
[ "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
train
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): """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)
[ "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", ")" ]
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", "particular", "hardware", "and", "situation", ".", "They", "are", "stackable", "so", "that", "you", "can", "specify", "a", "chip", "and", "a", "configuration", "for", "that", "chip", "for", "example", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L380-L393
train
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): """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"
[ "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\"" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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]]
[ "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", "]", "]" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """Get the current value of a user timer.""" 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
train
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): """Set the current value of a user timer.""" 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
train
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): """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]
[ "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", "]" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """ 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)
[ "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", ")" ]
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
train
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): """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('', ['']))
[ "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", "(", "''", ",", "[", "''", "]", ")", ")" ]
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
train
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): """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')
[ "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'", ")" ]
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
train
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): """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]
[ "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", "]" ]
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
train
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", ",", "slash", "+", "c", ")", "# print(\"ESCAPE RESULT: %s\" % arg)", "return", "'\"'", "+", "arg", "+", "'\"'" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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
[ "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" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)} $)'
[ "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)} $)'" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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): """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)
[ "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", ")" ]
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
train
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 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)
[ "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
train
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): """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
[ "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" ]
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
train
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): """ Returns an object that re-binds the underlying "method" to the specified 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
train
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): """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())
[ "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", "(", ")", ")" ]
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
train
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): """ 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)
[ "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", "itself", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L597-L604
train