idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
21,500 | def get_nowait ( self , name , default = _MISSING , autoremove = False ) : self . _ensure_declared ( name ) try : future = self . _data [ name ] if future . done ( ) : return future . result ( ) if default is _MISSING : raise KeyError ( "Key {} has not been assigned a value and no default given" . format ( name ) ) return default finally : if autoremove : self . _data [ name ] . cancel ( ) del self . _data [ name ] | Get the value of a key if it is already set . | 119 | 12 |
21,501 | def set ( self , name , value , autodeclare = False ) : if not autodeclare and name not in self . _data : raise KeyError ( "Key {} has not been declared and autodeclare=False" . format ( name ) ) self . _ensure_declared ( name ) self . _data [ name ] . set_result ( value ) | Set the value of a key . | 82 | 7 |
21,502 | def dump_tree ( self , statement = None , indent_level = 0 ) : out = u"" indent = u" " * indent_level if statement is None : for root_statement in self . statements : out += self . dump_tree ( root_statement , indent_level ) else : out += indent + str ( statement ) + u'\n' if len ( statement . children ) > 0 : for child in statement . children : out += self . dump_tree ( child , indent_level = indent_level + 4 ) return out | Dump the AST for this parsed file . | 116 | 9 |
21,503 | def parse_file ( self , sg_file = None , data = None ) : if sg_file is not None and data is not None : raise ArgumentError ( "You must pass either a path to an sgf file or the sgf contents but not both" ) if sg_file is None and data is None : raise ArgumentError ( "You must pass either a path to an sgf file or the sgf contents, neither passed" ) if sg_file is not None : try : with open ( sg_file , "r" ) as inf : data = inf . read ( ) except IOError : raise ArgumentError ( "Could not read sensor graph file" , path = sg_file ) # convert tabs to spaces so our line numbers match correctly data = data . replace ( u'\t' , u' ' ) lang = get_language ( ) result = lang . parseString ( data ) for statement in result : parsed = self . parse_statement ( statement , orig_contents = data ) self . statements . append ( parsed ) | Parse a sensor graph file into an AST describing the file . | 231 | 13 |
21,504 | def compile ( self , model ) : log = SensorLog ( InMemoryStorageEngine ( model ) , model ) self . sensor_graph = SensorGraph ( log , model ) allocator = StreamAllocator ( self . sensor_graph , model ) self . _scope_stack = [ ] # Create a root scope root = RootScope ( self . sensor_graph , allocator ) self . _scope_stack . append ( root ) for statement in self . statements : statement . execute ( self . sensor_graph , self . _scope_stack ) self . sensor_graph . initialize_remaining_constants ( ) self . sensor_graph . sort_nodes ( ) | Compile this file into a SensorGraph . | 142 | 9 |
21,505 | def parse_statement ( self , statement , orig_contents ) : children = [ ] is_block = False name = statement . getName ( ) # Recursively parse all children statements in a block # before parsing the block itself. # If this is a non-block statement, parse it using the statement # parser to figure out what specific statement it is before # processing it further. # This two step process produces better syntax error messsages if name == 'block' : children_statements = statement [ 1 ] for child in children_statements : parsed = self . parse_statement ( child , orig_contents = orig_contents ) children . append ( parsed ) locn = statement [ 0 ] [ 'location' ] statement = statement [ 0 ] [ 1 ] name = statement . getName ( ) is_block = True else : stmt_language = get_statement ( ) locn = statement [ 'location' ] statement = statement [ 'match' ] statement_string = str ( u"" . join ( statement . asList ( ) ) ) # Try to parse this generic statement into an actual statement. # Do this here in a separate step so we have good error messages when there # is a problem parsing a step. try : statement = stmt_language . parseString ( statement_string ) [ 0 ] except ( pyparsing . ParseException , pyparsing . ParseSyntaxException ) as exc : raise SensorGraphSyntaxError ( "Error parsing statement in sensor graph file" , message = exc . msg , line = pyparsing . line ( locn , orig_contents ) . strip ( ) , line_number = pyparsing . lineno ( locn , orig_contents ) , column = pyparsing . col ( locn , orig_contents ) ) except SensorGraphSemanticError as exc : # Reraise semantic errors with line information raise SensorGraphSemanticError ( exc . msg , line = pyparsing . line ( locn , orig_contents ) . strip ( ) , line_number = pyparsing . lineno ( locn , orig_contents ) , * * exc . params ) name = statement . getName ( ) if name not in statement_map : raise ArgumentError ( "Unknown statement in sensor graph file" , parsed_statement = statement , name = name ) # Save off our location information so we can give good error and warning information line = pyparsing . line ( locn , orig_contents ) . strip ( ) line_number = pyparsing . lineno ( locn , orig_contents ) column = pyparsing . col ( locn , orig_contents ) location_info = LocationInfo ( line , line_number , column ) if is_block : return statement_map [ name ] ( statement , children = children , location = location_info ) return statement_map [ name ] ( statement , location_info ) | Parse a statement possibly called recursively . | 633 | 10 |
21,506 | def stream ( self , report , callback = None ) : if self . _push_channel is None : return self . _push_channel . stream ( report , callback = callback ) | Stream a report asynchronously . | 38 | 7 |
21,507 | def stream_realtime ( self , stream , value ) : if not self . stream_iface_open : return reading = IOTileReading ( 0 , stream , value ) report = IndividualReadingReport . FromReadings ( self . iotile_id , [ reading ] ) self . stream ( report ) | Stream a realtime value as an IndividualReadingReport . | 66 | 11 |
21,508 | def trace ( self , data , callback = None ) : if self . _push_channel is None : return self . _push_channel . trace ( data , callback = callback ) | Trace data asynchronously . | 38 | 7 |
21,509 | def register_rpc ( self , address , rpc_id , func ) : if rpc_id < 0 or rpc_id > 0xFFFF : raise RPCInvalidIDError ( "Invalid RPC ID: {}" . format ( rpc_id ) ) if address not in self . _rpc_overlays : self . _rpc_overlays [ address ] = RPCDispatcher ( ) self . _rpc_overlays [ address ] . add_rpc ( rpc_id , func ) | Register a single RPC handler with the given info . | 115 | 10 |
21,510 | def add_tile ( self , address , tile ) : if address in self . _tiles : raise ArgumentError ( "Tried to add two tiles at the same address" , address = address ) self . _tiles [ address ] = tile | Add a tile to handle all RPCs at a given address . | 52 | 13 |
21,511 | def iter_tiles ( self , include_controller = True ) : for address , tile in sorted ( self . _tiles . items ( ) ) : if address == 8 and not include_controller : continue yield address , tile | Iterate over all tiles in this device in order . | 48 | 11 |
21,512 | def open_streaming_interface ( self ) : super ( ReferenceDevice , self ) . open_streaming_interface ( ) self . rpc ( 8 , rpcs . SG_GRAPH_INPUT , 8 , streams . COMM_TILE_OPEN ) return [ ] | Called when someone opens a streaming interface to the device . | 61 | 12 |
21,513 | def close_streaming_interface ( self ) : super ( ReferenceDevice , self ) . close_streaming_interface ( ) self . rpc ( 8 , rpcs . SG_GRAPH_INPUT , 8 , streams . COMM_TILE_CLOSED ) | Called when someone closes the streaming interface to the device . | 58 | 12 |
21,514 | def build_parser ( ) : parser = argparse . ArgumentParser ( description = "The IOTile task supervisor" ) parser . add_argument ( '-c' , '--config' , help = "config json with options" ) parser . add_argument ( '-v' , '--verbose' , action = "count" , default = 0 , help = "Increase logging verbosity" ) return parser | Build the script s argument parser . | 89 | 7 |
21,515 | def configure_logging ( verbosity ) : root = logging . getLogger ( ) formatter = logging . Formatter ( '%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s' , '%y-%m-%d %H:%M:%S' ) handler = logging . StreamHandler ( ) handler . setFormatter ( formatter ) loglevels = [ logging . CRITICAL , logging . ERROR , logging . WARNING , logging . INFO , logging . DEBUG ] if verbosity >= len ( loglevels ) : verbosity = len ( loglevels ) - 1 level = loglevels [ verbosity ] root . setLevel ( level ) root . addHandler ( handler ) | Set up the global logging level . | 175 | 7 |
21,516 | def createProgBuilder ( env ) : try : program = env [ 'BUILDERS' ] [ 'Program' ] except KeyError : import SCons . Defaults program = SCons . Builder . Builder ( action = SCons . Defaults . LinkAction , emitter = '$PROGEMITTER' , prefix = '$PROGPREFIX' , suffix = '$PROGSUFFIX' , src_suffix = '$OBJSUFFIX' , src_builder = 'Object' , target_scanner = ProgramScanner ) env [ 'BUILDERS' ] [ 'Program' ] = program return program | This is a utility function that creates the Program Builder in an Environment if it is not there already . | 138 | 20 |
21,517 | def createStaticLibBuilder ( env ) : try : static_lib = env [ 'BUILDERS' ] [ 'StaticLibrary' ] except KeyError : action_list = [ SCons . Action . Action ( "$ARCOM" , "$ARCOMSTR" ) ] if env . get ( 'RANLIB' , False ) or env . Detect ( 'ranlib' ) : ranlib_action = SCons . Action . Action ( "$RANLIBCOM" , "$RANLIBCOMSTR" ) action_list . append ( ranlib_action ) static_lib = SCons . Builder . Builder ( action = action_list , emitter = '$LIBEMITTER' , prefix = '$LIBPREFIX' , suffix = '$LIBSUFFIX' , src_suffix = '$OBJSUFFIX' , src_builder = 'StaticObject' ) env [ 'BUILDERS' ] [ 'StaticLibrary' ] = static_lib env [ 'BUILDERS' ] [ 'Library' ] = static_lib return static_lib | This is a utility function that creates the StaticLibrary Builder in an Environment if it is not there already . | 231 | 21 |
21,518 | def createSharedLibBuilder ( env ) : try : shared_lib = env [ 'BUILDERS' ] [ 'SharedLibrary' ] except KeyError : import SCons . Defaults action_list = [ SCons . Defaults . SharedCheck , SCons . Defaults . ShLinkAction , LibSymlinksAction ] shared_lib = SCons . Builder . Builder ( action = action_list , emitter = "$SHLIBEMITTER" , prefix = ShLibPrefixGenerator , suffix = ShLibSuffixGenerator , target_scanner = ProgramScanner , src_suffix = '$SHOBJSUFFIX' , src_builder = 'SharedObject' ) env [ 'BUILDERS' ] [ 'SharedLibrary' ] = shared_lib return shared_lib | This is a utility function that creates the SharedLibrary Builder in an Environment if it is not there already . | 175 | 21 |
21,519 | def createLoadableModuleBuilder ( env ) : try : ld_module = env [ 'BUILDERS' ] [ 'LoadableModule' ] except KeyError : import SCons . Defaults action_list = [ SCons . Defaults . SharedCheck , SCons . Defaults . LdModuleLinkAction , LibSymlinksAction ] ld_module = SCons . Builder . Builder ( action = action_list , emitter = "$LDMODULEEMITTER" , prefix = LdModPrefixGenerator , suffix = LdModSuffixGenerator , target_scanner = ProgramScanner , src_suffix = '$SHOBJSUFFIX' , src_builder = 'SharedObject' ) env [ 'BUILDERS' ] [ 'LoadableModule' ] = ld_module return ld_module | This is a utility function that creates the LoadableModule Builder in an Environment if it is not there already . | 183 | 22 |
21,520 | def createObjBuilders ( env ) : try : static_obj = env [ 'BUILDERS' ] [ 'StaticObject' ] except KeyError : static_obj = SCons . Builder . Builder ( action = { } , emitter = { } , prefix = '$OBJPREFIX' , suffix = '$OBJSUFFIX' , src_builder = [ 'CFile' , 'CXXFile' ] , source_scanner = SourceFileScanner , single_source = 1 ) env [ 'BUILDERS' ] [ 'StaticObject' ] = static_obj env [ 'BUILDERS' ] [ 'Object' ] = static_obj try : shared_obj = env [ 'BUILDERS' ] [ 'SharedObject' ] except KeyError : shared_obj = SCons . Builder . Builder ( action = { } , emitter = { } , prefix = '$SHOBJPREFIX' , suffix = '$SHOBJSUFFIX' , src_builder = [ 'CFile' , 'CXXFile' ] , source_scanner = SourceFileScanner , single_source = 1 ) env [ 'BUILDERS' ] [ 'SharedObject' ] = shared_obj return ( static_obj , shared_obj ) | This is a utility function that creates the StaticObject and SharedObject Builders in an Environment if they are not there already . | 276 | 25 |
21,521 | def CreateJarBuilder ( env ) : try : java_jar = env [ 'BUILDERS' ] [ 'JarFile' ] except KeyError : fs = SCons . Node . FS . get_default_fs ( ) jar_com = SCons . Action . Action ( '$JARCOM' , '$JARCOMSTR' ) java_jar = SCons . Builder . Builder ( action = jar_com , suffix = '$JARSUFFIX' , src_suffix = '$JAVACLASSSUFFIX' , src_builder = 'JavaClassFile' , source_factory = fs . Entry ) env [ 'BUILDERS' ] [ 'JarFile' ] = java_jar return java_jar | The Jar builder expects a list of class files which it can package into a jar file . | 160 | 18 |
21,522 | def get_builder ( self , env ) : builder = getattr ( env , self . __name__ ) self . initializer . apply_tools ( env ) builder = getattr ( env , self . __name__ ) if builder is self : # There was no Builder added, which means no valid Tool # for this name was found (or possibly there's a mismatch # between the name we were called by and the Builder name # added by the Tool module). return None self . initializer . remove_methods ( env ) return builder | Returns the appropriate real Builder for this method name after having the associated ToolInitializer object apply the appropriate Tool module . | 112 | 23 |
21,523 | def remove_methods ( self , env ) : for method in list ( self . methods . values ( ) ) : env . RemoveMethod ( method ) | Removes the methods that were added by the tool initialization so we no longer copy and re - bind them when the construction environment gets cloned . | 32 | 29 |
21,524 | def apply_tools ( self , env ) : for t in self . tools : tool = SCons . Tool . Tool ( t ) if tool . exists ( env ) : env . Tool ( tool ) return | Searches the list of associated Tool modules for one that exists and applies that to the construction environment . | 43 | 21 |
21,525 | def get_contents_entry ( node ) : try : node = node . disambiguate ( must_exist = 1 ) except SCons . Errors . UserError : # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_contents() in emitters and the # like (e.g. in qt.py) don't have to disambiguate by hand # or catch the exception. return '' else : return _get_contents_map [ node . _func_get_contents ] ( node ) | Fetch the contents of the entry . Returns the exact binary contents of the file . | 134 | 17 |
21,526 | def get_contents_dir ( node ) : contents = [ ] for n in sorted ( node . children ( ) , key = lambda t : t . name ) : contents . append ( '%s %s\n' % ( n . get_csig ( ) , n . name ) ) return '' . join ( contents ) | Return content signatures and names of all our children separated by new - lines . Ensure that the nodes are sorted . | 71 | 22 |
21,527 | def get_build_env ( self ) : try : return self . _memo [ 'get_build_env' ] except KeyError : pass result = self . get_executor ( ) . get_build_env ( ) self . _memo [ 'get_build_env' ] = result return result | Fetch the appropriate Environment to build this node . | 68 | 10 |
21,528 | def get_executor ( self , create = 1 ) : try : executor = self . executor except AttributeError : if not create : raise try : act = self . builder . action except AttributeError : executor = SCons . Executor . Null ( targets = [ self ] ) else : executor = SCons . Executor . Executor ( act , self . env or self . builder . env , [ self . builder . overrides ] , [ self ] , self . sources ) self . executor = executor return executor | Fetch the action executor for this node . Create one if there isn t already one and requested to do so . | 116 | 24 |
21,529 | def executor_cleanup ( self ) : try : executor = self . get_executor ( create = None ) except AttributeError : pass else : if executor is not None : executor . cleanup ( ) | Let the executor clean up any cached information . | 47 | 10 |
21,530 | def prepare ( self ) : if self . depends is not None : for d in self . depends : if d . missing ( ) : msg = "Explicit dependency `%s' not found, needed by target `%s'." raise SCons . Errors . StopError ( msg % ( d , self ) ) if self . implicit is not None : for i in self . implicit : if i . missing ( ) : msg = "Implicit dependency `%s' not found, needed by target `%s'." raise SCons . Errors . StopError ( msg % ( i , self ) ) self . binfo = self . get_binfo ( ) | Prepare for this Node to be built . | 137 | 9 |
21,531 | def build ( self , * * kw ) : try : self . get_executor ( ) ( self , * * kw ) except SCons . Errors . BuildError as e : e . node = self raise | Actually build the node . | 46 | 5 |
21,532 | def built ( self ) : # Clear the implicit dependency caches of any Nodes # waiting for this Node to be built. for parent in self . waiting_parents : parent . implicit = None self . clear ( ) if self . pseudo : if self . exists ( ) : raise SCons . Errors . UserError ( "Pseudo target " + str ( self ) + " must not exist" ) else : if not self . exists ( ) and do_store_info : SCons . Warnings . warn ( SCons . Warnings . TargetNotBuiltWarning , "Cannot find target " + str ( self ) + " after building" ) self . ninfo . update ( self ) | Called just after this node is successfully built . | 144 | 10 |
21,533 | def has_builder ( self ) : try : b = self . builder except AttributeError : # There was no explicit builder for this Node, so initialize # the self.builder attribute to None now. b = self . builder = None return b is not None | Return whether this Node has a builder or not . | 54 | 10 |
21,534 | def get_implicit_deps ( self , env , initial_scanner , path_func , kw = { } ) : nodes = [ self ] seen = set ( nodes ) dependencies = [ ] path_memo = { } root_node_scanner = self . _get_scanner ( env , initial_scanner , None , kw ) while nodes : node = nodes . pop ( 0 ) scanner = node . _get_scanner ( env , initial_scanner , root_node_scanner , kw ) if not scanner : continue try : path = path_memo [ scanner ] except KeyError : path = path_func ( scanner ) path_memo [ scanner ] = path included_deps = [ x for x in node . get_found_includes ( env , scanner , path ) if x not in seen ] if included_deps : dependencies . extend ( included_deps ) seen . update ( included_deps ) nodes . extend ( scanner . recurse_nodes ( included_deps ) ) return dependencies | Return a list of implicit dependencies for this node . | 227 | 10 |
21,535 | def get_source_scanner ( self , node ) : scanner = None try : scanner = self . builder . source_scanner except AttributeError : pass if not scanner : # The builder didn't have an explicit scanner, so go look up # a scanner from env['SCANNERS'] based on the node's scanner # key (usually the file extension). scanner = self . get_env_scanner ( self . get_build_env ( ) ) if scanner : scanner = scanner . select ( node ) return scanner | Fetch the source scanner for the specified node | 110 | 9 |
21,536 | def scan ( self ) : # Don't bother scanning non-derived files, because we don't # care what their dependencies are. # Don't scan again, if we already have scanned. if self . implicit is not None : return self . implicit = [ ] self . implicit_set = set ( ) self . _children_reset ( ) if not self . has_builder ( ) : return build_env = self . get_build_env ( ) executor = self . get_executor ( ) # Here's where we implement --implicit-cache. if implicit_cache and not implicit_deps_changed : implicit = self . get_stored_implicit ( ) if implicit is not None : # We now add the implicit dependencies returned from the # stored .sconsign entry to have already been converted # to Nodes for us. (We used to run them through a # source_factory function here.) # Update all of the targets with them. This # essentially short-circuits an N*M scan of the # sources for each individual target, which is a hell # of a lot more efficient. for tgt in executor . get_all_targets ( ) : tgt . add_to_implicit ( implicit ) if implicit_deps_unchanged or self . is_up_to_date ( ) : return # one of this node's sources has changed, # so we must recalculate the implicit deps for all targets for tgt in executor . get_all_targets ( ) : tgt . implicit = [ ] tgt . implicit_set = set ( ) # Have the executor scan the sources. executor . scan_sources ( self . builder . source_scanner ) # If there's a target scanner, have the executor scan the target # node itself and associated targets that might be built. scanner = self . get_target_scanner ( ) if scanner : executor . scan_targets ( scanner ) | Scan this node s dependents for implicit dependencies . | 423 | 10 |
21,537 | def get_binfo ( self ) : try : return self . binfo except AttributeError : pass binfo = self . new_binfo ( ) self . binfo = binfo executor = self . get_executor ( ) ignore_set = self . ignore_set if self . has_builder ( ) : binfo . bact = str ( executor ) binfo . bactsig = SCons . Util . MD5signature ( executor . get_contents ( ) ) if self . _specific_sources : sources = [ s for s in self . sources if not s in ignore_set ] else : sources = executor . get_unignored_sources ( self , self . ignore ) seen = set ( ) binfo . bsources = [ s for s in sources if s not in seen and not seen . add ( s ) ] binfo . bsourcesigs = [ s . get_ninfo ( ) for s in binfo . bsources ] binfo . bdepends = self . depends binfo . bdependsigs = [ d . get_ninfo ( ) for d in self . depends if d not in ignore_set ] binfo . bimplicit = self . implicit or [ ] binfo . bimplicitsigs = [ i . get_ninfo ( ) for i in binfo . bimplicit if i not in ignore_set ] return binfo | Fetch a node s build information . | 308 | 8 |
21,538 | def add_dependency ( self , depend ) : try : self . _add_child ( self . depends , self . depends_set , depend ) except TypeError as e : e = e . args [ 0 ] if SCons . Util . is_List ( e ) : s = list ( map ( str , e ) ) else : s = str ( e ) raise SCons . Errors . UserError ( "attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % ( str ( self ) , s , type ( e ) ) ) | Adds dependencies . | 132 | 3 |
21,539 | def add_ignore ( self , depend ) : try : self . _add_child ( self . ignore , self . ignore_set , depend ) except TypeError as e : e = e . args [ 0 ] if SCons . Util . is_List ( e ) : s = list ( map ( str , e ) ) else : s = str ( e ) raise SCons . Errors . UserError ( "attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % ( str ( self ) , s , type ( e ) ) ) | Adds dependencies to ignore . | 131 | 5 |
21,540 | def add_source ( self , source ) : if self . _specific_sources : return try : self . _add_child ( self . sources , self . sources_set , source ) except TypeError as e : e = e . args [ 0 ] if SCons . Util . is_List ( e ) : s = list ( map ( str , e ) ) else : s = str ( e ) raise SCons . Errors . UserError ( "attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % ( str ( self ) , s , type ( e ) ) ) | Adds sources . | 142 | 3 |
21,541 | def _add_child ( self , collection , set , child ) : added = None for c in child : if c not in set : set . add ( c ) collection . append ( c ) added = 1 if added : self . _children_reset ( ) | Adds child to collection first checking set to see if it s already present . | 55 | 15 |
21,542 | def all_children ( self , scan = 1 ) : if scan : self . scan ( ) # The return list may contain duplicate Nodes, especially in # source trees where there are a lot of repeated #includes # of a tangle of .h files. Profiling shows, however, that # eliminating the duplicates with a brute-force approach that # preserves the order (that is, something like: # # u = [] # for n in list: # if n not in u: # u.append(n)" # # takes more cycles than just letting the underlying methods # hand back cached values if a Node's information is requested # multiple times. (Other methods of removing duplicates, like # using dictionary keys, lose the order, and the only ordered # dictionary patterns I found all ended up using "not in" # internally anyway...) return list ( chain . from_iterable ( [ _f for _f in [ self . sources , self . depends , self . implicit ] if _f ] ) ) | Return a list of all the node s direct children . | 211 | 11 |
21,543 | def Tag ( self , key , value ) : if not self . _tags : self . _tags = { } self . _tags [ key ] = value | Add a user - defined tag . | 33 | 7 |
21,544 | def render_include_tree ( self ) : if self . is_derived ( ) : env = self . get_build_env ( ) if env : for s in self . sources : scanner = self . get_source_scanner ( s ) if scanner : path = self . get_build_scanner_path ( scanner ) else : path = None def f ( node , env = env , scanner = scanner , path = path ) : return node . get_found_includes ( env , scanner , path ) return SCons . Util . render_tree ( s , f , 1 ) else : return None | Return a text representation suitable for displaying to the user of the include tree for the sources of this node . | 130 | 21 |
21,545 | def get_next ( self ) : while self . stack : if self . stack [ - 1 ] . wkids : node = self . stack [ - 1 ] . wkids . pop ( 0 ) if not self . stack [ - 1 ] . wkids : self . stack [ - 1 ] . wkids = None if node in self . history : self . cycle_func ( node , self . stack ) else : node . wkids = copy . copy ( self . kids_func ( node , self . stack [ - 1 ] ) ) self . stack . append ( node ) self . history [ node ] = None else : node = self . stack . pop ( ) del self . history [ node ] if node : if self . stack : parent = self . stack [ - 1 ] else : parent = None self . eval_func ( node , parent ) return node return None | Return the next node for this walk of the tree . | 184 | 11 |
21,546 | def timeout_thread_handler ( timeout , stop_event ) : stop_happened = stop_event . wait ( timeout ) if stop_happened is False : print ( "Killing program due to %f second timeout" % timeout ) os . _exit ( 2 ) | A background thread to kill the process if it takes too long . | 60 | 13 |
21,547 | def create_parser ( ) : parser = argparse . ArgumentParser ( description = DESCRIPTION , formatter_class = argparse . RawDescriptionHelpFormatter ) parser . add_argument ( '-v' , '--verbose' , action = "count" , default = 0 , help = "Increase logging level (goes error, warn, info, debug)" ) parser . add_argument ( '-l' , '--logfile' , help = "The file where we should log all logging messages" ) parser . add_argument ( '-i' , '--include' , action = "append" , default = [ ] , help = "Only include the specified loggers" ) parser . add_argument ( '-e' , '--exclude' , action = "append" , default = [ ] , help = "Exclude the specified loggers, including all others" ) parser . add_argument ( '-q' , '--quit' , action = "store_true" , help = "Do not spawn a shell after executing any commands" ) parser . add_argument ( '-t' , '--timeout' , type = float , help = "Do not allow this process to run for more than a specified number of seconds." ) parser . add_argument ( 'commands' , nargs = argparse . REMAINDER , help = "The command(s) to execute" ) return parser | Create the argument parser for iotile . | 305 | 9 |
21,548 | def parse_global_args ( argv ) : parser = create_parser ( ) args = parser . parse_args ( argv ) should_log = args . include or args . exclude or ( args . verbose > 0 ) verbosity = args . verbose root = logging . getLogger ( ) if should_log : formatter = logging . Formatter ( '%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s' , '%y-%m-%d %H:%M:%S' ) if args . logfile : handler = logging . FileHandler ( args . logfile ) else : handler = logging . StreamHandler ( ) handler . setFormatter ( formatter ) if args . include and args . exclude : print ( "You cannot combine whitelisted (-i) and blacklisted (-e) loggers, you must use one or the other." ) sys . exit ( 1 ) loglevels = [ logging . ERROR , logging . WARNING , logging . INFO , logging . DEBUG ] if verbosity >= len ( loglevels ) : verbosity = len ( loglevels ) - 1 level = loglevels [ verbosity ] if args . include : for name in args . include : logger = logging . getLogger ( name ) logger . setLevel ( level ) logger . addHandler ( handler ) root . addHandler ( logging . NullHandler ( ) ) else : # Disable propagation of log events from disabled loggers for name in args . exclude : logger = logging . getLogger ( name ) logger . disabled = True root . setLevel ( level ) root . addHandler ( handler ) else : root . addHandler ( logging . NullHandler ( ) ) return args | Parse all global iotile tool arguments . | 383 | 10 |
21,549 | def setup_completion ( shell ) : # Handle special case of importing pyreadline on Windows # See: http://stackoverflow.com/questions/6024952/readline-functionality-on-windows-with-python-2-7 import glob try : import readline except ImportError : import pyreadline as readline def _complete ( text , state ) : buf = readline . get_line_buffer ( ) if buf . startswith ( 'help ' ) or " " not in buf : return [ x for x in shell . valid_identifiers ( ) if x . startswith ( text ) ] [ state ] return ( glob . glob ( os . path . expanduser ( text ) + '*' ) + [ None ] ) [ state ] readline . set_completer_delims ( ' \t\n;' ) # Handle Mac OS X special libedit based readline # See: http://stackoverflow.com/questions/7116038/python-tab-completion-mac-osx-10-7-lion if readline . __doc__ is not None and 'libedit' in readline . __doc__ : readline . parse_and_bind ( "bind ^I rl_complete" ) else : readline . parse_and_bind ( "tab: complete" ) readline . set_completer ( _complete ) | Setup readline to tab complete in a cross platform way . | 306 | 12 |
21,550 | def main ( argv = None ) : if argv is None : argv = sys . argv [ 1 : ] args = parse_global_args ( argv ) type_system . interactive = True line = args . commands timeout_thread = None timeout_stop_event = threading . Event ( ) if args . timeout : timeout_thread = threading . Thread ( target = timeout_thread_handler , args = ( args . timeout , timeout_stop_event ) ) timeout_thread . daemon = True timeout_thread . start ( ) shell = HierarchicalShell ( 'iotile' ) shell . root_add ( "registry" , "iotile.core.dev.annotated_registry,registry" ) shell . root_add ( "config" , "iotile.core.dev.config,ConfigManager" ) shell . root_add ( 'hw' , "iotile.core.hw.hwmanager,HardwareManager" ) reg = ComponentRegistry ( ) plugins = reg . list_plugins ( ) for key , val in plugins . items ( ) : shell . root_add ( key , val ) finished = False try : if len ( line ) > 0 : finished = shell . invoke ( line ) except IOTileException as exc : print ( exc . format ( ) ) # if the command passed on the command line fails, then we should # just exit rather than drop the user into a shell. SharedLoop . stop ( ) return 1 except Exception : # pylint:disable=broad-except; We need to make sure we always call cmdstream.do_final_close() # Catch all exceptions because otherwise we won't properly close cmdstreams # since the program will be said to except 'abnormally' traceback . print_exc ( ) SharedLoop . stop ( ) return 1 # If the user tells us to never spawn a shell, make sure we don't # Also, if we finished our command and there is no context, quit now if args . quit or finished : SharedLoop . stop ( ) return 0 setup_completion ( shell ) # We ended the initial command with a context, start a shell try : while True : try : linebuf = input ( "(%s) " % shell . context_name ( ) ) # Skip comments automatically if len ( linebuf ) > 0 and linebuf [ 0 ] == '#' : continue except KeyboardInterrupt : print ( "" ) continue # Catch exception outside the loop so we stop invoking submethods if a parent # fails because then the context and results would be unpredictable try : finished = shell . invoke_string ( linebuf ) except KeyboardInterrupt : print ( "" ) if timeout_stop_event . is_set ( ) : break except IOTileException as exc : print ( exc . format ( ) ) except Exception : #pylint:disable=broad-except; # We want to make sure the iotile tool never crashes when in interactive shell mode traceback . print_exc ( ) if shell . finished ( ) : break # Make sure to catch ^C and ^D so that we can cleanly dispose of subprocess resources if # there are any. except EOFError : print ( "" ) except KeyboardInterrupt : print ( "" ) finally : # Make sure we close any open CMDStream communication channels so that we don't lockup at exit SharedLoop . stop ( ) # Make sure we cleanly join our timeout thread before exiting if timeout_thread is not None : timeout_stop_event . set ( ) timeout_thread . join ( ) | Run the iotile shell tool . | 754 | 8 |
21,551 | def build ( args ) : # Do some sleuthing work to find scons if it's not installed into an importable # place, as it is usually not. scons_path = "Error" try : scons_path = resource_path ( 'scons-local-{}' . format ( SCONS_VERSION ) , expect = 'folder' ) sys . path . insert ( 0 , scons_path ) import SCons . Script except ImportError : raise BuildError ( "Couldn't find internal scons packaged w/ iotile-build. This is a bug that should be reported" , scons_path = scons_path ) site_path = resource_path ( 'site_scons' , expect = 'folder' ) all_args = [ 'iotile' , '--site-dir=%s' % site_path , '-Q' ] sys . argv = all_args + list ( args ) SCons . Script . main ( ) | Invoke the scons build system from the current directory exactly as if the scons tool had been invoked . | 212 | 22 |
21,552 | def archs ( self , as_list = False ) : archs = self . arch_list ( ) . split ( '/' ) if as_list : return archs return set ( archs ) | Return all of the architectures for this target . | 43 | 9 |
21,553 | def retarget ( self , remove = [ ] , add = [ ] ) : archs = self . arch_list ( ) . split ( '/' ) for r in remove : if r in archs : archs . remove ( r ) archs . extend ( add ) archstr = "/" . join ( archs ) return self . family . find ( archstr , self . module_name ( ) ) | Return a TargetSettings object for the same module but with some of the architectures removed and others added . | 87 | 20 |
21,554 | def property ( self , name , default = MISSING ) : if name in self . settings : return self . settings [ name ] if default is not MISSING : return default raise ArgumentError ( "property %s not found for target '%s' and no default given" % ( name , self . name ) ) | Get the value of the given property for this chip using the default value if not found and one is provided . If not found and default is None raise an Exception . | 66 | 33 |
21,555 | def combined_properties ( self , suffix ) : props = [ y for x , y in self . settings . items ( ) if x . endswith ( suffix ) ] properties = itertools . chain ( * props ) processed_props = [ x for x in properties ] return processed_props | Get the value of all properties whose name ends with suffix and join them together into a list . | 64 | 19 |
21,556 | def includes ( self ) : incs = self . combined_properties ( 'includes' ) processed_incs = [ ] for prop in incs : if isinstance ( prop , str ) : processed_incs . append ( prop ) else : processed_incs . append ( os . path . join ( * prop ) ) # All include paths are relative to base directory of the fullpaths = [ os . path . normpath ( os . path . join ( '.' , x ) ) for x in processed_incs ] fullpaths . append ( os . path . normpath ( os . path . abspath ( self . build_dirs ( ) [ 'build' ] ) ) ) return fullpaths | Return all of the include directories for this chip as a list . | 152 | 13 |
21,557 | def arch_prefixes ( self ) : archs = self . archs ( as_list = True ) prefixes = [ ] for i in range ( 1 , len ( archs ) + 1 ) : prefixes . append ( archs [ : i ] ) return prefixes | Return the initial 1 2 ... N architectures as a prefix list | 59 | 12 |
21,558 | def targets ( self , module ) : if module not in self . module_targets : raise BuildError ( "Could not find module in targets()" , module = module ) return [ self . find ( x , module ) for x in self . module_targets [ module ] ] | Find the targets for a given module . | 62 | 8 |
21,559 | def for_all_targets ( self , module , func , filter_func = None ) : for target in self . targets ( module ) : if filter_func is None or filter_func ( target ) : func ( target ) | Call func once for all of the targets of this module . | 50 | 12 |
21,560 | def validate_target ( self , target ) : archs = target . split ( '/' ) for arch in archs : if not arch in self . archs : return False return True | Make sure that the specified target only contains architectures that we know about . | 39 | 14 |
21,561 | def _load_architectures ( self , family ) : if "architectures" not in family : raise InternalError ( "required architectures key not in build_settings.json for desired family" ) for key , val in family [ 'architectures' ] . items ( ) : if not isinstance ( val , dict ) : raise InternalError ( "All entries under chip_settings must be dictionaries" ) self . archs [ key ] = deepcopy ( val ) | Load in all of the architectural overlays for this family . An architecture adds configuration information that is used to build a common set of source code for a particular hardware and situation . They are stackable so that you can specify a chip and a configuration for that chip for example . | 101 | 55 |
21,562 | def generate ( env ) : c_file , cxx_file = SCons . Tool . createCFileBuilders ( env ) # C c_file . add_action ( ".l" , LexAction ) c_file . add_emitter ( ".l" , lexEmitter ) c_file . add_action ( ".lex" , LexAction ) c_file . add_emitter ( ".lex" , lexEmitter ) # Objective-C cxx_file . add_action ( ".lm" , LexAction ) cxx_file . add_emitter ( ".lm" , lexEmitter ) # C++ cxx_file . add_action ( ".ll" , LexAction ) cxx_file . add_emitter ( ".ll" , lexEmitter ) env [ "LEX" ] = env . Detect ( "flex" ) or "lex" env [ "LEXFLAGS" ] = SCons . Util . CLVar ( "" ) env [ "LEXCOM" ] = "$LEX $LEXFLAGS -t $SOURCES > $TARGET" | Add Builders and construction variables for lex to an Environment . | 241 | 12 |
21,563 | def handle_tick ( self ) : self . uptime += 1 for name , interval in self . ticks . items ( ) : if interval == 0 : continue self . tick_counters [ name ] += 1 if self . tick_counters [ name ] == interval : self . graph_input ( self . TICK_STREAMS [ name ] , self . uptime ) self . tick_counters [ name ] = 0 | Internal callback every time 1 second has passed . | 91 | 9 |
21,564 | def set_tick ( self , index , interval ) : name = self . tick_name ( index ) if name is None : return pack_error ( ControllerSubsystem . SENSOR_GRAPH , Error . INVALID_ARRAY_KEY ) self . ticks [ name ] = interval return Error . NO_ERROR | Update the a tick s interval . | 68 | 7 |
21,565 | def get_tick ( self , index ) : name = self . tick_name ( index ) if name is None : return [ pack_error ( ControllerSubsystem . SENSOR_GRAPH , Error . INVALID_ARRAY_KEY ) , 0 ] return [ Error . NO_ERROR , self . ticks [ name ] ] | Get a tick s interval . | 71 | 6 |
21,566 | def get_time ( self , force_uptime = False ) : if force_uptime : return self . uptime time = self . uptime + self . time_offset if self . is_utc : time |= ( 1 << 31 ) return time | Get the current UTC time or uptime . | 56 | 9 |
21,567 | def synchronize_clock ( self , offset ) : self . time_offset = offset - self . uptime self . is_utc = True if self . has_rtc : self . stored_offset = self . time_offset | Persistently synchronize the clock to UTC time . | 50 | 11 |
21,568 | def get_user_timer ( self , index ) : err , tick = self . clock_manager . get_tick ( index ) return [ err , tick ] | Get the current value of a user timer . | 34 | 9 |
21,569 | def set_user_timer ( self , value , index ) : err = self . clock_manager . set_tick ( index , value ) return [ err ] | Set the current value of a user timer . | 34 | 9 |
21,570 | def set_time_offset ( self , offset , is_utc ) : is_utc = bool ( is_utc ) self . clock_manager . time_offset = offset self . clock_manager . is_utc = is_utc return [ Error . NO_ERROR ] | Temporarily set the current time offset . | 63 | 9 |
21,571 | def device_id_to_slug ( did ) : try : device_slug = IOTileDeviceSlug ( did , allow_64bits = False ) except ValueError : raise ArgumentError ( "Unable to recognize {} as a device id" . format ( did ) ) return str ( device_slug ) | Converts a device id into a correct device slug . | 69 | 11 |
21,572 | def fleet_id_to_slug ( did ) : try : fleet_slug = IOTileFleetSlug ( did ) except ValueError : raise ArgumentError ( "Unable to recognize {} as a fleet id" . format ( did ) ) return str ( fleet_slug ) | Converts a fleet id into a correct fleet slug . | 63 | 11 |
21,573 | def get_architecture ( arch = None ) : if arch is None : arch = os . environ . get ( 'PROCESSOR_ARCHITEW6432' ) if not arch : arch = os . environ . get ( 'PROCESSOR_ARCHITECTURE' ) return SupportedArchitectureMap . get ( arch , ArchDefinition ( '' , [ '' ] ) ) | Returns the definition for the specified architecture string . | 85 | 9 |
21,574 | def generate ( env ) : try : bld = env [ 'BUILDERS' ] [ 'Rpm' ] except KeyError : bld = RpmBuilder env [ 'BUILDERS' ] [ 'Rpm' ] = bld env . SetDefault ( RPM = 'LC_ALL=C rpmbuild' ) env . SetDefault ( RPMFLAGS = SCons . Util . CLVar ( '-ta' ) ) env . SetDefault ( RPMCOM = rpmAction ) env . SetDefault ( RPMSUFFIX = '.rpm' ) | Add Builders and construction variables for rpm to an Environment . | 120 | 12 |
21,575 | def next_id ( self , channel ) : if channel not in self . topics : self . topics [ channel ] = 0 return 0 self . topics [ channel ] += 1 return self . topics [ channel ] | Get the next sequence number for a named channel or topic | 43 | 11 |
21,576 | def escape ( arg ) : slash = '\\' special = '"$' arg = arg . replace ( slash , slash + slash ) for c in special : arg = arg . replace ( c , slash + c ) # print("ESCAPE RESULT: %s" % arg) return '"' + arg + '"' | escape shell special characters | 69 | 4 |
21,577 | def process_streamer ( self , streamer , callback = None ) : index = streamer . index if index in self . _in_progress_streamers : raise InternalError ( "You cannot add a streamer again until it has finished streaming." ) queue_item = QueuedStreamer ( streamer , callback ) self . _in_progress_streamers . add ( index ) self . _logger . debug ( "Streamer %d: queued to send %d readings" , index , queue_item . initial_count ) self . _queue . put_nowait ( queue_item ) | Start streaming a streamer . | 127 | 6 |
21,578 | def pack_rpc_response ( response = None , exception = None ) : if response is None : response = bytes ( ) if exception is None : status = ( 1 << 6 ) if len ( response ) > 0 : status |= ( 1 << 7 ) elif isinstance ( exception , ( RPCInvalidIDError , RPCNotFoundError ) ) : status = 2 elif isinstance ( exception , BusyRPCResponse ) : status = 0 elif isinstance ( exception , TileNotFoundError ) : status = 0xFF elif isinstance ( exception , RPCErrorCode ) : status = ( 1 << 6 ) | ( exception . params [ 'code' ] & ( ( 1 << 6 ) - 1 ) ) else : status = 3 return status , response | Convert a response payload or exception to a status code and payload . | 164 | 14 |
21,579 | def unpack_rpc_response ( status , response = None , rpc_id = 0 , address = 0 ) : status_code = status & ( ( 1 << 6 ) - 1 ) if address == 8 : status_code &= ~ ( 1 << 7 ) if status == 0 : raise BusyRPCResponse ( ) elif status == 2 : raise RPCNotFoundError ( "rpc %d:%04X not found" % ( address , rpc_id ) ) elif status == 3 : raise RPCErrorCode ( status_code ) elif status == 0xFF : raise TileNotFoundError ( "tile %d not found" % address ) elif status_code != 0 : raise RPCErrorCode ( status_code ) if response is None : response = b'' return response | Unpack an RPC status back in to payload or exception . | 176 | 12 |
21,580 | def pack_rpc_payload ( arg_format , args ) : code = _create_respcode ( arg_format , args ) packed_result = struct . pack ( code , * args ) unpacked_validation = struct . unpack ( code , packed_result ) if tuple ( args ) != unpacked_validation : raise RPCInvalidArgumentsError ( "Passed values would be truncated, please validate the size of your string" , code = code , args = args ) return packed_result | Pack an RPC payload according to arg_format . | 109 | 10 |
21,581 | def unpack_rpc_payload ( resp_format , payload ) : code = _create_argcode ( resp_format , payload ) return struct . unpack ( code , payload ) | Unpack an RPC payload according to resp_format . | 41 | 11 |
21,582 | def isfortran ( env , source ) : try : fsuffixes = env [ 'FORTRANSUFFIXES' ] except KeyError : # If no FORTRANSUFFIXES, no fortran tool, so there is no need to look # for fortran sources. return 0 if not source : # Source might be None for unusual cases like SConf. return 0 for s in source : if s . sources : ext = os . path . splitext ( str ( s . sources [ 0 ] ) ) [ 1 ] if ext in fsuffixes : return 1 return 0 | Return 1 if any of code in source has fortran files in it 0 otherwise . | 129 | 18 |
21,583 | def ComputeFortranSuffixes ( suffixes , ppsuffixes ) : assert len ( suffixes ) > 0 s = suffixes [ 0 ] sup = s . upper ( ) upper_suffixes = [ _ . upper ( ) for _ in suffixes ] if SCons . Util . case_sensitive_suffixes ( s , sup ) : ppsuffixes . extend ( upper_suffixes ) else : suffixes . extend ( upper_suffixes ) | suffixes are fortran source files and ppsuffixes the ones to be pre - processed . Both should be sequences not strings . | 107 | 30 |
21,584 | def CreateDialectActions ( dialect ) : CompAction = SCons . Action . Action ( '$%sCOM ' % dialect , '$%sCOMSTR' % dialect ) CompPPAction = SCons . Action . Action ( '$%sPPCOM ' % dialect , '$%sPPCOMSTR' % dialect ) ShCompAction = SCons . Action . Action ( '$SH%sCOM ' % dialect , '$SH%sCOMSTR' % dialect ) ShCompPPAction = SCons . Action . Action ( '$SH%sPPCOM ' % dialect , '$SH%sPPCOMSTR' % dialect ) return CompAction , CompPPAction , ShCompAction , ShCompPPAction | Create dialect specific actions . | 162 | 5 |
21,585 | def add_fortran_to_env ( env ) : try : FortranSuffixes = env [ 'FORTRANFILESUFFIXES' ] except KeyError : FortranSuffixes = [ '.f' , '.for' , '.ftn' ] #print("Adding %s to fortran suffixes" % FortranSuffixes) try : FortranPPSuffixes = env [ 'FORTRANPPFILESUFFIXES' ] except KeyError : FortranPPSuffixes = [ '.fpp' , '.FPP' ] DialectAddToEnv ( env , "FORTRAN" , FortranSuffixes , FortranPPSuffixes , support_module = 1 ) env [ 'FORTRANMODPREFIX' ] = '' # like $LIBPREFIX env [ 'FORTRANMODSUFFIX' ] = '.mod' # like $LIBSUFFIX env [ 'FORTRANMODDIR' ] = '' # where the compiler should place .mod files env [ 'FORTRANMODDIRPREFIX' ] = '' # some prefix to $FORTRANMODDIR - similar to $INCPREFIX env [ 'FORTRANMODDIRSUFFIX' ] = '' # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX env [ '_FORTRANMODFLAG' ] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' | Add Builders and construction variables for Fortran to an Environment . | 354 | 13 |
21,586 | def add_f77_to_env ( env ) : try : F77Suffixes = env [ 'F77FILESUFFIXES' ] except KeyError : F77Suffixes = [ '.f77' ] #print("Adding %s to f77 suffixes" % F77Suffixes) try : F77PPSuffixes = env [ 'F77PPFILESUFFIXES' ] except KeyError : F77PPSuffixes = [ ] DialectAddToEnv ( env , "F77" , F77Suffixes , F77PPSuffixes ) | Add Builders and construction variables for f77 to an Environment . | 137 | 13 |
21,587 | def add_f90_to_env ( env ) : try : F90Suffixes = env [ 'F90FILESUFFIXES' ] except KeyError : F90Suffixes = [ '.f90' ] #print("Adding %s to f90 suffixes" % F90Suffixes) try : F90PPSuffixes = env [ 'F90PPFILESUFFIXES' ] except KeyError : F90PPSuffixes = [ ] DialectAddToEnv ( env , "F90" , F90Suffixes , F90PPSuffixes , support_module = 1 ) | Add Builders and construction variables for f90 to an Environment . | 143 | 13 |
21,588 | def add_f95_to_env ( env ) : try : F95Suffixes = env [ 'F95FILESUFFIXES' ] except KeyError : F95Suffixes = [ '.f95' ] #print("Adding %s to f95 suffixes" % F95Suffixes) try : F95PPSuffixes = env [ 'F95PPFILESUFFIXES' ] except KeyError : F95PPSuffixes = [ ] DialectAddToEnv ( env , "F95" , F95Suffixes , F95PPSuffixes , support_module = 1 ) | Add Builders and construction variables for f95 to an Environment . | 143 | 13 |
21,589 | def add_f03_to_env ( env ) : try : F03Suffixes = env [ 'F03FILESUFFIXES' ] except KeyError : F03Suffixes = [ '.f03' ] #print("Adding %s to f95 suffixes" % F95Suffixes) try : F03PPSuffixes = env [ 'F03PPFILESUFFIXES' ] except KeyError : F03PPSuffixes = [ ] DialectAddToEnv ( env , "F03" , F03Suffixes , F03PPSuffixes , support_module = 1 ) | Add Builders and construction variables for f03 to an Environment . | 143 | 13 |
21,590 | def add_f08_to_env ( env ) : try : F08Suffixes = env [ 'F08FILESUFFIXES' ] except KeyError : F08Suffixes = [ '.f08' ] try : F08PPSuffixes = env [ 'F08PPFILESUFFIXES' ] except KeyError : F08PPSuffixes = [ ] DialectAddToEnv ( env , "F08" , F08Suffixes , F08PPSuffixes , support_module = 1 ) | Add Builders and construction variables for f08 to an Environment . | 123 | 13 |
21,591 | def add_all_to_env ( env ) : add_fortran_to_env ( env ) add_f77_to_env ( env ) add_f90_to_env ( env ) add_f95_to_env ( env ) add_f03_to_env ( env ) add_f08_to_env ( env ) | Add builders and construction variables for all supported fortran dialects . | 78 | 14 |
21,592 | def _delete_duplicates ( l , keep_last ) : seen = set ( ) result = [ ] if keep_last : # reverse in & out, then keep first l . reverse ( ) for i in l : try : if i not in seen : result . append ( i ) seen . add ( i ) except TypeError : # probably unhashable. Just keep it. result . append ( i ) if keep_last : result . reverse ( ) return result | Delete duplicates from a sequence keeping the first or last . | 100 | 12 |
21,593 | def clone ( self , new_object ) : return self . __class__ ( new_object , self . method , self . name ) | Returns an object that re - binds the underlying method to the specified new object . | 29 | 16 |
21,594 | def _init_special ( self ) : self . _special_del = { } self . _special_del [ 'SCANNERS' ] = _del_SCANNERS self . _special_set = { } for key in reserved_construction_var_names : self . _special_set [ key ] = _set_reserved for key in future_reserved_construction_var_names : self . _special_set [ key ] = _set_future_reserved self . _special_set [ 'BUILDERS' ] = _set_BUILDERS self . _special_set [ 'SCANNERS' ] = _set_SCANNERS # Freeze the keys of self._special_set in a list for use by # methods that need to check. (Empirically, list scanning has # gotten better than dict.has_key() in Python 2.5.) self . _special_set_keys = list ( self . _special_set . keys ( ) ) | Initial the dispatch tables for special handling of special construction variables . | 216 | 12 |
21,595 | def AddMethod ( self , function , name = None ) : method = MethodWrapper ( self , function , name ) self . added_methods . append ( method ) | Adds the specified function as a method of this construction environment with the specified name . If the name is omitted the default name is the name of the function itself . | 36 | 32 |
21,596 | def RemoveMethod ( self , function ) : self . added_methods = [ dm for dm in self . added_methods if not dm . method is function ] | Removes the specified function s MethodWrapper from the added_methods list so we don t re - bind it when making a clone . | 38 | 29 |
21,597 | def Override ( self , overrides ) : if not overrides : return self o = copy_non_reserved_keywords ( overrides ) if not o : return self overrides = { } merges = None for key , value in o . items ( ) : if key == 'parse_flags' : merges = value else : overrides [ key ] = SCons . Subst . scons_subst_once ( value , self , key ) env = OverrideEnvironment ( self , overrides ) if merges : env . MergeFlags ( merges ) return env | Produce a modified environment whose variables are overridden by the overrides dictionaries . overrides is a dictionary that will override the variables of this environment . | 123 | 31 |
21,598 | def MergeFlags ( self , args , unique = 1 , dict = None ) : if dict is None : dict = self if not SCons . Util . is_Dict ( args ) : args = self . ParseFlags ( args ) if not unique : self . Append ( * * args ) return self for key , value in args . items ( ) : if not value : continue try : orig = self [ key ] except KeyError : orig = value else : if not orig : orig = value elif value : # Add orig and value. The logic here was lifted from # part of env.Append() (see there for a lot of comments # about the order in which things are tried) and is # used mainly to handle coercion of strings to CLVar to # "do the right thing" given (e.g.) an original CCFLAGS # string variable like '-pipe -Wall'. try : orig = orig + value except ( KeyError , TypeError ) : try : add_to_orig = orig . append except AttributeError : value . insert ( 0 , orig ) orig = value else : add_to_orig ( value ) t = [ ] if key [ - 4 : ] == 'PATH' : ### keep left-most occurence for v in orig : if v not in t : t . append ( v ) else : ### keep right-most occurence orig . reverse ( ) for v in orig : if v not in t : t . insert ( 0 , v ) self [ key ] = t return self | Merge the dict in args into the construction variables of this env or the passed - in dict . If args is not a dict it is converted into a dict using ParseFlags . If unique is not set the flags are appended rather than merged . | 326 | 51 |
21,599 | def get_factory ( self , factory , default = 'File' ) : name = default try : is_node = issubclass ( factory , SCons . Node . FS . Base ) except TypeError : # The specified factory isn't a Node itself--it's # most likely None, or possibly a callable. pass else : if is_node : # The specified factory is a Node (sub)class. Try to # return the FS method that corresponds to the Node's # name--that is, we return self.fs.Dir if they want a Dir, # self.fs.File for a File, etc. try : name = factory . __name__ except AttributeError : pass else : factory = None if not factory : # They passed us None, or we picked up a name from a specified # class, so return the FS method. (Note that we *don't* # use our own self.{Dir,File} methods because that would # cause env.subst() to be called twice on the file name, # interfering with files that have $$ in them.) factory = getattr ( self . fs , name ) return factory | Return a factory function for creating Nodes for this construction environment . | 242 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.