Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _save_file(self, data): if platform.system() == 'Windows': with open(self.file, "w") as outfile: json.dump(data, outfile) else: newpath = self.file + '.new' with open(newpath, "w") as outfile:...
[ "Attempt to atomically save file by saving and then moving into position\n\n The goal is to make it difficult for a crash to corrupt our data file since\n the move operation can be made atomic if needed on mission critical filesystems.\n " ]
Please provide a description of the function:def remove(self, key): data = self._load_file() del data[key] self._save_file(data)
[ "Remove a key from the data store\n\n Args:\n key (string): The key to remove\n\n Raises:\n KeyError: if the key was not found\n " ]
Please provide a description of the function:def set(self, key, value): data = self._load_file() data[key] = value self._save_file(data)
[ "Set the value of a key\n\n Args:\n key (string): The key used to store this value\n value (string): The value to store\n " ]
Please provide a description of the function:def trigger_chain(self): trigger_stream = self.allocator.attach_stream(self.trigger_stream) return (trigger_stream, self.trigger_cond)
[ "Return a NodeInput tuple for creating a node.\n\n Returns:\n (StreamIdentifier, InputTrigger)\n " ]
Please provide a description of the function:def add_common_cc_variables(env): if '_CCCOMCOM' not in env: env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS' # It's a hack to test for darwin here, but the alternative # of creating an applecc.py to contain this seems overkill. ...
[ "\n Add underlying common \"C compiler\" variables that\n are used by multiple tools (specifically, c++).\n " ]
Please provide a description of the function:def generate(env): static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.ShCAction) static_obj.add_emitter(s...
[ "\n Add Builders and construction variables for C compilers to an Environment.\n " ]
Please provide a description of the function:def build_args(): parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument(u'sensor_graph', type=str, help=u"The sensor graph file to load and run.") parser.add_argument(u'--stop', u...
[ "Create command line argument parser." ]
Please provide a description of the function:def process_mock_rpc(input_string): spec, equals, value = input_string.partition(u'=') if len(equals) == 0: print("Could not parse mock RPC argument: {}".format(input_string)) sys.exit(1) try: value = int(value.strip(), 0) exce...
[ "Process a mock RPC argument.\n\n Args:\n input_string (str): The input string that should be in the format\n <slot id>:<rpc id> = value\n " ]
Please provide a description of the function:def watch_printer(watch, value): print("({: 8} s) {}: {}".format(value.raw_time, watch, value.value))
[ "Print a watched value.\n\n Args:\n watch (DataStream): The stream that was watched\n value (IOTileReading): The value to was seen\n " ]
Please provide a description of the function:def main(argv=None): if argv is None: argv = sys.argv[1:] try: executor = None parser = build_args() args = parser.parse_args(args=argv) model = DeviceModel() parser = SensorGraphFileParser() parser.par...
[ "Main entry point for iotile sensorgraph simulator.\n\n This is the iotile-sgrun command line program. It takes\n an optional set of command line parameters to allow for\n testing.\n\n Args:\n argv (list of str): An optional set of command line\n parameters. If not passed, these are ...
Please provide a description of the function:def _verify_tile_versions(self, hw): for tile, expected_tile_version in self._tile_versions.items(): actual_tile_version = str(hw.get(tile).tile_version()) if expected_tile_version != actual_tile_version: raise Argumen...
[ "Verify that the tiles have the correct versions\n " ]
Please provide a description of the function:def _verify_os_app_settings(self, hw): con = hw.controller() info = con.test_interface().get_info() if self._os_tag is not None: if info['os_tag'] != self._os_tag: raise ArgumentError("Incorrect os_tag", actual_os_...
[ "Verify that the os and app tags/versions are set correctly\n " ]
Please provide a description of the function:def _verify_realtime_streams(self, hw): print("--> Testing realtime data (takes 2 seconds)") time.sleep(2.1) reports = [x for x in hw.iter_reports()] reports_seen = {key: 0 for key in self._realtime_streams} for report in rep...
[ "Check that the realtime streams are being produced\n " ]
Please provide a description of the function:def _update_pot_file(target, source, env): import re import os import SCons.Action nop = lambda target, source, env: 0 # Save scons cwd and os cwd (NOTE: they may be different. After the job, we # revert each one to its original state). save...
[ " Action function for `POTUpdate` builder " ]
Please provide a description of the function:def _scan_xgettext_from_files(target, source, env, files=None, path=None): import re import SCons.Util import SCons.Node.FS if files is None: return 0 if not SCons.Util.is_List(files): files = [files] if path is None: if...
[ " Parses `POTFILES.in`-like file and returns list of extracted file names.\n " ]
Please provide a description of the function:def _pot_update_emitter(target, source, env): from SCons.Tool.GettextCommon import _POTargetFactory import SCons.Util import SCons.Node.FS if 'XGETTEXTFROM' in env: xfrom = env['XGETTEXTFROM'] else: return target, source if not S...
[ " Emitter function for `POTUpdate` builder " ]
Please provide a description of the function:def _POTUpdateBuilder(env, **kw): import SCons.Action from SCons.Tool.GettextCommon import _POTargetFactory kw['action'] = SCons.Action.Action(_update_pot_file, None) kw['suffix'] = '$POTSUFFIX' kw['target_factory'] = _POTargetFactory(env, alias='$PO...
[ " Creates `POTUpdate` builder object " ]
Please provide a description of the function:def generate(env, **kw): import SCons.Util from SCons.Tool.GettextCommon import RPaths, _detect_xgettext try: env['XGETTEXT'] = _detect_xgettext(env) except: env['XGETTEXT'] = 'xgettext' # NOTE: sources="$SOURCES" would work as well....
[ " Generate `xgettext` tool " ]
Please provide a description of the function:def generate(env): if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] cc.generate(env) if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons...
[ "Add Builders and construction variables for gcc to an Environment." ]
Please provide a description of the function:def detect_version(env, cc): cc = env.subst(cc) if not cc: return None version = None #pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'], pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['--version'], ...
[ "Return the version of the GNU compiler, or None if it is not a GNU compiler." ]
Please provide a description of the function:def convert_to_id(s, id_set): charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.' if s[0] in '0123456789.': s += '_'+s id = [c for c in s if c in charset] # did we already generate an id for this file? try: re...
[ " Some parts of .wxs need an Id attribute (for example: The File and\n Directory directives. The charset is limited to A-Z, a-z, digits,\n underscores, periods. Each Id must begin with a letter or with a\n underscore. Google for \"CNDL0015\" for information about this.\n\n Requirements:\n * the stri...
Please provide a description of the function:def is_dos_short_file_name(file): fname, ext = os.path.splitext(file) proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot proper_fname = file.isupper() and len(fname) <= 8 return proper_ext and proper_fname
[ " Examine if the given file is in the 8.3 form.\n " ]
Please provide a description of the function:def gen_dos_short_file_name(file, filename_set): # guard this to not confuse the generation if is_dos_short_file_name(file): return file fname, ext = os.path.splitext(file) # ext contains the dot # first try if it suffices to convert to upper ...
[ " See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982\n\n These are no complete 8.3 dos short names. The ~ char is missing and \n replaced with one character from the filename. WiX warns about such\n filenames, since a collision might occur. Google for \"CNDL1014\" for\n more information...
Please provide a description of the function:def create_feature_dict(files): dict = {} def add_to_dict( feature, file ): if not SCons.Util.is_List( feature ): feature = [ feature ] for f in feature: if f not in dict: dict[ f ] = [ file ] ...
[ " X_MSI_FEATURE and doc FileTag's can be used to collect files in a\n hierarchy. This function collects the files into this hierarchy.\n " ]
Please provide a description of the function:def generate_guids(root): from hashlib import md5 # specify which tags need a guid and in which attribute this should be stored. needs_id = { 'Product' : 'Id', 'Package' : 'Id', 'Component' : 'Guid', } ...
[ " generates globally unique identifiers for parts of the xml which need\n them.\n\n Component tags have a special requirement. Their UUID is only allowed to\n change if the list of their contained resources has changed. This allows\n for clean removal and proper updates.\n\n To handle this requiremen...
Please provide a description of the function:def build_wxsfile(target, source, env): file = open(target[0].get_abspath(), 'w') try: # Create a document with the Wix root tag doc = Document() root = doc.createElement( 'Wix' ) root.attributes['xmlns']='http://schemas.microso...
[ " Compiles a .wxs file from the keywords given in env['msi_spec'] and\n by analyzing the tree of source nodes and their tags.\n " ]
Please provide a description of the function:def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set): doc = Document() d1 = doc.createElement( 'Directory' ) d1.attributes['Id'] = 'TARGETDIR' d1.attributes['Name'] = 'SourceDir' d2 = doc.createElement( 'Directory' ) ...
[ " Create the wix default target directory layout and return the innermost\n directory.\n\n We assume that the XML tree delivered in the root argument already contains\n the Product tag.\n\n Everything is put under the PFiles directory property defined by WiX.\n After that a directory with the 'VENDO...
Please provide a description of the function:def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set): root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set ) components = create_feature_dict( files ) factory = Document() def get...
[ " Builds the Component sections of the wxs file with their included files.\n\n Files need to be specified in 8.3 format and in the long name format, long\n filenames will be converted automatically.\n\n Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag.\n ", " Returns the node under th...
Please provide a description of the function:def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set): factory = Document() Feature = factory.createElement('Feature') Feature.attributes['Id'] = 'complete' Feature.attributes['ConfigurableDirectory'] = 'MY_DE...
[ " This function creates the <features> tag based on the supplied xml tree.\n\n This is achieved by finding all <component>s and adding them to a default target.\n\n It should be called after the tree has been built completly. We assume\n that a MY_DEFAULT_FOLDER Property is defined in the wxs file tree.\n...
Please provide a description of the function:def build_wxsfile_default_gui(root): factory = Document() Product = root.getElementsByTagName('Product')[0] UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_Mondo' Product.childNodes.append(UIRef) UIRef = factory.creat...
[ " This function adds a default GUI to the wxs file\n " ]
Please provide a description of the function:def build_license_file(directory, spec): name, text = '', '' try: name = spec['LICENSE'] text = spec['X_MSI_LICENSE_TEXT'] except KeyError: pass # ignore this as X_MSI_LICENSE_TEXT is optional if name!='' or text!='': fi...
[ " Creates a License.rtf file with the content of \"X_MSI_LICENSE_TEXT\"\n in the given directory\n " ]
Please provide a description of the function:def build_wxsfile_header_section(root, spec): # Create the needed DOM nodes and add them at the correct position in the tree. factory = Document() Product = factory.createElement( 'Product' ) Package = factory.createElement( 'Package' ) root.childNo...
[ " Adds the xml file node which define the package meta-data.\n " ]
Please provide a description of the function:def generate(env): path, cxx, shcxx, version = get_cppc(env) if path: cxx = os.path.join(path, cxx) shcxx = os.path.join(path, shcxx) cplusplus.generate(env) env['CXX'] = cxx env['SHCXX'] = shcxx env['CXXVERSION'] = version ...
[ "Add Builders and construction variables for SunPRO C++." ]
Please provide a description of the function:def FromReadings(cls, uuid, readings, events, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0x100, sent_timestamp=0, received_time=None): lowest_id = IOTileReading.InvalidReadingID highest_id = IOTileReadin...
[ "Create a flexible dictionary report from a list of readings and events.\n\n Args:\n uuid (int): The uuid of the device that this report came from\n readings (list of IOTileReading): A list of IOTileReading objects containing the data in the report\n events (list of IOTileEve...
Please provide a description of the function:def decode(self): report_dict = msgpack.unpackb(self.raw_report, raw=False) events = [IOTileEvent.FromDict(x) for x in report_dict.get('events', [])] readings = [IOTileReading.FromDict(x) for x in report_dict.get('data', [])] if 'd...
[ "Decode this report from a msgpack encoded binary blob." ]
Please provide a description of the function:def _callable_contents(obj): try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.__func__)...
[ "Return the signature contents of a callable Python object.\n " ]
Please provide a description of the function:def _object_contents(obj): try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.__func__) ...
[ "Return the signature contents of any Python object.\n\n We have to handle the case where object contains a code object\n since it can be pickled directly.\n " ]
Please provide a description of the function:def _code_contents(code, docstring=None): # contents = [] # The code contents depends on the number of local variables # but not their actual names. contents = bytearray("{}, {}".format(code.co_argcount, len(code.co_varnames)), 'utf-8') contents.e...
[ "Return the signature contents of a code object.\n\n By providing direct access to the code object of the\n function, Python makes this extremely easy. Hooray!\n\n Unfortunately, older versions of Python include line\n number indications in the compiled byte code. Boo!\n So we remove the line numbe...
Please provide a description of the function:def _function_contents(func): contents = [_code_contents(func.__code__, func.__doc__)] # The function contents depends on the value of defaults arguments if func.__defaults__: function_defaults_contents = [_object_contents(cc) for cc in func.__def...
[ "\n The signature is as follows (should be byte/chars):\n < _code_contents (see above) from func.__code__ >\n ,( comma separated _object_contents for function argument defaults)\n ,( comma separated _object_contents for any closure contents )\n\n\n See also: https://docs.python.org/3/reference/datamo...
Please provide a description of the function:def _object_instance_content(obj): retval = bytearray() if obj is None: return b'N.' if isinstance(obj, SCons.Util.BaseStringTypes): return SCons.Util.to_bytes(obj) inst_class = obj.__class__ inst_class_name = bytearray(obj.__class...
[ "\n Returns consistant content for a action class or an instance thereof\n\n :Parameters:\n - `obj` Should be either and action class or an instance thereof\n\n :Returns:\n bytearray or bytes representing the obj suitable for generating a signature from.\n " ]
Please provide a description of the function:def _do_create_keywords(args, kw): v = kw.get('varlist', ()) # prevent varlist="FOO" from being interpreted as ['F', 'O', 'O'] if is_String(v): v = (v,) kw['varlist'] = tuple(v) if args: # turn positional args into equivalent keywords ...
[ "This converts any arguments after the action argument into\n their equivalent keywords and adds them to the kw argument.\n " ]
Please provide a description of the function:def _do_create_action(act, kw): if isinstance(act, ActionBase): return act if is_String(act): var=SCons.Util.get_environment_var(act) if var: # This looks like a string that is purely an Environment # variable re...
[ "This is the actual \"implementation\" for the\n Action factory method, below. This handles the\n fact that passing lists to Action() itself has\n different semantics than passing lists as elements\n of lists.\n\n The former will create a ListAction, the latter\n will create a CommandAction by co...
Please provide a description of the function:def _do_create_list_action(act, kw): acts = [] for a in act: aa = _do_create_action(a, kw) if aa is not None: acts.append(aa) if not acts: return ListAction([]) elif len(acts) == 1: return acts[0] else: return ...
[ "A factory for list actions. Convert the input list into Actions\n and then wrap them in a ListAction." ]
Please provide a description of the function:def Action(act, *args, **kw): # Really simple: the _do_create_* routines do the heavy lifting. _do_create_keywords(args, kw) if is_List(act): return _do_create_list_action(act, kw) return _do_create_action(act, kw)
[ "A factory for action objects." ]
Please provide a description of the function:def _string_from_cmd_list(cmd_list): cl = [] for arg in map(str, cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) return ' '.join(cl)
[ "Takes a list of command line arguments and returns a pretty\n representation for printing." ]
Please provide a description of the function:def get_default_ENV(env): global default_ENV try: return env['ENV'] except KeyError: if not default_ENV: import SCons.Environment # This is a hideously expensive way to get a default shell # environment. W...
[ "\n A fiddlin' little function that has an 'import SCons.Environment' which\n can't be moved to the top level without creating an import loop. Since\n this import creates a local variable named 'SCons', it blocks access to\n the global variable, so we move it here to prevent complaints about local\n ...
Please provide a description of the function:def _subproc(scons_env, cmd, error = 'ignore', **kw): # allow std{in,out,err} to be "'devnull'" io = kw.get('stdin') if is_String(io) and io == 'devnull': kw['stdin'] = open(os.devnull) io = kw.get('stdout') if is_String(io) and io == 'devnul...
[ "Do common setup for a subprocess.Popen() call\n\n This function is still in draft mode. We're going to need something like\n it in the long run as more and more places use subprocess, but I'm sure\n it'll have to be tweaked to get the full desired functionality.\n one special arg (so far?), 'error', t...
Please provide a description of the function:def print_cmd_line(self, s, target, source, env): try: sys.stdout.write(s + u"\n") except UnicodeDecodeError: sys.stdout.write(s + "\n")
[ "\n In python 3, and in some of our tests, sys.stdout is\n a String io object, and it takes unicode strings only\n In other cases it's a regular Python 2.x file object\n which takes strings (bytes), and if you pass those a\n unicode object they try to decode with 'ascii' codec\n ...
Please provide a description of the function:def execute(self, target, source, env, executor=None): escape_list = SCons.Subst.escape_list flatten_sequence = SCons.Util.flatten_sequence try: shell = env['SHELL'] except KeyError: raise SCons.Errors.UserErr...
[ "Execute a command action.\n\n This will handle lists of commands as well as individual commands,\n because construction variable substitution may turn a single\n \"command\" into a list. This means that this class can actually\n handle lists of commands, even though that's not how we u...
Please provide a description of the function:def get_presig(self, target, source, env, executor=None): from SCons.Subst import SUBST_SIG cmd = self.cmd_list if is_List(cmd): cmd = ' '.join(map(str, cmd)) else: cmd = str(cmd) if executor: ...
[ "Return the signature contents of this action's command line.\n\n This strips $(-$) and everything in between the string,\n since those parts don't affect signatures.\n " ]
Please provide a description of the function:def get_presig(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).get_presig(target, source, env)
[ "Return the signature contents of this action's command line.\n\n This strips $(-$) and everything in between the string,\n since those parts don't affect signatures.\n " ]
Please provide a description of the function:def get_presig(self, target, source, env): try: return self.gc(target, source, env) except AttributeError: return self.funccontents
[ "Return the signature contents of this callable action." ]
Please provide a description of the function:def get_presig(self, target, source, env): return b"".join([bytes(x.get_contents(target, source, env)) for x in self.list])
[ "Return the signature contents of this action list.\n\n Simple concatenation of the signatures of the elements.\n " ]
Please provide a description of the function:def generate(env): SCons.Tool.createStaticLibBuilder(env) if env.Detect('CC'): env['AR'] = 'CC' env['ARFLAGS'] = SCons.Util.CLVar('-ar') env['ARCOM'] = '$AR $ARFLAGS -o $TARGET $SOURCES' else: env['AR']...
[ "Add Builders and construction variables for ar to an Environment." ]
Please provide a description of the function:async def _notify_update(self, name, change_type, change_info=None, directed_client=None): for monitor in self._monitors: try: result = monitor(name, change_type, change_info, directed_client=directed_client) if i...
[ "Notify updates on a service to anyone who cares." ]
Please provide a description of the function:async def update_state(self, short_name, state): if short_name not in self.services: raise ArgumentError("Service name is unknown", short_name=short_name) if state not in states.KNOWN_STATES: raise ArgumentError("Invalid ser...
[ "Set the current state of a service.\n\n If the state is unchanged from a previous attempt, this routine does\n nothing.\n\n Args:\n short_name (string): The short name of the service\n state (int): The new stae of the service\n " ]
Please provide a description of the function:def add_service(self, name, long_name, preregistered=False, notify=True): if name in self.services: raise ArgumentError("Could not add service because the long_name is taken", long_name=long_name) serv_state = states.ServiceState(name, ...
[ "Add a service to the list of tracked services.\n\n Args:\n name (string): A unique short service name for the service\n long_name (string): A longer, user friendly name for the service\n preregistered (bool): Whether this service is an expected preregistered\n ...
Please provide a description of the function:def service_info(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) info = {} info['short_name'] = short_name info['long_name'] = self.services[short...
[ "Get static information about a service.\n\n Args:\n short_name (string): The short name of the service to query\n\n Returns:\n dict: A dictionary with the long_name and preregistered info\n on this service.\n " ]
Please provide a description of the function:def service_messages(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return list(self.services[short_name]['state'].messages)
[ "Get the messages stored for a service.\n\n Args:\n short_name (string): The short name of the service to get messages for\n\n Returns:\n list(ServiceMessage): A list of the ServiceMessages stored for this service\n " ]
Please provide a description of the function:def service_headline(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return self.services[short_name]['state'].headline
[ "Get the headline stored for a service.\n\n Args:\n short_name (string): The short name of the service to get messages for\n\n Returns:\n ServiceMessage: the headline or None if there is no headline\n " ]
Please provide a description of the function:def service_status(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) info = {} service = self.services[short_name]['state'] info['heartbeat_age'] ...
[ "Get the current status of a service.\n\n Returns information about the service such as the length since the last\n heartbeat, any status messages that have been posted about the service\n and whether the heartbeat should be considered out of the ordinary.\n\n Args:\n short_na...
Please provide a description of the function:async def send_message(self, name, level, message): if name not in self.services: raise ArgumentError("Unknown service name", short_name=name) msg = self.services[name]['state'].post_message(level, message) await self._notify_up...
[ "Post a message for a service.\n\n Args:\n name (string): The short name of the service to query\n level (int): The level of the message (info, warning, error)\n message (string): The message contents\n " ]
Please provide a description of the function:async def set_headline(self, name, level, message): if name not in self.services: raise ArgumentError("Unknown service name", short_name=name) self.services[name]['state'].set_headline(level, message) headline = self.services[n...
[ "Set the sticky headline for a service.\n\n Args:\n name (string): The short name of the service to query\n level (int): The level of the message (info, warning, error)\n message (string): The message contents\n " ]
Please provide a description of the function:async def send_heartbeat(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) self.services[short_name]['state'].heartbeat() await self._notify_update(short_na...
[ "Post a heartbeat for a service.\n\n Args:\n short_name (string): The short name of the service to query\n " ]
Please provide a description of the function:def set_agent(self, short_name, client_id): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) self.agents[short_name] = client_id
[ "Register a client id that handlers commands for a service.\n\n Args:\n short_name (str): The name of the service to set an agent\n for.\n client_id (str): A globally unique id for the client that\n should receive commands for this service.\n " ]
Please provide a description of the function:def clear_agent(self, short_name, client_id): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) if short_name not in self.agents: raise ArgumentError("No agent registered ...
[ "Remove a client id from being the command handler for a service.\n\n Args:\n short_name (str): The name of the service to set an agent\n for.\n client_id (str): A globally unique id for the client that\n should no longer receive commands for this service.\...
Please provide a description of the function:async def send_rpc_command(self, short_name, rpc_id, payload, sender_client, timeout=1.0): rpc_tag = str(uuid.uuid4()) self.rpc_results.declare(rpc_tag) if short_name in self.services and short_name in self.agents: agent_tag =...
[ "Send an RPC to a service using its registered agent.\n\n Args:\n short_name (str): The name of the service we would like to send\n and RPC to\n rpc_id (int): The rpc id that we would like to call\n payload (bytes): The raw bytes that we would like to send as a...
Please provide a description of the function:def send_rpc_response(self, rpc_tag, result, response): if rpc_tag not in self.in_flight_rpcs: raise ArgumentError("In flight RPC could not be found, it may have timed out", rpc_tag=rpc_tag) del self.in_flight_rpcs[rpc_tag] res...
[ "Send a response to an RPC.\n\n Args:\n rpc_tag (str): The exact string given in a previous call to send_rpc_command\n result (str): The result of the operation. The possible values of response are:\n service_not_found, rpc_not_found, timeout, success, invalid_response,\...
Please provide a description of the function:def periodic_service_rpcs(self): to_remove = [] now = monotonic() for rpc_tag, rpc in self.in_flight_rpcs.items(): expiry = rpc.sent_timestamp + rpc.timeout if now > expiry: to_remove.append(rpc_tag) ...
[ "Check if any RPC has expired and remove it from the in flight list.\n\n This function should be called periodically to expire any RPCs that never complete.\n " ]
Please provide a description of the function:def PackageVariable(key, help, default, searchfunc=None): # NB: searchfunc is currently undocumented and unsupported help = '\n '.join( (help, '( yes | no | /path/to/%s )' % key)) return (key, help, default, lambda k, v, e: _validator(...
[ "\n The input parameters describe a 'package list' option, thus they\n are returned with the correct converter and validator appended. The\n result is usable for input to opts.Add() .\n\n A 'package list' option may either be 'all', 'none' or a list of\n package names (separated by space).\n " ]
Please provide a description of the function:def settings_directory(): system = platform.system() basedir = None if system == 'Windows': if 'APPDATA' in os.environ: basedir = os.environ['APPDATA'] # If we're not on Windows assume we're on some # kind of posix system or M...
[ "Find a per user settings directory that is appropriate for each\n type of system that we are installed on.\n " ]
Please provide a description of the function:def generate(env): global GhostscriptAction # The following try-except block enables us to use the Tool # in standalone mode (without the accompanying pdf.py), # whenever we need an explicit call of gs via the Gs() # Builder ... try: if G...
[ "Add Builders and construction variables for Ghostscript to an\n Environment." ]
Please provide a description of the function:def resource_path(relative_path=None, expect=None): if expect not in (None, 'file', 'folder'): raise ArgumentError("Invalid expect parameter, must be None, 'file' or 'folder'", expect=expect) this_dir = os.path.dirname(__fil...
[ "Return the absolute path to a resource in iotile-build.\n\n This method finds the path to the `config` folder inside\n iotile-build, appends `relative_path` to it and then\n checks to make sure the desired file or directory exists.\n\n You can specify expect=(None, 'file', or 'folder') for\n what yo...
Please provide a description of the function:def unpack(fmt, arg): if isinstance(arg, bytearray) and not (sys.version_info >= (2, 7, 5)): return struct.unpack(fmt, str(arg)) return struct.unpack(fmt, arg)
[ "A shim around struct.unpack to allow it to work on python 2.7.3." ]
Please provide a description of the function:async def initialize(self, timeout=2.0): if self.initialized.is_set(): raise InternalError("initialize called when already initialized") self._emulator.add_task(8, self._reset_vector()) await asyncio.wait_for(self.initialized.w...
[ "Launch any background tasks associated with this subsystem.\n\n This method will synchronously await self.initialized() which makes\n sure that the background tasks start up correctly.\n " ]
Please provide a description of the function:def _check_registry_type(folder=None): folder = _registry_folder(folder) default_file = os.path.join(folder, 'registry_type.txt') try: with open(default_file, "r") as infile: data = infile.read() data = data.strip() ...
[ "Check if the user has placed a registry_type.txt file to choose the registry type\n\n If a default registry type file is found, the DefaultBackingType and DefaultBackingFile\n class parameters in ComponentRegistry are updated accordingly.\n\n Args:\n folder (string): The folder that we should check...
Please provide a description of the function:def _ensure_package_loaded(path, component): logger = logging.getLogger(__name__) packages = component.find_products('support_package') if len(packages) == 0: return None elif len(packages) > 1: raise ExternalError("Component had multip...
[ "Ensure that the given module is loaded as a submodule.\n\n Returns:\n str: The name that the module should be imported as.\n " ]
Please provide a description of the function:def _try_load_module(path, import_name=None): logger = logging.getLogger(__name__) obj_name = None if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths path, _, obj_name = path.rpartition(":") folder, basename = os.path.sp...
[ "Try to programmatically load a python module by path.\n\n Path should point to a python file (optionally without the .py) at the\n end. If it ends in a :<name> then name must point to an object defined in\n the module, which is returned instead of the module itself.\n\n Args:\n path (str): The ...
Please provide a description of the function:def frozen(self): frozen_path = os.path.join(_registry_folder(), 'frozen_extensions.json') return os.path.isfile(frozen_path)
[ "Return whether we have a cached list of all installed entry_points." ]
Please provide a description of the function:def kvstore(self): if self._kvstore is None: self._kvstore = self.BackingType(self.BackingFileName, respect_venv=True) return self._kvstore
[ "Lazily load the underlying key-value store backing this registry." ]
Please provide a description of the function:def plugins(self): if self._plugins is None: self._plugins = {} for _, plugin in self.load_extensions('iotile.plugin'): links = plugin() for name, value in links: self._plugins[nam...
[ "Lazily load iotile plugins only on demand.\n\n This is a slow operation on computers with a slow FS and is rarely\n accessed information, so only compute it when it is actually asked\n for.\n " ]
Please provide a description of the function:def load_extensions(self, group, name_filter=None, comp_filter=None, class_filter=None, product_name=None, unique=False): found_extensions = [] if product_name is not None: for comp in self.iter_components(): if comp_fil...
[ "Dynamically load and return extension objects of a given type.\n\n This is the centralized way for all parts of CoreTools to allow plugin\n behavior. Whenever a plugin is needed, this method should be called\n to load it. Examples of plugins are proxy modules, emulated tiles,\n iotile...
Please provide a description of the function:def register_extension(self, group, name, extension): if isinstance(extension, str): name, extension = self.load_extension(extension)[0] if group not in self._registered_extensions: self._registered_extensions[group] = [] ...
[ "Register an extension.\n\n Args:\n group (str): The type of the extension\n name (str): A name for the extension\n extension (str or class): If this is a string, then it will be\n interpreted as a path to import and load. Otherwise it\n will be...
Please provide a description of the function:def clear_extensions(self, group=None): if group is None: ComponentRegistry._registered_extensions = {} return if group in self._registered_extensions: self._registered_extensions[group] = []
[ "Clear all previously registered extensions." ]
Please provide a description of the function:def freeze_extensions(self): output_path = os.path.join(_registry_folder(), 'frozen_extensions.json') with open(output_path, "w") as outfile: json.dump(self._dump_extensions(), outfile)
[ "Freeze the set of extensions into a single file.\n\n Freezing extensions can speed up the extension loading process on\n machines with slow file systems since it requires only a single file\n to store all of the extensions.\n\n Calling this method will save a file into the current virtu...
Please provide a description of the function:def unfreeze_extensions(self): output_path = os.path.join(_registry_folder(), 'frozen_extensions.json') if not os.path.isfile(output_path): raise ExternalError("There is no frozen extension list") os.remove(output_path) ...
[ "Remove a previously frozen list of extensions." ]
Please provide a description of the function:def load_extension(self, path, name_filter=None, class_filter=None, unique=False, component=None): import_name = None if component is not None: import_name = _ensure_package_loaded(path, component) name, ext = _try_load_module(p...
[ "Load a single python module extension.\n\n This function is similar to using the imp module directly to load a\n module and potentially inspecting the objects it declares to filter\n them by class.\n\n Args:\n path (str): The path to the python file to load\n name_...
Please provide a description of the function:def _filter_nonextensions(cls, obj): # Not all objects have __dict__ attributes. For example, tuples don't. # and tuples are used in iotile.build for some entry points. if hasattr(obj, '__dict__') and obj.__dict__.get('__NO_EXTENSION__', Fa...
[ "Remove all classes marked as not extensions.\n\n This allows us to have a deeper hierarchy of classes than just\n one base class that is filtered by _filter_subclasses. Any\n class can define a class propery named:\n\n __NO_EXTENSION__ = True\n\n That class will never be returne...
Please provide a description of the function:def SetBackingStore(cls, backing): if backing not in ['json', 'sqlite', 'memory']: raise ArgumentError("Unknown backing store type that is not json or sqlite", backing=backing) if backing == 'json': cls.BackingType = JSONKVS...
[ "Set the global backing type used by the ComponentRegistry from this point forward\n\n This function must be called before any operations that use the registry are initiated\n otherwise they will work from different registries that will likely contain different data\n " ]
Please provide a description of the function:def add_component(self, component, temporary=False): tile = IOTile(component) value = os.path.normpath(os.path.abspath(component)) if temporary is True: self._component_overlays[tile.name] = value else: self....
[ "Register a component with ComponentRegistry.\n\n Component must be a buildable object with a module_settings.json file\n that describes its name and the domain that it is part of. By\n default, this component is saved in the permanent registry associated\n with this environment and wil...
Please provide a description of the function:def list_plugins(self): vals = self.plugins.items() return {x: y for x, y in vals}
[ "\n List all of the plugins that have been registerd for the iotile program on this computer\n " ]
Please provide a description of the function:def clear_components(self): ComponentRegistry._component_overlays = {} for key in self.list_components(): self.remove_component(key)
[ "Clear all of the registered components\n " ]
Please provide a description of the function:def list_components(self): overlays = list(self._component_overlays) items = self.kvstore.get_all() return overlays + [x[0] for x in items if not x[0].startswith('config:')]
[ "List all of the registered component names.\n\n This list will include all of the permanently stored components as\n well as any temporary components that were added with a temporary=True\n flag in this session.\n\n Returns:\n list of str: The list of component names.\n\n ...
Please provide a description of the function:def iter_components(self): names = self.list_components() for name in names: yield self.get_component(name)
[ "Iterate over all defined components yielding IOTile objects." ]
Please provide a description of the function:def list_config(self): items = self.kvstore.get_all() return ["{0}={1}".format(x[0][len('config:'):], x[1]) for x in items if x[0].startswith('config:')]
[ "List all of the configuration variables\n " ]
Please provide a description of the function:def set_config(self, key, value): keyname = "config:" + key self.kvstore.set(keyname, value)
[ "Set a persistent config key to a value, stored in the registry\n\n Args:\n key (string): The key name\n value (string): The key value\n " ]
Please provide a description of the function:def get_config(self, key, default=MISSING): keyname = "config:" + key try: return self.kvstore.get(keyname) except KeyError: if default is MISSING: raise ArgumentError("No config value found for key",...
[ "Get the value of a persistent config key from the registry\n\n If no default is specified and the key is not found ArgumentError is raised.\n\n Args:\n key (string): The key name to fetch\n default (string): an optional value to be returned if key cannot be found\n\n Retu...
Please provide a description of the function:def execute_action_list(obj, target, kw): env = obj.get_build_env() kw = obj.get_kw(kw) status = 0 for act in obj.get_action_list(): args = ([], [], env) status = act(*args, **kw) if isinstance(status, SCons.Errors.BuildError): ...
[ "Actually execute the action list." ]
Please provide a description of the function:def get_all_targets(self): result = [] for batch in self.batches: result.extend(batch.targets) return result
[ "Returns all targets for all batches of this Executor." ]
Please provide a description of the function:def get_all_sources(self): result = [] for batch in self.batches: result.extend(batch.sources) return result
[ "Returns all sources for all batches of this Executor." ]