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
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_config
def add_config(self, slot, config_id, config_type, value): """Add a config variable assignment to this sensor graph. Args: slot (SlotIdentifier): The slot identifier that this config variable is assigned to. config_id (int): The 16-bit id of this config_id config_type (str): The type of the config variable, currently supported are fixed width integer types, strings and binary blobs. value (str|int|bytes): The value to assign to the config variable. """ if slot not in self.config_database: self.config_database[slot] = {} self.config_database[slot][config_id] = (config_type, value)
python
def add_config(self, slot, config_id, config_type, value): """Add a config variable assignment to this sensor graph. Args: slot (SlotIdentifier): The slot identifier that this config variable is assigned to. config_id (int): The 16-bit id of this config_id config_type (str): The type of the config variable, currently supported are fixed width integer types, strings and binary blobs. value (str|int|bytes): The value to assign to the config variable. """ if slot not in self.config_database: self.config_database[slot] = {} self.config_database[slot][config_id] = (config_type, value)
[ "def", "add_config", "(", "self", ",", "slot", ",", "config_id", ",", "config_type", ",", "value", ")", ":", "if", "slot", "not", "in", "self", ".", "config_database", ":", "self", ".", "config_database", "[", "slot", "]", "=", "{", "}", "self", ".", "config_database", "[", "slot", "]", "[", "config_id", "]", "=", "(", "config_type", ",", "value", ")" ]
Add a config variable assignment to this sensor graph. Args: slot (SlotIdentifier): The slot identifier that this config variable is assigned to. config_id (int): The 16-bit id of this config_id config_type (str): The type of the config variable, currently supported are fixed width integer types, strings and binary blobs. value (str|int|bytes): The value to assign to the config variable.
[ "Add", "a", "config", "variable", "assignment", "to", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L129-L145
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_streamer
def add_streamer(self, streamer): """Add a streamer to this sensor graph. Args: streamer (DataStreamer): The streamer we want to add """ if self._max_streamers is not None and len(self.streamers) >= self._max_streamers: raise ResourceUsageError("Maximum number of streamers exceeded", max_streamers=self._max_streamers) streamer.link_to_storage(self.sensor_log) streamer.index = len(self.streamers) self.streamers.append(streamer)
python
def add_streamer(self, streamer): """Add a streamer to this sensor graph. Args: streamer (DataStreamer): The streamer we want to add """ if self._max_streamers is not None and len(self.streamers) >= self._max_streamers: raise ResourceUsageError("Maximum number of streamers exceeded", max_streamers=self._max_streamers) streamer.link_to_storage(self.sensor_log) streamer.index = len(self.streamers) self.streamers.append(streamer)
[ "def", "add_streamer", "(", "self", ",", "streamer", ")", ":", "if", "self", ".", "_max_streamers", "is", "not", "None", "and", "len", "(", "self", ".", "streamers", ")", ">=", "self", ".", "_max_streamers", ":", "raise", "ResourceUsageError", "(", "\"Maximum number of streamers exceeded\"", ",", "max_streamers", "=", "self", ".", "_max_streamers", ")", "streamer", ".", "link_to_storage", "(", "self", ".", "sensor_log", ")", "streamer", ".", "index", "=", "len", "(", "self", ".", "streamers", ")", "self", ".", "streamers", ".", "append", "(", "streamer", ")" ]
Add a streamer to this sensor graph. Args: streamer (DataStreamer): The streamer we want to add
[ "Add", "a", "streamer", "to", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L147-L160
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_constant
def add_constant(self, stream, value): """Store a constant value for use in this sensor graph. Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers. Args: stream (DataStream): The constant stream to assign the value to value (int): The value to assign. """ if stream in self.constant_database: raise ArgumentError("Attempted to set the same constant twice", stream=stream, old_value=self.constant_database[stream], new_value=value) self.constant_database[stream] = value
python
def add_constant(self, stream, value): """Store a constant value for use in this sensor graph. Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers. Args: stream (DataStream): The constant stream to assign the value to value (int): The value to assign. """ if stream in self.constant_database: raise ArgumentError("Attempted to set the same constant twice", stream=stream, old_value=self.constant_database[stream], new_value=value) self.constant_database[stream] = value
[ "def", "add_constant", "(", "self", ",", "stream", ",", "value", ")", ":", "if", "stream", "in", "self", ".", "constant_database", ":", "raise", "ArgumentError", "(", "\"Attempted to set the same constant twice\"", ",", "stream", "=", "stream", ",", "old_value", "=", "self", ".", "constant_database", "[", "stream", "]", ",", "new_value", "=", "value", ")", "self", ".", "constant_database", "[", "stream", "]", "=", "value" ]
Store a constant value for use in this sensor graph. Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers. Args: stream (DataStream): The constant stream to assign the value to value (int): The value to assign.
[ "Store", "a", "constant", "value", "for", "use", "in", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L162-L177
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_metadata
def add_metadata(self, name, value): """Attach a piece of metadata to this sensorgraph. Metadata is not used during the simulation of a sensorgraph but allows it to convey additional context that may be used during code generation. For example, associating an `app_tag` with a sensorgraph allows the snippet code generator to set that app_tag on a device when programming the sensorgraph. Arg: name (str): The name of the metadata that we wish to associate with this sensorgraph. value (object): The value we wish to store. """ if name in self.metadata_database: raise ArgumentError("Attempted to set the same metadata value twice", name=name, old_value=self.metadata_database[name], new_value=value) self.metadata_database[name] = value
python
def add_metadata(self, name, value): """Attach a piece of metadata to this sensorgraph. Metadata is not used during the simulation of a sensorgraph but allows it to convey additional context that may be used during code generation. For example, associating an `app_tag` with a sensorgraph allows the snippet code generator to set that app_tag on a device when programming the sensorgraph. Arg: name (str): The name of the metadata that we wish to associate with this sensorgraph. value (object): The value we wish to store. """ if name in self.metadata_database: raise ArgumentError("Attempted to set the same metadata value twice", name=name, old_value=self.metadata_database[name], new_value=value) self.metadata_database[name] = value
[ "def", "add_metadata", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "in", "self", ".", "metadata_database", ":", "raise", "ArgumentError", "(", "\"Attempted to set the same metadata value twice\"", ",", "name", "=", "name", ",", "old_value", "=", "self", ".", "metadata_database", "[", "name", "]", ",", "new_value", "=", "value", ")", "self", ".", "metadata_database", "[", "name", "]", "=", "value" ]
Attach a piece of metadata to this sensorgraph. Metadata is not used during the simulation of a sensorgraph but allows it to convey additional context that may be used during code generation. For example, associating an `app_tag` with a sensorgraph allows the snippet code generator to set that app_tag on a device when programming the sensorgraph. Arg: name (str): The name of the metadata that we wish to associate with this sensorgraph. value (object): The value we wish to store.
[ "Attach", "a", "piece", "of", "metadata", "to", "this", "sensorgraph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L179-L197
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.initialize_remaining_constants
def initialize_remaining_constants(self, value=0): """Ensure that all constant streams referenced in the sensor graph have a value. Constant streams that are automatically created by the compiler are initialized as part of the compilation process but it's possible that the user references other constant streams but never assigns them an explicit initial value. This function will initialize them all to a default value (0 if not passed) and return the streams that were so initialized. Args: value (int): Optional value to use to initialize all uninitialized constants. Defaults to 0 if not passed. Returns: list(DataStream): A list of all of the constant streams that were not previously initialized and were initialized to the given value in this function. """ remaining = [] for node, _inputs, _outputs in self.iterate_bfs(): streams = node.input_streams() + [node.stream] for stream in streams: if stream.stream_type is not DataStream.ConstantType: continue if stream not in self.constant_database: self.add_constant(stream, value) remaining.append(stream) return remaining
python
def initialize_remaining_constants(self, value=0): """Ensure that all constant streams referenced in the sensor graph have a value. Constant streams that are automatically created by the compiler are initialized as part of the compilation process but it's possible that the user references other constant streams but never assigns them an explicit initial value. This function will initialize them all to a default value (0 if not passed) and return the streams that were so initialized. Args: value (int): Optional value to use to initialize all uninitialized constants. Defaults to 0 if not passed. Returns: list(DataStream): A list of all of the constant streams that were not previously initialized and were initialized to the given value in this function. """ remaining = [] for node, _inputs, _outputs in self.iterate_bfs(): streams = node.input_streams() + [node.stream] for stream in streams: if stream.stream_type is not DataStream.ConstantType: continue if stream not in self.constant_database: self.add_constant(stream, value) remaining.append(stream) return remaining
[ "def", "initialize_remaining_constants", "(", "self", ",", "value", "=", "0", ")", ":", "remaining", "=", "[", "]", "for", "node", ",", "_inputs", ",", "_outputs", "in", "self", ".", "iterate_bfs", "(", ")", ":", "streams", "=", "node", ".", "input_streams", "(", ")", "+", "[", "node", ".", "stream", "]", "for", "stream", "in", "streams", ":", "if", "stream", ".", "stream_type", "is", "not", "DataStream", ".", "ConstantType", ":", "continue", "if", "stream", "not", "in", "self", ".", "constant_database", ":", "self", ".", "add_constant", "(", "stream", ",", "value", ")", "remaining", ".", "append", "(", "stream", ")", "return", "remaining" ]
Ensure that all constant streams referenced in the sensor graph have a value. Constant streams that are automatically created by the compiler are initialized as part of the compilation process but it's possible that the user references other constant streams but never assigns them an explicit initial value. This function will initialize them all to a default value (0 if not passed) and return the streams that were so initialized. Args: value (int): Optional value to use to initialize all uninitialized constants. Defaults to 0 if not passed. Returns: list(DataStream): A list of all of the constant streams that were not previously initialized and were initialized to the given value in this function.
[ "Ensure", "that", "all", "constant", "streams", "referenced", "in", "the", "sensor", "graph", "have", "a", "value", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L199-L230
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.load_constants
def load_constants(self): """Load all constants into their respective streams. All previous calls to add_constant stored a constant value that should be associated with virtual stream walkers. This function actually calls push_stream in order to push all of the constant values to their walkers. """ for stream, value in self.constant_database.items(): self.sensor_log.push(stream, IOTileReading(0, stream.encode(), value))
python
def load_constants(self): """Load all constants into their respective streams. All previous calls to add_constant stored a constant value that should be associated with virtual stream walkers. This function actually calls push_stream in order to push all of the constant values to their walkers. """ for stream, value in self.constant_database.items(): self.sensor_log.push(stream, IOTileReading(0, stream.encode(), value))
[ "def", "load_constants", "(", "self", ")", ":", "for", "stream", ",", "value", "in", "self", ".", "constant_database", ".", "items", "(", ")", ":", "self", ".", "sensor_log", ".", "push", "(", "stream", ",", "IOTileReading", "(", "0", ",", "stream", ".", "encode", "(", ")", ",", "value", ")", ")" ]
Load all constants into their respective streams. All previous calls to add_constant stored a constant value that should be associated with virtual stream walkers. This function actually calls push_stream in order to push all of the constant values to their walkers.
[ "Load", "all", "constants", "into", "their", "respective", "streams", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L232-L242
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.get_config
def get_config(self, slot, config_id): """Get a config variable assignment previously set on this sensor graph. Args: slot (SlotIdentifier): The slot that we are setting this config variable on. config_id (int): The 16-bit config variable identifier. Returns: (str, str|int): Returns a tuple with the type of the config variable and the value that is being set. Raises: ArgumentError: If the config variable is not currently set on the specified slot. """ if slot not in self.config_database: raise ArgumentError("No config variables have been set on specified slot", slot=slot) if config_id not in self.config_database[slot]: raise ArgumentError("Config variable has not been set on specified slot", slot=slot, config_id=config_id) return self.config_database[slot][config_id]
python
def get_config(self, slot, config_id): """Get a config variable assignment previously set on this sensor graph. Args: slot (SlotIdentifier): The slot that we are setting this config variable on. config_id (int): The 16-bit config variable identifier. Returns: (str, str|int): Returns a tuple with the type of the config variable and the value that is being set. Raises: ArgumentError: If the config variable is not currently set on the specified slot. """ if slot not in self.config_database: raise ArgumentError("No config variables have been set on specified slot", slot=slot) if config_id not in self.config_database[slot]: raise ArgumentError("Config variable has not been set on specified slot", slot=slot, config_id=config_id) return self.config_database[slot][config_id]
[ "def", "get_config", "(", "self", ",", "slot", ",", "config_id", ")", ":", "if", "slot", "not", "in", "self", ".", "config_database", ":", "raise", "ArgumentError", "(", "\"No config variables have been set on specified slot\"", ",", "slot", "=", "slot", ")", "if", "config_id", "not", "in", "self", ".", "config_database", "[", "slot", "]", ":", "raise", "ArgumentError", "(", "\"Config variable has not been set on specified slot\"", ",", "slot", "=", "slot", ",", "config_id", "=", "config_id", ")", "return", "self", ".", "config_database", "[", "slot", "]", "[", "config_id", "]" ]
Get a config variable assignment previously set on this sensor graph. Args: slot (SlotIdentifier): The slot that we are setting this config variable on. config_id (int): The 16-bit config variable identifier. Returns: (str, str|int): Returns a tuple with the type of the config variable and the value that is being set. Raises: ArgumentError: If the config variable is not currently set on the specified slot.
[ "Get", "a", "config", "variable", "assignment", "previously", "set", "on", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L244-L267
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.is_output
def is_output(self, stream): """Check if a stream is a sensor graph output. Return: bool """ for streamer in self.streamers: if streamer.selector.matches(stream): return True return False
python
def is_output(self, stream): """Check if a stream is a sensor graph output. Return: bool """ for streamer in self.streamers: if streamer.selector.matches(stream): return True return False
[ "def", "is_output", "(", "self", ",", "stream", ")", ":", "for", "streamer", "in", "self", ".", "streamers", ":", "if", "streamer", ".", "selector", ".", "matches", "(", "stream", ")", ":", "return", "True", "return", "False" ]
Check if a stream is a sensor graph output. Return: bool
[ "Check", "if", "a", "stream", "is", "a", "sensor", "graph", "output", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L269-L280
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.get_tick
def get_tick(self, name): """Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph compiler and used for fast operations and finally there are several field configurable ticks that can be used for setting up configurable timers. This is done by setting a config variable on the controller with the desired tick interval, which is then interpreted by this function. The appropriate config_id to use is listed in `known_constants.py` Returns: int: 0 if the tick is disabled, otherwise the number of seconds between each tick """ name_map = { 'fast': config_fast_tick_secs, 'user1': config_tick1_secs, 'user2': config_tick2_secs } config = name_map.get(name) if config is None: raise ArgumentError("Unknown tick requested", name=name) slot = SlotIdentifier.FromString('controller') try: var = self.get_config(slot, config) return var[1] except ArgumentError: return 0
python
def get_tick(self, name): """Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph compiler and used for fast operations and finally there are several field configurable ticks that can be used for setting up configurable timers. This is done by setting a config variable on the controller with the desired tick interval, which is then interpreted by this function. The appropriate config_id to use is listed in `known_constants.py` Returns: int: 0 if the tick is disabled, otherwise the number of seconds between each tick """ name_map = { 'fast': config_fast_tick_secs, 'user1': config_tick1_secs, 'user2': config_tick2_secs } config = name_map.get(name) if config is None: raise ArgumentError("Unknown tick requested", name=name) slot = SlotIdentifier.FromString('controller') try: var = self.get_config(slot, config) return var[1] except ArgumentError: return 0
[ "def", "get_tick", "(", "self", ",", "name", ")", ":", "name_map", "=", "{", "'fast'", ":", "config_fast_tick_secs", ",", "'user1'", ":", "config_tick1_secs", ",", "'user2'", ":", "config_tick2_secs", "}", "config", "=", "name_map", ".", "get", "(", "name", ")", "if", "config", "is", "None", ":", "raise", "ArgumentError", "(", "\"Unknown tick requested\"", ",", "name", "=", "name", ")", "slot", "=", "SlotIdentifier", ".", "FromString", "(", "'controller'", ")", "try", ":", "var", "=", "self", ".", "get_config", "(", "slot", ",", "config", ")", "return", "var", "[", "1", "]", "except", "ArgumentError", ":", "return", "0" ]
Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph compiler and used for fast operations and finally there are several field configurable ticks that can be used for setting up configurable timers. This is done by setting a config variable on the controller with the desired tick interval, which is then interpreted by this function. The appropriate config_id to use is listed in `known_constants.py` Returns: int: 0 if the tick is disabled, otherwise the number of seconds between each tick
[ "Check", "the", "config", "variables", "to", "see", "if", "there", "is", "a", "configurable", "tick", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L282-L318
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.mark_streamer
def mark_streamer(self, index): """Manually mark a streamer that should trigger. The next time check_streamers is called, the given streamer will be manually marked that it should trigger, which will cause it to trigger unless it has no data. Args: index (int): The index of the streamer that we should mark as manually triggered. Raises: ArgumentError: If the streamer index is invalid. """ self._logger.debug("Marking streamer %d manually", index) if index >= len(self.streamers): raise ArgumentError("Invalid streamer index", index=index, num_streamers=len(self.streamers)) self._manually_triggered_streamers.add(index)
python
def mark_streamer(self, index): """Manually mark a streamer that should trigger. The next time check_streamers is called, the given streamer will be manually marked that it should trigger, which will cause it to trigger unless it has no data. Args: index (int): The index of the streamer that we should mark as manually triggered. Raises: ArgumentError: If the streamer index is invalid. """ self._logger.debug("Marking streamer %d manually", index) if index >= len(self.streamers): raise ArgumentError("Invalid streamer index", index=index, num_streamers=len(self.streamers)) self._manually_triggered_streamers.add(index)
[ "def", "mark_streamer", "(", "self", ",", "index", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Marking streamer %d manually\"", ",", "index", ")", "if", "index", ">=", "len", "(", "self", ".", "streamers", ")", ":", "raise", "ArgumentError", "(", "\"Invalid streamer index\"", ",", "index", "=", "index", ",", "num_streamers", "=", "len", "(", "self", ".", "streamers", ")", ")", "self", ".", "_manually_triggered_streamers", ".", "add", "(", "index", ")" ]
Manually mark a streamer that should trigger. The next time check_streamers is called, the given streamer will be manually marked that it should trigger, which will cause it to trigger unless it has no data. Args: index (int): The index of the streamer that we should mark as manually triggered. Raises: ArgumentError: If the streamer index is invalid.
[ "Manually", "mark", "a", "streamer", "that", "should", "trigger", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L358-L377
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.check_streamers
def check_streamers(self, blacklist=None): """Check if any streamers are ready to produce a report. You can limit what streamers are checked by passing a set-like object into blacklist. This method is the primary way to see when you should poll a given streamer for its next report. Note, this function is not idempotent. If a streamer is marked as manual and it is triggered from a node rule inside the sensor_graph, that trigger will only last as long as the next call to check_streamers() so you need to explicitly build a report on all ready streamers before calling check_streamers again. Args: blacklist (set): Optional set of streamer indices that should not be checked right now. Returns: list of DataStreamer: A list of the ready streamers. """ ready = [] selected = set() for i, streamer in enumerate(self.streamers): if blacklist is not None and i in blacklist: continue if i in selected: continue marked = False if i in self._manually_triggered_streamers: marked = True self._manually_triggered_streamers.remove(i) if streamer.triggered(marked): self._logger.debug("Streamer %d triggered, manual=%s", i, marked) ready.append(streamer) selected.add(i) # Handle streamers triggered with another for j, streamer2 in enumerate(self.streamers[i:]): if streamer2.with_other == i and j not in selected and streamer2.triggered(True): self._logger.debug("Streamer %d triggered due to with-other on %d", j, i) ready.append(streamer2) selected.add(j) return ready
python
def check_streamers(self, blacklist=None): """Check if any streamers are ready to produce a report. You can limit what streamers are checked by passing a set-like object into blacklist. This method is the primary way to see when you should poll a given streamer for its next report. Note, this function is not idempotent. If a streamer is marked as manual and it is triggered from a node rule inside the sensor_graph, that trigger will only last as long as the next call to check_streamers() so you need to explicitly build a report on all ready streamers before calling check_streamers again. Args: blacklist (set): Optional set of streamer indices that should not be checked right now. Returns: list of DataStreamer: A list of the ready streamers. """ ready = [] selected = set() for i, streamer in enumerate(self.streamers): if blacklist is not None and i in blacklist: continue if i in selected: continue marked = False if i in self._manually_triggered_streamers: marked = True self._manually_triggered_streamers.remove(i) if streamer.triggered(marked): self._logger.debug("Streamer %d triggered, manual=%s", i, marked) ready.append(streamer) selected.add(i) # Handle streamers triggered with another for j, streamer2 in enumerate(self.streamers[i:]): if streamer2.with_other == i and j not in selected and streamer2.triggered(True): self._logger.debug("Streamer %d triggered due to with-other on %d", j, i) ready.append(streamer2) selected.add(j) return ready
[ "def", "check_streamers", "(", "self", ",", "blacklist", "=", "None", ")", ":", "ready", "=", "[", "]", "selected", "=", "set", "(", ")", "for", "i", ",", "streamer", "in", "enumerate", "(", "self", ".", "streamers", ")", ":", "if", "blacklist", "is", "not", "None", "and", "i", "in", "blacklist", ":", "continue", "if", "i", "in", "selected", ":", "continue", "marked", "=", "False", "if", "i", "in", "self", ".", "_manually_triggered_streamers", ":", "marked", "=", "True", "self", ".", "_manually_triggered_streamers", ".", "remove", "(", "i", ")", "if", "streamer", ".", "triggered", "(", "marked", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Streamer %d triggered, manual=%s\"", ",", "i", ",", "marked", ")", "ready", ".", "append", "(", "streamer", ")", "selected", ".", "add", "(", "i", ")", "# Handle streamers triggered with another", "for", "j", ",", "streamer2", "in", "enumerate", "(", "self", ".", "streamers", "[", "i", ":", "]", ")", ":", "if", "streamer2", ".", "with_other", "==", "i", "and", "j", "not", "in", "selected", "and", "streamer2", ".", "triggered", "(", "True", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Streamer %d triggered due to with-other on %d\"", ",", "j", ",", "i", ")", "ready", ".", "append", "(", "streamer2", ")", "selected", ".", "add", "(", "j", ")", "return", "ready" ]
Check if any streamers are ready to produce a report. You can limit what streamers are checked by passing a set-like object into blacklist. This method is the primary way to see when you should poll a given streamer for its next report. Note, this function is not idempotent. If a streamer is marked as manual and it is triggered from a node rule inside the sensor_graph, that trigger will only last as long as the next call to check_streamers() so you need to explicitly build a report on all ready streamers before calling check_streamers again. Args: blacklist (set): Optional set of streamer indices that should not be checked right now. Returns: list of DataStreamer: A list of the ready streamers.
[ "Check", "if", "any", "streamers", "are", "ready", "to", "produce", "a", "report", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L379-L429
train
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.sort_nodes
def sort_nodes(self): """Topologically sort all of our nodes. Topologically sorting our nodes makes nodes that are inputs to other nodes come first in the list of nodes. This is important to do before programming a sensorgraph into an embedded device whose engine assumes a topologically sorted graph. The sorting is done in place on self.nodes """ node_map = {id(node): i for i, node in enumerate(self.nodes)} node_deps = {} for node, inputs, _outputs in self.iterate_bfs(): node_index = node_map[id(node)] deps = {node_map[id(x)] for x in inputs} node_deps[node_index] = deps # Now that we have our dependency tree properly built, topologically # sort the nodes and reorder them. node_order = toposort_flatten(node_deps) self.nodes = [self.nodes[x] for x in node_order] #Check root nodes all topographically sorted to the beginning for root in self.roots: if root not in self.nodes[0:len(self.roots)]: raise NodeConnectionError("Inputs not sorted in the beginning", node=str(root), node_position=self.nodes.index(root))
python
def sort_nodes(self): """Topologically sort all of our nodes. Topologically sorting our nodes makes nodes that are inputs to other nodes come first in the list of nodes. This is important to do before programming a sensorgraph into an embedded device whose engine assumes a topologically sorted graph. The sorting is done in place on self.nodes """ node_map = {id(node): i for i, node in enumerate(self.nodes)} node_deps = {} for node, inputs, _outputs in self.iterate_bfs(): node_index = node_map[id(node)] deps = {node_map[id(x)] for x in inputs} node_deps[node_index] = deps # Now that we have our dependency tree properly built, topologically # sort the nodes and reorder them. node_order = toposort_flatten(node_deps) self.nodes = [self.nodes[x] for x in node_order] #Check root nodes all topographically sorted to the beginning for root in self.roots: if root not in self.nodes[0:len(self.roots)]: raise NodeConnectionError("Inputs not sorted in the beginning", node=str(root), node_position=self.nodes.index(root))
[ "def", "sort_nodes", "(", "self", ")", ":", "node_map", "=", "{", "id", "(", "node", ")", ":", "i", "for", "i", ",", "node", "in", "enumerate", "(", "self", ".", "nodes", ")", "}", "node_deps", "=", "{", "}", "for", "node", ",", "inputs", ",", "_outputs", "in", "self", ".", "iterate_bfs", "(", ")", ":", "node_index", "=", "node_map", "[", "id", "(", "node", ")", "]", "deps", "=", "{", "node_map", "[", "id", "(", "x", ")", "]", "for", "x", "in", "inputs", "}", "node_deps", "[", "node_index", "]", "=", "deps", "# Now that we have our dependency tree properly built, topologically", "# sort the nodes and reorder them.", "node_order", "=", "toposort_flatten", "(", "node_deps", ")", "self", ".", "nodes", "=", "[", "self", ".", "nodes", "[", "x", "]", "for", "x", "in", "node_order", "]", "#Check root nodes all topographically sorted to the beginning", "for", "root", "in", "self", ".", "roots", ":", "if", "root", "not", "in", "self", ".", "nodes", "[", "0", ":", "len", "(", "self", ".", "roots", ")", "]", ":", "raise", "NodeConnectionError", "(", "\"Inputs not sorted in the beginning\"", ",", "node", "=", "str", "(", "root", ")", ",", "node_position", "=", "self", ".", "nodes", ".", "index", "(", "root", ")", ")" ]
Topologically sort all of our nodes. Topologically sorting our nodes makes nodes that are inputs to other nodes come first in the list of nodes. This is important to do before programming a sensorgraph into an embedded device whose engine assumes a topologically sorted graph. The sorting is done in place on self.nodes
[ "Topologically", "sort", "all", "of", "our", "nodes", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L461-L489
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ipkg.py
generate
def generate(env): """Add Builders and construction variables for ipkg to an Environment.""" try: bld = env['BUILDERS']['Ipkg'] except KeyError: bld = SCons.Builder.Builder(action='$IPKGCOM', suffix='$IPKGSUFFIX', source_scanner=None, target_scanner=None) env['BUILDERS']['Ipkg'] = bld env['IPKG'] = 'ipkg-build' env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}' if env.WhereIs('id'): env['IPKGUSER'] = os.popen('id -un').read().strip() env['IPKGGROUP'] = os.popen('id -gn').read().strip() env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP') env['IPKGSUFFIX'] = '.ipk'
python
def generate(env): """Add Builders and construction variables for ipkg to an Environment.""" try: bld = env['BUILDERS']['Ipkg'] except KeyError: bld = SCons.Builder.Builder(action='$IPKGCOM', suffix='$IPKGSUFFIX', source_scanner=None, target_scanner=None) env['BUILDERS']['Ipkg'] = bld env['IPKG'] = 'ipkg-build' env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}' if env.WhereIs('id'): env['IPKGUSER'] = os.popen('id -un').read().strip() env['IPKGGROUP'] = os.popen('id -gn').read().strip() env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP') env['IPKGSUFFIX'] = '.ipk'
[ "def", "generate", "(", "env", ")", ":", "try", ":", "bld", "=", "env", "[", "'BUILDERS'", "]", "[", "'Ipkg'", "]", "except", "KeyError", ":", "bld", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "'$IPKGCOM'", ",", "suffix", "=", "'$IPKGSUFFIX'", ",", "source_scanner", "=", "None", ",", "target_scanner", "=", "None", ")", "env", "[", "'BUILDERS'", "]", "[", "'Ipkg'", "]", "=", "bld", "env", "[", "'IPKG'", "]", "=", "'ipkg-build'", "env", "[", "'IPKGCOM'", "]", "=", "'$IPKG $IPKGFLAGS ${SOURCE}'", "if", "env", ".", "WhereIs", "(", "'id'", ")", ":", "env", "[", "'IPKGUSER'", "]", "=", "os", ".", "popen", "(", "'id -un'", ")", ".", "read", "(", ")", ".", "strip", "(", ")", "env", "[", "'IPKGGROUP'", "]", "=", "os", ".", "popen", "(", "'id -gn'", ")", ".", "read", "(", ")", ".", "strip", "(", ")", "env", "[", "'IPKGFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-o $IPKGUSER -g $IPKGGROUP'", ")", "env", "[", "'IPKGSUFFIX'", "]", "=", "'.ipk'" ]
Add Builders and construction variables for ipkg to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "ipkg", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ipkg.py#L42-L61
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
InputTrigger.triggered
def triggered(self, walker): """Check if this input is triggered on the given stream walker. Args: walker (StreamWalker): The walker to check Returns: bool: Whether this trigger is triggered or not """ if self.use_count: comp_value = walker.count() else: if walker.count() == 0: return False comp_value = walker.peek().value return self.comp_function(comp_value, self.reference)
python
def triggered(self, walker): """Check if this input is triggered on the given stream walker. Args: walker (StreamWalker): The walker to check Returns: bool: Whether this trigger is triggered or not """ if self.use_count: comp_value = walker.count() else: if walker.count() == 0: return False comp_value = walker.peek().value return self.comp_function(comp_value, self.reference)
[ "def", "triggered", "(", "self", ",", "walker", ")", ":", "if", "self", ".", "use_count", ":", "comp_value", "=", "walker", ".", "count", "(", ")", "else", ":", "if", "walker", ".", "count", "(", ")", "==", "0", ":", "return", "False", "comp_value", "=", "walker", ".", "peek", "(", ")", ".", "value", "return", "self", ".", "comp_function", "(", "comp_value", ",", "self", ".", "reference", ")" ]
Check if this input is triggered on the given stream walker. Args: walker (StreamWalker): The walker to check Returns: bool: Whether this trigger is triggered or not
[ "Check", "if", "this", "input", "is", "triggered", "on", "the", "given", "stream", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L75-L93
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.connect_input
def connect_input(self, index, walker, trigger=None): """Connect an input to a stream walker. If the input is already connected to something an exception is thrown. Otherwise the walker is used to read inputs for that input. A triggering condition can optionally be passed that will determine when this input will be considered as triggered. Args: index (int): The index of the input that we want to connect walker (StreamWalker): The stream walker to use for the input trigger (InputTrigger): The trigger to use for the input. If no trigger is specified, the input is considered to always be triggered (so TrueTrigger is used) """ if trigger is None: trigger = TrueTrigger() if index >= len(self.inputs): raise TooManyInputsError("Input index exceeded max number of inputs", index=index, max_inputs=len(self.inputs), stream=self.stream) self.inputs[index] = (walker, trigger)
python
def connect_input(self, index, walker, trigger=None): """Connect an input to a stream walker. If the input is already connected to something an exception is thrown. Otherwise the walker is used to read inputs for that input. A triggering condition can optionally be passed that will determine when this input will be considered as triggered. Args: index (int): The index of the input that we want to connect walker (StreamWalker): The stream walker to use for the input trigger (InputTrigger): The trigger to use for the input. If no trigger is specified, the input is considered to always be triggered (so TrueTrigger is used) """ if trigger is None: trigger = TrueTrigger() if index >= len(self.inputs): raise TooManyInputsError("Input index exceeded max number of inputs", index=index, max_inputs=len(self.inputs), stream=self.stream) self.inputs[index] = (walker, trigger)
[ "def", "connect_input", "(", "self", ",", "index", ",", "walker", ",", "trigger", "=", "None", ")", ":", "if", "trigger", "is", "None", ":", "trigger", "=", "TrueTrigger", "(", ")", "if", "index", ">=", "len", "(", "self", ".", "inputs", ")", ":", "raise", "TooManyInputsError", "(", "\"Input index exceeded max number of inputs\"", ",", "index", "=", "index", ",", "max_inputs", "=", "len", "(", "self", ".", "inputs", ")", ",", "stream", "=", "self", ".", "stream", ")", "self", ".", "inputs", "[", "index", "]", "=", "(", "walker", ",", "trigger", ")" ]
Connect an input to a stream walker. If the input is already connected to something an exception is thrown. Otherwise the walker is used to read inputs for that input. A triggering condition can optionally be passed that will determine when this input will be considered as triggered. Args: index (int): The index of the input that we want to connect walker (StreamWalker): The stream walker to use for the input trigger (InputTrigger): The trigger to use for the input. If no trigger is specified, the input is considered to always be triggered (so TrueTrigger is used)
[ "Connect", "an", "input", "to", "a", "stream", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L177-L200
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.input_streams
def input_streams(self): """Return a list of DataStream objects for all singular input streams. This function only returns individual streams, not the streams that would be selected from a selector like 'all outputs' for example. Returns: list(DataStream): A list of all of the individual DataStreams that are inputs of the node. Input selectors that select multiple streams are not included """ streams = [] for walker, _trigger in self.inputs: if walker.selector is None or not walker.selector.singular: continue streams.append(walker.selector.as_stream()) return streams
python
def input_streams(self): """Return a list of DataStream objects for all singular input streams. This function only returns individual streams, not the streams that would be selected from a selector like 'all outputs' for example. Returns: list(DataStream): A list of all of the individual DataStreams that are inputs of the node. Input selectors that select multiple streams are not included """ streams = [] for walker, _trigger in self.inputs: if walker.selector is None or not walker.selector.singular: continue streams.append(walker.selector.as_stream()) return streams
[ "def", "input_streams", "(", "self", ")", ":", "streams", "=", "[", "]", "for", "walker", ",", "_trigger", "in", "self", ".", "inputs", ":", "if", "walker", ".", "selector", "is", "None", "or", "not", "walker", ".", "selector", ".", "singular", ":", "continue", "streams", ".", "append", "(", "walker", ".", "selector", ".", "as_stream", "(", ")", ")", "return", "streams" ]
Return a list of DataStream objects for all singular input streams. This function only returns individual streams, not the streams that would be selected from a selector like 'all outputs' for example. Returns: list(DataStream): A list of all of the individual DataStreams that are inputs of the node. Input selectors that select multiple streams are not included
[ "Return", "a", "list", "of", "DataStream", "objects", "for", "all", "singular", "input", "streams", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L202-L221
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.find_input
def find_input(self, stream): """Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None """ for i, input_x in enumerate(self.inputs): if input_x[0].matches(stream): return i
python
def find_input(self, stream): """Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None """ for i, input_x in enumerate(self.inputs): if input_x[0].matches(stream): return i
[ "def", "find_input", "(", "self", ",", "stream", ")", ":", "for", "i", ",", "input_x", "in", "enumerate", "(", "self", ".", "inputs", ")", ":", "if", "input_x", "[", "0", "]", ".", "matches", "(", "stream", ")", ":", "return", "i" ]
Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None
[ "Find", "the", "input", "that", "responds", "to", "this", "stream", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L223-L235
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.num_inputs
def num_inputs(self): """Return the number of connected inputs. Returns: int: The number of connected inputs """ num = 0 for walker, _ in self.inputs: if not isinstance(walker, InvalidStreamWalker): num += 1 return num
python
def num_inputs(self): """Return the number of connected inputs. Returns: int: The number of connected inputs """ num = 0 for walker, _ in self.inputs: if not isinstance(walker, InvalidStreamWalker): num += 1 return num
[ "def", "num_inputs", "(", "self", ")", ":", "num", "=", "0", "for", "walker", ",", "_", "in", "self", ".", "inputs", ":", "if", "not", "isinstance", "(", "walker", ",", "InvalidStreamWalker", ")", ":", "num", "+=", "1", "return", "num" ]
Return the number of connected inputs. Returns: int: The number of connected inputs
[ "Return", "the", "number", "of", "connected", "inputs", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L238-L251
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.connect_output
def connect_output(self, node): """Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output """ if len(self.outputs) == self.max_outputs: raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
python
def connect_output(self, node): """Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output """ if len(self.outputs) == self.max_outputs: raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
[ "def", "connect_output", "(", "self", ",", "node", ")", ":", "if", "len", "(", "self", ".", "outputs", ")", "==", "self", ".", "max_outputs", ":", "raise", "TooManyOutputsError", "(", "\"Attempted to connect too many nodes to the output of a node\"", ",", "max_outputs", "=", "self", ".", "max_outputs", ",", "stream", "=", "self", ".", "stream", ")", "self", ".", "outputs", ".", "append", "(", "node", ")" ]
Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output
[ "Connect", "another", "node", "to", "our", "output", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L273-L286
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.triggered
def triggered(self): """Test if we should trigger our operation. We test the trigger condition on each of our inputs and then combine those triggers using our configured trigger combiner to get an overall result for whether this node is triggered. Returns: bool: True if we should trigger and False otherwise """ trigs = [x[1].triggered(x[0]) for x in self.inputs] if self.trigger_combiner == self.OrTriggerCombiner: return True in trigs return False not in trigs
python
def triggered(self): """Test if we should trigger our operation. We test the trigger condition on each of our inputs and then combine those triggers using our configured trigger combiner to get an overall result for whether this node is triggered. Returns: bool: True if we should trigger and False otherwise """ trigs = [x[1].triggered(x[0]) for x in self.inputs] if self.trigger_combiner == self.OrTriggerCombiner: return True in trigs return False not in trigs
[ "def", "triggered", "(", "self", ")", ":", "trigs", "=", "[", "x", "[", "1", "]", ".", "triggered", "(", "x", "[", "0", "]", ")", "for", "x", "in", "self", ".", "inputs", "]", "if", "self", ".", "trigger_combiner", "==", "self", ".", "OrTriggerCombiner", ":", "return", "True", "in", "trigs", "return", "False", "not", "in", "trigs" ]
Test if we should trigger our operation. We test the trigger condition on each of our inputs and then combine those triggers using our configured trigger combiner to get an overall result for whether this node is triggered. Returns: bool: True if we should trigger and False otherwise
[ "Test", "if", "we", "should", "trigger", "our", "operation", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L288-L304
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.set_func
def set_func(self, name, func): """Set the processing function to use for this node. Args: name (str): The name of the function to use. This is just stored for reference in case we need to serialize the node later. func (callable): A function that is called to process inputs for this node. It should have the following signature: callable(input1_walker, input2_walker, ...) It should return a list of IOTileReadings that are then pushed into the node's output stream """ self.func_name = name self.func = func
python
def set_func(self, name, func): """Set the processing function to use for this node. Args: name (str): The name of the function to use. This is just stored for reference in case we need to serialize the node later. func (callable): A function that is called to process inputs for this node. It should have the following signature: callable(input1_walker, input2_walker, ...) It should return a list of IOTileReadings that are then pushed into the node's output stream """ self.func_name = name self.func = func
[ "def", "set_func", "(", "self", ",", "name", ",", "func", ")", ":", "self", ".", "func_name", "=", "name", "self", ".", "func", "=", "func" ]
Set the processing function to use for this node. Args: name (str): The name of the function to use. This is just stored for reference in case we need to serialize the node later. func (callable): A function that is called to process inputs for this node. It should have the following signature: callable(input1_walker, input2_walker, ...) It should return a list of IOTileReadings that are then pushed into the node's output stream
[ "Set", "the", "processing", "function", "to", "use", "for", "this", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L306-L321
train
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.process
def process(self, rpc_executor, mark_streamer=None): """Run this node's processing function. Args: rpc_executor (RPCExecutor): An object capable of executing RPCs in case we need to do that. mark_streamer (callable): Function that can be called to manually mark a streamer as triggered by index. Returns: list(IOTileReading): A list of IOTileReadings with the results of the processing function or an empty list if no results were produced """ if self.func is None: raise ProcessingFunctionError('No processing function set for node', stream=self.stream) results = self.func(*[x[0] for x in self.inputs], rpc_executor=rpc_executor, mark_streamer=mark_streamer) if results is None: results = [] return results
python
def process(self, rpc_executor, mark_streamer=None): """Run this node's processing function. Args: rpc_executor (RPCExecutor): An object capable of executing RPCs in case we need to do that. mark_streamer (callable): Function that can be called to manually mark a streamer as triggered by index. Returns: list(IOTileReading): A list of IOTileReadings with the results of the processing function or an empty list if no results were produced """ if self.func is None: raise ProcessingFunctionError('No processing function set for node', stream=self.stream) results = self.func(*[x[0] for x in self.inputs], rpc_executor=rpc_executor, mark_streamer=mark_streamer) if results is None: results = [] return results
[ "def", "process", "(", "self", ",", "rpc_executor", ",", "mark_streamer", "=", "None", ")", ":", "if", "self", ".", "func", "is", "None", ":", "raise", "ProcessingFunctionError", "(", "'No processing function set for node'", ",", "stream", "=", "self", ".", "stream", ")", "results", "=", "self", ".", "func", "(", "*", "[", "x", "[", "0", "]", "for", "x", "in", "self", ".", "inputs", "]", ",", "rpc_executor", "=", "rpc_executor", ",", "mark_streamer", "=", "mark_streamer", ")", "if", "results", "is", "None", ":", "results", "=", "[", "]", "return", "results" ]
Run this node's processing function. Args: rpc_executor (RPCExecutor): An object capable of executing RPCs in case we need to do that. mark_streamer (callable): Function that can be called to manually mark a streamer as triggered by index. Returns: list(IOTileReading): A list of IOTileReadings with the results of the processing function or an empty list if no results were produced
[ "Run", "this", "node", "s", "processing", "function", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L323-L345
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Fortran.py
FortranScan
def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = "(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = """(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case insensitive # \s+ : match one or more white space characters # (?!PROCEDURE) : but *don't* match if the next word matches # PROCEDURE (negative lookahead assertion), # case insensitive # (\w+) : match one or more alphanumeric characters # that make up the defined module name and # save it in a group def_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner
python
def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = "(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = """(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case insensitive # \s+ : match one or more white space characters # (?!PROCEDURE) : but *don't* match if the next word matches # PROCEDURE (negative lookahead assertion), # case insensitive # (\w+) : match one or more alphanumeric characters # that make up the defined module name and # save it in a group def_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner
[ "def", "FortranScan", "(", "path_variable", "=", "\"FORTRANPATH\"", ")", ":", "# The USE statement regex matches the following:", "#", "# USE module_name", "# USE :: module_name", "# USE, INTRINSIC :: module_name", "# USE, NON_INTRINSIC :: module_name", "#", "# Limitations", "#", "# -- While the regex can handle multiple USE statements on one line,", "# it cannot properly handle them if they are commented out.", "# In either of the following cases:", "#", "# ! USE mod_a ; USE mod_b [entire line is commented out]", "# USE mod_a ! ; USE mod_b [in-line comment of second USE statement]", "#", "# the second module name (mod_b) will be picked up as a dependency", "# even though it should be ignored. The only way I can see", "# to rectify this would be to modify the scanner to eliminate", "# the call to re.findall, read in the contents of the file,", "# treating the comment character as an end-of-line character", "# in addition to the normal linefeed, loop over each line,", "# weeding out the comments, and looking for the USE statements.", "# One advantage to this is that the regex passed to the scanner", "# would no longer need to match a semicolon.", "#", "# -- I question whether or not we need to detect dependencies to", "# INTRINSIC modules because these are built-in to the compiler.", "# If we consider them a dependency, will SCons look for them, not", "# find them, and kill the build? Or will we there be standard", "# compiler-specific directories we will need to point to so the", "# compiler and SCons can locate the proper object and mod files?", "# Here is a breakdown of the regex:", "#", "# (?i) : regex is case insensitive", "# ^ : start of line", "# (?: : group a collection of regex symbols without saving the match as a \"group\"", "# ^|; : matches either the start of the line or a semicolon - semicolon", "# ) : end the unsaved grouping", "# \\s* : any amount of white space", "# USE : match the string USE, case insensitive", "# (?: : group a collection of regex symbols without saving the match as a \"group\"", "# \\s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols)", "# (?: : group a collection of regex symbols without saving the match as a \"group\"", "# (?: : establish another unsaved grouping of regex symbols", "# \\s* : any amount of white space", "# , : match a comma", "# \\s* : any amount of white space", "# (?:NON_)? : optionally match the prefix NON_, case insensitive", "# INTRINSIC : match the string INTRINSIC, case insensitive", "# )? : optionally match the \", INTRINSIC/NON_INTRINSIC\" grouped expression", "# \\s* : any amount of white space", "# :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute", "# ) : end the unsaved grouping", "# ) : end the unsaved grouping", "# \\s* : match any amount of white space", "# (\\w+) : match the module name that is being USE'd", "#", "#", "use_regex", "=", "\"(?i)(?:^|;)\\s*USE(?:\\s+|(?:(?:\\s*,\\s*(?:NON_)?INTRINSIC)?\\s*::))\\s*(\\w+)\"", "# The INCLUDE statement regex matches the following:", "#", "# INCLUDE 'some_Text'", "# INCLUDE \"some_Text\"", "# INCLUDE \"some_Text\" ; INCLUDE \"some_Text\"", "# INCLUDE kind_\"some_Text\"", "# INCLUDE kind_'some_Text\"", "#", "# where some_Text can include any alphanumeric and/or special character", "# as defined by the Fortran 2003 standard.", "#", "# Limitations:", "#", "# -- The Fortran standard dictates that a \" or ' in the INCLUDE'd", "# string must be represented as a \"\" or '', if the quotes that wrap", "# the entire string are either a ' or \", respectively. While the", "# regular expression below can detect the ' or \" characters just fine,", "# the scanning logic, presently is unable to detect them and reduce", "# them to a single instance. This probably isn't an issue since,", "# in practice, ' or \" are not generally used in filenames.", "#", "# -- This regex will not properly deal with multiple INCLUDE statements", "# when the entire line has been commented out, ala", "#", "# ! INCLUDE 'some_file' ; INCLUDE 'some_file'", "#", "# In such cases, it will properly ignore the first INCLUDE file,", "# but will actually still pick up the second. Interestingly enough,", "# the regex will properly deal with these cases:", "#", "# INCLUDE 'some_file'", "# INCLUDE 'some_file' !; INCLUDE 'some_file'", "#", "# To get around the above limitation, the FORTRAN programmer could", "# simply comment each INCLUDE statement separately, like this", "#", "# ! INCLUDE 'some_file' !; INCLUDE 'some_file'", "#", "# The way I see it, the only way to get around this limitation would", "# be to modify the scanning logic to replace the calls to re.findall", "# with a custom loop that processes each line separately, throwing", "# away fully commented out lines before attempting to match against", "# the INCLUDE syntax.", "#", "# Here is a breakdown of the regex:", "#", "# (?i) : regex is case insensitive", "# (?: : begin a non-saving group that matches the following:", "# ^ : either the start of the line", "# | : or", "# ['\">]\\s*; : a semicolon that follows a single quote,", "# double quote or greater than symbol (with any", "# amount of whitespace in between). This will", "# allow the regex to match multiple INCLUDE", "# statements per line (although it also requires", "# the positive lookahead assertion that is", "# used below). It will even properly deal with", "# (i.e. ignore) cases in which the additional", "# INCLUDES are part of an in-line comment, ala", "# \" INCLUDE 'someFile' ! ; INCLUDE 'someFile2' \"", "# ) : end of non-saving group", "# \\s* : any amount of white space", "# INCLUDE : match the string INCLUDE, case insensitive", "# \\s+ : match one or more white space characters", "# (?\\w+_)? : match the optional \"kind-param _\" prefix allowed by the standard", "# [<\"'] : match the include delimiter - an apostrophe, double quote, or less than symbol", "# (.+?) : match one or more characters that make up", "# the included path and file name and save it", "# in a group. The Fortran standard allows for", "# any non-control character to be used. The dot", "# operator will pick up any character, including", "# control codes, but I can't conceive of anyone", "# putting control codes in their file names.", "# The question mark indicates it is non-greedy so", "# that regex will match only up to the next quote,", "# double quote, or greater than symbol", "# (?=[\"'>]) : positive lookahead assertion to match the include", "# delimiter - an apostrophe, double quote, or", "# greater than symbol. This level of complexity", "# is required so that the include delimiter is", "# not consumed by the match, thus allowing the", "# sub-regex discussed above to uniquely match a", "# set of semicolon-separated INCLUDE statements", "# (as allowed by the F2003 standard)", "include_regex", "=", "\"\"\"(?i)(?:^|['\">]\\s*;)\\s*INCLUDE\\s+(?:\\w+_)?[<\"'](.+?)(?=[\"'>])\"\"\"", "# The MODULE statement regex finds module definitions by matching", "# the following:", "#", "# MODULE module_name", "#", "# but *not* the following:", "#", "# MODULE PROCEDURE procedure_name", "#", "# Here is a breakdown of the regex:", "#", "# (?i) : regex is case insensitive", "# ^\\s* : any amount of white space", "# MODULE : match the string MODULE, case insensitive", "# \\s+ : match one or more white space characters", "# (?!PROCEDURE) : but *don't* match if the next word matches", "# PROCEDURE (negative lookahead assertion),", "# case insensitive", "# (\\w+) : match one or more alphanumeric characters", "# that make up the defined module name and", "# save it in a group", "def_regex", "=", "\"\"\"(?i)^\\s*MODULE\\s+(?!PROCEDURE)(\\w+)\"\"\"", "scanner", "=", "F90Scanner", "(", "\"FortranScan\"", ",", "\"$FORTRANSUFFIXES\"", ",", "path_variable", ",", "use_regex", ",", "include_regex", ",", "def_regex", ")", "return", "scanner" ]
Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "source", "files", "for", "Fortran", "USE", "&", "INCLUDE", "statements" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Fortran.py#L126-L310
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cvf.py
generate
def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['OBJSUFFIX'] = '.obj' env['FORTRANMODDIR'] = '${TARGET.dir}' env['FORTRANMODDIRPREFIX'] = '/module:' env['FORTRANMODDIRSUFFIX'] = ''
python
def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['OBJSUFFIX'] = '.obj' env['FORTRANMODDIR'] = '${TARGET.dir}' env['FORTRANMODDIRPREFIX'] = '/module:' env['FORTRANMODDIRSUFFIX'] = ''
[ "def", "generate", "(", "env", ")", ":", "fortran", ".", "generate", "(", "env", ")", "env", "[", "'FORTRAN'", "]", "=", "'f90'", "env", "[", "'FORTRANCOM'", "]", "=", "'$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'", "env", "[", "'FORTRANPPCOM'", "]", "=", "'$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'", "env", "[", "'SHFORTRANCOM'", "]", "=", "'$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'", "env", "[", "'SHFORTRANPPCOM'", "]", "=", "'$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}'", "env", "[", "'OBJSUFFIX'", "]", "=", "'.obj'", "env", "[", "'FORTRANMODDIR'", "]", "=", "'${TARGET.dir}'", "env", "[", "'FORTRANMODDIRPREFIX'", "]", "=", "'/module:'", "env", "[", "'FORTRANMODDIRSUFFIX'", "]", "=", "''" ]
Add Builders and construction variables for compaq visual fortran to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "compaq", "visual", "fortran", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cvf.py#L36-L49
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py
Value.read
def read(self): """Return the value. If necessary, the value is built.""" self.build() if not hasattr(self, 'built_value'): self.built_value = self.value return self.built_value
python
def read(self): """Return the value. If necessary, the value is built.""" self.build() if not hasattr(self, 'built_value'): self.built_value = self.value return self.built_value
[ "def", "read", "(", "self", ")", ":", "self", ".", "build", "(", ")", "if", "not", "hasattr", "(", "self", ",", "'built_value'", ")", ":", "self", ".", "built_value", "=", "self", ".", "value", "return", "self", ".", "built_value" ]
Return the value. If necessary, the value is built.
[ "Return", "the", "value", ".", "If", "necessary", "the", "value", "is", "built", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py#L120-L125
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py
Value.get_csig
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() self.get_ninfo().csig = contents return contents
python
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() self.get_ninfo().csig = contents return contents
[ "def", "get_csig", "(", "self", ",", "calc", "=", "None", ")", ":", "try", ":", "return", "self", ".", "ninfo", ".", "csig", "except", "AttributeError", ":", "pass", "contents", "=", "self", ".", "get_contents", "(", ")", "self", ".", "get_ninfo", "(", ")", ".", "csig", "=", "contents", "return", "contents" ]
Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.
[ "Because", "we", "re", "a", "Python", "value", "node", "and", "don", "t", "have", "a", "real", "timestamp", "we", "get", "to", "ignore", "the", "calculator", "and", "just", "use", "the", "value", "contents", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py#L155-L165
train
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_complex
def mark_complex(self, name, serializer, deserializer): """Mark a property as complex with serializer and deserializer functions. Args: name (str): The name of the complex property. serializer (callable): The function to call to serialize the property's value to something that can be saved in a json. deserializer (callable): The function to call to unserialize the property from a dict loaded by a json back to the original value. """ self._complex_properties[name] = (serializer, deserializer)
python
def mark_complex(self, name, serializer, deserializer): """Mark a property as complex with serializer and deserializer functions. Args: name (str): The name of the complex property. serializer (callable): The function to call to serialize the property's value to something that can be saved in a json. deserializer (callable): The function to call to unserialize the property from a dict loaded by a json back to the original value. """ self._complex_properties[name] = (serializer, deserializer)
[ "def", "mark_complex", "(", "self", ",", "name", ",", "serializer", ",", "deserializer", ")", ":", "self", ".", "_complex_properties", "[", "name", "]", "=", "(", "serializer", ",", "deserializer", ")" ]
Mark a property as complex with serializer and deserializer functions. Args: name (str): The name of the complex property. serializer (callable): The function to call to serialize the property's value to something that can be saved in a json. deserializer (callable): The function to call to unserialize the property from a dict loaded by a json back to the original value.
[ "Mark", "a", "property", "as", "complex", "with", "serializer", "and", "deserializer", "functions", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L63-L74
train
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_typed_list
def mark_typed_list(self, name, type_object): """Mark a property as containing serializable objects of a given type. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a list of objects. This method requires that all members of the given list be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this list. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_list(obj): if obj is None: return None if not isinstance(obj, list): raise DataError("Property %s marked as list was not a list: %s" % (name, repr(obj))) return [x.dump() for x in obj] def _restore_list(obj): if obj is None: return obj return [type_object.Restore(x) for x in obj] self.mark_complex(name, _dump_list, _restore_list)
python
def mark_typed_list(self, name, type_object): """Mark a property as containing serializable objects of a given type. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a list of objects. This method requires that all members of the given list be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this list. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_list(obj): if obj is None: return None if not isinstance(obj, list): raise DataError("Property %s marked as list was not a list: %s" % (name, repr(obj))) return [x.dump() for x in obj] def _restore_list(obj): if obj is None: return obj return [type_object.Restore(x) for x in obj] self.mark_complex(name, _dump_list, _restore_list)
[ "def", "mark_typed_list", "(", "self", ",", "name", ",", "type_object", ")", ":", "if", "not", "hasattr", "(", "type_object", ",", "'dump'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: dump()\"", "%", "type_object", ")", "if", "not", "hasattr", "(", "type_object", ",", "'Restore'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: Restore()\"", "%", "type_object", ")", "def", "_dump_list", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "obj", ",", "list", ")", ":", "raise", "DataError", "(", "\"Property %s marked as list was not a list: %s\"", "%", "(", "name", ",", "repr", "(", "obj", ")", ")", ")", "return", "[", "x", ".", "dump", "(", ")", "for", "x", "in", "obj", "]", "def", "_restore_list", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "return", "[", "type_object", ".", "Restore", "(", "x", ")", "for", "x", "in", "obj", "]", "self", ".", "mark_complex", "(", "name", ",", "_dump_list", ",", "_restore_list", ")" ]
Mark a property as containing serializable objects of a given type. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a list of objects. This method requires that all members of the given list be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this list.
[ "Mark", "a", "property", "as", "containing", "serializable", "objects", "of", "a", "given", "type", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L76-L111
train
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_typed_map
def mark_typed_map(self, name, type_object): """Mark a property as containing a map str to serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a dict of objects. This method requires that all members of the given dict be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this dict. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_map(obj): if obj is None: return None if not isinstance(obj, dict): raise DataError("Property %s marked as list was not a dict: %s" % (name, repr(obj))) return {key: val.dump() for key, val in obj.items()} def _restore_map(obj): if obj is None: return obj return {key: type_object.Restore(val) for key, val in obj.items()} self.mark_complex(name, _dump_map, _restore_map)
python
def mark_typed_map(self, name, type_object): """Mark a property as containing a map str to serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a dict of objects. This method requires that all members of the given dict be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this dict. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_map(obj): if obj is None: return None if not isinstance(obj, dict): raise DataError("Property %s marked as list was not a dict: %s" % (name, repr(obj))) return {key: val.dump() for key, val in obj.items()} def _restore_map(obj): if obj is None: return obj return {key: type_object.Restore(val) for key, val in obj.items()} self.mark_complex(name, _dump_map, _restore_map)
[ "def", "mark_typed_map", "(", "self", ",", "name", ",", "type_object", ")", ":", "if", "not", "hasattr", "(", "type_object", ",", "'dump'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: dump()\"", "%", "type_object", ")", "if", "not", "hasattr", "(", "type_object", ",", "'Restore'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: Restore()\"", "%", "type_object", ")", "def", "_dump_map", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "obj", ",", "dict", ")", ":", "raise", "DataError", "(", "\"Property %s marked as list was not a dict: %s\"", "%", "(", "name", ",", "repr", "(", "obj", ")", ")", ")", "return", "{", "key", ":", "val", ".", "dump", "(", ")", "for", "key", ",", "val", "in", "obj", ".", "items", "(", ")", "}", "def", "_restore_map", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "return", "{", "key", ":", "type_object", ".", "Restore", "(", "val", ")", "for", "key", ",", "val", "in", "obj", ".", "items", "(", ")", "}", "self", ".", "mark_complex", "(", "name", ",", "_dump_map", ",", "_restore_map", ")" ]
Mark a property as containing a map str to serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a dict of objects. This method requires that all members of the given dict be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this dict.
[ "Mark", "a", "property", "as", "containing", "a", "map", "str", "to", "serializable", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L113-L148
train
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_typed_object
def mark_typed_object(self, name, type_object): """Mark a property as containing a serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a complex object. This method requires that property ``name`` be a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this property. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_obj(obj): if obj is None: return None return obj.dump() def _restore_obj(obj): if obj is None: return obj return type_object.Restore(obj) self.mark_complex(name, _dump_obj, _restore_obj)
python
def mark_typed_object(self, name, type_object): """Mark a property as containing a serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a complex object. This method requires that property ``name`` be a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this property. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_obj(obj): if obj is None: return None return obj.dump() def _restore_obj(obj): if obj is None: return obj return type_object.Restore(obj) self.mark_complex(name, _dump_obj, _restore_obj)
[ "def", "mark_typed_object", "(", "self", ",", "name", ",", "type_object", ")", ":", "if", "not", "hasattr", "(", "type_object", ",", "'dump'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: dump()\"", "%", "type_object", ")", "if", "not", "hasattr", "(", "type_object", ",", "'Restore'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: Restore()\"", "%", "type_object", ")", "def", "_dump_obj", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "return", "obj", ".", "dump", "(", ")", "def", "_restore_obj", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "return", "type_object", ".", "Restore", "(", "obj", ")", "self", ".", "mark_complex", "(", "name", ",", "_dump_obj", ",", "_restore_obj", ")" ]
Mark a property as containing a serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a complex object. This method requires that property ``name`` be a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this property.
[ "Mark", "a", "property", "as", "containing", "a", "serializable", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L150-L182
train
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.dump_property
def dump_property(self, name): """Serialize a property of this class by name. Args: name (str): The name of the property to dump. Returns: object: The serialized value of the property. """ if not hasattr(self, name): raise ArgumentError("Unknown property %s" % name) value = getattr(self, name) if name in self._complex_properties: value = self._complex_properties[name][0](value) return value
python
def dump_property(self, name): """Serialize a property of this class by name. Args: name (str): The name of the property to dump. Returns: object: The serialized value of the property. """ if not hasattr(self, name): raise ArgumentError("Unknown property %s" % name) value = getattr(self, name) if name in self._complex_properties: value = self._complex_properties[name][0](value) return value
[ "def", "dump_property", "(", "self", ",", "name", ")", ":", "if", "not", "hasattr", "(", "self", ",", "name", ")", ":", "raise", "ArgumentError", "(", "\"Unknown property %s\"", "%", "name", ")", "value", "=", "getattr", "(", "self", ",", "name", ")", "if", "name", "in", "self", ".", "_complex_properties", ":", "value", "=", "self", ".", "_complex_properties", "[", "name", "]", "[", "0", "]", "(", "value", ")", "return", "value" ]
Serialize a property of this class by name. Args: name (str): The name of the property to dump. Returns: object: The serialized value of the property.
[ "Serialize", "a", "property", "of", "this", "class", "by", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L184-L201
train
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.get_properties
def get_properties(self): """Get a list of all of the public data properties of this class. Returns: list of str: A list of all of the public properties in this class. """ names = inspect.getmembers(self, predicate=lambda x: not inspect.ismethod(x)) return [x[0] for x in names if not x[0].startswith("_") and x[0] not in self._ignored_properties]
python
def get_properties(self): """Get a list of all of the public data properties of this class. Returns: list of str: A list of all of the public properties in this class. """ names = inspect.getmembers(self, predicate=lambda x: not inspect.ismethod(x)) return [x[0] for x in names if not x[0].startswith("_") and x[0] not in self._ignored_properties]
[ "def", "get_properties", "(", "self", ")", ":", "names", "=", "inspect", ".", "getmembers", "(", "self", ",", "predicate", "=", "lambda", "x", ":", "not", "inspect", ".", "ismethod", "(", "x", ")", ")", "return", "[", "x", "[", "0", "]", "for", "x", "in", "names", "if", "not", "x", "[", "0", "]", ".", "startswith", "(", "\"_\"", ")", "and", "x", "[", "0", "]", "not", "in", "self", ".", "_ignored_properties", "]" ]
Get a list of all of the public data properties of this class. Returns: list of str: A list of all of the public properties in this class.
[ "Get", "a", "list", "of", "all", "of", "the", "public", "data", "properties", "of", "this", "class", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L203-L211
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py
get_default_version
def get_default_version(env): """Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version. """ if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): # get all versions, and remember them for speed later versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: debug('get_default_version: WARNING: no installed versions found, ' 'using first in SupportedVSList (%s)'%SupportedVSList[0].version) env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION']
python
def get_default_version(env): """Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version. """ if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): # get all versions, and remember them for speed later versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: debug('get_default_version: WARNING: no installed versions found, ' 'using first in SupportedVSList (%s)'%SupportedVSList[0].version) env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION']
[ "def", "get_default_version", "(", "env", ")", ":", "if", "'MSVS'", "not", "in", "env", "or", "not", "SCons", ".", "Util", ".", "is_Dict", "(", "env", "[", "'MSVS'", "]", ")", ":", "# get all versions, and remember them for speed later", "versions", "=", "[", "vs", ".", "version", "for", "vs", "in", "get_installed_visual_studios", "(", ")", "]", "env", "[", "'MSVS'", "]", "=", "{", "'VERSIONS'", ":", "versions", "}", "else", ":", "versions", "=", "env", "[", "'MSVS'", "]", ".", "get", "(", "'VERSIONS'", ",", "[", "]", ")", "if", "'MSVS_VERSION'", "not", "in", "env", ":", "if", "versions", ":", "env", "[", "'MSVS_VERSION'", "]", "=", "versions", "[", "0", "]", "#use highest version by default", "else", ":", "debug", "(", "'get_default_version: WARNING: no installed versions found, '", "'using first in SupportedVSList (%s)'", "%", "SupportedVSList", "[", "0", "]", ".", "version", ")", "env", "[", "'MSVS_VERSION'", "]", "=", "SupportedVSList", "[", "0", "]", ".", "version", "env", "[", "'MSVS'", "]", "[", "'VERSION'", "]", "=", "env", "[", "'MSVS_VERSION'", "]", "return", "env", "[", "'MSVS_VERSION'", "]" ]
Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version.
[ "Returns", "the", "default", "version", "string", "to", "use", "for", "MSVS", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py#L477-L506
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py
get_default_arch
def get_default_arch(env): """Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str """ arch = env.get('MSVS_ARCH', 'x86') msvs = InstalledVSMap.get(env['MSVS_VERSION']) if not msvs: arch = 'x86' elif not arch in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch
python
def get_default_arch(env): """Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str """ arch = env.get('MSVS_ARCH', 'x86') msvs = InstalledVSMap.get(env['MSVS_VERSION']) if not msvs: arch = 'x86' elif not arch in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch
[ "def", "get_default_arch", "(", "env", ")", ":", "arch", "=", "env", ".", "get", "(", "'MSVS_ARCH'", ",", "'x86'", ")", "msvs", "=", "InstalledVSMap", ".", "get", "(", "env", "[", "'MSVS_VERSION'", "]", ")", "if", "not", "msvs", ":", "arch", "=", "'x86'", "elif", "not", "arch", "in", "msvs", ".", "get_supported_arch", "(", ")", ":", "fmt", "=", "\"Visual Studio version %s does not support architecture %s\"", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "fmt", "%", "(", "env", "[", "'MSVS_VERSION'", "]", ",", "arch", ")", ")", "return", "arch" ]
Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str
[ "Return", "the", "default", "arch", "to", "use", "for", "MSVS" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py#L508-L528
train
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/structures.py
ControlStructure.format_rpc
def format_rpc(self, address, rpc_id, payload): """Create a formated word list that encodes this rpc.""" addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24)) send_length = len(payload) if len(payload) < 20: payload = payload + b'\0'*(20 - len(payload)) payload_words = struct.unpack("<5L", payload) return self.base_address + self.RPC_TLS_OFFSET + 8, ([addr_word, send_length, 0] + [x for x in payload_words])
python
def format_rpc(self, address, rpc_id, payload): """Create a formated word list that encodes this rpc.""" addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24)) send_length = len(payload) if len(payload) < 20: payload = payload + b'\0'*(20 - len(payload)) payload_words = struct.unpack("<5L", payload) return self.base_address + self.RPC_TLS_OFFSET + 8, ([addr_word, send_length, 0] + [x for x in payload_words])
[ "def", "format_rpc", "(", "self", ",", "address", ",", "rpc_id", ",", "payload", ")", ":", "addr_word", "=", "(", "rpc_id", "|", "(", "address", "<<", "16", ")", "|", "(", "(", "1", "<<", "1", ")", "<<", "24", ")", ")", "send_length", "=", "len", "(", "payload", ")", "if", "len", "(", "payload", ")", "<", "20", ":", "payload", "=", "payload", "+", "b'\\0'", "*", "(", "20", "-", "len", "(", "payload", ")", ")", "payload_words", "=", "struct", ".", "unpack", "(", "\"<5L\"", ",", "payload", ")", "return", "self", ".", "base_address", "+", "self", ".", "RPC_TLS_OFFSET", "+", "8", ",", "(", "[", "addr_word", ",", "send_length", ",", "0", "]", "+", "[", "x", "for", "x", "in", "payload_words", "]", ")" ]
Create a formated word list that encodes this rpc.
[ "Create", "a", "formated", "word", "list", "that", "encodes", "this", "rpc", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/structures.py#L62-L73
train
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/structures.py
ControlStructure.format_response
def format_response(self, response_data): """Format an RPC response.""" _addr, length = self.response_info() if len(response_data) != length: raise HardwareError("Invalid response read length, should be the same as what response_info() returns", expected=length, actual=len(response_data)) resp, flags, received_length, payload = struct.unpack("<HxBL4x20s", response_data) resp = resp & 0xFF if flags & (1 << 3): raise HardwareError("Could not grab external gate") if received_length > 20: raise HardwareError("Invalid received payload length > 20 bytes", received_length=received_length) payload = payload[:received_length] return { 'status': resp, 'payload': payload }
python
def format_response(self, response_data): """Format an RPC response.""" _addr, length = self.response_info() if len(response_data) != length: raise HardwareError("Invalid response read length, should be the same as what response_info() returns", expected=length, actual=len(response_data)) resp, flags, received_length, payload = struct.unpack("<HxBL4x20s", response_data) resp = resp & 0xFF if flags & (1 << 3): raise HardwareError("Could not grab external gate") if received_length > 20: raise HardwareError("Invalid received payload length > 20 bytes", received_length=received_length) payload = payload[:received_length] return { 'status': resp, 'payload': payload }
[ "def", "format_response", "(", "self", ",", "response_data", ")", ":", "_addr", ",", "length", "=", "self", ".", "response_info", "(", ")", "if", "len", "(", "response_data", ")", "!=", "length", ":", "raise", "HardwareError", "(", "\"Invalid response read length, should be the same as what response_info() returns\"", ",", "expected", "=", "length", ",", "actual", "=", "len", "(", "response_data", ")", ")", "resp", ",", "flags", ",", "received_length", ",", "payload", "=", "struct", ".", "unpack", "(", "\"<HxBL4x20s\"", ",", "response_data", ")", "resp", "=", "resp", "&", "0xFF", "if", "flags", "&", "(", "1", "<<", "3", ")", ":", "raise", "HardwareError", "(", "\"Could not grab external gate\"", ")", "if", "received_length", ">", "20", ":", "raise", "HardwareError", "(", "\"Invalid received payload length > 20 bytes\"", ",", "received_length", "=", "received_length", ")", "payload", "=", "payload", "[", ":", "received_length", "]", "return", "{", "'status'", ":", "resp", ",", "'payload'", ":", "payload", "}" ]
Format an RPC response.
[ "Format", "an", "RPC", "response", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/structures.py#L75-L95
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py
ProgramScanner
def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps
python
def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps
[ "def", "ProgramScanner", "(", "*", "*", "kw", ")", ":", "kw", "[", "'path_function'", "]", "=", "SCons", ".", "Scanner", ".", "FindPathDirs", "(", "'LIBPATH'", ")", "ps", "=", "SCons", ".", "Scanner", ".", "Base", "(", "scan", ",", "\"ProgramScanner\"", ",", "*", "*", "kw", ")", "return", "ps" ]
Return a prototype Scanner instance for scanning executable files for static-lib dependencies
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "executable", "files", "for", "static", "-", "lib", "dependencies" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py#L34-L39
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py
_subst_libs
def _subst_libs(env, libs): """ Substitute environment variables and split into list. """ if SCons.Util.is_String(libs): libs = env.subst(libs) if SCons.Util.is_String(libs): libs = libs.split() elif SCons.Util.is_Sequence(libs): _libs = [] for l in libs: _libs += _subst_libs(env, l) libs = _libs else: # libs is an object (Node, for example) libs = [libs] return libs
python
def _subst_libs(env, libs): """ Substitute environment variables and split into list. """ if SCons.Util.is_String(libs): libs = env.subst(libs) if SCons.Util.is_String(libs): libs = libs.split() elif SCons.Util.is_Sequence(libs): _libs = [] for l in libs: _libs += _subst_libs(env, l) libs = _libs else: # libs is an object (Node, for example) libs = [libs] return libs
[ "def", "_subst_libs", "(", "env", ",", "libs", ")", ":", "if", "SCons", ".", "Util", ".", "is_String", "(", "libs", ")", ":", "libs", "=", "env", ".", "subst", "(", "libs", ")", "if", "SCons", ".", "Util", ".", "is_String", "(", "libs", ")", ":", "libs", "=", "libs", ".", "split", "(", ")", "elif", "SCons", ".", "Util", ".", "is_Sequence", "(", "libs", ")", ":", "_libs", "=", "[", "]", "for", "l", "in", "libs", ":", "_libs", "+=", "_subst_libs", "(", "env", ",", "l", ")", "libs", "=", "_libs", "else", ":", "# libs is an object (Node, for example)", "libs", "=", "[", "libs", "]", "return", "libs" ]
Substitute environment variables and split into list.
[ "Substitute", "environment", "variables", "and", "split", "into", "list", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py#L41-L57
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py
scan
def scan(node, env, libpath = ()): """ This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies. """ try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] libs = _subst_libs(env, libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result
python
def scan(node, env, libpath = ()): """ This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies. """ try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] libs = _subst_libs(env, libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result
[ "def", "scan", "(", "node", ",", "env", ",", "libpath", "=", "(", ")", ")", ":", "try", ":", "libs", "=", "env", "[", "'LIBS'", "]", "except", "KeyError", ":", "# There are no LIBS in this environment, so just return a null list:", "return", "[", "]", "libs", "=", "_subst_libs", "(", "env", ",", "libs", ")", "try", ":", "prefix", "=", "env", "[", "'LIBPREFIXES'", "]", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "prefix", ")", ":", "prefix", "=", "[", "prefix", "]", "except", "KeyError", ":", "prefix", "=", "[", "''", "]", "try", ":", "suffix", "=", "env", "[", "'LIBSUFFIXES'", "]", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "suffix", ")", ":", "suffix", "=", "[", "suffix", "]", "except", "KeyError", ":", "suffix", "=", "[", "''", "]", "pairs", "=", "[", "]", "for", "suf", "in", "map", "(", "env", ".", "subst", ",", "suffix", ")", ":", "for", "pref", "in", "map", "(", "env", ".", "subst", ",", "prefix", ")", ":", "pairs", ".", "append", "(", "(", "pref", ",", "suf", ")", ")", "result", "=", "[", "]", "if", "callable", "(", "libpath", ")", ":", "libpath", "=", "libpath", "(", ")", "find_file", "=", "SCons", ".", "Node", ".", "FS", ".", "find_file", "adjustixes", "=", "SCons", ".", "Util", ".", "adjustixes", "for", "lib", "in", "libs", ":", "if", "SCons", ".", "Util", ".", "is_String", "(", "lib", ")", ":", "for", "pref", ",", "suf", "in", "pairs", ":", "l", "=", "adjustixes", "(", "lib", ",", "pref", ",", "suf", ")", "l", "=", "find_file", "(", "l", ",", "libpath", ",", "verbose", "=", "print_find_libs", ")", "if", "l", ":", "result", ".", "append", "(", "l", ")", "else", ":", "result", ".", "append", "(", "lib", ")", "return", "result" ]
This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies.
[ "This", "scanner", "scans", "program", "files", "for", "static", "-", "library", "dependencies", ".", "It", "will", "search", "the", "LIBPATH", "environment", "variable", "for", "libraries", "specified", "in", "the", "LIBS", "variable", "returning", "any", "files", "it", "finds", "as", "dependencies", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py#L59-L110
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeState.clear_to_reset
def clear_to_reset(self, config_vars): """Clear the RemoteBridge subsystem to its reset state.""" super(RemoteBridgeState, self).clear_to_reset(config_vars) self.status = BRIDGE_STATUS.IDLE self.error = 0
python
def clear_to_reset(self, config_vars): """Clear the RemoteBridge subsystem to its reset state.""" super(RemoteBridgeState, self).clear_to_reset(config_vars) self.status = BRIDGE_STATUS.IDLE self.error = 0
[ "def", "clear_to_reset", "(", "self", ",", "config_vars", ")", ":", "super", "(", "RemoteBridgeState", ",", "self", ")", ".", "clear_to_reset", "(", "config_vars", ")", "self", ".", "status", "=", "BRIDGE_STATUS", ".", "IDLE", "self", ".", "error", "=", "0" ]
Clear the RemoteBridge subsystem to its reset state.
[ "Clear", "the", "RemoteBridge", "subsystem", "to", "its", "reset", "state", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L42-L47
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.begin_script
def begin_script(self): """Indicate we are going to start loading a script.""" if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING): return [1] #FIXME: Return correct error here self.remote_bridge.status = BRIDGE_STATUS.WAITING self.remote_bridge.error = 0 self.remote_bridge.script_error = None self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
python
def begin_script(self): """Indicate we are going to start loading a script.""" if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING): return [1] #FIXME: Return correct error here self.remote_bridge.status = BRIDGE_STATUS.WAITING self.remote_bridge.error = 0 self.remote_bridge.script_error = None self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
[ "def", "begin_script", "(", "self", ")", ":", "if", "self", ".", "remote_bridge", ".", "status", "in", "(", "BRIDGE_STATUS", ".", "RECEIVED", ",", "BRIDGE_STATUS", ".", "VALIDATED", ",", "BRIDGE_STATUS", ".", "EXECUTING", ")", ":", "return", "[", "1", "]", "#FIXME: Return correct error here", "self", ".", "remote_bridge", ".", "status", "=", "BRIDGE_STATUS", ".", "WAITING", "self", ".", "remote_bridge", ".", "error", "=", "0", "self", ".", "remote_bridge", ".", "script_error", "=", "None", "self", ".", "remote_bridge", ".", "parsed_script", "=", "None", "self", ".", "_device", ".", "script", "=", "bytearray", "(", ")", "return", "[", "0", "]" ]
Indicate we are going to start loading a script.
[ "Indicate", "we", "are", "going", "to", "start", "loading", "a", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L77-L90
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.end_script
def end_script(self): """Indicate that we have finished receiving a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] #FIXME: State change self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
python
def end_script(self): """Indicate that we have finished receiving a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] #FIXME: State change self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
[ "def", "end_script", "(", "self", ")", ":", "if", "self", ".", "remote_bridge", ".", "status", "not", "in", "(", "BRIDGE_STATUS", ".", "RECEIVED", ",", "BRIDGE_STATUS", ".", "WAITING", ")", ":", "return", "[", "1", "]", "#FIXME: State change", "self", ".", "remote_bridge", ".", "status", "=", "BRIDGE_STATUS", ".", "RECEIVED", "return", "[", "0", "]" ]
Indicate that we have finished receiving a script.
[ "Indicate", "that", "we", "have", "finished", "receiving", "a", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L93-L100
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.trigger_script
def trigger_script(self): """Actually process a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,): return [1] #FIXME: State change # This is asynchronous in real life so just cache the error try: self.remote_bridge.parsed_script = UpdateScript.FromBinary(self._device.script) #FIXME: Actually run the script self.remote_bridge.status = BRIDGE_STATUS.IDLE except Exception as exc: self._logger.exception("Error parsing script streamed to device") self.remote_bridge.script_error = exc self.remote_bridge.error = 1 # FIXME: Error code return [0]
python
def trigger_script(self): """Actually process a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,): return [1] #FIXME: State change # This is asynchronous in real life so just cache the error try: self.remote_bridge.parsed_script = UpdateScript.FromBinary(self._device.script) #FIXME: Actually run the script self.remote_bridge.status = BRIDGE_STATUS.IDLE except Exception as exc: self._logger.exception("Error parsing script streamed to device") self.remote_bridge.script_error = exc self.remote_bridge.error = 1 # FIXME: Error code return [0]
[ "def", "trigger_script", "(", "self", ")", ":", "if", "self", ".", "remote_bridge", ".", "status", "not", "in", "(", "BRIDGE_STATUS", ".", "RECEIVED", ",", ")", ":", "return", "[", "1", "]", "#FIXME: State change", "# This is asynchronous in real life so just cache the error", "try", ":", "self", ".", "remote_bridge", ".", "parsed_script", "=", "UpdateScript", ".", "FromBinary", "(", "self", ".", "_device", ".", "script", ")", "#FIXME: Actually run the script", "self", ".", "remote_bridge", ".", "status", "=", "BRIDGE_STATUS", ".", "IDLE", "except", "Exception", "as", "exc", ":", "self", ".", "_logger", ".", "exception", "(", "\"Error parsing script streamed to device\"", ")", "self", ".", "remote_bridge", ".", "script_error", "=", "exc", "self", ".", "remote_bridge", ".", "error", "=", "1", "# FIXME: Error code", "return", "[", "0", "]" ]
Actually process a script.
[ "Actually", "process", "a", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L103-L120
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.reset_script
def reset_script(self): """Clear any partially received script.""" self.remote_bridge.status = BRIDGE_STATUS.IDLE self.remote_bridge.error = 0 self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
python
def reset_script(self): """Clear any partially received script.""" self.remote_bridge.status = BRIDGE_STATUS.IDLE self.remote_bridge.error = 0 self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
[ "def", "reset_script", "(", "self", ")", ":", "self", ".", "remote_bridge", ".", "status", "=", "BRIDGE_STATUS", ".", "IDLE", "self", ".", "remote_bridge", ".", "error", "=", "0", "self", ".", "remote_bridge", ".", "parsed_script", "=", "None", "self", ".", "_device", ".", "script", "=", "bytearray", "(", ")", "return", "[", "0", "]" ]
Clear any partially received script.
[ "Clear", "any", "partially", "received", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L129-L137
train
iotile/coretools
iotilebuild/iotile/build/utilities/template.py
render_template_inplace
def render_template_inplace(template_path, info, dry_run=False, extra_filters=None, resolver=None): """Render a template file in place. This function expects template path to be a path to a file that ends in .tpl. It will be rendered to a file in the same directory with the .tpl suffix removed. Args: template_path (str): The path to the template file that we want to render in place. info (dict): A dictionary of variables passed into the template to perform substitutions. dry_run (bool): Whether to actually render the output file or just return the file path that would be generated. extra_filters (dict of str -> callable): An optional group of filters that will be made available to the template. The dict key will be the name at which callable is made available. resolver (ProductResolver): The specific ProductResolver class to use in the find_product filter. Returns: str: The path to the output file generated. """ filters = {} if resolver is not None: filters['find_product'] = _create_resolver_filter(resolver) if extra_filters is not None: filters.update(extra_filters) basedir = os.path.dirname(template_path) template_name = os.path.basename(template_path) if not template_name.endswith('.tpl'): raise ArgumentError("You must specify a filename that ends in .tpl", filepath=template_path) out_path = os.path.join(basedir, template_name[:-4]) if basedir == '': basedir = '.' env = Environment(loader=FileSystemLoader(basedir), trim_blocks=True, lstrip_blocks=True) # Load any filters the user wants us to use for name, func in filters.items(): env.filters[name] = func template = env.get_template(template_name) result = template.render(info) if not dry_run: with open(out_path, 'wb') as outfile: outfile.write(result.encode('utf-8')) return out_path
python
def render_template_inplace(template_path, info, dry_run=False, extra_filters=None, resolver=None): """Render a template file in place. This function expects template path to be a path to a file that ends in .tpl. It will be rendered to a file in the same directory with the .tpl suffix removed. Args: template_path (str): The path to the template file that we want to render in place. info (dict): A dictionary of variables passed into the template to perform substitutions. dry_run (bool): Whether to actually render the output file or just return the file path that would be generated. extra_filters (dict of str -> callable): An optional group of filters that will be made available to the template. The dict key will be the name at which callable is made available. resolver (ProductResolver): The specific ProductResolver class to use in the find_product filter. Returns: str: The path to the output file generated. """ filters = {} if resolver is not None: filters['find_product'] = _create_resolver_filter(resolver) if extra_filters is not None: filters.update(extra_filters) basedir = os.path.dirname(template_path) template_name = os.path.basename(template_path) if not template_name.endswith('.tpl'): raise ArgumentError("You must specify a filename that ends in .tpl", filepath=template_path) out_path = os.path.join(basedir, template_name[:-4]) if basedir == '': basedir = '.' env = Environment(loader=FileSystemLoader(basedir), trim_blocks=True, lstrip_blocks=True) # Load any filters the user wants us to use for name, func in filters.items(): env.filters[name] = func template = env.get_template(template_name) result = template.render(info) if not dry_run: with open(out_path, 'wb') as outfile: outfile.write(result.encode('utf-8')) return out_path
[ "def", "render_template_inplace", "(", "template_path", ",", "info", ",", "dry_run", "=", "False", ",", "extra_filters", "=", "None", ",", "resolver", "=", "None", ")", ":", "filters", "=", "{", "}", "if", "resolver", "is", "not", "None", ":", "filters", "[", "'find_product'", "]", "=", "_create_resolver_filter", "(", "resolver", ")", "if", "extra_filters", "is", "not", "None", ":", "filters", ".", "update", "(", "extra_filters", ")", "basedir", "=", "os", ".", "path", ".", "dirname", "(", "template_path", ")", "template_name", "=", "os", ".", "path", ".", "basename", "(", "template_path", ")", "if", "not", "template_name", ".", "endswith", "(", "'.tpl'", ")", ":", "raise", "ArgumentError", "(", "\"You must specify a filename that ends in .tpl\"", ",", "filepath", "=", "template_path", ")", "out_path", "=", "os", ".", "path", ".", "join", "(", "basedir", ",", "template_name", "[", ":", "-", "4", "]", ")", "if", "basedir", "==", "''", ":", "basedir", "=", "'.'", "env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "basedir", ")", ",", "trim_blocks", "=", "True", ",", "lstrip_blocks", "=", "True", ")", "# Load any filters the user wants us to use", "for", "name", ",", "func", "in", "filters", ".", "items", "(", ")", ":", "env", ".", "filters", "[", "name", "]", "=", "func", "template", "=", "env", ".", "get_template", "(", "template_name", ")", "result", "=", "template", ".", "render", "(", "info", ")", "if", "not", "dry_run", ":", "with", "open", "(", "out_path", ",", "'wb'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "result", ".", "encode", "(", "'utf-8'", ")", ")", "return", "out_path" ]
Render a template file in place. This function expects template path to be a path to a file that ends in .tpl. It will be rendered to a file in the same directory with the .tpl suffix removed. Args: template_path (str): The path to the template file that we want to render in place. info (dict): A dictionary of variables passed into the template to perform substitutions. dry_run (bool): Whether to actually render the output file or just return the file path that would be generated. extra_filters (dict of str -> callable): An optional group of filters that will be made available to the template. The dict key will be the name at which callable is made available. resolver (ProductResolver): The specific ProductResolver class to use in the find_product filter. Returns: str: The path to the output file generated.
[ "Render", "a", "template", "file", "in", "place", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/template.py#L20-L76
train
iotile/coretools
iotilebuild/iotile/build/utilities/template.py
render_template
def render_template(template_name, info, out_path=None): """Render a template using the variables in info. You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package out_path (str): An optional path of where to save the output file, otherwise it is just returned as a string. info (dict): A dictionary of variables passed into the template to perform substitutions. Returns: string: The rendered template data. """ env = Environment(loader=PackageLoader('iotile.build', 'config/templates'), trim_blocks=True, lstrip_blocks=True) template = env.get_template(template_name) result = template.render(info) if out_path is not None: with open(out_path, 'wb') as outfile: outfile.write(result.encode('utf-8')) return result
python
def render_template(template_name, info, out_path=None): """Render a template using the variables in info. You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package out_path (str): An optional path of where to save the output file, otherwise it is just returned as a string. info (dict): A dictionary of variables passed into the template to perform substitutions. Returns: string: The rendered template data. """ env = Environment(loader=PackageLoader('iotile.build', 'config/templates'), trim_blocks=True, lstrip_blocks=True) template = env.get_template(template_name) result = template.render(info) if out_path is not None: with open(out_path, 'wb') as outfile: outfile.write(result.encode('utf-8')) return result
[ "def", "render_template", "(", "template_name", ",", "info", ",", "out_path", "=", "None", ")", ":", "env", "=", "Environment", "(", "loader", "=", "PackageLoader", "(", "'iotile.build'", ",", "'config/templates'", ")", ",", "trim_blocks", "=", "True", ",", "lstrip_blocks", "=", "True", ")", "template", "=", "env", ".", "get_template", "(", "template_name", ")", "result", "=", "template", ".", "render", "(", "info", ")", "if", "out_path", "is", "not", "None", ":", "with", "open", "(", "out_path", ",", "'wb'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "result", ".", "encode", "(", "'utf-8'", ")", ")", "return", "result" ]
Render a template using the variables in info. You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package out_path (str): An optional path of where to save the output file, otherwise it is just returned as a string. info (dict): A dictionary of variables passed into the template to perform substitutions. Returns: string: The rendered template data.
[ "Render", "a", "template", "using", "the", "variables", "in", "info", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/template.py#L79-L106
train
iotile/coretools
iotilebuild/iotile/build/utilities/template.py
render_recursive_template
def render_recursive_template(template_folder, info, out_folder, preserve=None, dry_run=False): """Copy a directory tree rendering all templates found within. This function inspects all of the files in template_folder recursively. If any file ends .tpl, it is rendered using render_template and the .tpl suffix is removed. All other files are copied without modification. out_folder is not cleaned before rendering so you must delete its contents yourself if you want that behavior. If you just want to see all of the file paths that would be generated, call with dry_run=True. This will not render anything but just inspect what would be generated. Args: template_folder (str): A relative path from config/templates with the folder that should be rendered recursively. info (dict): A dictionary of variables to be substituted into any templates found in template_folder. out_folder (str): The path to the output folder where the template will be generated. dry_run (bool): Whether to actually render output files or just return the files that would be generated. preserve (list of str): A list of file names relative to the start of the template folder that we are rendering that end in .tpl but should not be rendered and should not have their .tpl suffix removed. This allows you to partially render a template so that you can render a specific file later. Returns: dict, list: The dict is map of output file path (relative to out_folder) to the absolute path of the input file that it depends on. This result is suitable for using in a dependency graph like SCons. The list is a list of all of the directories that would need to be created to hold these files (not including out_folder). """ if isinstance(preserve, str): raise ArgumentError("You must pass a list of strings to preserve, not a string", preserve=preserve) if preserve is None: preserve = [] preserve = set(preserve) template_dir = resource_path('templates', expect='folder') indir = os.path.join(template_dir, template_folder) if not os.path.exists(indir): raise ArgumentError("Input template folder for recursive template not found", template_folder=template_folder, absolute_path=indir) elif not os.path.isdir(indir): raise ArgumentError("Input template folder is not a directory", template_folder=template_folder, absolute_path=indir) create_dirs = [] file_map = {} # Walk over all input files for dirpath, dirs, files in os.walk(indir): for file in files: in_abspath = os.path.abspath(os.path.join(dirpath, file)) in_path = os.path.relpath(os.path.join(dirpath, file), start=indir) if file.endswith(".tpl") and not in_path in preserve: out_path = in_path[:-4] else: out_path = in_path file_map[out_path] = (in_path, in_abspath) for folder in dirs: dir_path = os.path.relpath(os.path.join(dirpath, folder), start=indir) create_dirs.append(dir_path) # Actually render / copy all files if we are not doing a dry run if not dry_run: for folder in create_dirs: out_path = os.path.join(out_folder, folder) if not os.path.isdir(out_path): os.makedirs(out_path) for out_rel, (in_path, in_abspath) in file_map.items(): out_path = os.path.join(out_folder, out_rel) if in_path in preserve or not in_path.endswith(".tpl"): shutil.copyfile(in_abspath, out_path) else: # jinja needs to have unix path separators regardless of the platform and a relative path # from the templates base directory in_template_path = os.path.join(template_folder, in_path).replace(os.path.sep, '/') render_template(in_template_path, info, out_path=out_path) return file_map, create_dirs
python
def render_recursive_template(template_folder, info, out_folder, preserve=None, dry_run=False): """Copy a directory tree rendering all templates found within. This function inspects all of the files in template_folder recursively. If any file ends .tpl, it is rendered using render_template and the .tpl suffix is removed. All other files are copied without modification. out_folder is not cleaned before rendering so you must delete its contents yourself if you want that behavior. If you just want to see all of the file paths that would be generated, call with dry_run=True. This will not render anything but just inspect what would be generated. Args: template_folder (str): A relative path from config/templates with the folder that should be rendered recursively. info (dict): A dictionary of variables to be substituted into any templates found in template_folder. out_folder (str): The path to the output folder where the template will be generated. dry_run (bool): Whether to actually render output files or just return the files that would be generated. preserve (list of str): A list of file names relative to the start of the template folder that we are rendering that end in .tpl but should not be rendered and should not have their .tpl suffix removed. This allows you to partially render a template so that you can render a specific file later. Returns: dict, list: The dict is map of output file path (relative to out_folder) to the absolute path of the input file that it depends on. This result is suitable for using in a dependency graph like SCons. The list is a list of all of the directories that would need to be created to hold these files (not including out_folder). """ if isinstance(preserve, str): raise ArgumentError("You must pass a list of strings to preserve, not a string", preserve=preserve) if preserve is None: preserve = [] preserve = set(preserve) template_dir = resource_path('templates', expect='folder') indir = os.path.join(template_dir, template_folder) if not os.path.exists(indir): raise ArgumentError("Input template folder for recursive template not found", template_folder=template_folder, absolute_path=indir) elif not os.path.isdir(indir): raise ArgumentError("Input template folder is not a directory", template_folder=template_folder, absolute_path=indir) create_dirs = [] file_map = {} # Walk over all input files for dirpath, dirs, files in os.walk(indir): for file in files: in_abspath = os.path.abspath(os.path.join(dirpath, file)) in_path = os.path.relpath(os.path.join(dirpath, file), start=indir) if file.endswith(".tpl") and not in_path in preserve: out_path = in_path[:-4] else: out_path = in_path file_map[out_path] = (in_path, in_abspath) for folder in dirs: dir_path = os.path.relpath(os.path.join(dirpath, folder), start=indir) create_dirs.append(dir_path) # Actually render / copy all files if we are not doing a dry run if not dry_run: for folder in create_dirs: out_path = os.path.join(out_folder, folder) if not os.path.isdir(out_path): os.makedirs(out_path) for out_rel, (in_path, in_abspath) in file_map.items(): out_path = os.path.join(out_folder, out_rel) if in_path in preserve or not in_path.endswith(".tpl"): shutil.copyfile(in_abspath, out_path) else: # jinja needs to have unix path separators regardless of the platform and a relative path # from the templates base directory in_template_path = os.path.join(template_folder, in_path).replace(os.path.sep, '/') render_template(in_template_path, info, out_path=out_path) return file_map, create_dirs
[ "def", "render_recursive_template", "(", "template_folder", ",", "info", ",", "out_folder", ",", "preserve", "=", "None", ",", "dry_run", "=", "False", ")", ":", "if", "isinstance", "(", "preserve", ",", "str", ")", ":", "raise", "ArgumentError", "(", "\"You must pass a list of strings to preserve, not a string\"", ",", "preserve", "=", "preserve", ")", "if", "preserve", "is", "None", ":", "preserve", "=", "[", "]", "preserve", "=", "set", "(", "preserve", ")", "template_dir", "=", "resource_path", "(", "'templates'", ",", "expect", "=", "'folder'", ")", "indir", "=", "os", ".", "path", ".", "join", "(", "template_dir", ",", "template_folder", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "indir", ")", ":", "raise", "ArgumentError", "(", "\"Input template folder for recursive template not found\"", ",", "template_folder", "=", "template_folder", ",", "absolute_path", "=", "indir", ")", "elif", "not", "os", ".", "path", ".", "isdir", "(", "indir", ")", ":", "raise", "ArgumentError", "(", "\"Input template folder is not a directory\"", ",", "template_folder", "=", "template_folder", ",", "absolute_path", "=", "indir", ")", "create_dirs", "=", "[", "]", "file_map", "=", "{", "}", "# Walk over all input files", "for", "dirpath", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "indir", ")", ":", "for", "file", "in", "files", ":", "in_abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "dirpath", ",", "file", ")", ")", "in_path", "=", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "join", "(", "dirpath", ",", "file", ")", ",", "start", "=", "indir", ")", "if", "file", ".", "endswith", "(", "\".tpl\"", ")", "and", "not", "in_path", "in", "preserve", ":", "out_path", "=", "in_path", "[", ":", "-", "4", "]", "else", ":", "out_path", "=", "in_path", "file_map", "[", "out_path", "]", "=", "(", "in_path", ",", "in_abspath", ")", "for", "folder", "in", "dirs", ":", "dir_path", "=", "os", ".", "path", ".", "relpath", "(", "os", ".", "path", ".", "join", "(", "dirpath", ",", "folder", ")", ",", "start", "=", "indir", ")", "create_dirs", ".", "append", "(", "dir_path", ")", "# Actually render / copy all files if we are not doing a dry run", "if", "not", "dry_run", ":", "for", "folder", "in", "create_dirs", ":", "out_path", "=", "os", ".", "path", ".", "join", "(", "out_folder", ",", "folder", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "out_path", ")", ":", "os", ".", "makedirs", "(", "out_path", ")", "for", "out_rel", ",", "(", "in_path", ",", "in_abspath", ")", "in", "file_map", ".", "items", "(", ")", ":", "out_path", "=", "os", ".", "path", ".", "join", "(", "out_folder", ",", "out_rel", ")", "if", "in_path", "in", "preserve", "or", "not", "in_path", ".", "endswith", "(", "\".tpl\"", ")", ":", "shutil", ".", "copyfile", "(", "in_abspath", ",", "out_path", ")", "else", ":", "# jinja needs to have unix path separators regardless of the platform and a relative path", "# from the templates base directory", "in_template_path", "=", "os", ".", "path", ".", "join", "(", "template_folder", ",", "in_path", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")", "render_template", "(", "in_template_path", ",", "info", ",", "out_path", "=", "out_path", ")", "return", "file_map", ",", "create_dirs" ]
Copy a directory tree rendering all templates found within. This function inspects all of the files in template_folder recursively. If any file ends .tpl, it is rendered using render_template and the .tpl suffix is removed. All other files are copied without modification. out_folder is not cleaned before rendering so you must delete its contents yourself if you want that behavior. If you just want to see all of the file paths that would be generated, call with dry_run=True. This will not render anything but just inspect what would be generated. Args: template_folder (str): A relative path from config/templates with the folder that should be rendered recursively. info (dict): A dictionary of variables to be substituted into any templates found in template_folder. out_folder (str): The path to the output folder where the template will be generated. dry_run (bool): Whether to actually render output files or just return the files that would be generated. preserve (list of str): A list of file names relative to the start of the template folder that we are rendering that end in .tpl but should not be rendered and should not have their .tpl suffix removed. This allows you to partially render a template so that you can render a specific file later. Returns: dict, list: The dict is map of output file path (relative to out_folder) to the absolute path of the input file that it depends on. This result is suitable for using in a dependency graph like SCons. The list is a list of all of the directories that would need to be created to hold these files (not including out_folder).
[ "Copy", "a", "directory", "tree", "rendering", "all", "templates", "found", "within", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/utilities/template.py#L109-L201
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
_find_monitor
def _find_monitor(monitors, handle): """Find all devices and events with a given monitor installed.""" found_devs = set() found_events = set() for conn_string, device in monitors.items(): for event, handles in device.items(): if handle in handles: found_events.add(event) found_devs.add(conn_string) return found_devs, found_events
python
def _find_monitor(monitors, handle): """Find all devices and events with a given monitor installed.""" found_devs = set() found_events = set() for conn_string, device in monitors.items(): for event, handles in device.items(): if handle in handles: found_events.add(event) found_devs.add(conn_string) return found_devs, found_events
[ "def", "_find_monitor", "(", "monitors", ",", "handle", ")", ":", "found_devs", "=", "set", "(", ")", "found_events", "=", "set", "(", ")", "for", "conn_string", ",", "device", "in", "monitors", ".", "items", "(", ")", ":", "for", "event", ",", "handles", "in", "device", ".", "items", "(", ")", ":", "if", "handle", "in", "handles", ":", "found_events", ".", "add", "(", "event", ")", "found_devs", ".", "add", "(", "conn_string", ")", "return", "found_devs", ",", "found_events" ]
Find all devices and events with a given monitor installed.
[ "Find", "all", "devices", "and", "events", "with", "a", "given", "monitor", "installed", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L289-L301
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
_add_monitor
def _add_monitor(monitors, handle, callback, devices, events): """Add the given monitor to the listed devices and events.""" for conn_string in devices: data = monitors.get(conn_string) if data is None: data = dict() monitors[conn_string] = data for event in events: event_dict = data.get(event) if event_dict is None: event_dict = dict() data[event] = event_dict event_dict[handle] = callback
python
def _add_monitor(monitors, handle, callback, devices, events): """Add the given monitor to the listed devices and events.""" for conn_string in devices: data = monitors.get(conn_string) if data is None: data = dict() monitors[conn_string] = data for event in events: event_dict = data.get(event) if event_dict is None: event_dict = dict() data[event] = event_dict event_dict[handle] = callback
[ "def", "_add_monitor", "(", "monitors", ",", "handle", ",", "callback", ",", "devices", ",", "events", ")", ":", "for", "conn_string", "in", "devices", ":", "data", "=", "monitors", ".", "get", "(", "conn_string", ")", "if", "data", "is", "None", ":", "data", "=", "dict", "(", ")", "monitors", "[", "conn_string", "]", "=", "data", "for", "event", "in", "events", ":", "event_dict", "=", "data", ".", "get", "(", "event", ")", "if", "event_dict", "is", "None", ":", "event_dict", "=", "dict", "(", ")", "data", "[", "event", "]", "=", "event_dict", "event_dict", "[", "handle", "]", "=", "callback" ]
Add the given monitor to the listed devices and events.
[ "Add", "the", "given", "monitor", "to", "the", "listed", "devices", "and", "events", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L304-L319
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
_remove_monitor
def _remove_monitor(monitors, handle, devices, events): """Remove the given monitor from the listed devices and events.""" empty_devices = [] for conn_string in devices: data = monitors.get(conn_string) if data is None: continue for event in events: event_dict = data.get(event) if event_dict is None: continue if handle in event_dict: del event_dict[handle] if len(event_dict) == 0: del data[event] if len(data) == 0: empty_devices.append(conn_string) return empty_devices
python
def _remove_monitor(monitors, handle, devices, events): """Remove the given monitor from the listed devices and events.""" empty_devices = [] for conn_string in devices: data = monitors.get(conn_string) if data is None: continue for event in events: event_dict = data.get(event) if event_dict is None: continue if handle in event_dict: del event_dict[handle] if len(event_dict) == 0: del data[event] if len(data) == 0: empty_devices.append(conn_string) return empty_devices
[ "def", "_remove_monitor", "(", "monitors", ",", "handle", ",", "devices", ",", "events", ")", ":", "empty_devices", "=", "[", "]", "for", "conn_string", "in", "devices", ":", "data", "=", "monitors", ".", "get", "(", "conn_string", ")", "if", "data", "is", "None", ":", "continue", "for", "event", "in", "events", ":", "event_dict", "=", "data", ".", "get", "(", "event", ")", "if", "event_dict", "is", "None", ":", "continue", "if", "handle", "in", "event_dict", ":", "del", "event_dict", "[", "handle", "]", "if", "len", "(", "event_dict", ")", "==", "0", ":", "del", "data", "[", "event", "]", "if", "len", "(", "data", ")", "==", "0", ":", "empty_devices", ".", "append", "(", "conn_string", ")", "return", "empty_devices" ]
Remove the given monitor from the listed devices and events.
[ "Remove", "the", "given", "monitor", "from", "the", "listed", "devices", "and", "events", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L322-L346
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
BasicNotificationMixin.register_monitor
def register_monitor(self, devices, events, callback): """Register a callback when events happen. If this method is called, it is guaranteed to take effect before the next call to ``_notify_event`` after this method returns. This method is safe to call from within a callback that is itself called by ``notify_event``. See :meth:`AbstractDeviceAdapter.register_monitor`. """ # Ensure we don't exhaust any iterables events = list(events) devices = list(devices) for event in events: if event not in self.SUPPORTED_EVENTS: raise ArgumentError("Unknown event type {} specified".format(event), events=events) monitor_id = str(uuid.uuid4()) action = (monitor_id, "add", devices, events) self._callbacks[monitor_id] = callback if self._currently_notifying: self._deferred_adjustments.append(action) else: self._adjust_monitor_internal(*action) return monitor_id
python
def register_monitor(self, devices, events, callback): """Register a callback when events happen. If this method is called, it is guaranteed to take effect before the next call to ``_notify_event`` after this method returns. This method is safe to call from within a callback that is itself called by ``notify_event``. See :meth:`AbstractDeviceAdapter.register_monitor`. """ # Ensure we don't exhaust any iterables events = list(events) devices = list(devices) for event in events: if event not in self.SUPPORTED_EVENTS: raise ArgumentError("Unknown event type {} specified".format(event), events=events) monitor_id = str(uuid.uuid4()) action = (monitor_id, "add", devices, events) self._callbacks[monitor_id] = callback if self._currently_notifying: self._deferred_adjustments.append(action) else: self._adjust_monitor_internal(*action) return monitor_id
[ "def", "register_monitor", "(", "self", ",", "devices", ",", "events", ",", "callback", ")", ":", "# Ensure we don't exhaust any iterables", "events", "=", "list", "(", "events", ")", "devices", "=", "list", "(", "devices", ")", "for", "event", "in", "events", ":", "if", "event", "not", "in", "self", ".", "SUPPORTED_EVENTS", ":", "raise", "ArgumentError", "(", "\"Unknown event type {} specified\"", ".", "format", "(", "event", ")", ",", "events", "=", "events", ")", "monitor_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "action", "=", "(", "monitor_id", ",", "\"add\"", ",", "devices", ",", "events", ")", "self", ".", "_callbacks", "[", "monitor_id", "]", "=", "callback", "if", "self", ".", "_currently_notifying", ":", "self", ".", "_deferred_adjustments", ".", "append", "(", "action", ")", "else", ":", "self", ".", "_adjust_monitor_internal", "(", "*", "action", ")", "return", "monitor_id" ]
Register a callback when events happen. If this method is called, it is guaranteed to take effect before the next call to ``_notify_event`` after this method returns. This method is safe to call from within a callback that is itself called by ``notify_event``. See :meth:`AbstractDeviceAdapter.register_monitor`.
[ "Register", "a", "callback", "when", "events", "happen", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L58-L87
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
BasicNotificationMixin.adjust_monitor
def adjust_monitor(self, handle, action, devices, events): """Adjust a previously registered callback. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ events = list(events) devices = list(devices) for event in events: if event not in self.SUPPORTED_EVENTS: raise ArgumentError("Unknown event type {} specified".format(event), events=events) if action not in self.SUPPORTED_ADJUSTMENTS: raise ArgumentError("Unknown adjustment {} specified".format(action)) action = (handle, action, devices, events) if self._currently_notifying: self._deferred_adjustments.append(action) else: self._adjust_monitor_internal(*action)
python
def adjust_monitor(self, handle, action, devices, events): """Adjust a previously registered callback. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ events = list(events) devices = list(devices) for event in events: if event not in self.SUPPORTED_EVENTS: raise ArgumentError("Unknown event type {} specified".format(event), events=events) if action not in self.SUPPORTED_ADJUSTMENTS: raise ArgumentError("Unknown adjustment {} specified".format(action)) action = (handle, action, devices, events) if self._currently_notifying: self._deferred_adjustments.append(action) else: self._adjust_monitor_internal(*action)
[ "def", "adjust_monitor", "(", "self", ",", "handle", ",", "action", ",", "devices", ",", "events", ")", ":", "events", "=", "list", "(", "events", ")", "devices", "=", "list", "(", "devices", ")", "for", "event", "in", "events", ":", "if", "event", "not", "in", "self", ".", "SUPPORTED_EVENTS", ":", "raise", "ArgumentError", "(", "\"Unknown event type {} specified\"", ".", "format", "(", "event", ")", ",", "events", "=", "events", ")", "if", "action", "not", "in", "self", ".", "SUPPORTED_ADJUSTMENTS", ":", "raise", "ArgumentError", "(", "\"Unknown adjustment {} specified\"", ".", "format", "(", "action", ")", ")", "action", "=", "(", "handle", ",", "action", ",", "devices", ",", "events", ")", "if", "self", ".", "_currently_notifying", ":", "self", ".", "_deferred_adjustments", ".", "append", "(", "action", ")", "else", ":", "self", ".", "_adjust_monitor_internal", "(", "*", "action", ")" ]
Adjust a previously registered callback. See :meth:`AbstractDeviceAdapter.adjust_monitor`.
[ "Adjust", "a", "previously", "registered", "callback", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L118-L138
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
BasicNotificationMixin.remove_monitor
def remove_monitor(self, handle): """Remove a previously registered monitor. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ action = (handle, "delete", None, None) if self._currently_notifying: self._deferred_adjustments.append(action) else: self._adjust_monitor_internal(*action)
python
def remove_monitor(self, handle): """Remove a previously registered monitor. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ action = (handle, "delete", None, None) if self._currently_notifying: self._deferred_adjustments.append(action) else: self._adjust_monitor_internal(*action)
[ "def", "remove_monitor", "(", "self", ",", "handle", ")", ":", "action", "=", "(", "handle", ",", "\"delete\"", ",", "None", ",", "None", ")", "if", "self", ".", "_currently_notifying", ":", "self", ".", "_deferred_adjustments", ".", "append", "(", "action", ")", "else", ":", "self", ".", "_adjust_monitor_internal", "(", "*", "action", ")" ]
Remove a previously registered monitor. See :meth:`AbstractDeviceAdapter.adjust_monitor`.
[ "Remove", "a", "previously", "registered", "monitor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L140-L150
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
BasicNotificationMixin._notify_event_internal
async def _notify_event_internal(self, conn_string, name, event): """Notify that an event has occured. This method will send a notification and ensure that all callbacks registered for it have completed by the time it returns. In particular, if the callbacks are awaitable, this method will await them before returning. The order in which the callbacks are called is undefined. This is a low level method that is not intended to be called directly. You should use the high level public notify_* methods for each of the types of events to ensure consistency in how the event objects are created. Args: conn_string (str): The connection string for the device that the event is associated with. name (str): The name of the event. Must be in SUPPORTED_EVENTS. event (object): The event object. The type of this object will depend on what is being notified. """ try: self._currently_notifying = True conn_id = self._get_conn_id(conn_string) event_maps = self._monitors.get(conn_string, {}) wildcard_maps = self._monitors.get(None, {}) wildcard_handlers = wildcard_maps.get(name, {}) event_handlers = event_maps.get(name, {}) for handler, func in itertools.chain(event_handlers.items(), wildcard_handlers.items()): try: result = func(conn_string, conn_id, name, event) if inspect.isawaitable(result): await result except: #pylint:disable=bare-except;This is a background function and we are logging exceptions self._logger.warning("Error calling notification callback id=%s, func=%s", handler, func, exc_info=True) finally: for action in self._deferred_adjustments: self._adjust_monitor_internal(*action) self._deferred_adjustments = [] self._currently_notifying = False
python
async def _notify_event_internal(self, conn_string, name, event): """Notify that an event has occured. This method will send a notification and ensure that all callbacks registered for it have completed by the time it returns. In particular, if the callbacks are awaitable, this method will await them before returning. The order in which the callbacks are called is undefined. This is a low level method that is not intended to be called directly. You should use the high level public notify_* methods for each of the types of events to ensure consistency in how the event objects are created. Args: conn_string (str): The connection string for the device that the event is associated with. name (str): The name of the event. Must be in SUPPORTED_EVENTS. event (object): The event object. The type of this object will depend on what is being notified. """ try: self._currently_notifying = True conn_id = self._get_conn_id(conn_string) event_maps = self._monitors.get(conn_string, {}) wildcard_maps = self._monitors.get(None, {}) wildcard_handlers = wildcard_maps.get(name, {}) event_handlers = event_maps.get(name, {}) for handler, func in itertools.chain(event_handlers.items(), wildcard_handlers.items()): try: result = func(conn_string, conn_id, name, event) if inspect.isawaitable(result): await result except: #pylint:disable=bare-except;This is a background function and we are logging exceptions self._logger.warning("Error calling notification callback id=%s, func=%s", handler, func, exc_info=True) finally: for action in self._deferred_adjustments: self._adjust_monitor_internal(*action) self._deferred_adjustments = [] self._currently_notifying = False
[ "async", "def", "_notify_event_internal", "(", "self", ",", "conn_string", ",", "name", ",", "event", ")", ":", "try", ":", "self", ".", "_currently_notifying", "=", "True", "conn_id", "=", "self", ".", "_get_conn_id", "(", "conn_string", ")", "event_maps", "=", "self", ".", "_monitors", ".", "get", "(", "conn_string", ",", "{", "}", ")", "wildcard_maps", "=", "self", ".", "_monitors", ".", "get", "(", "None", ",", "{", "}", ")", "wildcard_handlers", "=", "wildcard_maps", ".", "get", "(", "name", ",", "{", "}", ")", "event_handlers", "=", "event_maps", ".", "get", "(", "name", ",", "{", "}", ")", "for", "handler", ",", "func", "in", "itertools", ".", "chain", "(", "event_handlers", ".", "items", "(", ")", ",", "wildcard_handlers", ".", "items", "(", ")", ")", ":", "try", ":", "result", "=", "func", "(", "conn_string", ",", "conn_id", ",", "name", ",", "event", ")", "if", "inspect", ".", "isawaitable", "(", "result", ")", ":", "await", "result", "except", ":", "#pylint:disable=bare-except;This is a background function and we are logging exceptions", "self", ".", "_logger", ".", "warning", "(", "\"Error calling notification callback id=%s, func=%s\"", ",", "handler", ",", "func", ",", "exc_info", "=", "True", ")", "finally", ":", "for", "action", "in", "self", ".", "_deferred_adjustments", ":", "self", ".", "_adjust_monitor_internal", "(", "*", "action", ")", "self", ".", "_deferred_adjustments", "=", "[", "]", "self", ".", "_currently_notifying", "=", "False" ]
Notify that an event has occured. This method will send a notification and ensure that all callbacks registered for it have completed by the time it returns. In particular, if the callbacks are awaitable, this method will await them before returning. The order in which the callbacks are called is undefined. This is a low level method that is not intended to be called directly. You should use the high level public notify_* methods for each of the types of events to ensure consistency in how the event objects are created. Args: conn_string (str): The connection string for the device that the event is associated with. name (str): The name of the event. Must be in SUPPORTED_EVENTS. event (object): The event object. The type of this object will depend on what is being notified.
[ "Notify", "that", "an", "event", "has", "occured", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L152-L196
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py
BasicNotificationMixin.notify_progress
def notify_progress(self, conn_string, operation, finished, total, wait=True): """Send a progress event. Progress events can be sent for ``debug`` and ``script`` operations and notify the caller about the progress of these potentially long-running operations. They have two integer properties that specify what fraction of the operation has been completed. Args: conn_string (str): The device that is sending the event. operations (str): The operation that is in progress: debug or script finished (int): The number of "steps" that have finished. total (int): The total number of steps to perform. wait (bool): Whether to return an awaitable that we can use to block until the notification has made it to all callbacks. Returns: awaitable or None: An awaitable if wait=True. If wait is False, the notification is run in the background with no way to check its progress and None is returned. """ if operation not in self.PROGRESS_OPERATIONS: raise ArgumentError("Invalid operation for progress event: {}".format(operation)) event = dict(operation=operation, finished=finished, total=total) if wait: return self.notify_event(conn_string, 'progress', event) self.notify_event_nowait(conn_string, 'progress', event) return None
python
def notify_progress(self, conn_string, operation, finished, total, wait=True): """Send a progress event. Progress events can be sent for ``debug`` and ``script`` operations and notify the caller about the progress of these potentially long-running operations. They have two integer properties that specify what fraction of the operation has been completed. Args: conn_string (str): The device that is sending the event. operations (str): The operation that is in progress: debug or script finished (int): The number of "steps" that have finished. total (int): The total number of steps to perform. wait (bool): Whether to return an awaitable that we can use to block until the notification has made it to all callbacks. Returns: awaitable or None: An awaitable if wait=True. If wait is False, the notification is run in the background with no way to check its progress and None is returned. """ if operation not in self.PROGRESS_OPERATIONS: raise ArgumentError("Invalid operation for progress event: {}".format(operation)) event = dict(operation=operation, finished=finished, total=total) if wait: return self.notify_event(conn_string, 'progress', event) self.notify_event_nowait(conn_string, 'progress', event) return None
[ "def", "notify_progress", "(", "self", ",", "conn_string", ",", "operation", ",", "finished", ",", "total", ",", "wait", "=", "True", ")", ":", "if", "operation", "not", "in", "self", ".", "PROGRESS_OPERATIONS", ":", "raise", "ArgumentError", "(", "\"Invalid operation for progress event: {}\"", ".", "format", "(", "operation", ")", ")", "event", "=", "dict", "(", "operation", "=", "operation", ",", "finished", "=", "finished", ",", "total", "=", "total", ")", "if", "wait", ":", "return", "self", ".", "notify_event", "(", "conn_string", ",", "'progress'", ",", "event", ")", "self", ".", "notify_event_nowait", "(", "conn_string", ",", "'progress'", ",", "event", ")", "return", "None" ]
Send a progress event. Progress events can be sent for ``debug`` and ``script`` operations and notify the caller about the progress of these potentially long-running operations. They have two integer properties that specify what fraction of the operation has been completed. Args: conn_string (str): The device that is sending the event. operations (str): The operation that is in progress: debug or script finished (int): The number of "steps" that have finished. total (int): The total number of steps to perform. wait (bool): Whether to return an awaitable that we can use to block until the notification has made it to all callbacks. Returns: awaitable or None: An awaitable if wait=True. If wait is False, the notification is run in the background with no way to check its progress and None is returned.
[ "Send", "a", "progress", "event", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/mixin_notifications.py#L254-L286
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgicxx.py
generate
def generate(env): """Add Builders and construction variables for SGI MIPS C++ to an Environment.""" cplusplus.generate(env) env['CXX'] = 'CC' env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std') env['SHCXX'] = '$CXX' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
python
def generate(env): """Add Builders and construction variables for SGI MIPS C++ to an Environment.""" cplusplus.generate(env) env['CXX'] = 'CC' env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std') env['SHCXX'] = '$CXX' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
[ "def", "generate", "(", "env", ")", ":", "cplusplus", ".", "generate", "(", "env", ")", "env", "[", "'CXX'", "]", "=", "'CC'", "env", "[", "'CXXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-LANG:std'", ")", "env", "[", "'SHCXX'", "]", "=", "'$CXX'", "env", "[", "'SHOBJSUFFIX'", "]", "=", "'.o'", "env", "[", "'STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'", "]", "=", "1" ]
Add Builders and construction variables for SGI MIPS C++ to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "SGI", "MIPS", "C", "++", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgicxx.py#L43-L52
train
iotile/coretools
transport_plugins/bled112/iotile_transport_bled112/async_packet.py
AsyncPacketBuffer.read_packet
def read_packet(self, timeout=3.0): """read one packet, timeout if one packet is not available in the timeout period""" try: return self.queue.get(timeout=timeout) except Empty: raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer")
python
def read_packet(self, timeout=3.0): """read one packet, timeout if one packet is not available in the timeout period""" try: return self.queue.get(timeout=timeout) except Empty: raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer")
[ "def", "read_packet", "(", "self", ",", "timeout", "=", "3.0", ")", ":", "try", ":", "return", "self", ".", "queue", ".", "get", "(", "timeout", "=", "timeout", ")", "except", "Empty", ":", "raise", "InternalTimeoutError", "(", "\"Timeout waiting for packet in AsyncPacketBuffer\"", ")" ]
read one packet, timeout if one packet is not available in the timeout period
[ "read", "one", "packet", "timeout", "if", "one", "packet", "is", "not", "available", "in", "the", "timeout", "period" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/async_packet.py#L45-L51
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javac.py
generate
def generate(env): """Add Builders and construction variables for javac to an Environment.""" java_file = SCons.Tool.CreateJavaFileBuilder(env) java_class = SCons.Tool.CreateJavaClassFileBuilder(env) java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env) java_class.add_emitter(None, emit_java_classes) java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes) java_class_dir.emitter = emit_java_classes env.AddMethod(Java) env['JAVAC'] = 'javac' env['JAVACFLAGS'] = SCons.Util.CLVar('') env['JAVABOOTCLASSPATH'] = [] env['JAVACLASSPATH'] = [] env['JAVASOURCEPATH'] = [] env['_javapathopt'] = pathopt env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} ' env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} ' env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} ' env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}' env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES' env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}" env['JAVACLASSSUFFIX'] = '.class' env['JAVASUFFIX'] = '.java'
python
def generate(env): """Add Builders and construction variables for javac to an Environment.""" java_file = SCons.Tool.CreateJavaFileBuilder(env) java_class = SCons.Tool.CreateJavaClassFileBuilder(env) java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env) java_class.add_emitter(None, emit_java_classes) java_class.add_emitter(env.subst('$JAVASUFFIX'), emit_java_classes) java_class_dir.emitter = emit_java_classes env.AddMethod(Java) env['JAVAC'] = 'javac' env['JAVACFLAGS'] = SCons.Util.CLVar('') env['JAVABOOTCLASSPATH'] = [] env['JAVACLASSPATH'] = [] env['JAVASOURCEPATH'] = [] env['_javapathopt'] = pathopt env['_JAVABOOTCLASSPATH'] = '${_javapathopt("-bootclasspath", "JAVABOOTCLASSPATH")} ' env['_JAVACLASSPATH'] = '${_javapathopt("-classpath", "JAVACLASSPATH")} ' env['_JAVASOURCEPATH'] = '${_javapathopt("-sourcepath", "JAVASOURCEPATH", "_JAVASOURCEPATHDEFAULT")} ' env['_JAVASOURCEPATHDEFAULT'] = '${TARGET.attributes.java_sourcedir}' env['_JAVACCOM'] = '$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES' env['JAVACCOM'] = "${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}" env['JAVACLASSSUFFIX'] = '.class' env['JAVASUFFIX'] = '.java'
[ "def", "generate", "(", "env", ")", ":", "java_file", "=", "SCons", ".", "Tool", ".", "CreateJavaFileBuilder", "(", "env", ")", "java_class", "=", "SCons", ".", "Tool", ".", "CreateJavaClassFileBuilder", "(", "env", ")", "java_class_dir", "=", "SCons", ".", "Tool", ".", "CreateJavaClassDirBuilder", "(", "env", ")", "java_class", ".", "add_emitter", "(", "None", ",", "emit_java_classes", ")", "java_class", ".", "add_emitter", "(", "env", ".", "subst", "(", "'$JAVASUFFIX'", ")", ",", "emit_java_classes", ")", "java_class_dir", ".", "emitter", "=", "emit_java_classes", "env", ".", "AddMethod", "(", "Java", ")", "env", "[", "'JAVAC'", "]", "=", "'javac'", "env", "[", "'JAVACFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "env", "[", "'JAVABOOTCLASSPATH'", "]", "=", "[", "]", "env", "[", "'JAVACLASSPATH'", "]", "=", "[", "]", "env", "[", "'JAVASOURCEPATH'", "]", "=", "[", "]", "env", "[", "'_javapathopt'", "]", "=", "pathopt", "env", "[", "'_JAVABOOTCLASSPATH'", "]", "=", "'${_javapathopt(\"-bootclasspath\", \"JAVABOOTCLASSPATH\")} '", "env", "[", "'_JAVACLASSPATH'", "]", "=", "'${_javapathopt(\"-classpath\", \"JAVACLASSPATH\")} '", "env", "[", "'_JAVASOURCEPATH'", "]", "=", "'${_javapathopt(\"-sourcepath\", \"JAVASOURCEPATH\", \"_JAVASOURCEPATHDEFAULT\")} '", "env", "[", "'_JAVASOURCEPATHDEFAULT'", "]", "=", "'${TARGET.attributes.java_sourcedir}'", "env", "[", "'_JAVACCOM'", "]", "=", "'$JAVAC $JAVACFLAGS $_JAVABOOTCLASSPATH $_JAVACLASSPATH -d ${TARGET.attributes.java_classdir} $_JAVASOURCEPATH $SOURCES'", "env", "[", "'JAVACCOM'", "]", "=", "\"${TEMPFILE('$_JAVACCOM','$JAVACCOMSTR')}\"", "env", "[", "'JAVACLASSSUFFIX'", "]", "=", "'.class'", "env", "[", "'JAVASUFFIX'", "]", "=", "'.java'" ]
Add Builders and construction variables for javac to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "javac", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/javac.py#L199-L223
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py
Variables.Add
def Add(self, key, help="", default=None, validator=None, converter=None, **kw): """ Add an option. @param key: the name of the variable, or a list or tuple of arguments @param help: optional help text for the options @param default: optional default value @param validator: optional function that is called to validate the option's value @type validator: Called with (key, value, environment) @param converter: optional function that is called to convert the option's value before putting it in the environment. """ if SCons.Util.is_List(key) or isinstance(key, tuple): self._do_add(*key) return if not SCons.Util.is_String(key) or \ not SCons.Environment.is_valid_construction_var(key): raise SCons.Errors.UserError("Illegal Variables.Add() key `%s'" % str(key)) self._do_add(key, help, default, validator, converter)
python
def Add(self, key, help="", default=None, validator=None, converter=None, **kw): """ Add an option. @param key: the name of the variable, or a list or tuple of arguments @param help: optional help text for the options @param default: optional default value @param validator: optional function that is called to validate the option's value @type validator: Called with (key, value, environment) @param converter: optional function that is called to convert the option's value before putting it in the environment. """ if SCons.Util.is_List(key) or isinstance(key, tuple): self._do_add(*key) return if not SCons.Util.is_String(key) or \ not SCons.Environment.is_valid_construction_var(key): raise SCons.Errors.UserError("Illegal Variables.Add() key `%s'" % str(key)) self._do_add(key, help, default, validator, converter)
[ "def", "Add", "(", "self", ",", "key", ",", "help", "=", "\"\"", ",", "default", "=", "None", ",", "validator", "=", "None", ",", "converter", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "SCons", ".", "Util", ".", "is_List", "(", "key", ")", "or", "isinstance", "(", "key", ",", "tuple", ")", ":", "self", ".", "_do_add", "(", "*", "key", ")", "return", "if", "not", "SCons", ".", "Util", ".", "is_String", "(", "key", ")", "or", "not", "SCons", ".", "Environment", ".", "is_valid_construction_var", "(", "key", ")", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"Illegal Variables.Add() key `%s'\"", "%", "str", "(", "key", ")", ")", "self", ".", "_do_add", "(", "key", ",", "help", ",", "default", ",", "validator", ",", "converter", ")" ]
Add an option. @param key: the name of the variable, or a list or tuple of arguments @param help: optional help text for the options @param default: optional default value @param validator: optional function that is called to validate the option's value @type validator: Called with (key, value, environment) @param converter: optional function that is called to convert the option's value before putting it in the environment.
[ "Add", "an", "option", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L115-L136
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py
Variables.Update
def Update(self, env, args=None): """ Update an environment with the option variables. env - the environment to update. """ values = {} # first set the defaults: for option in self.options: if not option.default is None: values[option.key] = option.default # next set the value specified in the options file for filename in self.files: if os.path.exists(filename): dir = os.path.split(os.path.abspath(filename))[0] if dir: sys.path.insert(0, dir) try: values['__name__'] = filename with open(filename, 'r') as f: contents = f.read() exec(contents, {}, values) finally: if dir: del sys.path[0] del values['__name__'] # set the values specified on the command line if args is None: args = self.args for arg, value in args.items(): added = False for option in self.options: if arg in list(option.aliases) + [ option.key ]: values[option.key] = value added = True if not added: self.unknown[arg] = value # put the variables in the environment: # (don't copy over variables that are not declared as options) for option in self.options: try: env[option.key] = values[option.key] except KeyError: pass # Call the convert functions: for option in self.options: if option.converter and option.key in values: value = env.subst('${%s}'%option.key) try: try: env[option.key] = option.converter(value) except TypeError: env[option.key] = option.converter(value, env) except ValueError as x: raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x)) # Finally validate the values: for option in self.options: if option.validator and option.key in values: option.validator(option.key, env.subst('${%s}'%option.key), env)
python
def Update(self, env, args=None): """ Update an environment with the option variables. env - the environment to update. """ values = {} # first set the defaults: for option in self.options: if not option.default is None: values[option.key] = option.default # next set the value specified in the options file for filename in self.files: if os.path.exists(filename): dir = os.path.split(os.path.abspath(filename))[0] if dir: sys.path.insert(0, dir) try: values['__name__'] = filename with open(filename, 'r') as f: contents = f.read() exec(contents, {}, values) finally: if dir: del sys.path[0] del values['__name__'] # set the values specified on the command line if args is None: args = self.args for arg, value in args.items(): added = False for option in self.options: if arg in list(option.aliases) + [ option.key ]: values[option.key] = value added = True if not added: self.unknown[arg] = value # put the variables in the environment: # (don't copy over variables that are not declared as options) for option in self.options: try: env[option.key] = values[option.key] except KeyError: pass # Call the convert functions: for option in self.options: if option.converter and option.key in values: value = env.subst('${%s}'%option.key) try: try: env[option.key] = option.converter(value) except TypeError: env[option.key] = option.converter(value, env) except ValueError as x: raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x)) # Finally validate the values: for option in self.options: if option.validator and option.key in values: option.validator(option.key, env.subst('${%s}'%option.key), env)
[ "def", "Update", "(", "self", ",", "env", ",", "args", "=", "None", ")", ":", "values", "=", "{", "}", "# first set the defaults:", "for", "option", "in", "self", ".", "options", ":", "if", "not", "option", ".", "default", "is", "None", ":", "values", "[", "option", ".", "key", "]", "=", "option", ".", "default", "# next set the value specified in the options file", "for", "filename", "in", "self", ".", "files", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "dir", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "[", "0", "]", "if", "dir", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "dir", ")", "try", ":", "values", "[", "'__name__'", "]", "=", "filename", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "contents", "=", "f", ".", "read", "(", ")", "exec", "(", "contents", ",", "{", "}", ",", "values", ")", "finally", ":", "if", "dir", ":", "del", "sys", ".", "path", "[", "0", "]", "del", "values", "[", "'__name__'", "]", "# set the values specified on the command line", "if", "args", "is", "None", ":", "args", "=", "self", ".", "args", "for", "arg", ",", "value", "in", "args", ".", "items", "(", ")", ":", "added", "=", "False", "for", "option", "in", "self", ".", "options", ":", "if", "arg", "in", "list", "(", "option", ".", "aliases", ")", "+", "[", "option", ".", "key", "]", ":", "values", "[", "option", ".", "key", "]", "=", "value", "added", "=", "True", "if", "not", "added", ":", "self", ".", "unknown", "[", "arg", "]", "=", "value", "# put the variables in the environment:", "# (don't copy over variables that are not declared as options)", "for", "option", "in", "self", ".", "options", ":", "try", ":", "env", "[", "option", ".", "key", "]", "=", "values", "[", "option", ".", "key", "]", "except", "KeyError", ":", "pass", "# Call the convert functions:", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "converter", "and", "option", ".", "key", "in", "values", ":", "value", "=", "env", ".", "subst", "(", "'${%s}'", "%", "option", ".", "key", ")", "try", ":", "try", ":", "env", "[", "option", ".", "key", "]", "=", "option", ".", "converter", "(", "value", ")", "except", "TypeError", ":", "env", "[", "option", ".", "key", "]", "=", "option", ".", "converter", "(", "value", ",", "env", ")", "except", "ValueError", "as", "x", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'Error converting option: %s\\n%s'", "%", "(", "option", ".", "key", ",", "x", ")", ")", "# Finally validate the values:", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "validator", "and", "option", ".", "key", "in", "values", ":", "option", ".", "validator", "(", "option", ".", "key", ",", "env", ".", "subst", "(", "'${%s}'", "%", "option", ".", "key", ")", ",", "env", ")" ]
Update an environment with the option variables. env - the environment to update.
[ "Update", "an", "environment", "with", "the", "option", "variables", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L160-L227
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py
Variables.Save
def Save(self, filename, env): """ Saves all the options in the given file. This file can then be used to load the options next run. This can be used to create an option cache file. filename - Name of the file to save into env - the environment get the option values from """ # Create the file and write out the header try: fh = open(filename, 'w') try: # Make an assignment in the file for each option # within the environment that was assigned a value # other than the default. for option in self.options: try: value = env[option.key] try: prepare = value.prepare_to_store except AttributeError: try: eval(repr(value)) except KeyboardInterrupt: raise except: # Convert stuff that has a repr() that # cannot be evaluated into a string value = SCons.Util.to_String(value) else: value = prepare() defaultVal = env.subst(SCons.Util.to_String(option.default)) if option.converter: defaultVal = option.converter(defaultVal) if str(env.subst('${%s}' % option.key)) != str(defaultVal): fh.write('%s = %s\n' % (option.key, repr(value))) except KeyError: pass finally: fh.close() except IOError as x: raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x))
python
def Save(self, filename, env): """ Saves all the options in the given file. This file can then be used to load the options next run. This can be used to create an option cache file. filename - Name of the file to save into env - the environment get the option values from """ # Create the file and write out the header try: fh = open(filename, 'w') try: # Make an assignment in the file for each option # within the environment that was assigned a value # other than the default. for option in self.options: try: value = env[option.key] try: prepare = value.prepare_to_store except AttributeError: try: eval(repr(value)) except KeyboardInterrupt: raise except: # Convert stuff that has a repr() that # cannot be evaluated into a string value = SCons.Util.to_String(value) else: value = prepare() defaultVal = env.subst(SCons.Util.to_String(option.default)) if option.converter: defaultVal = option.converter(defaultVal) if str(env.subst('${%s}' % option.key)) != str(defaultVal): fh.write('%s = %s\n' % (option.key, repr(value))) except KeyError: pass finally: fh.close() except IOError as x: raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x))
[ "def", "Save", "(", "self", ",", "filename", ",", "env", ")", ":", "# Create the file and write out the header", "try", ":", "fh", "=", "open", "(", "filename", ",", "'w'", ")", "try", ":", "# Make an assignment in the file for each option", "# within the environment that was assigned a value", "# other than the default.", "for", "option", "in", "self", ".", "options", ":", "try", ":", "value", "=", "env", "[", "option", ".", "key", "]", "try", ":", "prepare", "=", "value", ".", "prepare_to_store", "except", "AttributeError", ":", "try", ":", "eval", "(", "repr", "(", "value", ")", ")", "except", "KeyboardInterrupt", ":", "raise", "except", ":", "# Convert stuff that has a repr() that", "# cannot be evaluated into a string", "value", "=", "SCons", ".", "Util", ".", "to_String", "(", "value", ")", "else", ":", "value", "=", "prepare", "(", ")", "defaultVal", "=", "env", ".", "subst", "(", "SCons", ".", "Util", ".", "to_String", "(", "option", ".", "default", ")", ")", "if", "option", ".", "converter", ":", "defaultVal", "=", "option", ".", "converter", "(", "defaultVal", ")", "if", "str", "(", "env", ".", "subst", "(", "'${%s}'", "%", "option", ".", "key", ")", ")", "!=", "str", "(", "defaultVal", ")", ":", "fh", ".", "write", "(", "'%s = %s\\n'", "%", "(", "option", ".", "key", ",", "repr", "(", "value", ")", ")", ")", "except", "KeyError", ":", "pass", "finally", ":", "fh", ".", "close", "(", ")", "except", "IOError", "as", "x", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'Error writing options to file: %s\\n%s'", "%", "(", "filename", ",", "x", ")", ")" ]
Saves all the options in the given file. This file can then be used to load the options next run. This can be used to create an option cache file. filename - Name of the file to save into env - the environment get the option values from
[ "Saves", "all", "the", "options", "in", "the", "given", "file", ".", "This", "file", "can", "then", "be", "used", "to", "load", "the", "options", "next", "run", ".", "This", "can", "be", "used", "to", "create", "an", "option", "cache", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L236-L283
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py
Variables.GenerateHelpText
def GenerateHelpText(self, env, sort=None): """ Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1 or a boolean to indicate if it should be sorted. """ if callable(sort): options = sorted(self.options, key=cmp_to_key(lambda x,y: sort(x.key,y.key))) elif sort is True: options = sorted(self.options, key=lambda x: x.key) else: options = self.options def format(opt, self=self, env=env): if opt.key in env: actual = env.subst('${%s}' % opt.key) else: actual = None return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases) lines = [_f for _f in map(format, options) if _f] return ''.join(lines)
python
def GenerateHelpText(self, env, sort=None): """ Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1 or a boolean to indicate if it should be sorted. """ if callable(sort): options = sorted(self.options, key=cmp_to_key(lambda x,y: sort(x.key,y.key))) elif sort is True: options = sorted(self.options, key=lambda x: x.key) else: options = self.options def format(opt, self=self, env=env): if opt.key in env: actual = env.subst('${%s}' % opt.key) else: actual = None return self.FormatVariableHelpText(env, opt.key, opt.help, opt.default, actual, opt.aliases) lines = [_f for _f in map(format, options) if _f] return ''.join(lines)
[ "def", "GenerateHelpText", "(", "self", ",", "env", ",", "sort", "=", "None", ")", ":", "if", "callable", "(", "sort", ")", ":", "options", "=", "sorted", "(", "self", ".", "options", ",", "key", "=", "cmp_to_key", "(", "lambda", "x", ",", "y", ":", "sort", "(", "x", ".", "key", ",", "y", ".", "key", ")", ")", ")", "elif", "sort", "is", "True", ":", "options", "=", "sorted", "(", "self", ".", "options", ",", "key", "=", "lambda", "x", ":", "x", ".", "key", ")", "else", ":", "options", "=", "self", ".", "options", "def", "format", "(", "opt", ",", "self", "=", "self", ",", "env", "=", "env", ")", ":", "if", "opt", ".", "key", "in", "env", ":", "actual", "=", "env", ".", "subst", "(", "'${%s}'", "%", "opt", ".", "key", ")", "else", ":", "actual", "=", "None", "return", "self", ".", "FormatVariableHelpText", "(", "env", ",", "opt", ".", "key", ",", "opt", ".", "help", ",", "opt", ".", "default", ",", "actual", ",", "opt", ".", "aliases", ")", "lines", "=", "[", "_f", "for", "_f", "in", "map", "(", "format", ",", "options", ")", "if", "_f", "]", "return", "''", ".", "join", "(", "lines", ")" ]
Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1 or a boolean to indicate if it should be sorted.
[ "Generate", "the", "help", "text", "for", "the", "options", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/__init__.py#L285-L310
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
render_tree
def render_tree(root, child_func, prune=0, margin=[0], visited=None): """ Render a tree of nodes into an ASCII tree view. :Parameters: - `root`: the root node of the tree - `child_func`: the function called to get the children of a node - `prune`: don't visit the same node twice - `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. - `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) # Initialize 'visited' dict, if required if visited is None: visited = {} children = child_func(root) retval = "" for pipe in margin[:-1]: if pipe: retval = retval + "| " else: retval = retval + " " if rname in visited: return retval + "+-[" + rname + "]\n" retval = retval + "+-" + rname + "\n" if not prune: visited = copy.copy(visited) visited[rname] = 1 for i in range(len(children)): margin.append(i < len(children)-1) retval = retval + render_tree(children[i], child_func, prune, margin, visited) margin.pop() return retval
python
def render_tree(root, child_func, prune=0, margin=[0], visited=None): """ Render a tree of nodes into an ASCII tree view. :Parameters: - `root`: the root node of the tree - `child_func`: the function called to get the children of a node - `prune`: don't visit the same node twice - `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. - `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) # Initialize 'visited' dict, if required if visited is None: visited = {} children = child_func(root) retval = "" for pipe in margin[:-1]: if pipe: retval = retval + "| " else: retval = retval + " " if rname in visited: return retval + "+-[" + rname + "]\n" retval = retval + "+-" + rname + "\n" if not prune: visited = copy.copy(visited) visited[rname] = 1 for i in range(len(children)): margin.append(i < len(children)-1) retval = retval + render_tree(children[i], child_func, prune, margin, visited) margin.pop() return retval
[ "def", "render_tree", "(", "root", ",", "child_func", ",", "prune", "=", "0", ",", "margin", "=", "[", "0", "]", ",", "visited", "=", "None", ")", ":", "rname", "=", "str", "(", "root", ")", "# Initialize 'visited' dict, if required", "if", "visited", "is", "None", ":", "visited", "=", "{", "}", "children", "=", "child_func", "(", "root", ")", "retval", "=", "\"\"", "for", "pipe", "in", "margin", "[", ":", "-", "1", "]", ":", "if", "pipe", ":", "retval", "=", "retval", "+", "\"| \"", "else", ":", "retval", "=", "retval", "+", "\" \"", "if", "rname", "in", "visited", ":", "return", "retval", "+", "\"+-[\"", "+", "rname", "+", "\"]\\n\"", "retval", "=", "retval", "+", "\"+-\"", "+", "rname", "+", "\"\\n\"", "if", "not", "prune", ":", "visited", "=", "copy", ".", "copy", "(", "visited", ")", "visited", "[", "rname", "]", "=", "1", "for", "i", "in", "range", "(", "len", "(", "children", ")", ")", ":", "margin", ".", "append", "(", "i", "<", "len", "(", "children", ")", "-", "1", ")", "retval", "=", "retval", "+", "render_tree", "(", "children", "[", "i", "]", ",", "child_func", ",", "prune", ",", "margin", ",", "visited", ")", "margin", ".", "pop", "(", ")", "return", "retval" ]
Render a tree of nodes into an ASCII tree view. :Parameters: - `root`: the root node of the tree - `child_func`: the function called to get the children of a node - `prune`: don't visit the same node twice - `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. - `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
[ "Render", "a", "tree", "of", "nodes", "into", "an", "ASCII", "tree", "view", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L235-L274
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
print_tree
def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None): """ Print a tree of nodes. This is like render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be printed. :Parameters: - `root` - the root node of the tree - `child_func` - the function called to get the children of a node - `prune` - don't visit the same node twice - `showtags` - print status information to the left of each node line - `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. - `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) # Initialize 'visited' dict, if required if visited is None: visited = {} if showtags: if showtags == 2: legend = (' E = exists\n' + ' R = exists in repository only\n' + ' b = implicit builder\n' + ' B = explicit builder\n' + ' S = side effect\n' + ' P = precious\n' + ' A = always build\n' + ' C = current\n' + ' N = no clean\n' + ' H = no cache\n' + '\n') sys.stdout.write(legend) tags = ['['] tags.append(' E'[IDX(root.exists())]) tags.append(' R'[IDX(root.rexists() and not root.exists())]) tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] + [0,2][IDX(root.has_builder())]]) tags.append(' S'[IDX(root.side_effect)]) tags.append(' P'[IDX(root.precious)]) tags.append(' A'[IDX(root.always_build)]) tags.append(' C'[IDX(root.is_up_to_date())]) tags.append(' N'[IDX(root.noclean)]) tags.append(' H'[IDX(root.nocache)]) tags.append(']') else: tags = [] def MMM(m): return [" ","| "][m] margins = list(map(MMM, margin[:-1])) children = child_func(root) if prune and rname in visited and children: sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n') return sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n') visited[rname] = 1 if children: margin.append(1) idx = IDX(showtags) for C in children[:-1]: print_tree(C, child_func, prune, idx, margin, visited) margin[-1] = 0 print_tree(children[-1], child_func, prune, idx, margin, visited) margin.pop()
python
def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None): """ Print a tree of nodes. This is like render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be printed. :Parameters: - `root` - the root node of the tree - `child_func` - the function called to get the children of a node - `prune` - don't visit the same node twice - `showtags` - print status information to the left of each node line - `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. - `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune. """ rname = str(root) # Initialize 'visited' dict, if required if visited is None: visited = {} if showtags: if showtags == 2: legend = (' E = exists\n' + ' R = exists in repository only\n' + ' b = implicit builder\n' + ' B = explicit builder\n' + ' S = side effect\n' + ' P = precious\n' + ' A = always build\n' + ' C = current\n' + ' N = no clean\n' + ' H = no cache\n' + '\n') sys.stdout.write(legend) tags = ['['] tags.append(' E'[IDX(root.exists())]) tags.append(' R'[IDX(root.rexists() and not root.exists())]) tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] + [0,2][IDX(root.has_builder())]]) tags.append(' S'[IDX(root.side_effect)]) tags.append(' P'[IDX(root.precious)]) tags.append(' A'[IDX(root.always_build)]) tags.append(' C'[IDX(root.is_up_to_date())]) tags.append(' N'[IDX(root.noclean)]) tags.append(' H'[IDX(root.nocache)]) tags.append(']') else: tags = [] def MMM(m): return [" ","| "][m] margins = list(map(MMM, margin[:-1])) children = child_func(root) if prune and rname in visited and children: sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n') return sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n') visited[rname] = 1 if children: margin.append(1) idx = IDX(showtags) for C in children[:-1]: print_tree(C, child_func, prune, idx, margin, visited) margin[-1] = 0 print_tree(children[-1], child_func, prune, idx, margin, visited) margin.pop()
[ "def", "print_tree", "(", "root", ",", "child_func", ",", "prune", "=", "0", ",", "showtags", "=", "0", ",", "margin", "=", "[", "0", "]", ",", "visited", "=", "None", ")", ":", "rname", "=", "str", "(", "root", ")", "# Initialize 'visited' dict, if required", "if", "visited", "is", "None", ":", "visited", "=", "{", "}", "if", "showtags", ":", "if", "showtags", "==", "2", ":", "legend", "=", "(", "' E = exists\\n'", "+", "' R = exists in repository only\\n'", "+", "' b = implicit builder\\n'", "+", "' B = explicit builder\\n'", "+", "' S = side effect\\n'", "+", "' P = precious\\n'", "+", "' A = always build\\n'", "+", "' C = current\\n'", "+", "' N = no clean\\n'", "+", "' H = no cache\\n'", "+", "'\\n'", ")", "sys", ".", "stdout", ".", "write", "(", "legend", ")", "tags", "=", "[", "'['", "]", "tags", ".", "append", "(", "' E'", "[", "IDX", "(", "root", ".", "exists", "(", ")", ")", "]", ")", "tags", ".", "append", "(", "' R'", "[", "IDX", "(", "root", ".", "rexists", "(", ")", "and", "not", "root", ".", "exists", "(", ")", ")", "]", ")", "tags", ".", "append", "(", "' BbB'", "[", "[", "0", ",", "1", "]", "[", "IDX", "(", "root", ".", "has_explicit_builder", "(", ")", ")", "]", "+", "[", "0", ",", "2", "]", "[", "IDX", "(", "root", ".", "has_builder", "(", ")", ")", "]", "]", ")", "tags", ".", "append", "(", "' S'", "[", "IDX", "(", "root", ".", "side_effect", ")", "]", ")", "tags", ".", "append", "(", "' P'", "[", "IDX", "(", "root", ".", "precious", ")", "]", ")", "tags", ".", "append", "(", "' A'", "[", "IDX", "(", "root", ".", "always_build", ")", "]", ")", "tags", ".", "append", "(", "' C'", "[", "IDX", "(", "root", ".", "is_up_to_date", "(", ")", ")", "]", ")", "tags", ".", "append", "(", "' N'", "[", "IDX", "(", "root", ".", "noclean", ")", "]", ")", "tags", ".", "append", "(", "' H'", "[", "IDX", "(", "root", ".", "nocache", ")", "]", ")", "tags", ".", "append", "(", "']'", ")", "else", ":", "tags", "=", "[", "]", "def", "MMM", "(", "m", ")", ":", "return", "[", "\" \"", ",", "\"| \"", "]", "[", "m", "]", "margins", "=", "list", "(", "map", "(", "MMM", ",", "margin", "[", ":", "-", "1", "]", ")", ")", "children", "=", "child_func", "(", "root", ")", "if", "prune", "and", "rname", "in", "visited", "and", "children", ":", "sys", ".", "stdout", ".", "write", "(", "''", ".", "join", "(", "tags", "+", "margins", "+", "[", "'+-['", ",", "rname", ",", "']'", "]", ")", "+", "'\\n'", ")", "return", "sys", ".", "stdout", ".", "write", "(", "''", ".", "join", "(", "tags", "+", "margins", "+", "[", "'+-'", ",", "rname", "]", ")", "+", "'\\n'", ")", "visited", "[", "rname", "]", "=", "1", "if", "children", ":", "margin", ".", "append", "(", "1", ")", "idx", "=", "IDX", "(", "showtags", ")", "for", "C", "in", "children", "[", ":", "-", "1", "]", ":", "print_tree", "(", "C", ",", "child_func", ",", "prune", ",", "idx", ",", "margin", ",", "visited", ")", "margin", "[", "-", "1", "]", "=", "0", "print_tree", "(", "children", "[", "-", "1", "]", ",", "child_func", ",", "prune", ",", "idx", ",", "margin", ",", "visited", ")", "margin", ".", "pop", "(", ")" ]
Print a tree of nodes. This is like render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be printed. :Parameters: - `root` - the root node of the tree - `child_func` - the function called to get the children of a node - `prune` - don't visit the same node twice - `showtags` - print status information to the left of each node line - `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe. - `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
[ "Print", "a", "tree", "of", "nodes", ".", "This", "is", "like", "render_tree", "except", "it", "prints", "lines", "directly", "instead", "of", "creating", "a", "string", "representation", "in", "memory", "so", "that", "huge", "trees", "can", "be", "printed", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L279-L354
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
flatten
def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would. """ if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes): return [obj] result = [] for item in obj: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result
python
def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would. """ if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes): return [obj] result = [] for item in obj: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result
[ "def", "flatten", "(", "obj", ",", "isinstance", "=", "isinstance", ",", "StringTypes", "=", "StringTypes", ",", "SequenceTypes", "=", "SequenceTypes", ",", "do_flatten", "=", "do_flatten", ")", ":", "if", "isinstance", "(", "obj", ",", "StringTypes", ")", "or", "not", "isinstance", "(", "obj", ",", "SequenceTypes", ")", ":", "return", "[", "obj", "]", "result", "=", "[", "]", "for", "item", "in", "obj", ":", "if", "isinstance", "(", "item", ",", "StringTypes", ")", "or", "not", "isinstance", "(", "item", ",", "SequenceTypes", ")", ":", "result", ".", "append", "(", "item", ")", "else", ":", "do_flatten", "(", "item", ",", "result", ")", "return", "result" ]
Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would.
[ "Flatten", "a", "sequence", "to", "a", "non", "-", "nested", "list", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L423-L439
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
unique
def unique(s): """Return a list of the elements in s, but without duplicates. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], unique("abcabc") some permutation of ["a", "b", "c"], and unique(([1, 2], [2, 3], [1, 2])) some permutation of [[2, 3], [1, 2]]. For best speed, all sequence elements should be hashable. Then unique() will usually work in linear time. If not possible, the sequence elements should enjoy a total ordering, and if list(s).sort() doesn't raise TypeError it's assumed that they do enjoy a total ordering. Then unique() will usually work in O(N*log2(N)) time. If that's not possible either, the sequence elements must support equality-testing. Then unique() will usually work in quadratic time. """ n = len(s) if n == 0: return [] # Try using a dict first, as that's the fastest and will usually # work. If it doesn't work, it will usually fail quickly, so it # usually doesn't cost much to *try* it. It requires that all the # sequence elements be hashable, and support equality comparison. u = {} try: for x in s: u[x] = 1 except TypeError: pass # move on to the next method else: return list(u.keys()) del u # We can't hash all the elements. Second fastest is to sort, # which brings the equal elements together; then duplicates are # easy to weed out in a single pass. # NOTE: Python's list.sort() was designed to be efficient in the # presence of many duplicate elements. This isn't true of all # sort functions in all languages or libraries, so this approach # is more effective in Python than it may be elsewhere. try: t = sorted(s) except TypeError: pass # move on to the next method else: assert n > 0 last = t[0] lasti = i = 1 while i < n: if t[i] != last: t[lasti] = last = t[i] lasti = lasti + 1 i = i + 1 return t[:lasti] del t # Brute force is all that's left. u = [] for x in s: if x not in u: u.append(x) return u
python
def unique(s): """Return a list of the elements in s, but without duplicates. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], unique("abcabc") some permutation of ["a", "b", "c"], and unique(([1, 2], [2, 3], [1, 2])) some permutation of [[2, 3], [1, 2]]. For best speed, all sequence elements should be hashable. Then unique() will usually work in linear time. If not possible, the sequence elements should enjoy a total ordering, and if list(s).sort() doesn't raise TypeError it's assumed that they do enjoy a total ordering. Then unique() will usually work in O(N*log2(N)) time. If that's not possible either, the sequence elements must support equality-testing. Then unique() will usually work in quadratic time. """ n = len(s) if n == 0: return [] # Try using a dict first, as that's the fastest and will usually # work. If it doesn't work, it will usually fail quickly, so it # usually doesn't cost much to *try* it. It requires that all the # sequence elements be hashable, and support equality comparison. u = {} try: for x in s: u[x] = 1 except TypeError: pass # move on to the next method else: return list(u.keys()) del u # We can't hash all the elements. Second fastest is to sort, # which brings the equal elements together; then duplicates are # easy to weed out in a single pass. # NOTE: Python's list.sort() was designed to be efficient in the # presence of many duplicate elements. This isn't true of all # sort functions in all languages or libraries, so this approach # is more effective in Python than it may be elsewhere. try: t = sorted(s) except TypeError: pass # move on to the next method else: assert n > 0 last = t[0] lasti = i = 1 while i < n: if t[i] != last: t[lasti] = last = t[i] lasti = lasti + 1 i = i + 1 return t[:lasti] del t # Brute force is all that's left. u = [] for x in s: if x not in u: u.append(x) return u
[ "def", "unique", "(", "s", ")", ":", "n", "=", "len", "(", "s", ")", "if", "n", "==", "0", ":", "return", "[", "]", "# Try using a dict first, as that's the fastest and will usually", "# work. If it doesn't work, it will usually fail quickly, so it", "# usually doesn't cost much to *try* it. It requires that all the", "# sequence elements be hashable, and support equality comparison.", "u", "=", "{", "}", "try", ":", "for", "x", "in", "s", ":", "u", "[", "x", "]", "=", "1", "except", "TypeError", ":", "pass", "# move on to the next method", "else", ":", "return", "list", "(", "u", ".", "keys", "(", ")", ")", "del", "u", "# We can't hash all the elements. Second fastest is to sort,", "# which brings the equal elements together; then duplicates are", "# easy to weed out in a single pass.", "# NOTE: Python's list.sort() was designed to be efficient in the", "# presence of many duplicate elements. This isn't true of all", "# sort functions in all languages or libraries, so this approach", "# is more effective in Python than it may be elsewhere.", "try", ":", "t", "=", "sorted", "(", "s", ")", "except", "TypeError", ":", "pass", "# move on to the next method", "else", ":", "assert", "n", ">", "0", "last", "=", "t", "[", "0", "]", "lasti", "=", "i", "=", "1", "while", "i", "<", "n", ":", "if", "t", "[", "i", "]", "!=", "last", ":", "t", "[", "lasti", "]", "=", "last", "=", "t", "[", "i", "]", "lasti", "=", "lasti", "+", "1", "i", "=", "i", "+", "1", "return", "t", "[", ":", "lasti", "]", "del", "t", "# Brute force is all that's left.", "u", "=", "[", "]", "for", "x", "in", "s", ":", "if", "x", "not", "in", "u", ":", "u", ".", "append", "(", "x", ")", "return", "u" ]
Return a list of the elements in s, but without duplicates. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], unique("abcabc") some permutation of ["a", "b", "c"], and unique(([1, 2], [2, 3], [1, 2])) some permutation of [[2, 3], [1, 2]]. For best speed, all sequence elements should be hashable. Then unique() will usually work in linear time. If not possible, the sequence elements should enjoy a total ordering, and if list(s).sort() doesn't raise TypeError it's assumed that they do enjoy a total ordering. Then unique() will usually work in O(N*log2(N)) time. If that's not possible either, the sequence elements must support equality-testing. Then unique() will usually work in quadratic time.
[ "Return", "a", "list", "of", "the", "elements", "in", "s", "but", "without", "duplicates", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1155-L1222
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
make_path_relative
def make_path_relative(path): """ makes an absolute path name to a relative pathname. """ if os.path.isabs(path): drive_s,path = os.path.splitdrive(path) import re if not drive_s: path=re.compile("/*(.*)").findall(path)[0] else: path=path[1:] assert( not os.path.isabs( path ) ), path return path
python
def make_path_relative(path): """ makes an absolute path name to a relative pathname. """ if os.path.isabs(path): drive_s,path = os.path.splitdrive(path) import re if not drive_s: path=re.compile("/*(.*)").findall(path)[0] else: path=path[1:] assert( not os.path.isabs( path ) ), path return path
[ "def", "make_path_relative", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "drive_s", ",", "path", "=", "os", ".", "path", ".", "splitdrive", "(", "path", ")", "import", "re", "if", "not", "drive_s", ":", "path", "=", "re", ".", "compile", "(", "\"/*(.*)\"", ")", ".", "findall", "(", "path", ")", "[", "0", "]", "else", ":", "path", "=", "path", "[", "1", ":", "]", "assert", "(", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ")", ",", "path", "return", "path" ]
makes an absolute path name to a relative pathname.
[ "makes", "an", "absolute", "path", "name", "to", "a", "relative", "pathname", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1411-L1424
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py
RenameFunction
def RenameFunction(function, name): """ Returns a function identical to the specified function, but with the specified name. """ return FunctionType(function.__code__, function.__globals__, name, function.__defaults__)
python
def RenameFunction(function, name): """ Returns a function identical to the specified function, but with the specified name. """ return FunctionType(function.__code__, function.__globals__, name, function.__defaults__)
[ "def", "RenameFunction", "(", "function", ",", "name", ")", ":", "return", "FunctionType", "(", "function", ".", "__code__", ",", "function", ".", "__globals__", ",", "name", ",", "function", ".", "__defaults__", ")" ]
Returns a function identical to the specified function, but with the specified name.
[ "Returns", "a", "function", "identical", "to", "the", "specified", "function", "but", "with", "the", "specified", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1488-L1496
train
iotile/coretools
iotilecore/iotile/core/hw/proxy/proxy.py
_create_old_return_value
def _create_old_return_value(payload, num_ints, buff): """Parse the response of an RPC call into a dictionary with integer and buffer results""" parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error', 'is_error': False, 'return_value': 0} if buff: parsed['buffer'] = bytearray(payload[-1]) return parsed
python
def _create_old_return_value(payload, num_ints, buff): """Parse the response of an RPC call into a dictionary with integer and buffer results""" parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error', 'is_error': False, 'return_value': 0} if buff: parsed['buffer'] = bytearray(payload[-1]) return parsed
[ "def", "_create_old_return_value", "(", "payload", ",", "num_ints", ",", "buff", ")", ":", "parsed", "=", "{", "'ints'", ":", "payload", "[", ":", "num_ints", "]", ",", "'buffer'", ":", "None", ",", "'error'", ":", "'No Error'", ",", "'is_error'", ":", "False", ",", "'return_value'", ":", "0", "}", "if", "buff", ":", "parsed", "[", "'buffer'", "]", "=", "bytearray", "(", "payload", "[", "-", "1", "]", ")", "return", "parsed" ]
Parse the response of an RPC call into a dictionary with integer and buffer results
[ "Parse", "the", "response", "of", "an", "RPC", "call", "into", "a", "dictionary", "with", "integer", "and", "buffer", "results" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L382-L391
train
iotile/coretools
iotilecore/iotile/core/hw/proxy/proxy.py
TileBusProxyObject.hardware_version
def hardware_version(self): """Return the embedded hardware version string for this tile. The hardware version is an up to 10 byte user readable string that is meant to encode any necessary information about the specific hardware that this tile is running on. For example, if you have multiple assembly variants of a given tile, you could encode that information here. Returns: str: The hardware version read from the tile. """ res = self.rpc(0x00, 0x02, result_type=(0, True)) # Result is a string but with zero appended to the end to make it a fixed 10 byte size binary_version = res['buffer'] ver = "" for x in binary_version: if x != 0: ver += chr(x) return ver
python
def hardware_version(self): """Return the embedded hardware version string for this tile. The hardware version is an up to 10 byte user readable string that is meant to encode any necessary information about the specific hardware that this tile is running on. For example, if you have multiple assembly variants of a given tile, you could encode that information here. Returns: str: The hardware version read from the tile. """ res = self.rpc(0x00, 0x02, result_type=(0, True)) # Result is a string but with zero appended to the end to make it a fixed 10 byte size binary_version = res['buffer'] ver = "" for x in binary_version: if x != 0: ver += chr(x) return ver
[ "def", "hardware_version", "(", "self", ")", ":", "res", "=", "self", ".", "rpc", "(", "0x00", ",", "0x02", ",", "result_type", "=", "(", "0", ",", "True", ")", ")", "# Result is a string but with zero appended to the end to make it a fixed 10 byte size", "binary_version", "=", "res", "[", "'buffer'", "]", "ver", "=", "\"\"", "for", "x", "in", "binary_version", ":", "if", "x", "!=", "0", ":", "ver", "+=", "chr", "(", "x", ")", "return", "ver" ]
Return the embedded hardware version string for this tile. The hardware version is an up to 10 byte user readable string that is meant to encode any necessary information about the specific hardware that this tile is running on. For example, if you have multiple assembly variants of a given tile, you could encode that information here. Returns: str: The hardware version read from the tile.
[ "Return", "the", "embedded", "hardware", "version", "string", "for", "this", "tile", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L102-L125
train
iotile/coretools
iotilecore/iotile/core/hw/proxy/proxy.py
TileBusProxyObject.check_hardware
def check_hardware(self, expected): """Make sure the hardware version is what we expect. This convenience function is meant for ensuring that we are talking to a tile that has the correct hardware version. Args: expected (str): The expected hardware string that is compared against what is reported by the hardware_version RPC. Returns: bool: true if the hardware is the expected version, false otherwise """ if len(expected) < 10: expected += '\0'*(10 - len(expected)) err, = self.rpc(0x00, 0x03, expected, result_format="L") if err == 0: return True return False
python
def check_hardware(self, expected): """Make sure the hardware version is what we expect. This convenience function is meant for ensuring that we are talking to a tile that has the correct hardware version. Args: expected (str): The expected hardware string that is compared against what is reported by the hardware_version RPC. Returns: bool: true if the hardware is the expected version, false otherwise """ if len(expected) < 10: expected += '\0'*(10 - len(expected)) err, = self.rpc(0x00, 0x03, expected, result_format="L") if err == 0: return True return False
[ "def", "check_hardware", "(", "self", ",", "expected", ")", ":", "if", "len", "(", "expected", ")", "<", "10", ":", "expected", "+=", "'\\0'", "*", "(", "10", "-", "len", "(", "expected", ")", ")", "err", ",", "=", "self", ".", "rpc", "(", "0x00", ",", "0x03", ",", "expected", ",", "result_format", "=", "\"L\"", ")", "if", "err", "==", "0", ":", "return", "True", "return", "False" ]
Make sure the hardware version is what we expect. This convenience function is meant for ensuring that we are talking to a tile that has the correct hardware version. Args: expected (str): The expected hardware string that is compared against what is reported by the hardware_version RPC. Returns: bool: true if the hardware is the expected version, false otherwise
[ "Make", "sure", "the", "hardware", "version", "is", "what", "we", "expect", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L129-L150
train
iotile/coretools
iotilecore/iotile/core/hw/proxy/proxy.py
TileBusProxyObject.status
def status(self): """Query the status of an IOTile including its name and version""" hw_type, name, major, minor, patch, status = self.rpc(0x00, 0x04, result_format="H6sBBBB") status = { 'hw_type': hw_type, 'name': name.decode('utf-8'), 'version': (major, minor, patch), 'status': status } return status
python
def status(self): """Query the status of an IOTile including its name and version""" hw_type, name, major, minor, patch, status = self.rpc(0x00, 0x04, result_format="H6sBBBB") status = { 'hw_type': hw_type, 'name': name.decode('utf-8'), 'version': (major, minor, patch), 'status': status } return status
[ "def", "status", "(", "self", ")", ":", "hw_type", ",", "name", ",", "major", ",", "minor", ",", "patch", ",", "status", "=", "self", ".", "rpc", "(", "0x00", ",", "0x04", ",", "result_format", "=", "\"H6sBBBB\"", ")", "status", "=", "{", "'hw_type'", ":", "hw_type", ",", "'name'", ":", "name", ".", "decode", "(", "'utf-8'", ")", ",", "'version'", ":", "(", "major", ",", "minor", ",", "patch", ")", ",", "'status'", ":", "status", "}", "return", "status" ]
Query the status of an IOTile including its name and version
[ "Query", "the", "status", "of", "an", "IOTile", "including", "its", "name", "and", "version" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L153-L165
train
iotile/coretools
iotilecore/iotile/core/hw/proxy/proxy.py
TileBusProxyObject.tile_status
def tile_status(self): """Get the current status of this tile""" stat = self.status() flags = stat['status'] # FIXME: This needs to stay in sync with lib_common: cdb_status.h status = {} status['debug_mode'] = bool(flags & (1 << 3)) status['configured'] = bool(flags & (1 << 1)) status['app_running'] = bool(flags & (1 << 0)) status['trapped'] = bool(flags & (1 << 2)) return status
python
def tile_status(self): """Get the current status of this tile""" stat = self.status() flags = stat['status'] # FIXME: This needs to stay in sync with lib_common: cdb_status.h status = {} status['debug_mode'] = bool(flags & (1 << 3)) status['configured'] = bool(flags & (1 << 1)) status['app_running'] = bool(flags & (1 << 0)) status['trapped'] = bool(flags & (1 << 2)) return status
[ "def", "tile_status", "(", "self", ")", ":", "stat", "=", "self", ".", "status", "(", ")", "flags", "=", "stat", "[", "'status'", "]", "# FIXME: This needs to stay in sync with lib_common: cdb_status.h", "status", "=", "{", "}", "status", "[", "'debug_mode'", "]", "=", "bool", "(", "flags", "&", "(", "1", "<<", "3", ")", ")", "status", "[", "'configured'", "]", "=", "bool", "(", "flags", "&", "(", "1", "<<", "1", ")", ")", "status", "[", "'app_running'", "]", "=", "bool", "(", "flags", "&", "(", "1", "<<", "0", ")", ")", "status", "[", "'trapped'", "]", "=", "bool", "(", "flags", "&", "(", "1", "<<", "2", ")", ")", "return", "status" ]
Get the current status of this tile
[ "Get", "the", "current", "status", "of", "this", "tile" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/proxy.py#L190-L203
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.client_event_handler
async def client_event_handler(self, client_id, event_tuple, user_data): """Method called to actually send an event to a client. Users of this class should override this method to actually forward device events to their clients. It is called with the client_id passed to (or returned from) :meth:`setup_client` as well as the user_data object that was included there. The event tuple is a 3-tuple of: - connection string - event name - event object If you override this to be acoroutine, it will be awaited. The default implementation just logs the event. Args: client_id (str): The client_id that this event should be forwarded to. event_tuple (tuple): The connection_string, event_name and event_object that should be forwarded. user_data (object): Any user data that was passed to setup_client. """ conn_string, event_name, _event = event_tuple self._logger.debug("Ignoring event %s from device %s forwarded for client %s", event_name, conn_string, client_id) return None
python
async def client_event_handler(self, client_id, event_tuple, user_data): """Method called to actually send an event to a client. Users of this class should override this method to actually forward device events to their clients. It is called with the client_id passed to (or returned from) :meth:`setup_client` as well as the user_data object that was included there. The event tuple is a 3-tuple of: - connection string - event name - event object If you override this to be acoroutine, it will be awaited. The default implementation just logs the event. Args: client_id (str): The client_id that this event should be forwarded to. event_tuple (tuple): The connection_string, event_name and event_object that should be forwarded. user_data (object): Any user data that was passed to setup_client. """ conn_string, event_name, _event = event_tuple self._logger.debug("Ignoring event %s from device %s forwarded for client %s", event_name, conn_string, client_id) return None
[ "async", "def", "client_event_handler", "(", "self", ",", "client_id", ",", "event_tuple", ",", "user_data", ")", ":", "conn_string", ",", "event_name", ",", "_event", "=", "event_tuple", "self", ".", "_logger", ".", "debug", "(", "\"Ignoring event %s from device %s forwarded for client %s\"", ",", "event_name", ",", "conn_string", ",", "client_id", ")", "return", "None" ]
Method called to actually send an event to a client. Users of this class should override this method to actually forward device events to their clients. It is called with the client_id passed to (or returned from) :meth:`setup_client` as well as the user_data object that was included there. The event tuple is a 3-tuple of: - connection string - event name - event object If you override this to be acoroutine, it will be awaited. The default implementation just logs the event. Args: client_id (str): The client_id that this event should be forwarded to. event_tuple (tuple): The connection_string, event_name and event_object that should be forwarded. user_data (object): Any user data that was passed to setup_client.
[ "Method", "called", "to", "actually", "send", "an", "event", "to", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L91-L120
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.setup_client
def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False): """Setup a newly connected client. ``client_id`` must be unique among all connected clients. If it is passed as None, a random client_id will be generated as a string and returned. This method reserves internal resources for tracking what devices this client has connected to and installs a monitor into the adapter on behalf of the client. It should be called whenever a new client connects to the device server before any other activities by that client are allowed. By default, all clients start receiving ``device_seen`` events but if you want your client to also receive broadcast events, you can pass broadcast=True. Args: client_id (str): A unique identifier for this client that will be used to refer to it in all future interactions. If this is None, then a random string will be generated for the client_id. user_data (object): An arbitrary object that you would like to store with this client and will be passed to your event handler when events are forwarded to this client. scan (bool): Whether to install a monitor to listen for device_found events. broadcast (bool): Whether to install a monitor to list for broadcast events. Returns: str: The client_id. If a client id was passed in, it will be the same as what was passed in. If no client id was passed in then it will be a random unique string. """ if client_id is None: client_id = str(uuid.uuid4()) if client_id in self._clients: raise ArgumentError("Duplicate client_id: {}".format(client_id)) async def _client_callback(conn_string, _, event_name, event): event_tuple = (conn_string, event_name, event) await self._forward_client_event(client_id, event_tuple) client_monitor = self.adapter.register_monitor([], [], _client_callback) self._clients[client_id] = dict(user_data=user_data, connections={}, monitor=client_monitor) self._adjust_global_events(client_id, scan, broadcast) return client_id
python
def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False): """Setup a newly connected client. ``client_id`` must be unique among all connected clients. If it is passed as None, a random client_id will be generated as a string and returned. This method reserves internal resources for tracking what devices this client has connected to and installs a monitor into the adapter on behalf of the client. It should be called whenever a new client connects to the device server before any other activities by that client are allowed. By default, all clients start receiving ``device_seen`` events but if you want your client to also receive broadcast events, you can pass broadcast=True. Args: client_id (str): A unique identifier for this client that will be used to refer to it in all future interactions. If this is None, then a random string will be generated for the client_id. user_data (object): An arbitrary object that you would like to store with this client and will be passed to your event handler when events are forwarded to this client. scan (bool): Whether to install a monitor to listen for device_found events. broadcast (bool): Whether to install a monitor to list for broadcast events. Returns: str: The client_id. If a client id was passed in, it will be the same as what was passed in. If no client id was passed in then it will be a random unique string. """ if client_id is None: client_id = str(uuid.uuid4()) if client_id in self._clients: raise ArgumentError("Duplicate client_id: {}".format(client_id)) async def _client_callback(conn_string, _, event_name, event): event_tuple = (conn_string, event_name, event) await self._forward_client_event(client_id, event_tuple) client_monitor = self.adapter.register_monitor([], [], _client_callback) self._clients[client_id] = dict(user_data=user_data, connections={}, monitor=client_monitor) self._adjust_global_events(client_id, scan, broadcast) return client_id
[ "def", "setup_client", "(", "self", ",", "client_id", "=", "None", ",", "user_data", "=", "None", ",", "scan", "=", "True", ",", "broadcast", "=", "False", ")", ":", "if", "client_id", "is", "None", ":", "client_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "client_id", "in", "self", ".", "_clients", ":", "raise", "ArgumentError", "(", "\"Duplicate client_id: {}\"", ".", "format", "(", "client_id", ")", ")", "async", "def", "_client_callback", "(", "conn_string", ",", "_", ",", "event_name", ",", "event", ")", ":", "event_tuple", "=", "(", "conn_string", ",", "event_name", ",", "event", ")", "await", "self", ".", "_forward_client_event", "(", "client_id", ",", "event_tuple", ")", "client_monitor", "=", "self", ".", "adapter", ".", "register_monitor", "(", "[", "]", ",", "[", "]", ",", "_client_callback", ")", "self", ".", "_clients", "[", "client_id", "]", "=", "dict", "(", "user_data", "=", "user_data", ",", "connections", "=", "{", "}", ",", "monitor", "=", "client_monitor", ")", "self", ".", "_adjust_global_events", "(", "client_id", ",", "scan", ",", "broadcast", ")", "return", "client_id" ]
Setup a newly connected client. ``client_id`` must be unique among all connected clients. If it is passed as None, a random client_id will be generated as a string and returned. This method reserves internal resources for tracking what devices this client has connected to and installs a monitor into the adapter on behalf of the client. It should be called whenever a new client connects to the device server before any other activities by that client are allowed. By default, all clients start receiving ``device_seen`` events but if you want your client to also receive broadcast events, you can pass broadcast=True. Args: client_id (str): A unique identifier for this client that will be used to refer to it in all future interactions. If this is None, then a random string will be generated for the client_id. user_data (object): An arbitrary object that you would like to store with this client and will be passed to your event handler when events are forwarded to this client. scan (bool): Whether to install a monitor to listen for device_found events. broadcast (bool): Whether to install a monitor to list for broadcast events. Returns: str: The client_id. If a client id was passed in, it will be the same as what was passed in. If no client id was passed in then it will be a random unique string.
[ "Setup", "a", "newly", "connected", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L122-L174
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.stop
async def stop(self): """Stop the server and teardown any remaining clients. If your subclass overrides this method, make sure to call super().stop() to ensure that all devices with open connections from thie server are properly closed. See :meth:`AbstractDeviceServer.stop`. """ clients = list(self._clients) for client in clients: self._logger.info("Tearing down client %s at server stop()", client) await self.teardown_client(client)
python
async def stop(self): """Stop the server and teardown any remaining clients. If your subclass overrides this method, make sure to call super().stop() to ensure that all devices with open connections from thie server are properly closed. See :meth:`AbstractDeviceServer.stop`. """ clients = list(self._clients) for client in clients: self._logger.info("Tearing down client %s at server stop()", client) await self.teardown_client(client)
[ "async", "def", "stop", "(", "self", ")", ":", "clients", "=", "list", "(", "self", ".", "_clients", ")", "for", "client", "in", "clients", ":", "self", ".", "_logger", ".", "info", "(", "\"Tearing down client %s at server stop()\"", ",", "client", ")", "await", "self", ".", "teardown_client", "(", "client", ")" ]
Stop the server and teardown any remaining clients. If your subclass overrides this method, make sure to call super().stop() to ensure that all devices with open connections from thie server are properly closed. See :meth:`AbstractDeviceServer.stop`.
[ "Stop", "the", "server", "and", "teardown", "any", "remaining", "clients", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L182-L196
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.teardown_client
async def teardown_client(self, client_id): """Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are disconnected cleanly. Args: client_id (str): The client that we should tear down. Raises: ArgumentError: The client_id is unknown. """ client_info = self._client_info(client_id) self.adapter.remove_monitor(client_info['monitor']) conns = client_info['connections'] for conn_string, conn_id in conns.items(): try: self._logger.debug("Disconnecting client %s from conn %s at teardown", client_id, conn_string) await self.adapter.disconnect(conn_id) except: #pylint:disable=bare-except; This is a finalization method that should not raise unexpectedly self._logger.exception("Error disconnecting device during teardown_client: conn_string=%s", conn_string) del self._clients[client_id]
python
async def teardown_client(self, client_id): """Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are disconnected cleanly. Args: client_id (str): The client that we should tear down. Raises: ArgumentError: The client_id is unknown. """ client_info = self._client_info(client_id) self.adapter.remove_monitor(client_info['monitor']) conns = client_info['connections'] for conn_string, conn_id in conns.items(): try: self._logger.debug("Disconnecting client %s from conn %s at teardown", client_id, conn_string) await self.adapter.disconnect(conn_id) except: #pylint:disable=bare-except; This is a finalization method that should not raise unexpectedly self._logger.exception("Error disconnecting device during teardown_client: conn_string=%s", conn_string) del self._clients[client_id]
[ "async", "def", "teardown_client", "(", "self", ",", "client_id", ")", ":", "client_info", "=", "self", ".", "_client_info", "(", "client_id", ")", "self", ".", "adapter", ".", "remove_monitor", "(", "client_info", "[", "'monitor'", "]", ")", "conns", "=", "client_info", "[", "'connections'", "]", "for", "conn_string", ",", "conn_id", "in", "conns", ".", "items", "(", ")", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "\"Disconnecting client %s from conn %s at teardown\"", ",", "client_id", ",", "conn_string", ")", "await", "self", ".", "adapter", ".", "disconnect", "(", "conn_id", ")", "except", ":", "#pylint:disable=bare-except; This is a finalization method that should not raise unexpectedly", "self", ".", "_logger", ".", "exception", "(", "\"Error disconnecting device during teardown_client: conn_string=%s\"", ",", "conn_string", ")", "del", "self", ".", "_clients", "[", "client_id", "]" ]
Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are disconnected cleanly. Args: client_id (str): The client that we should tear down. Raises: ArgumentError: The client_id is unknown.
[ "Release", "all", "resources", "held", "by", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L198-L225
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.connect
async def connect(self, client_id, conn_string): """Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: DeviceServerError: There is an issue with your client_id. DeviceAdapterError: The adapter had an issue connecting. """ conn_id = self.adapter.unique_conn_id() self._client_info(client_id) await self.adapter.connect(conn_id, conn_string) self._hook_connect(conn_string, conn_id, client_id)
python
async def connect(self, client_id, conn_string): """Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: DeviceServerError: There is an issue with your client_id. DeviceAdapterError: The adapter had an issue connecting. """ conn_id = self.adapter.unique_conn_id() self._client_info(client_id) await self.adapter.connect(conn_id, conn_string) self._hook_connect(conn_string, conn_id, client_id)
[ "async", "def", "connect", "(", "self", ",", "client_id", ",", "conn_string", ")", ":", "conn_id", "=", "self", ".", "adapter", ".", "unique_conn_id", "(", ")", "self", ".", "_client_info", "(", "client_id", ")", "await", "self", ".", "adapter", ".", "connect", "(", "conn_id", ",", "conn_string", ")", "self", ".", "_hook_connect", "(", "conn_string", ",", "conn_id", ",", "client_id", ")" ]
Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: DeviceServerError: There is an issue with your client_id. DeviceAdapterError: The adapter had an issue connecting.
[ "Connect", "to", "a", "device", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L244-L263
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.disconnect
async def disconnect(self, client_id, conn_string): """Disconnect from a device on behalf of a client. See :meth:`AbstractDeviceAdapter.disconnect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue disconnecting. """ conn_id = self._client_connection(client_id, conn_string) try: await self.adapter.disconnect(conn_id) finally: self._hook_disconnect(conn_string, client_id)
python
async def disconnect(self, client_id, conn_string): """Disconnect from a device on behalf of a client. See :meth:`AbstractDeviceAdapter.disconnect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue disconnecting. """ conn_id = self._client_connection(client_id, conn_string) try: await self.adapter.disconnect(conn_id) finally: self._hook_disconnect(conn_string, client_id)
[ "async", "def", "disconnect", "(", "self", ",", "client_id", ",", "conn_string", ")", ":", "conn_id", "=", "self", ".", "_client_connection", "(", "client_id", ",", "conn_string", ")", "try", ":", "await", "self", ".", "adapter", ".", "disconnect", "(", "conn_id", ")", "finally", ":", "self", ".", "_hook_disconnect", "(", "conn_string", ",", "client_id", ")" ]
Disconnect from a device on behalf of a client. See :meth:`AbstractDeviceAdapter.disconnect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue disconnecting.
[ "Disconnect", "from", "a", "device", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L265-L286
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.open_interface
async def open_interface(self, client_id, conn_string, interface): """Open a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.open_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. interface (str): The name of the interface to open. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue opening the interface. """ conn_id = self._client_connection(client_id, conn_string) # Hook first so there is no race on getting the first event self._hook_open_interface(conn_string, interface, client_id) await self.adapter.open_interface(conn_id, interface)
python
async def open_interface(self, client_id, conn_string, interface): """Open a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.open_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. interface (str): The name of the interface to open. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue opening the interface. """ conn_id = self._client_connection(client_id, conn_string) # Hook first so there is no race on getting the first event self._hook_open_interface(conn_string, interface, client_id) await self.adapter.open_interface(conn_id, interface)
[ "async", "def", "open_interface", "(", "self", ",", "client_id", ",", "conn_string", ",", "interface", ")", ":", "conn_id", "=", "self", ".", "_client_connection", "(", "client_id", ",", "conn_string", ")", "# Hook first so there is no race on getting the first event", "self", ".", "_hook_open_interface", "(", "conn_string", ",", "interface", ",", "client_id", ")", "await", "self", ".", "adapter", ".", "open_interface", "(", "conn_id", ",", "interface", ")" ]
Open a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.open_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. interface (str): The name of the interface to open. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue opening the interface.
[ "Open", "a", "device", "interface", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L288-L309
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.close_interface
async def close_interface(self, client_id, conn_string, interface): """Close a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.close_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. interface (str): The name of the interface to close. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue closing the interface. """ conn_id = self._client_connection(client_id, conn_string) await self.adapter.close_interface(conn_id, interface) self._hook_close_interface(conn_string, interface, client_id)
python
async def close_interface(self, client_id, conn_string, interface): """Close a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.close_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. interface (str): The name of the interface to close. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue closing the interface. """ conn_id = self._client_connection(client_id, conn_string) await self.adapter.close_interface(conn_id, interface) self._hook_close_interface(conn_string, interface, client_id)
[ "async", "def", "close_interface", "(", "self", ",", "client_id", ",", "conn_string", ",", "interface", ")", ":", "conn_id", "=", "self", ".", "_client_connection", "(", "client_id", ",", "conn_string", ")", "await", "self", ".", "adapter", ".", "close_interface", "(", "conn_id", ",", "interface", ")", "self", ".", "_hook_close_interface", "(", "conn_string", ",", "interface", ",", "client_id", ")" ]
Close a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.close_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. interface (str): The name of the interface to close. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had an issue closing the interface.
[ "Close", "a", "device", "interface", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L311-L331
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.send_rpc
async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout): """Send an RPC on behalf of a client. See :meth:`AbstractDeviceAdapter.send_rpc`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. address (int): The RPC address. rpc_id (int): The ID number of the RPC payload (bytes): The RPC argument payload timeout (float): The RPC's expected timeout to hand to the underlying device adapter. Returns: bytes: The RPC response. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. TileNotFoundError: The destination tile address does not exist RPCNotFoundError: The rpc_id does not exist on the given tile RPCErrorCode: The RPC was invoked successfully and wishes to fail with a non-zero status code. RPCInvalidIDError: The rpc_id is too large to fit in 16-bits. TileBusSerror: The tile was busy and could not respond to the RPC. Exception: The rpc raised an exception during processing. DeviceAdapterError: If there is a hardware or communication issue invoking the RPC. """ conn_id = self._client_connection(client_id, conn_string) return await self.adapter.send_rpc(conn_id, address, rpc_id, payload, timeout)
python
async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout): """Send an RPC on behalf of a client. See :meth:`AbstractDeviceAdapter.send_rpc`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. address (int): The RPC address. rpc_id (int): The ID number of the RPC payload (bytes): The RPC argument payload timeout (float): The RPC's expected timeout to hand to the underlying device adapter. Returns: bytes: The RPC response. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. TileNotFoundError: The destination tile address does not exist RPCNotFoundError: The rpc_id does not exist on the given tile RPCErrorCode: The RPC was invoked successfully and wishes to fail with a non-zero status code. RPCInvalidIDError: The rpc_id is too large to fit in 16-bits. TileBusSerror: The tile was busy and could not respond to the RPC. Exception: The rpc raised an exception during processing. DeviceAdapterError: If there is a hardware or communication issue invoking the RPC. """ conn_id = self._client_connection(client_id, conn_string) return await self.adapter.send_rpc(conn_id, address, rpc_id, payload, timeout)
[ "async", "def", "send_rpc", "(", "self", ",", "client_id", ",", "conn_string", ",", "address", ",", "rpc_id", ",", "payload", ",", "timeout", ")", ":", "conn_id", "=", "self", ".", "_client_connection", "(", "client_id", ",", "conn_string", ")", "return", "await", "self", ".", "adapter", ".", "send_rpc", "(", "conn_id", ",", "address", ",", "rpc_id", ",", "payload", ",", "timeout", ")" ]
Send an RPC on behalf of a client. See :meth:`AbstractDeviceAdapter.send_rpc`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. address (int): The RPC address. rpc_id (int): The ID number of the RPC payload (bytes): The RPC argument payload timeout (float): The RPC's expected timeout to hand to the underlying device adapter. Returns: bytes: The RPC response. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. TileNotFoundError: The destination tile address does not exist RPCNotFoundError: The rpc_id does not exist on the given tile RPCErrorCode: The RPC was invoked successfully and wishes to fail with a non-zero status code. RPCInvalidIDError: The rpc_id is too large to fit in 16-bits. TileBusSerror: The tile was busy and could not respond to the RPC. Exception: The rpc raised an exception during processing. DeviceAdapterError: If there is a hardware or communication issue invoking the RPC.
[ "Send", "an", "RPC", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L334-L367
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.send_script
async def send_script(self, client_id, conn_string, script): """Send a script to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. script (bytes): The script that we wish to send. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had a protocol issue sending the script. """ conn_id = self._client_connection(client_id, conn_string) await self.adapter.send_script(conn_id, script)
python
async def send_script(self, client_id, conn_string, script): """Send a script to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. script (bytes): The script that we wish to send. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had a protocol issue sending the script. """ conn_id = self._client_connection(client_id, conn_string) await self.adapter.send_script(conn_id, script)
[ "async", "def", "send_script", "(", "self", ",", "client_id", ",", "conn_string", ",", "script", ")", ":", "conn_id", "=", "self", ".", "_client_connection", "(", "client_id", ",", "conn_string", ")", "await", "self", ".", "adapter", ".", "send_script", "(", "conn_id", ",", "script", ")" ]
Send a script to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. script (bytes): The script that we wish to send. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had a protocol issue sending the script.
[ "Send", "a", "script", "to", "a", "device", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L369-L387
train
iotile/coretools
iotilecore/iotile/core/hw/transport/server/standard.py
StandardDeviceServer.debug
async def debug(self, client_id, conn_string, command, args): """Send a debug command to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. command (str): The name of the debug command to run. args (dict): Any command arguments. Returns: object: The response to the debug command. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had a protocol issue sending the debug command. """ conn_id = self._client_info(client_id, 'connections')[conn_string] return await self.adapter.debug(conn_id, command, args)
python
async def debug(self, client_id, conn_string, command, args): """Send a debug command to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. command (str): The name of the debug command to run. args (dict): Any command arguments. Returns: object: The response to the debug command. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had a protocol issue sending the debug command. """ conn_id = self._client_info(client_id, 'connections')[conn_string] return await self.adapter.debug(conn_id, command, args)
[ "async", "def", "debug", "(", "self", ",", "client_id", ",", "conn_string", ",", "command", ",", "args", ")", ":", "conn_id", "=", "self", ".", "_client_info", "(", "client_id", ",", "'connections'", ")", "[", "conn_string", "]", "return", "await", "self", ".", "adapter", ".", "debug", "(", "conn_id", ",", "command", ",", "args", ")" ]
Send a debug command to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter. command (str): The name of the debug command to run. args (dict): Any command arguments. Returns: object: The response to the debug command. Raises: DeviceServerError: There is an issue with your client_id such as not being connected to the device. DeviceAdapterError: The adapter had a protocol issue sending the debug command.
[ "Send", "a", "debug", "command", "to", "a", "device", "on", "behalf", "of", "a", "client", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/server/standard.py#L389-L412
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py
TileInfo.registration_packet
def registration_packet(self): """Serialize this into a tuple suitable for returning from an RPC. Returns: tuple: The serialized values. """ return (self.hw_type, self.api_info[0], self.api_info[1], self.name, self.fw_info[0], self.fw_info[1], self.fw_info[2], self.exec_info[0], self.exec_info[0], self.exec_info[0], self.slot, self.unique_id)
python
def registration_packet(self): """Serialize this into a tuple suitable for returning from an RPC. Returns: tuple: The serialized values. """ return (self.hw_type, self.api_info[0], self.api_info[1], self.name, self.fw_info[0], self.fw_info[1], self.fw_info[2], self.exec_info[0], self.exec_info[0], self.exec_info[0], self.slot, self.unique_id)
[ "def", "registration_packet", "(", "self", ")", ":", "return", "(", "self", ".", "hw_type", ",", "self", ".", "api_info", "[", "0", "]", ",", "self", ".", "api_info", "[", "1", "]", ",", "self", ".", "name", ",", "self", ".", "fw_info", "[", "0", "]", ",", "self", ".", "fw_info", "[", "1", "]", ",", "self", ".", "fw_info", "[", "2", "]", ",", "self", ".", "exec_info", "[", "0", "]", ",", "self", ".", "exec_info", "[", "0", "]", ",", "self", ".", "exec_info", "[", "0", "]", ",", "self", ".", "slot", ",", "self", ".", "unique_id", ")" ]
Serialize this into a tuple suitable for returning from an RPC. Returns: tuple: The serialized values.
[ "Serialize", "this", "into", "a", "tuple", "suitable", "for", "returning", "from", "an", "RPC", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L33-L41
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py
TileManagerState.clear_to_reset
def clear_to_reset(self, config_vars): """Clear to the state immediately after a reset.""" super(TileManagerState, self).clear_to_reset(config_vars) self.registered_tiles = self.registered_tiles[:1] self.safe_mode = False self.debug_mode = False
python
def clear_to_reset(self, config_vars): """Clear to the state immediately after a reset.""" super(TileManagerState, self).clear_to_reset(config_vars) self.registered_tiles = self.registered_tiles[:1] self.safe_mode = False self.debug_mode = False
[ "def", "clear_to_reset", "(", "self", ",", "config_vars", ")", ":", "super", "(", "TileManagerState", ",", "self", ")", ".", "clear_to_reset", "(", "config_vars", ")", "self", ".", "registered_tiles", "=", "self", ".", "registered_tiles", "[", ":", "1", "]", "self", ".", "safe_mode", "=", "False", "self", ".", "debug_mode", "=", "False" ]
Clear to the state immediately after a reset.
[ "Clear", "to", "the", "state", "immediately", "after", "a", "reset", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L86-L92
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py
TileManagerState.insert_tile
def insert_tile(self, tile_info): """Add or replace an entry in the tile cache. Args: tile_info (TileInfo): The newly registered tile. """ for i, tile in enumerate(self.registered_tiles): if tile.slot == tile_info.slot: self.registered_tiles[i] = tile_info return self.registered_tiles.append(tile_info)
python
def insert_tile(self, tile_info): """Add or replace an entry in the tile cache. Args: tile_info (TileInfo): The newly registered tile. """ for i, tile in enumerate(self.registered_tiles): if tile.slot == tile_info.slot: self.registered_tiles[i] = tile_info return self.registered_tiles.append(tile_info)
[ "def", "insert_tile", "(", "self", ",", "tile_info", ")", ":", "for", "i", ",", "tile", "in", "enumerate", "(", "self", ".", "registered_tiles", ")", ":", "if", "tile", ".", "slot", "==", "tile_info", ".", "slot", ":", "self", ".", "registered_tiles", "[", "i", "]", "=", "tile_info", "return", "self", ".", "registered_tiles", ".", "append", "(", "tile_info", ")" ]
Add or replace an entry in the tile cache. Args: tile_info (TileInfo): The newly registered tile.
[ "Add", "or", "replace", "an", "entry", "in", "the", "tile", "cache", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L108-L120
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py
TileManagerMixin.register_tile
def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id): """Register a tile with this controller. This function adds the tile immediately to its internal cache of registered tiles and queues RPCs to send all config variables and start tile rpcs back to the tile. """ api_info = (api_major, api_minor) fw_info = (fw_major, fw_minor, fw_patch) exec_info = (exec_major, exec_minor, exec_patch) address = 10 + slot info = TileInfo(hw_type, name, api_info, fw_info, exec_info, slot, unique_id, state=TileState.JUST_REGISTERED, address=address) self.tile_manager.insert_tile(info) debug = int(self.tile_manager.debug_mode) if self.tile_manager.safe_mode: run_level = RunLevel.SAFE_MODE info.state = TileState.SAFE_MODE config_rpcs = [] else: run_level = RunLevel.START_ON_COMMAND info.state = TileState.BEING_CONFIGURED config_rpcs = self.config_database.stream_matching(address, name) self.tile_manager.queue.put_nowait((info, config_rpcs)) return [address, run_level, debug]
python
def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id): """Register a tile with this controller. This function adds the tile immediately to its internal cache of registered tiles and queues RPCs to send all config variables and start tile rpcs back to the tile. """ api_info = (api_major, api_minor) fw_info = (fw_major, fw_minor, fw_patch) exec_info = (exec_major, exec_minor, exec_patch) address = 10 + slot info = TileInfo(hw_type, name, api_info, fw_info, exec_info, slot, unique_id, state=TileState.JUST_REGISTERED, address=address) self.tile_manager.insert_tile(info) debug = int(self.tile_manager.debug_mode) if self.tile_manager.safe_mode: run_level = RunLevel.SAFE_MODE info.state = TileState.SAFE_MODE config_rpcs = [] else: run_level = RunLevel.START_ON_COMMAND info.state = TileState.BEING_CONFIGURED config_rpcs = self.config_database.stream_matching(address, name) self.tile_manager.queue.put_nowait((info, config_rpcs)) return [address, run_level, debug]
[ "def", "register_tile", "(", "self", ",", "hw_type", ",", "api_major", ",", "api_minor", ",", "name", ",", "fw_major", ",", "fw_minor", ",", "fw_patch", ",", "exec_major", ",", "exec_minor", ",", "exec_patch", ",", "slot", ",", "unique_id", ")", ":", "api_info", "=", "(", "api_major", ",", "api_minor", ")", "fw_info", "=", "(", "fw_major", ",", "fw_minor", ",", "fw_patch", ")", "exec_info", "=", "(", "exec_major", ",", "exec_minor", ",", "exec_patch", ")", "address", "=", "10", "+", "slot", "info", "=", "TileInfo", "(", "hw_type", ",", "name", ",", "api_info", ",", "fw_info", ",", "exec_info", ",", "slot", ",", "unique_id", ",", "state", "=", "TileState", ".", "JUST_REGISTERED", ",", "address", "=", "address", ")", "self", ".", "tile_manager", ".", "insert_tile", "(", "info", ")", "debug", "=", "int", "(", "self", ".", "tile_manager", ".", "debug_mode", ")", "if", "self", ".", "tile_manager", ".", "safe_mode", ":", "run_level", "=", "RunLevel", ".", "SAFE_MODE", "info", ".", "state", "=", "TileState", ".", "SAFE_MODE", "config_rpcs", "=", "[", "]", "else", ":", "run_level", "=", "RunLevel", ".", "START_ON_COMMAND", "info", ".", "state", "=", "TileState", ".", "BEING_CONFIGURED", "config_rpcs", "=", "self", ".", "config_database", ".", "stream_matching", "(", "address", ",", "name", ")", "self", ".", "tile_manager", ".", "queue", ".", "put_nowait", "(", "(", "info", ",", "config_rpcs", ")", ")", "return", "[", "address", ",", "run_level", ",", "debug", "]" ]
Register a tile with this controller. This function adds the tile immediately to its internal cache of registered tiles and queues RPCs to send all config variables and start tile rpcs back to the tile.
[ "Register", "a", "tile", "with", "this", "controller", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L140-L169
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py
TileManagerMixin.describe_tile
def describe_tile(self, index): """Get the registration information for the tile at the given index.""" if index >= len(self.tile_manager.registered_tiles): tile = TileInfo.CreateInvalid() else: tile = self.tile_manager.registered_tiles[index] return tile.registration_packet()
python
def describe_tile(self, index): """Get the registration information for the tile at the given index.""" if index >= len(self.tile_manager.registered_tiles): tile = TileInfo.CreateInvalid() else: tile = self.tile_manager.registered_tiles[index] return tile.registration_packet()
[ "def", "describe_tile", "(", "self", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "tile_manager", ".", "registered_tiles", ")", ":", "tile", "=", "TileInfo", ".", "CreateInvalid", "(", ")", "else", ":", "tile", "=", "self", ".", "tile_manager", ".", "registered_tiles", "[", "index", "]", "return", "tile", ".", "registration_packet", "(", ")" ]
Get the registration information for the tile at the given index.
[ "Get", "the", "registration", "information", "for", "the", "tile", "at", "the", "given", "index", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L178-L186
train
iotile/coretools
iotilecore/iotile/core/hw/update/script.py
UpdateScript.ParseHeader
def ParseHeader(cls, script_data): """Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: script_data (bytearray): The script that we should parse. Raises: ArgumentError: If the script contains malformed data that cannot be parsed. Returns: ScriptHeader: The parsed script header information """ if len(script_data) < UpdateScript.SCRIPT_HEADER_LENGTH: raise ArgumentError("Script is too short to contain a script header", length=len(script_data), header_length=UpdateScript.SCRIPT_HEADER_LENGTH) embedded_hash, magic, total_length = struct.unpack_from("<16sLL", script_data) if magic != UpdateScript.SCRIPT_MAGIC: raise ArgumentError("Script has invalid magic value", expected=UpdateScript.SCRIPT_MAGIC, found=magic) if total_length != len(script_data): raise ArgumentError("Script length does not match embedded length", embedded_length=total_length, length=len(script_data)) hashed_data = script_data[16:] sha = hashlib.sha256() sha.update(hashed_data) hash_value = sha.digest()[:16] if not compare_digest(embedded_hash, hash_value): raise ArgumentError("Script has invalid embedded hash", embedded_hash=hexlify(embedded_hash), calculated_hash=hexlify(hash_value)) return ScriptHeader(UpdateScript.SCRIPT_HEADER_LENGTH, False, True, False)
python
def ParseHeader(cls, script_data): """Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: script_data (bytearray): The script that we should parse. Raises: ArgumentError: If the script contains malformed data that cannot be parsed. Returns: ScriptHeader: The parsed script header information """ if len(script_data) < UpdateScript.SCRIPT_HEADER_LENGTH: raise ArgumentError("Script is too short to contain a script header", length=len(script_data), header_length=UpdateScript.SCRIPT_HEADER_LENGTH) embedded_hash, magic, total_length = struct.unpack_from("<16sLL", script_data) if magic != UpdateScript.SCRIPT_MAGIC: raise ArgumentError("Script has invalid magic value", expected=UpdateScript.SCRIPT_MAGIC, found=magic) if total_length != len(script_data): raise ArgumentError("Script length does not match embedded length", embedded_length=total_length, length=len(script_data)) hashed_data = script_data[16:] sha = hashlib.sha256() sha.update(hashed_data) hash_value = sha.digest()[:16] if not compare_digest(embedded_hash, hash_value): raise ArgumentError("Script has invalid embedded hash", embedded_hash=hexlify(embedded_hash), calculated_hash=hexlify(hash_value)) return ScriptHeader(UpdateScript.SCRIPT_HEADER_LENGTH, False, True, False)
[ "def", "ParseHeader", "(", "cls", ",", "script_data", ")", ":", "if", "len", "(", "script_data", ")", "<", "UpdateScript", ".", "SCRIPT_HEADER_LENGTH", ":", "raise", "ArgumentError", "(", "\"Script is too short to contain a script header\"", ",", "length", "=", "len", "(", "script_data", ")", ",", "header_length", "=", "UpdateScript", ".", "SCRIPT_HEADER_LENGTH", ")", "embedded_hash", ",", "magic", ",", "total_length", "=", "struct", ".", "unpack_from", "(", "\"<16sLL\"", ",", "script_data", ")", "if", "magic", "!=", "UpdateScript", ".", "SCRIPT_MAGIC", ":", "raise", "ArgumentError", "(", "\"Script has invalid magic value\"", ",", "expected", "=", "UpdateScript", ".", "SCRIPT_MAGIC", ",", "found", "=", "magic", ")", "if", "total_length", "!=", "len", "(", "script_data", ")", ":", "raise", "ArgumentError", "(", "\"Script length does not match embedded length\"", ",", "embedded_length", "=", "total_length", ",", "length", "=", "len", "(", "script_data", ")", ")", "hashed_data", "=", "script_data", "[", "16", ":", "]", "sha", "=", "hashlib", ".", "sha256", "(", ")", "sha", ".", "update", "(", "hashed_data", ")", "hash_value", "=", "sha", ".", "digest", "(", ")", "[", ":", "16", "]", "if", "not", "compare_digest", "(", "embedded_hash", ",", "hash_value", ")", ":", "raise", "ArgumentError", "(", "\"Script has invalid embedded hash\"", ",", "embedded_hash", "=", "hexlify", "(", "embedded_hash", ")", ",", "calculated_hash", "=", "hexlify", "(", "hash_value", ")", ")", "return", "ScriptHeader", "(", "UpdateScript", ".", "SCRIPT_HEADER_LENGTH", ",", "False", ",", "True", ",", "False", ")" ]
Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: script_data (bytearray): The script that we should parse. Raises: ArgumentError: If the script contains malformed data that cannot be parsed. Returns: ScriptHeader: The parsed script header information
[ "Parse", "a", "script", "integrity", "header", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/script.py#L32-L72
train
iotile/coretools
iotilecore/iotile/core/hw/update/script.py
UpdateScript.FromBinary
def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False): """Parse a binary update script. Args: script_data (bytearray): The binary data containing the script. allow_unknown (bool): Allow the script to contain unknown records so long as they have correct headers to allow us to skip them. show_rpcs (bool): Show SendRPCRecord matches for each record rather than the more specific operation Raises: ArgumentError: If the script contains malformed data that cannot be parsed. DataError: If the script contains unknown records and allow_unknown=False Returns: UpdateScript: The parsed update script. """ curr = 0 records = [] header = cls.ParseHeader(script_data) curr = header.header_length cls.logger.debug("Parsed script header: %s, skipping %d bytes", header, curr) record_count = 0 record_data = bytearray() partial_match = None match_offset = 0 while curr < len(script_data): if len(script_data) - curr < UpdateRecord.HEADER_LENGTH: raise ArgumentError("Script ended with a partial record", remaining_length=len(script_data) - curr) # Add another record to our current list of records that we're parsing total_length, record_type = struct.unpack_from("<LB", script_data[curr:]) cls.logger.debug("Found record of type %d, length %d", record_type, total_length) record_data += script_data[curr:curr+total_length] record_count += 1 curr += total_length try: if show_rpcs and record_type == SendRPCRecord.MatchType(): cls.logger.debug(" {0}".format(hexlify(record_data))) record = SendRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:], record_count) elif show_rpcs and record_type == SendErrorCheckingRPCRecord.MatchType(): cls.logger.debug(" {0}".format(hexlify(record_data))) record = SendErrorCheckingRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:], record_count) else: record = UpdateRecord.FromBinary(record_data, record_count) except DeferMatching as defer: # If we're told to defer matching, continue accumulating record_data # until we get a complete match. If a partial match is available, keep track of # that partial match so that we can use it once the record no longer matches. if defer.partial_match is not None: partial_match = defer.partial_match match_offset = curr continue except DataError: if record_count > 1 and partial_match: record = partial_match curr = match_offset elif not allow_unknown: raise elif allow_unknown and record_count > 1: raise ArgumentError("A record matched an initial record subset but failed" " matching a subsequent addition without leaving a partial_match") else: record = UnknownRecord(record_type, record_data[UpdateRecord.HEADER_LENGTH:]) # Reset our record accumulator since we successfully matched one or more records record_count = 0 record_data = bytearray() partial_match = None match_offset = 0 records.append(record) return UpdateScript(records)
python
def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False): """Parse a binary update script. Args: script_data (bytearray): The binary data containing the script. allow_unknown (bool): Allow the script to contain unknown records so long as they have correct headers to allow us to skip them. show_rpcs (bool): Show SendRPCRecord matches for each record rather than the more specific operation Raises: ArgumentError: If the script contains malformed data that cannot be parsed. DataError: If the script contains unknown records and allow_unknown=False Returns: UpdateScript: The parsed update script. """ curr = 0 records = [] header = cls.ParseHeader(script_data) curr = header.header_length cls.logger.debug("Parsed script header: %s, skipping %d bytes", header, curr) record_count = 0 record_data = bytearray() partial_match = None match_offset = 0 while curr < len(script_data): if len(script_data) - curr < UpdateRecord.HEADER_LENGTH: raise ArgumentError("Script ended with a partial record", remaining_length=len(script_data) - curr) # Add another record to our current list of records that we're parsing total_length, record_type = struct.unpack_from("<LB", script_data[curr:]) cls.logger.debug("Found record of type %d, length %d", record_type, total_length) record_data += script_data[curr:curr+total_length] record_count += 1 curr += total_length try: if show_rpcs and record_type == SendRPCRecord.MatchType(): cls.logger.debug(" {0}".format(hexlify(record_data))) record = SendRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:], record_count) elif show_rpcs and record_type == SendErrorCheckingRPCRecord.MatchType(): cls.logger.debug(" {0}".format(hexlify(record_data))) record = SendErrorCheckingRPCRecord.FromBinary(record_data[UpdateRecord.HEADER_LENGTH:], record_count) else: record = UpdateRecord.FromBinary(record_data, record_count) except DeferMatching as defer: # If we're told to defer matching, continue accumulating record_data # until we get a complete match. If a partial match is available, keep track of # that partial match so that we can use it once the record no longer matches. if defer.partial_match is not None: partial_match = defer.partial_match match_offset = curr continue except DataError: if record_count > 1 and partial_match: record = partial_match curr = match_offset elif not allow_unknown: raise elif allow_unknown and record_count > 1: raise ArgumentError("A record matched an initial record subset but failed" " matching a subsequent addition without leaving a partial_match") else: record = UnknownRecord(record_type, record_data[UpdateRecord.HEADER_LENGTH:]) # Reset our record accumulator since we successfully matched one or more records record_count = 0 record_data = bytearray() partial_match = None match_offset = 0 records.append(record) return UpdateScript(records)
[ "def", "FromBinary", "(", "cls", ",", "script_data", ",", "allow_unknown", "=", "True", ",", "show_rpcs", "=", "False", ")", ":", "curr", "=", "0", "records", "=", "[", "]", "header", "=", "cls", ".", "ParseHeader", "(", "script_data", ")", "curr", "=", "header", ".", "header_length", "cls", ".", "logger", ".", "debug", "(", "\"Parsed script header: %s, skipping %d bytes\"", ",", "header", ",", "curr", ")", "record_count", "=", "0", "record_data", "=", "bytearray", "(", ")", "partial_match", "=", "None", "match_offset", "=", "0", "while", "curr", "<", "len", "(", "script_data", ")", ":", "if", "len", "(", "script_data", ")", "-", "curr", "<", "UpdateRecord", ".", "HEADER_LENGTH", ":", "raise", "ArgumentError", "(", "\"Script ended with a partial record\"", ",", "remaining_length", "=", "len", "(", "script_data", ")", "-", "curr", ")", "# Add another record to our current list of records that we're parsing", "total_length", ",", "record_type", "=", "struct", ".", "unpack_from", "(", "\"<LB\"", ",", "script_data", "[", "curr", ":", "]", ")", "cls", ".", "logger", ".", "debug", "(", "\"Found record of type %d, length %d\"", ",", "record_type", ",", "total_length", ")", "record_data", "+=", "script_data", "[", "curr", ":", "curr", "+", "total_length", "]", "record_count", "+=", "1", "curr", "+=", "total_length", "try", ":", "if", "show_rpcs", "and", "record_type", "==", "SendRPCRecord", ".", "MatchType", "(", ")", ":", "cls", ".", "logger", ".", "debug", "(", "\" {0}\"", ".", "format", "(", "hexlify", "(", "record_data", ")", ")", ")", "record", "=", "SendRPCRecord", ".", "FromBinary", "(", "record_data", "[", "UpdateRecord", ".", "HEADER_LENGTH", ":", "]", ",", "record_count", ")", "elif", "show_rpcs", "and", "record_type", "==", "SendErrorCheckingRPCRecord", ".", "MatchType", "(", ")", ":", "cls", ".", "logger", ".", "debug", "(", "\" {0}\"", ".", "format", "(", "hexlify", "(", "record_data", ")", ")", ")", "record", "=", "SendErrorCheckingRPCRecord", ".", "FromBinary", "(", "record_data", "[", "UpdateRecord", ".", "HEADER_LENGTH", ":", "]", ",", "record_count", ")", "else", ":", "record", "=", "UpdateRecord", ".", "FromBinary", "(", "record_data", ",", "record_count", ")", "except", "DeferMatching", "as", "defer", ":", "# If we're told to defer matching, continue accumulating record_data", "# until we get a complete match. If a partial match is available, keep track of", "# that partial match so that we can use it once the record no longer matches.", "if", "defer", ".", "partial_match", "is", "not", "None", ":", "partial_match", "=", "defer", ".", "partial_match", "match_offset", "=", "curr", "continue", "except", "DataError", ":", "if", "record_count", ">", "1", "and", "partial_match", ":", "record", "=", "partial_match", "curr", "=", "match_offset", "elif", "not", "allow_unknown", ":", "raise", "elif", "allow_unknown", "and", "record_count", ">", "1", ":", "raise", "ArgumentError", "(", "\"A record matched an initial record subset but failed\"", "\" matching a subsequent addition without leaving a partial_match\"", ")", "else", ":", "record", "=", "UnknownRecord", "(", "record_type", ",", "record_data", "[", "UpdateRecord", ".", "HEADER_LENGTH", ":", "]", ")", "# Reset our record accumulator since we successfully matched one or more records", "record_count", "=", "0", "record_data", "=", "bytearray", "(", ")", "partial_match", "=", "None", "match_offset", "=", "0", "records", ".", "append", "(", "record", ")", "return", "UpdateScript", "(", "records", ")" ]
Parse a binary update script. Args: script_data (bytearray): The binary data containing the script. allow_unknown (bool): Allow the script to contain unknown records so long as they have correct headers to allow us to skip them. show_rpcs (bool): Show SendRPCRecord matches for each record rather than the more specific operation Raises: ArgumentError: If the script contains malformed data that cannot be parsed. DataError: If the script contains unknown records and allow_unknown=False Returns: UpdateScript: The parsed update script.
[ "Parse", "a", "binary", "update", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/script.py#L75-L161
train
iotile/coretools
iotilecore/iotile/core/hw/update/script.py
UpdateScript.encode
def encode(self): """Encode this record into a binary blob. This binary blob could be parsed via a call to FromBinary(). Returns: bytearray: The binary encoded script. """ blob = bytearray() for record in self.records: blob += record.encode() header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH) blob = header + blob sha = hashlib.sha256() sha.update(blob) hash_value = sha.digest()[:16] return bytearray(hash_value) + blob
python
def encode(self): """Encode this record into a binary blob. This binary blob could be parsed via a call to FromBinary(). Returns: bytearray: The binary encoded script. """ blob = bytearray() for record in self.records: blob += record.encode() header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH) blob = header + blob sha = hashlib.sha256() sha.update(blob) hash_value = sha.digest()[:16] return bytearray(hash_value) + blob
[ "def", "encode", "(", "self", ")", ":", "blob", "=", "bytearray", "(", ")", "for", "record", "in", "self", ".", "records", ":", "blob", "+=", "record", ".", "encode", "(", ")", "header", "=", "struct", ".", "pack", "(", "\"<LL\"", ",", "self", ".", "SCRIPT_MAGIC", ",", "len", "(", "blob", ")", "+", "self", ".", "SCRIPT_HEADER_LENGTH", ")", "blob", "=", "header", "+", "blob", "sha", "=", "hashlib", ".", "sha256", "(", ")", "sha", ".", "update", "(", "blob", ")", "hash_value", "=", "sha", ".", "digest", "(", ")", "[", ":", "16", "]", "return", "bytearray", "(", "hash_value", ")", "+", "blob" ]
Encode this record into a binary blob. This binary blob could be parsed via a call to FromBinary(). Returns: bytearray: The binary encoded script.
[ "Encode", "this", "record", "into", "a", "binary", "blob", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/script.py#L163-L184
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/base_runnable.py
BaseRunnable.create_worker
def create_worker(self, func, interval, *args, **kwargs): """Spawn a worker thread running func. The worker will be automatically be started when start() is called and terminated when stop() is called on this object. This must be called only from the main thread, not from a worker thread. create_worker must not be called after stop() has been called. If it is called before start() is called, the thread is started when start() is called, otherwise it is started immediately. Args: func (callable): Either a function that will be called in a loop with a sleep of interval seconds with *args and **kwargs or a generator function that will be called once and expected to yield periodically so that the worker can check if it should be killed. interval (float): The time interval between invocations of func. This should not be 0 so that the thread doesn't peg the CPU and should be short enough so that the worker checks if it should be killed in a timely fashion. *args: Arguments that are passed to func as positional args **kwargs: Arguments that are passed to func as keyword args """ thread = StoppableWorkerThread(func, interval, args, kwargs) self._workers.append(thread) if self._started: thread.start()
python
def create_worker(self, func, interval, *args, **kwargs): """Spawn a worker thread running func. The worker will be automatically be started when start() is called and terminated when stop() is called on this object. This must be called only from the main thread, not from a worker thread. create_worker must not be called after stop() has been called. If it is called before start() is called, the thread is started when start() is called, otherwise it is started immediately. Args: func (callable): Either a function that will be called in a loop with a sleep of interval seconds with *args and **kwargs or a generator function that will be called once and expected to yield periodically so that the worker can check if it should be killed. interval (float): The time interval between invocations of func. This should not be 0 so that the thread doesn't peg the CPU and should be short enough so that the worker checks if it should be killed in a timely fashion. *args: Arguments that are passed to func as positional args **kwargs: Arguments that are passed to func as keyword args """ thread = StoppableWorkerThread(func, interval, args, kwargs) self._workers.append(thread) if self._started: thread.start()
[ "def", "create_worker", "(", "self", ",", "func", ",", "interval", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "StoppableWorkerThread", "(", "func", ",", "interval", ",", "args", ",", "kwargs", ")", "self", ".", "_workers", ".", "append", "(", "thread", ")", "if", "self", ".", "_started", ":", "thread", ".", "start", "(", ")" ]
Spawn a worker thread running func. The worker will be automatically be started when start() is called and terminated when stop() is called on this object. This must be called only from the main thread, not from a worker thread. create_worker must not be called after stop() has been called. If it is called before start() is called, the thread is started when start() is called, otherwise it is started immediately. Args: func (callable): Either a function that will be called in a loop with a sleep of interval seconds with *args and **kwargs or a generator function that will be called once and expected to yield periodically so that the worker can check if it should be killed. interval (float): The time interval between invocations of func. This should not be 0 so that the thread doesn't peg the CPU and should be short enough so that the worker checks if it should be killed in a timely fashion. *args: Arguments that are passed to func as positional args **kwargs: Arguments that are passed to func as keyword args
[ "Spawn", "a", "worker", "thread", "running", "func", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/base_runnable.py#L16-L45
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/base_runnable.py
BaseRunnable.stop_workers
def stop_workers(self): """Synchronously stop any potential workers.""" self._started = False for worker in self._workers: worker.stop()
python
def stop_workers(self): """Synchronously stop any potential workers.""" self._started = False for worker in self._workers: worker.stop()
[ "def", "stop_workers", "(", "self", ")", ":", "self", ".", "_started", "=", "False", "for", "worker", "in", "self", ".", "_workers", ":", "worker", ".", "stop", "(", ")" ]
Synchronously stop any potential workers.
[ "Synchronously", "stop", "any", "potential", "workers", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/base_runnable.py#L58-L64
train
iotile/coretools
iotilecore/iotile/core/hw/virtual/base_runnable.py
BaseRunnable.stop_workers_async
def stop_workers_async(self): """Signal that all workers should stop without waiting.""" self._started = False for worker in self._workers: worker.signal_stop()
python
def stop_workers_async(self): """Signal that all workers should stop without waiting.""" self._started = False for worker in self._workers: worker.signal_stop()
[ "def", "stop_workers_async", "(", "self", ")", ":", "self", ".", "_started", "=", "False", "for", "worker", "in", "self", ".", "_workers", ":", "worker", ".", "signal_stop", "(", ")" ]
Signal that all workers should stop without waiting.
[ "Signal", "that", "all", "workers", "should", "stop", "without", "waiting", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/base_runnable.py#L66-L71
train
iotile/coretools
iotile_ext_cloud/iotile/cloud/apps/ota_updater.py
_download_ota_script
def _download_ota_script(script_url): """Download the script from the cloud service and store to temporary file location""" try: blob = requests.get(script_url, stream=True) return blob.content except Exception as e: iprint("Failed to download OTA script") iprint(e) return False
python
def _download_ota_script(script_url): """Download the script from the cloud service and store to temporary file location""" try: blob = requests.get(script_url, stream=True) return blob.content except Exception as e: iprint("Failed to download OTA script") iprint(e) return False
[ "def", "_download_ota_script", "(", "script_url", ")", ":", "try", ":", "blob", "=", "requests", ".", "get", "(", "script_url", ",", "stream", "=", "True", ")", "return", "blob", ".", "content", "except", "Exception", "as", "e", ":", "iprint", "(", "\"Failed to download OTA script\"", ")", "iprint", "(", "e", ")", "return", "False" ]
Download the script from the cloud service and store to temporary file location
[ "Download", "the", "script", "from", "the", "cloud", "service", "and", "store", "to", "temporary", "file", "location" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotile_ext_cloud/iotile/cloud/apps/ota_updater.py#L27-L36
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/compat/__init__.py
rename_module
def rename_module(new, old): """ Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x. """ try: sys.modules[new] = imp.load_module(old, *imp.find_module(old)) return True except ImportError: return False
python
def rename_module(new, old): """ Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x. """ try: sys.modules[new] = imp.load_module(old, *imp.find_module(old)) return True except ImportError: return False
[ "def", "rename_module", "(", "new", ",", "old", ")", ":", "try", ":", "sys", ".", "modules", "[", "new", "]", "=", "imp", ".", "load_module", "(", "old", ",", "*", "imp", ".", "find_module", "(", "old", ")", ")", "return", "True", "except", "ImportError", ":", "return", "False" ]
Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x.
[ "Attempts", "to", "import", "the", "old", "module", "and", "load", "it", "under", "the", "new", "name", ".", "Used", "for", "purely", "cosmetic", "name", "changes", "in", "Python", "3", ".", "x", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/compat/__init__.py#L78-L87
train
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/jlink.py
JLinkAdapter._parse_conn_string
def _parse_conn_string(self, conn_string): """Parse a connection string passed from 'debug -c' or 'connect_direct' Returns True if any settings changed in the debug port, which would require a jlink disconnection """ disconnection_required = False """If device not in conn_string, set to default info""" if conn_string is None or 'device' not in conn_string: if self._default_device_info is not None and self._device_info != self._default_device_info: disconnection_required = True self._device_info = self._default_device_info if conn_string is None or len(conn_string) == 0: return disconnection_required if '@' in conn_string: raise ArgumentError("Configuration files are not yet supported as part of a connection string argument", conn_string=conn_string) pairs = conn_string.split(';') for pair in pairs: name, _, value = pair.partition('=') if len(name) == 0 or len(value) == 0: continue name = name.strip() value = value.strip() if name == 'device': if value in DEVICE_ALIASES: device_name = DEVICE_ALIASES[value] if device_name in KNOWN_DEVICES: device_info = KNOWN_DEVICES.get(device_name) if self._device_info != device_info: self._device_info = device_info disconnection_required = True else: raise ArgumentError("Unknown device name or alias, please select from known_devices", device_name=value, known_devices=[x for x in DEVICE_ALIASES.keys()]) elif name == 'channel': if self._mux_func is not None: if self._channel != int(value): self._channel = int(value) disconnection_required = True else: print("Warning: multiplexing architecture not selected, channel will not be set") return disconnection_required
python
def _parse_conn_string(self, conn_string): """Parse a connection string passed from 'debug -c' or 'connect_direct' Returns True if any settings changed in the debug port, which would require a jlink disconnection """ disconnection_required = False """If device not in conn_string, set to default info""" if conn_string is None or 'device' not in conn_string: if self._default_device_info is not None and self._device_info != self._default_device_info: disconnection_required = True self._device_info = self._default_device_info if conn_string is None or len(conn_string) == 0: return disconnection_required if '@' in conn_string: raise ArgumentError("Configuration files are not yet supported as part of a connection string argument", conn_string=conn_string) pairs = conn_string.split(';') for pair in pairs: name, _, value = pair.partition('=') if len(name) == 0 or len(value) == 0: continue name = name.strip() value = value.strip() if name == 'device': if value in DEVICE_ALIASES: device_name = DEVICE_ALIASES[value] if device_name in KNOWN_DEVICES: device_info = KNOWN_DEVICES.get(device_name) if self._device_info != device_info: self._device_info = device_info disconnection_required = True else: raise ArgumentError("Unknown device name or alias, please select from known_devices", device_name=value, known_devices=[x for x in DEVICE_ALIASES.keys()]) elif name == 'channel': if self._mux_func is not None: if self._channel != int(value): self._channel = int(value) disconnection_required = True else: print("Warning: multiplexing architecture not selected, channel will not be set") return disconnection_required
[ "def", "_parse_conn_string", "(", "self", ",", "conn_string", ")", ":", "disconnection_required", "=", "False", "\"\"\"If device not in conn_string, set to default info\"\"\"", "if", "conn_string", "is", "None", "or", "'device'", "not", "in", "conn_string", ":", "if", "self", ".", "_default_device_info", "is", "not", "None", "and", "self", ".", "_device_info", "!=", "self", ".", "_default_device_info", ":", "disconnection_required", "=", "True", "self", ".", "_device_info", "=", "self", ".", "_default_device_info", "if", "conn_string", "is", "None", "or", "len", "(", "conn_string", ")", "==", "0", ":", "return", "disconnection_required", "if", "'@'", "in", "conn_string", ":", "raise", "ArgumentError", "(", "\"Configuration files are not yet supported as part of a connection string argument\"", ",", "conn_string", "=", "conn_string", ")", "pairs", "=", "conn_string", ".", "split", "(", "';'", ")", "for", "pair", "in", "pairs", ":", "name", ",", "_", ",", "value", "=", "pair", ".", "partition", "(", "'='", ")", "if", "len", "(", "name", ")", "==", "0", "or", "len", "(", "value", ")", "==", "0", ":", "continue", "name", "=", "name", ".", "strip", "(", ")", "value", "=", "value", ".", "strip", "(", ")", "if", "name", "==", "'device'", ":", "if", "value", "in", "DEVICE_ALIASES", ":", "device_name", "=", "DEVICE_ALIASES", "[", "value", "]", "if", "device_name", "in", "KNOWN_DEVICES", ":", "device_info", "=", "KNOWN_DEVICES", ".", "get", "(", "device_name", ")", "if", "self", ".", "_device_info", "!=", "device_info", ":", "self", ".", "_device_info", "=", "device_info", "disconnection_required", "=", "True", "else", ":", "raise", "ArgumentError", "(", "\"Unknown device name or alias, please select from known_devices\"", ",", "device_name", "=", "value", ",", "known_devices", "=", "[", "x", "for", "x", "in", "DEVICE_ALIASES", ".", "keys", "(", ")", "]", ")", "elif", "name", "==", "'channel'", ":", "if", "self", ".", "_mux_func", "is", "not", "None", ":", "if", "self", ".", "_channel", "!=", "int", "(", "value", ")", ":", "self", ".", "_channel", "=", "int", "(", "value", ")", "disconnection_required", "=", "True", "else", ":", "print", "(", "\"Warning: multiplexing architecture not selected, channel will not be set\"", ")", "return", "disconnection_required" ]
Parse a connection string passed from 'debug -c' or 'connect_direct' Returns True if any settings changed in the debug port, which would require a jlink disconnection
[ "Parse", "a", "connection", "string", "passed", "from", "debug", "-", "c", "or", "connect_direct", "Returns", "True", "if", "any", "settings", "changed", "in", "the", "debug", "port", "which", "would", "require", "a", "jlink", "disconnection" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L85-L131
train
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/jlink.py
JLinkAdapter._try_connect
def _try_connect(self, connection_string): """If the connecton string settings are different, try and connect to an attached device""" if self._parse_conn_string(connection_string): self._trigger_callback('on_disconnect', self.id, self._connection_id) self.stop_sync() if self._mux_func is not None: self._mux_func(self._channel) if self._device_info is None: raise ArgumentError("Missing device name or alias, specify using device=name in port string " "or -c device=name in connect_direct or debug command", known_devices=[x for x in DEVICE_ALIASES.keys()]) try: self.jlink = pylink.JLink() self.jlink.open(serial_no=self._jlink_serial) self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) self.jlink.connect(self._device_info.jlink_name) self.jlink.set_little_endian() except pylink.errors.JLinkException as exc: if exc.code == exc.VCC_FAILURE: raise HardwareError("No target power detected", code=exc.code, suggestion="Check jlink connection and power wiring") raise except: raise self._control_thread = JLinkControlThread(self.jlink) self._control_thread.start() self.set_config('probe_required', True) self.set_config('probe_supported', True)
python
def _try_connect(self, connection_string): """If the connecton string settings are different, try and connect to an attached device""" if self._parse_conn_string(connection_string): self._trigger_callback('on_disconnect', self.id, self._connection_id) self.stop_sync() if self._mux_func is not None: self._mux_func(self._channel) if self._device_info is None: raise ArgumentError("Missing device name or alias, specify using device=name in port string " "or -c device=name in connect_direct or debug command", known_devices=[x for x in DEVICE_ALIASES.keys()]) try: self.jlink = pylink.JLink() self.jlink.open(serial_no=self._jlink_serial) self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) self.jlink.connect(self._device_info.jlink_name) self.jlink.set_little_endian() except pylink.errors.JLinkException as exc: if exc.code == exc.VCC_FAILURE: raise HardwareError("No target power detected", code=exc.code, suggestion="Check jlink connection and power wiring") raise except: raise self._control_thread = JLinkControlThread(self.jlink) self._control_thread.start() self.set_config('probe_required', True) self.set_config('probe_supported', True)
[ "def", "_try_connect", "(", "self", ",", "connection_string", ")", ":", "if", "self", ".", "_parse_conn_string", "(", "connection_string", ")", ":", "self", ".", "_trigger_callback", "(", "'on_disconnect'", ",", "self", ".", "id", ",", "self", ".", "_connection_id", ")", "self", ".", "stop_sync", "(", ")", "if", "self", ".", "_mux_func", "is", "not", "None", ":", "self", ".", "_mux_func", "(", "self", ".", "_channel", ")", "if", "self", ".", "_device_info", "is", "None", ":", "raise", "ArgumentError", "(", "\"Missing device name or alias, specify using device=name in port string \"", "\"or -c device=name in connect_direct or debug command\"", ",", "known_devices", "=", "[", "x", "for", "x", "in", "DEVICE_ALIASES", ".", "keys", "(", ")", "]", ")", "try", ":", "self", ".", "jlink", "=", "pylink", ".", "JLink", "(", ")", "self", ".", "jlink", ".", "open", "(", "serial_no", "=", "self", ".", "_jlink_serial", ")", "self", ".", "jlink", ".", "set_tif", "(", "pylink", ".", "enums", ".", "JLinkInterfaces", ".", "SWD", ")", "self", ".", "jlink", ".", "connect", "(", "self", ".", "_device_info", ".", "jlink_name", ")", "self", ".", "jlink", ".", "set_little_endian", "(", ")", "except", "pylink", ".", "errors", ".", "JLinkException", "as", "exc", ":", "if", "exc", ".", "code", "==", "exc", ".", "VCC_FAILURE", ":", "raise", "HardwareError", "(", "\"No target power detected\"", ",", "code", "=", "exc", ".", "code", ",", "suggestion", "=", "\"Check jlink connection and power wiring\"", ")", "raise", "except", ":", "raise", "self", ".", "_control_thread", "=", "JLinkControlThread", "(", "self", ".", "jlink", ")", "self", ".", "_control_thread", ".", "start", "(", ")", "self", ".", "set_config", "(", "'probe_required'", ",", "True", ")", "self", ".", "set_config", "(", "'probe_supported'", ",", "True", ")" ]
If the connecton string settings are different, try and connect to an attached device
[ "If", "the", "connecton", "string", "settings", "are", "different", "try", "and", "connect", "to", "an", "attached", "device" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L133-L167
train
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/jlink.py
JLinkAdapter.stop_sync
def stop_sync(self): """Synchronously stop this adapter and release all resources.""" if self._control_thread is not None and self._control_thread.is_alive(): self._control_thread.stop() self._control_thread.join() if self.jlink is not None: self.jlink.close()
python
def stop_sync(self): """Synchronously stop this adapter and release all resources.""" if self._control_thread is not None and self._control_thread.is_alive(): self._control_thread.stop() self._control_thread.join() if self.jlink is not None: self.jlink.close()
[ "def", "stop_sync", "(", "self", ")", ":", "if", "self", ".", "_control_thread", "is", "not", "None", "and", "self", ".", "_control_thread", ".", "is_alive", "(", ")", ":", "self", ".", "_control_thread", ".", "stop", "(", ")", "self", ".", "_control_thread", ".", "join", "(", ")", "if", "self", ".", "jlink", "is", "not", "None", ":", "self", ".", "jlink", ".", "close", "(", ")" ]
Synchronously stop this adapter and release all resources.
[ "Synchronously", "stop", "this", "adapter", "and", "release", "all", "resources", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/jlink.py#L169-L177
train