text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Returns the currently active relay. <END_TASK> <USER_TASK:> Description: def list_running_zones(self): """ Returns the currently active relay. :returns: Returns the running relay number or None if no relays are active. :rtype: string """
self.update_controller_info() if self.running is None or not self.running: return None return int(self.running[0]['relay'])
<SYSTEM_TASK:> Returns the state of the specified zone. <END_TASK> <USER_TASK:> Description: def is_zone_running(self, zone): """ Returns the state of the specified zone. :param zone: The zone to check. :type zone: int :returns: Returns True if the zone is currently running, otherwise returns False if the zone is not running. :rtype: boolean """
self.update_controller_info() if self.running is None or not self.running: return False if int(self.running[0]['relay']) == zone: return True return False
<SYSTEM_TASK:> Returns the amount of watering time left in seconds. <END_TASK> <USER_TASK:> Description: def time_remaining(self, zone): """ Returns the amount of watering time left in seconds. :param zone: The zone to check. :type zone: int :returns: If the zone is not running returns 0. If the zone doesn't exist returns None. Otherwise returns number of seconds left in the watering cycle. :rtype: None or seconds left in the waterting cycle. """
self.update_controller_info() if zone < 0 or zone > (self.num_relays-1): return None if self.is_zone_running(zone): return int(self.running[0]['time_left']) return 0
<SYSTEM_TASK:> Returns the instance of the element who owns the first line <END_TASK> <USER_TASK:> Description: def element(self): """Returns the instance of the element who owns the first line number for the operation in the cached source code."""
#We assume here that the entire operation is associated with a single #code element. Since the sequence matcher groups operations by contiguous #lines of code to change, this is a safe assumption. if self._element is None: line = self.icached[0] #If we are inserting a new line, the location at the start of the line #that used to be there interferes with the element finder. if self.mode == "insert": line -= 1 self._element = self.context.module.get_element(line, 0) return self._element
<SYSTEM_TASK:> Returns the instance of the element whose body owns the docstring <END_TASK> <USER_TASK:> Description: def docelement(self): """Returns the instance of the element whose body owns the docstring in the current operation. """
#This is needed since the decorating documentation #for types and executables is in the body of the module, but when they #get edited, the edit belongs to the type/executable because the character #falls within the absstart and end attributes. if self._docelement is None: if isinstance(self.element, Module): self._docelement = self.element else: ichar = self.element.module.charindex(self.icached[0], 1) if (ichar > self.element.docstart and ichar <= self.element.docend): self._docelement = self.element.parent else: self._docelement = self.element return self._docelement
<SYSTEM_TASK:> Handles the real time update of some code from the cached representation <END_TASK> <USER_TASK:> Description: def handle(self): """Handles the real time update of some code from the cached representation of the module. """
#If we have more statements in the buffer than the cached, it doesn't matter, #we just run the first few replacements of the cache concurrently and do #what's left over from the buffer. #REVIEW if self.mode == "insert": #then self.icached[0] == self.icached[1]: #We are inserting the lines from the buffer into the cached version for ib in range(len(self.buffered)): self.state = (ib, None) self.parser.parse(self) self._update_extent() elif self.mode == "delete": #then self.ibuffer[0] == self.ibuffer[1]: #We are deleting lines from the cached version for ic in range(len(self.cached)): self.state = (None, ic) self.parser.parse(self) self._update_extent() else: # mode == 'replace' #Need lines from both the buffer and the cached version #First we run all the statements in cached as deletions for ic in range(len(self.cached)): self.state = (None, ic) self.parser.parse(self, "delete") self._update_extent() #Then run all the buffer statements as insertions. for ib in range(len(self.buffered)): self.state = (ib, None) self.parser.parse(self, "insert") self._update_extent() self._handle_docstrings()
<SYSTEM_TASK:> Searches through the lines affected by this operation to find <END_TASK> <USER_TASK:> Description: def _handle_docstrings(self): """Searches through the lines affected by this operation to find blocks of adjacent docstrings to parse for the current element. """
#Docstrings have to be continuous sets of lines that start with !! #When they change in any way (i.e. any of the three modes), we #have to reparse the entire block because it has XML dependencies #Because of that, the cached version of the docstrings is actually #pointless and we only need to focus on the buffered. blocks = self._docstring_getblocks() if len(blocks) == 0: return xmldict = self._docstring_parse(blocks) delta = 0 if isinstance(self.docelement, Module): delta += self.docparser.rt_update_module(xmldict, self.docelement) else: #We just need to handle the type and executable internal defs. if self.docelement.name in xmldict: docs = self.docparser.to_doc(xmldict[self.docelement.name][0], self.docelement.name) self.docparser.process_memberdocs(docs, self.docelement, False) #Also update the docstrings for any embedded types or executables. if isinstance(self.docelement, Executable): delta += self.docparser.process_embedded(xmldict, self.docelement, False) #Finally, we need to handle the overall character length change #that this update caused to the element first and then for the #operation as a whole for updating the module and its children. buffertot = sum([len(self.context.bufferstr[i]) for i in self._doclines]) cachedtot = 0 for i in range(self.icached[0],self.icached[1]): if self.docparser.RE_DOCS.match(self.context.cachedstr[i]): cachedtot += len(self.context.cachedstr[i]) self.length = buffertot - cachedtot if delta == 0: #The update must have been to members variables of the module or the #executables/types. The element who owns the members is going to get #missed when the module updates its children. self.docelement.end += self.length else: #All the individual elements have been updated already, so just #set the length change for this operation. self.docdelta = delta
<SYSTEM_TASK:> Parses the XML from the specified blocks of docstrings. <END_TASK> <USER_TASK:> Description: def _docstring_parse(self, blocks): """Parses the XML from the specified blocks of docstrings."""
result = {} for block, docline, doclength, key in blocks: doctext = "<doc>{}</doc>".format(" ".join(block)) try: docs = ET.XML(doctext) docstart = self.parser.charindex(docline, 0, self.context) if not key in result: result[key] = [list(docs), docstart, docstart + doclength] else: #If there are docblocks separated by whitespace in the #same element we can't easily keep track of the start and #end character indices anymore. result[key][0].extend(list(docs)) except ET.ParseError: msg.warn(doctext) return result
<SYSTEM_TASK:> Gets the longest continuous block of docstrings from the buffer <END_TASK> <USER_TASK:> Description: def _docstring_getblocks(self): """Gets the longest continuous block of docstrings from the buffer code string if any of those lines are docstring lines. """
#If there are no lines to look at, we have nothing to do here. if self.ibuffer[0] == self.ibuffer[1]: return [] lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]] docblock = [] result = [] self._doclines = [] #We need to keep track of the line number for the start of the #documentation strings. docline = 0 doclength = 0 first = self.docparser.RE_DOCS.match(lines[0]) if first is not None: docblock.append(first.group("docstring")) docline = self.ibuffer[0] self._doclines.append(docline) doclength += len(lines[0]) + 1 # + 1 for \n removed by split. #We need to search backwards in the main buffer string for #additional tags to add to the block i = self.ibuffer[0] - 1 while i > 0: current = self.context.bufferstr[i] docmatch = self.docparser.RE_DOCS.match(current) if docmatch is not None: docblock.append(docmatch.group("docstring")) docline = i doclength += len(current) + 1 else: break i -= 1 #Reverse the docblock list since we were going backwards and appending. if len(docblock) > 0: docblock.reverse() #Now handle the lines following the first line. Also handle the #possibility of multiple, separate blocks that are still valid XML. #We have to keep going until we have exceed the operational changes #or found the decorating element. i = self.ibuffer[0] + 1 while (i < len(self.context.bufferstr) and (i < self.ibuffer[1] or len(docblock) > 0)): line = self.context.bufferstr[i] docmatch = self.docparser.RE_DOCS.match(line) if docmatch is not None: docblock.append(docmatch.group("docstring")) doclength += len(line) if docline == 0: docline = i #Only track actual documentation lines that are within the #operations list of lines. if i < self.ibuffer[1]: self._doclines.append(i) elif len(docblock) > 0: key = self._docstring_key(line) result.append((docblock, docline, doclength, key)) docblock = [] docline = 0 doclength = 0 #We need to exit the loop if we have exceeded the length of #the operational changes if len(docblock) == 0 and i > self.ibuffer[1]: break i += 1 return result
<SYSTEM_TASK:> Returns the key to use for the docblock immediately preceding <END_TASK> <USER_TASK:> Description: def _docstring_key(self, line): """Returns the key to use for the docblock immediately preceding the specified line."""
decormatch = self.docparser.RE_DECOR.match(line) if decormatch is not None: key = "{}.{}".format(self.docelement.name, decormatch.group("name")) else: key = self.element.name return key
<SYSTEM_TASK:> Updates the extent of the element being altered by this operation <END_TASK> <USER_TASK:> Description: def _update_extent(self): """Updates the extent of the element being altered by this operation to include the code that has changed."""
#For new instances, their length is being updated by the module #updater and will include *all* statements, so we don't want to #keep changing the endpoints. if self.bar_extent: return original = self.element.end if self.mode == "insert": #The end value needs to increase by the length of the current #statement being executed. self.element.end += self.curlength elif self.mode == "delete": #Reduce end by statement length self.element.end -= self.curlength elif self.mode == "replace": #Check whether we are currently doing the delete portion of the #replacement or the insert portion. if self.state[0] is None: self.element.end -= self.curlength else: self.element.end += self.curlength #Keep track of the total effect of all statements in this operation #so that it is easy to update the module once they are all done. self.length += self.element.end - original
<SYSTEM_TASK:> Gets a list of the statements that are new for the real time update. <END_TASK> <USER_TASK:> Description: def _get_buffered(self): """Gets a list of the statements that are new for the real time update."""
lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]] return self._get_statements(lines, self.ibuffer[0])
<SYSTEM_TASK:> Gets a list of statements that the operation will affect during the real <END_TASK> <USER_TASK:> Description: def _get_cached(self): """Gets a list of statements that the operation will affect during the real time update."""
lines = self.context.cachedstr[self.icached[0]:self.icached[1]] return self._get_statements(lines, self.icached[0])
<SYSTEM_TASK:> Updates all references in the cached representation of the module <END_TASK> <USER_TASK:> Description: def update(self, context): """Updates all references in the cached representation of the module with their latest code from the specified source code string that was extracted from the emacs buffer. :arg context: the buffer context information. """
#Get a list of all the operations that need to be performed and then #execute them. self._operations = self._get_operations(context) for i in range(len(self._operations)): self._operations[i].handle() self.update_extent(self._operations[i]) #Last of all, we update the string content of the cached version of #the module to have the latest source code. if len(self._operations) > 0: context.module.update_refstring(context.refstring)
<SYSTEM_TASK:> Returns a list of operations that need to be performed to turn the <END_TASK> <USER_TASK:> Description: def _get_operations(self, context): """Returns a list of operations that need to be performed to turn the cached source code into the one in the buffer."""
#Most of the time, the real-time update is going to fire with #incomplete statements that don't result in any changes being made #to the module instances. The SequenceMatches caches hashes for the #second argument. Logically, we want to turn the cached version into #the buffer version; however, the buffer is the string that keeps #changing. #in order to optimize the real-time update, we *switch* the two strings #when we set the sequence and then fix the references on the operations #after the fact. if context.module.changed or self.unset: self.matcher.set_seq2(context.cachedstr) self.unset = False #Set the changed flag back to false now that the sequencer has #reloaded it. context.module.changed = False self.matcher.set_seq1(context.bufferstr) opcodes = self.matcher.get_opcodes() result = [] #Index i keeps track of how many operations were actually added because #they constituted a change we need to take care of. i = 0 for code in opcodes: if code[0] != "equal": #Replacements don't have a mode change. All of the operations #switch the order of the line indices for the two strings. if code[0] == "insert": newcode = ("delete", code[3], code[4], code[1], code[2]) elif code[0] == "delete": newcode = ("insert", code[3], code[4], code[1], code[2]) else: newcode = ("replace", code[3], code[4], code[1], code[2]) op = Operation(context, self.parser, newcode, i) result.append(op) i += 1 return result
<SYSTEM_TASK:> Updates a new instance that was added to a module to be complete <END_TASK> <USER_TASK:> Description: def update_instance_extent(self, instance, module, operation): """Updates a new instance that was added to a module to be complete if the end token is present in any remaining, overlapping operations. """
#Essentially, we want to look in the rest of the statements that are #part of the current operation to see how many more of them pertain #to the new instance that was added. #New signatures only result in instances being added if mode is "insert" #or "replace". In both cases, the important code is in the buffered #statements, *not* the cached version. Iterate the remaining statements #in the buffer and look for the end_token for the instance. If we don't #find it, check for overlap between the operations' index specifiers. instance.end -= operation.curlength end_token = instance.end_token (ibuffer, length) = self._find_end_token(end_token, operation) cum_length = length opstack = [operation] while ibuffer is None and opstack[-1].index + 1 < len(self._operations): #We didn't find a natural termination to the new instance. Look for #overlap in the operations noperation = self._operations[opstack[-1].index + 1] #We only want to check the next operation if it is a neighbor #in line numbers in the buffer. if noperation.ibuffer[0] - opstack[-1].ibuffer[1] == 1: (ibuffer, length) = self._find_end_token(end_token, noperation) cum_length += length opstack.append(noperation) else: break if ibuffer is not None: instance.incomplete = False instance.end += cum_length for op in opstack: op.bar_extent = True op.set_element(instance) else: #We set the element for the current operation to be the new instance #for the rest of statements in its set. operation.set_element(instance)
<SYSTEM_TASK:> Looks for a statement in the operation's list that matches the specified <END_TASK> <USER_TASK:> Description: def _find_end_token(self, end_token, operation): """Looks for a statement in the operation's list that matches the specified end token. Returns the index of the statement in the operation that matches. """
ibuffer, icache = operation.state length = operation.buffered[ibuffer][2] result = None for i in range(len(operation.buffered) - ibuffer - 1): linenum, statement, charlength = operation.buffered[i + ibuffer + 1] length += charlength if end_token in statement.lower(): #We already have the absolute char index for the start of the #instance; we just need to update the end. result = (i + ibuffer + 1, length) break #If we didn't find a terminating statement, the full length of the operation #is a good estimate for the extent of the instance. if result is None: result = (None, length) return result
<SYSTEM_TASK:> Retrieve values for a set of keys. <END_TASK> <USER_TASK:> Description: def mget(self, *keys, **kwargs): """Retrieve values for a set of keys. Args: keys (str list): the list of keys whose value should be retrieved Keyword arguements: default (object): the value to use for non-existent keys coherent (bool): whether all fetched values should be "coherent", i.e no other update was performed on any of those values while fetching from the database. Yields: object: values for the keys, in the order they were passed """
default = kwargs.get('default') coherent = kwargs.get('coherent', False) for key in keys: yield self.get(key, default=default)
<SYSTEM_TASK:> Set the value of several keys at once. <END_TASK> <USER_TASK:> Description: def mset(self, values): """Set the value of several keys at once. Args: values (dict): maps a key to its value. """
for key, value in values.items(): self.set(key, value)
<SYSTEM_TASK:> Returns a list of possible completions for the symbol under the <END_TASK> <USER_TASK:> Description: def names(self): """Returns a list of possible completions for the symbol under the cursor in the current user context."""
#This is where the context information is extremely useful in #limiting the extent of the search space we need to examine. if self._names is None: attribute = self.get_attribute() if self.context.module is not None: symbol = self.context.symbol fullsymbol = self.context.full_symbol self._names = self._complete_el(symbol, attribute, fullsymbol) else: self._names = [] return self._names
<SYSTEM_TASK:> Returns a function call signature for completion whenever <END_TASK> <USER_TASK:> Description: def bracket_complete(self): """Returns a function call signature for completion whenever a bracket '(' is pressed."""
#The important thing to keep track of here is that '(' can be #pushed in the following places: # - in a subroutine/function definition # - when calling a function or subroutine, this includes calls within # the argument list of a function, e.g. function(a, fnb(c,d), e) # - when specifying the dimensions of an array for element selection # - inside of if/do/while blocks. #If there is a \s immediately preceding the bracket, then short_symbol #will be null string and we are most likely doing arithmetic of some #sort or a block statement. if self.context.short_symbol == "": return {} line = self.context.current_line.lower()[:self.context.pos[1]-1] if "subroutine" in line or "function" in line: #We are in the definition of the subroutine or function. They #are choosing the parameter names so we don't offer any suggestions. return {} #Sometimes people do if() with the condition immediately after #the keyword, this regex will catch that. symbol = self.context.short_symbol.lower() if symbol in ["if", "do", "while", "elseif", "case", "associate"]: return {} #All that should be left now are dimensions and legitimate function #calls. fullsymbol = self.context.short_full_symbol.lower() return self._bracket_complete_sig(symbol, fullsymbol)
<SYSTEM_TASK:> Returns the call signature and docstring for the executable <END_TASK> <USER_TASK:> Description: def _bracket_complete_sig(self, symbol, fullsymbol): """Returns the call signature and docstring for the executable immediately preceding a bracket '(' that was typed."""
if symbol != fullsymbol: #We have a sym%sym%... chain and the completion just needs to #be the signature of the member method. target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol) if symbol in target.executables: child = target.executables[symbol] return self._compile_signature(child.target, child.name) elif symbol in target.members: #We are dealing with a dimension request on an array that #is a member of the type. child = target.members[symbol] return self._bracket_dim_suggest(child) else: return {} else: #We must be dealing with a regular executable or builtin fxn #or a regular variable dimension. iexec = self._bracket_exact_exec(symbol) if iexec is not None: #It is indeed a function we are completing for. return self._compile_signature(iexec, iexec.name) else: #We need to look at local and global variables to find the #variable declaration and dimensionality. ivar = self._bracket_exact_var(symbol) return self._bracket_dim_suggest(ivar)
<SYSTEM_TASK:> Returns a dictionary of documentation for helping complete the <END_TASK> <USER_TASK:> Description: def _bracket_dim_suggest(self, variable): """Returns a dictionary of documentation for helping complete the dimensions of a variable."""
if variable is not None: #Look for <dimension> descriptors that are children of the variable #in its docstrings. dims = variable.doc_children("dimension", ["member", "parameter", "local"]) descript = str(variable) if len(dims) > 0: descript += " | " + " ".join([DocElement.format_dimension(d) for d in dims]) return dict( params=[variable.dimension], index=0, call_name=variable.name, description=descript, ) else: return []
<SYSTEM_TASK:> Checks variable and executable code elements based on the current <END_TASK> <USER_TASK:> Description: def get_definition(self): """Checks variable and executable code elements based on the current context for a code element whose name matches context.exact_match perfectly. """
#Check the variables first, then the functions. match = self._bracket_exact_var(self.context.exact_match) if match is None: match = self._bracket_exact_exec(self.context.exact_match) return match
<SYSTEM_TASK:> Checks local first and then module global variables for an exact <END_TASK> <USER_TASK:> Description: def _bracket_exact_var(self, symbol): """Checks local first and then module global variables for an exact match to the specified symbol name."""
if isinstance(self.element, Executable): if symbol in self.element.parameters: return self.element.parameters[symbol] if symbol in self.element.members: return self.element.members[symbol] if symbol in self.element.module.members: return self.element.module.members[symbol] return None
<SYSTEM_TASK:> Checks builtin, local and global executable collections for the <END_TASK> <USER_TASK:> Description: def _bracket_exact_exec(self, symbol): """Checks builtin, local and global executable collections for the specified symbol and returns it as soon as it is found."""
if symbol in self.context.module.executables: return self.context.module.executables[symbol] if symbol in self.context.module.interfaces: return self.context.module.interfaces[symbol] if symbol in cache.builtin: return cache.builtin[symbol] #Loop through all the dependencies of the current module and see #if one of them is the method we are looking for. return self.context.module.get_dependency_element(symbol)
<SYSTEM_TASK:> Compiles the signature for the specified executable and returns <END_TASK> <USER_TASK:> Description: def _compile_signature(self, iexec, call_name): """Compiles the signature for the specified executable and returns as a dictionary."""
if iexec is not None: summary = iexec.summary if isinstance(iexec, Function): summary = iexec.returns + "| " + iexec.summary elif isinstance(iexec, Subroutine) and len(iexec.modifiers) > 0: summary = ", ".join(iexec.modifiers) + " | " + iexec.summary elif isinstance(iexec, Interface): summary = iexec.describe() else: summary = iexec.summary #Add the name of the module who owns the method. Useful in case the #same executable is defined in multiple modules, but only one is #referenced in the current context. if iexec.parent is not None: summary += " | MODULE: {}".format(iexec.module.name) else: summary += " | BUILTIN" return dict( params=[p.name for p in iexec.ordered_parameters], index=0, call_name=call_name, description=summary, ) else: return []
<SYSTEM_TASK:> Gets completion or call signature information for the current cursor. <END_TASK> <USER_TASK:> Description: def signature(self): """Gets completion or call signature information for the current cursor."""
#We can't really do anything sensible without the name of the function #whose signature we are completing. iexec, execmod = self.context.parser.tree_find(self.context.el_name, self.context.module, "executables") if iexec is None: #Look in the interfaces next using a tree find as well iexec, execmod = self.context.parser.tree_find(self.context.el_name, self.context.module, "interfaces") if iexec is None: return [] return self._signature_index(iexec)
<SYSTEM_TASK:> Determines where in the call signature the cursor is to decide which <END_TASK> <USER_TASK:> Description: def _signature_index(self, iexec): """Determines where in the call signature the cursor is to decide which parameter needs to have its information returned for the intellisense. """
#Find out where in the signature the cursor is at the moment. call_index = self.context.call_arg_index if call_index is not None: #We found the index of the parameter whose docstring we want #to return. param = iexec.get_parameter(call_index) paramlist = [ p.name for p in iexec.ordered_parameters ] paramlist[call_index] = "*{}*".format(paramlist[call_index]) if not isinstance(param, list) and param is not None: #Write a nice description that includes the parameter type and #intent as well as dimension. summary = "{} | {}".format(str(param), param.summary) #We also want to determine if this parameter has its value changed #by the function we are completing on. changedby = iexec.changed(param.name) if changedby is not None: summary += " *MODIFIED*" elif isinstance(param, list) and len(param) > 0: act_type = [] for iparam in param: if iparam is not None and iparam.strtype not in act_type: act_type.append(iparam.strtype) act_text = ', '.join(act_type) summary = "SUMMARY: {} | ACCEPTS: {}".format(param[0].summary, act_text) if iexec.changed(param[0].name): summary += " | *MODIFIED*" else: summary = "No matching variable definition." #Add the name of the module who owns the executable. summary += " | MODULE: {}".format(iexec.module.name) return dict( params=paramlist, index=call_index, call_name=self.context.el_name, description=summary, ) else: return result
<SYSTEM_TASK:> Gets a list of completion objects for the symbol under the cursor. <END_TASK> <USER_TASK:> Description: def complete(self): """Gets a list of completion objects for the symbol under the cursor."""
if self._possible is None: self._possible = [] for possible in self.names: c = Completion(self.context, self.names[possible], len(self.context.symbol)) self._possible.append(c) return self._possible
<SYSTEM_TASK:> Checks whether the specified symbol is part of the name for completion. <END_TASK> <USER_TASK:> Description: def _symbol_in(self, symbol, name): """Checks whether the specified symbol is part of the name for completion."""
lsymbol = symbol.lower() lname = name.lower() return lsymbol == lname[:len(symbol)] or "_" + lsymbol in lname
<SYSTEM_TASK:> Gets the code element object for the parent of the specified <END_TASK> <USER_TASK:> Description: def _get_chain_parent_symbol(self, symbol, fullsymbol): """Gets the code element object for the parent of the specified symbol in the fullsymbol chain."""
#We are only interested in the type of the variable immediately preceding our symbol #in the chain so we can list its members. chain = fullsymbol.split("%") #We assume that if symbol != fullsymbol, we have at least a % at the end that #tricked the symbol regex. if len(chain) < 2: return ([], None) previous = chain[-2].lower() #Now we need to use the name of the variable to find the actual type name target_name = "" if previous in self.element.members: target_name = self.element.members[previous].kind #The contextual element could be a module, in which case it has no parameters if hasattr(self.element, "parameters") and previous in self.element.parameters: target_name = self.element.parameters[previous].kind if target_name == "": return (None, None) return self.context.parser.tree_find(target_name, self.context.module, "types")
<SYSTEM_TASK:> Suggests completion for the end of a type chain. <END_TASK> <USER_TASK:> Description: def _complete_type_chain(self, symbol, fullsymbol): """Suggests completion for the end of a type chain."""
target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol) if target is None: return {} result = {} #We might know what kind of symbol to limit the completion by depending on whether #it was preceded by a "call " for example. Check the context's el_call if symbol != "": if self.context.el_call != "sub": for mkey in target.members: if self._symbol_in(symbol, mkey): result[mkey] = target.members[mkey] for ekey in target.executables: if (self._symbol_in(symbol, ekey)): if self.context.el_call == "sub": if (isinstance(target.executables[ekey], Subroutine)): result[ekey] = target.executables[ekey] else: if (isinstance(target.executables[ekey], Function)): result[ekey] = target.executables[ekey] else: if self.context.el_call != "sub": result.update(target.members) subdict = {k: target.executables[k] for k in target.executables if isinstance(target.executables[k].target, Function)} result.update(subdict) else: subdict = {k: target.executables[k] for k in target.executables if isinstance(target.executables[k].target, Subroutine)} result.update(subdict) return result
<SYSTEM_TASK:> Suggests completion for calling a function or subroutine. <END_TASK> <USER_TASK:> Description: def _complete_sig(self, symbol, attribute): """Suggests completion for calling a function or subroutine."""
#Return a list of valid parameters for the function being called fncall = self.context.el_name iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "executables") if iexec is None: #Try the interfaces as a possible executable to complete. iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "interfaces") if iexec is not None: if symbol == "": return iexec.parameters else: result = {} for ikey in iexec.parameters: if self._symbol_in(symbol, ikey): result[ikey] = iexec.parameters[ikey] return result else: return self._complete_word(symbol, attribute)
<SYSTEM_TASK:> Suggests context completions based exclusively on the word <END_TASK> <USER_TASK:> Description: def _complete_word(self, symbol, attribute): """Suggests context completions based exclusively on the word preceding the cursor."""
#The cursor is after a %(,\s and the user is looking for a list #of possibilities that is a bit smarter that regular AC. if self.context.el_call in ["sub", "fun", "assign", "arith"]: if symbol == "": #The only possibilities are local vars, global vars or functions #presented in that order of likelihood. return self._complete_values() else: #It is also possible that subroutines are being called, but that #the full name hasn't been entered yet. return self._complete_values(symbol) else: return self.context.module.completions(symbol, attribute, True)
<SYSTEM_TASK:> Compiles a list of possible symbols that can hold a value in <END_TASK> <USER_TASK:> Description: def _complete_values(self, symbol = ""): """Compiles a list of possible symbols that can hold a value in place. These consist of local vars, global vars, and functions."""
result = {} #Also add the subroutines from the module and its dependencies. moddict = self._generic_filter_execs(self.context.module) self._cond_update(result, moddict, symbol) self._cond_update(result, self.context.module.interfaces, symbol) for depend in self.context.module.dependencies: if depend in self.context.module.parent.modules: #We don't want to display executables that are part of an interface, or that are embedded in #a derived type, since those will be called through the type or interface filtdict = self._generic_filter_execs(self.context.module.parent.modules[depend]) self._cond_update(result, filtdict, symbol) self._cond_update(result, self.context.module.parent.modules[depend].interfaces, symbol) #Add all the local vars if we are in an executable if (isinstance(self.context.element, Function) or isinstance(self.context.element, Subroutine)): self._cond_update(result, self.element.members, symbol) #Next add the global variables from the module if self.context.module is not None: self._cond_update(result, self.context.module.members, symbol) #Next add user defined functions to the mix for execkey in self.context.module.executables: iexec = self.context.module.executables[execkey] if isinstance(iexec, Function) and self._symbol_in(symbol, iexec.name): result[iexec.name] = iexec #Finally add the builtin functions to the mix. We need to add support #for these in a separate file so we have their call signatures. if symbol == "": #Use the abbreviated list of most common fortran builtins self._cond_update(result, cache.common_builtin, symbol) else: #we can use the full list as there will probably not be that #many left over. self._cond_update(result, cache.builtin, symbol) return result
<SYSTEM_TASK:> Overwrites the keys and values in the first dictionary with those <END_TASK> <USER_TASK:> Description: def _cond_update(self, first, second, symbol, maxadd = -1): """Overwrites the keys and values in the first dictionary with those of the second as long as the symbol matches part of the key. :arg maxadd: specifies a limit on the number of entries from the second dict that will be added to the first."""
if symbol != "": added = 0 for key in second: if self._symbol_in(symbol, key) and (maxadd == -1 or added <= maxadd): first[key] = second[key] added += 1 else: first.update(second)
<SYSTEM_TASK:> Gets the appropriate module attribute name for a collection <END_TASK> <USER_TASK:> Description: def get_attribute(self): """Gets the appropriate module attribute name for a collection corresponding to the context's element type."""
attributes = ['dependencies', 'publics', 'members', 'types', 'executables'] #Find the correct attribute based on the type of the context if self.context.el_type in [Function, Subroutine]: attribute = attributes[4] elif self.context.el_type == CustomType: attribute = attributes[3] else: attribute = attributes[2] return attribute
<SYSTEM_TASK:> Parses the rawtext to extract contents and references. <END_TASK> <USER_TASK:> Description: def parse(self, parser, xml): """Parses the rawtext to extract contents and references."""
#We can only process references if the XML tag has inner-XML if xml.text is not None: matches = parser.RE_REFS.finditer(xml.text) if matches: for match in matches: #Handle "special" references to this.name and param.name here. self.references.append(match.group("reference")) #We also need to get all the XML attributes into the element for key in list(xml.keys()): self.attributes[key] = xml.get(key)
<SYSTEM_TASK:> If -examples was specified in 'args', the specified function <END_TASK> <USER_TASK:> Description: def exhandler(function, parser): """If -examples was specified in 'args', the specified function is called and the application exits. :arg function: the function that prints the examples. :arg parser: the initialized instance of the parser that has the additional, script-specific parameters. """
args = vars(bparser.parse_known_args()[0]) if args["examples"]: function() exit(0) if args["verbose"]: from msg import set_verbosity set_verbosity(args["verbose"]) args.update(vars(parser.parse_known_args()[0])) return args
<SYSTEM_TASK:> Returns a parser with common command-line options for all the scripts <END_TASK> <USER_TASK:> Description: def _common_parser(): """Returns a parser with common command-line options for all the scripts in the fortpy suite. """
import argparse parser = argparse.ArgumentParser(add_help=False) parser.add_argument("-examples", action="store_true", help="See detailed help and examples for this script.") parser.add_argument("-verbose", action="store_true", help="See verbose output as the script runs.") parser.add_argument('-action', nargs=1, choices=['save','print'], default='print', help="Specify what to do with the output (print or save)") parser.add_argument("-debug", action="store_true", help="Print verbose calculation information for debugging.") return parser
<SYSTEM_TASK:> create headers list for flask wrapper <END_TASK> <USER_TASK:> Description: def _getHeaders(self, updateParams=None): """ create headers list for flask wrapper """
if not updateParams: updateParams = {} policies = self.defaultPolicies if len(updateParams) > 0: for k,v in updateParams.items(): k = k.replace('-','_') c = globals()[k](v) try: policies[k] = c.update_policy(self.defaultPolicies[k]) except Exception, e: raise return [globals()[k](v).create_header() for k,v in policies.items() if v is not None]
<SYSTEM_TASK:> create wrapper for flask app route <END_TASK> <USER_TASK:> Description: def wrapper(self, updateParams=None): """ create wrapper for flask app route """
def decorator(f): _headers = self._getHeaders(updateParams) """ flask decorator to include headers """ @wraps(f) def decorated_function(*args, **kwargs): resp = make_response(f(*args, **kwargs)) self._setRespHeader(resp, _headers) resp.has_secure_headers = True return resp return decorated_function return decorator
<SYSTEM_TASK:> Attempts to load the specified module from a serialized, cached <END_TASK> <USER_TASK:> Description: def load_module(self, path, changed_time, parser=None): """Attempts to load the specified module from a serialized, cached version. If that fails, the method returns none."""
if settings.use_filesystem_cache == False: return None try: pickle_changed_time = self._index[path] except KeyError: return None if (changed_time is not None and pickle_changed_time < changed_time): # the pickle file is outdated return None target_path = self._get_hashed_path(path) with open(target_path, 'rb') as f: try: gc.disable() cache_module = pickle.load(f) if parser is not None: for mod in cache_module: mod.unpickle(parser) finally: gc.enable() debug.dbg('pickle loaded: %s', path) return cache_module
<SYSTEM_TASK:> Saves the specified module and its contents to the file system <END_TASK> <USER_TASK:> Description: def save_module(self, path, module, change_time=None): """Saves the specified module and its contents to the file system so that it doesn't have to be parsed again unless it has changed."""
#First, get a list of the module paths that have already been #pickled. We will add to that list of pickling this module. if settings.use_filesystem_cache == False: return self.__index = None try: files = self._index except KeyError: files = {} self._index = files target_path = self._get_hashed_path(path) with open(target_path, 'wb') as f: pickle.dump(module, f, pickle.HIGHEST_PROTOCOL) if change_time is None: files[path] = module[0].change_time else: files[path] = change_time #Save the list back to the disk self._flush_index()
<SYSTEM_TASK:> Keys a list of file paths that have been pickled in this directory. <END_TASK> <USER_TASK:> Description: def _index(self): """Keys a list of file paths that have been pickled in this directory. The index is stored in a json file in the same directory as the pickled objects."""
if self.__index is None: try: with open(self._get_path('index.json')) as f: data = json.load(f) except (IOError, ValueError): self.__index = {} else: # 0 means version is not defined (= always delete cache): if data.get('version', 0) != self.version: self.clear_cache() self.__index = {} else: self.__index = data['index'] return self.__index
<SYSTEM_TASK:> Returns the full path to the cache directory as specified in settings. <END_TASK> <USER_TASK:> Description: def _cache_directory(self): """Returns the full path to the cache directory as specified in settings. """
if settings.unit_testing_mode or settings.use_test_cache: return os.path.join(settings.cache_directory.replace("Fortpy", "Fortpy_Testing"), self.py_tag) else: return os.path.join(settings.cache_directory, self.py_tag)
<SYSTEM_TASK:> Takes a tag string and returns the tag library and tag name. For example, <END_TASK> <USER_TASK:> Description: def get_lib_and_tag_name(tag): """ Takes a tag string and returns the tag library and tag name. For example, "app_tags.tag_name" is returned as "app_tags", "tag_name" and "app_tags.sub.tag_name" is returned as "app_tags.sub", "tag_name" """
if '.' not in tag: raise ValueError('Tag string must be in the format "tag_lib.tag_name"') lib = tag.rpartition('.')[0] tag_name = tag.rpartition('.')[-1] return lib, tag_name
<SYSTEM_TASK:> Expands the contents of the specified auto tag within its parent container. <END_TASK> <USER_TASK:> Description: def _expand_autotag(atag, container): """Expands the contents of the specified auto tag within its parent container. """
if atag.tag != "auto": return if "names" in atag.attrib: i = -1 for name in re.split("[\s,]+", atag.attrib["names"]): if name[0] == '^': name = name[1::] insert = True i += 1 else: insert = False for child in atag: dupe = child.copy() for attr, value in dupe.items(): dupe.attrib[attr] = value.replace("$", name) if insert: container.insert(i, dupe) else: container.append(dupe) else: from fortpy.msg import warn warn("'names' is a required attribute of the <auto> tag.")
<SYSTEM_TASK:> Sets up the patterns and regex objects for parsing the docstrings. <END_TASK> <USER_TASK:> Description: def setup_regex(self): """Sets up the patterns and regex objects for parsing the docstrings."""
#Regex for grabbing out valid XML tags that represent known docstrings that we can work with. self.keywords = [ "summary", "usage", "errors", "member", "group", "local", "comments", "parameter" ] #Regex for extracting the contents of docstrings minus the !! and any leading spaces. self._RX_DOCS = "^\s*!!(?P<docstring>.+?)$" self.RE_DOCS = re.compile(self._RX_DOCS, re.M) #Regex for handling cross references in the documentation self._RX_REFS = r"@CREF\[(?P<reference>[^\]]+)\]" self.RE_REFS = re.compile(self._RX_REFS) #Regex to match first lines of declarations for code elements that can be #decorated by docstrings. self._RX_DECOR = (r"((?P<type>character|real|type|logical|integer|complex)?" r"(?P<kind>\([a-z0-9_]+\))?)?(,?(?P<modifiers>[^\n]+?))?" r"\s*(?P<codetype>subroutine|function|type|module|interface)\s+(?P<name>[^(]+)") self.RE_DECOR = re.compile(self._RX_DECOR, re.I) #Regex for getting the docstrings decorating one or more modules in a code file, #Since they aren't contained inside any other code element, we can't just use #the normal docblocks routines. self._RX_MODDOCS = (r"^(?P<docstring>\s*!!.+?)\n\s*module\s+(?P<name>[A-Za-z0-9_]+)" ".+?end\s+module(\s+(?P=name))?") self.RE_MODDOCS = re.compile(self._RX_MODDOCS, re.DOTALL | re.I)
<SYSTEM_TASK:> Parses the docstrings from the specified string that is the contents of container. <END_TASK> <USER_TASK:> Description: def parse_docs(self, string, container = None): """Parses the docstrings from the specified string that is the contents of container. Returns a dictionary with keys as parent.code_element_name and the values a list of XML elements for corresponding docstrings. :arg container: the instance of the element who owns the string. """
from fortpy.utility import XML result = {} if container is None: #We are working with the code file at the module level. Extract the module #docstrings and XML and return the dictionary with module names as keys. for module in self.RE_MODDOCS.finditer(string): docstring = re.sub("\s*!!", "", module.group("docstring")) doctext = "<doc>{}</doc>".format(re.sub("\n", "\s", docstring)) try: docs = XML(doctext) #Get the name of the module to use as the key and then add the list #of XML docstrings to the result. key = module.group("name") if not key in result: result[key] = [list(docs), module.start(), module.end()] else: result[key][0].extend(list(docs)) except ET.ParseError: msg.err(doctext) else: #This is the text content of a code element that was buried inside of the module. #Get all the docblocks and the items they decorate from this parent. result = self._parse_docblocks(string, container) return result
<SYSTEM_TASK:> Explodes the group members into a list; adds the group to the <END_TASK> <USER_TASK:> Description: def _process_docgroup(self, group, code_el, add=True): """Explodes the group members into a list; adds the group to the specified code element and updates the group value for each of the docstring elements in the group. :arg add: when true, docgroups must be unique in the code element; otherwise, existing groups are overwritten."""
if group.name in code_el.groups and add: msg.warn("duplicate group names in code element {}".format(code_el.name)) else: code_el.groups[group.name] = group kids = self.to_doc(list(group.xml), group.decorates) for child in kids: child.group = group.name return kids
<SYSTEM_TASK:> Associates parameter documentation with parameters for the executable <END_TASK> <USER_TASK:> Description: def process_execdocs(self, docs, anexec, key, add=True): """Associates parameter documentation with parameters for the executable and any remaining docs with the executable itself. - key: the module.executable identifier for the function or subroutine. """
#Paramdocs has a list of docstrings for summary, usage, parameters, etc. #check which belong to parameters and associate them, otherwise append #them to the executable. for doc in docs: if doc.doctype == "parameter": if doc.pointsto is not None and doc.pointsto in anexec.parameters: if add: anexec.parameters[doc.pointsto].docstring.append(doc) else: anexec.parameters[doc.pointsto].overwrite_docs(doc) else: #the parameter docstring is orphaned, give a warning. wmsg = ("the docstring for parameter '{}' had no corresponding " "parameter in the executable definition for '{}' ({}).") msg.warn(wmsg.format(doc.pointsto, anexec.name, anexec.module.filepath)) elif doc.doctype == "group": if "name" not in doc.attributes: doc.attributes["name"] = "default" kids = self._process_docgroup(doc, anexec) if add: anexec.docstring.extend(kids) else: for kid in kids: anexec.overwrite_docs(kid) else: #The docstring must be for the executable if add: anexec.docstring.append(doc) else: anexec.overwrite_docs(doc)
<SYSTEM_TASK:> Associates member type DocElements with their corresponding members <END_TASK> <USER_TASK:> Description: def process_memberdocs(self, docs, codeEl, add=True): """Associates member type DocElements with their corresponding members in the specified code element. The element must have a dictionary of members already."""
#Now we need to associate the members with their docstrings #Some of the members may be buried inside a group tag and #need to be handled separately. remainingdocs = [] expandeddocs = [] #Process any groups that are in the doc list. for doc in docs: if isinstance(doc, DocGroup): kids = self._process_docgroup(doc, codeEl, add) expandeddocs.extend(kids) else: expandeddocs.append(doc) for doc in expandeddocs: #Process the docstring, if it doesn't belong to a member #we will add it to the list of unassigned docstrings, #these most likely point to type declarations. if not self._process_docstrings(doc, codeEl.members, add): remainingdocs.append(doc) return remainingdocs
<SYSTEM_TASK:> Adds the docstrings from the list of DocElements to their <END_TASK> <USER_TASK:> Description: def _process_docstrings(self, doc, members, add=True): """Adds the docstrings from the list of DocElements to their respective members. Returns true if the doc element belonged to a member."""
if ((doc.doctype == "member" or doc.doctype == "local") and doc.pointsto is not None and doc.pointsto in members): if add: members[doc.pointsto].docstring.append(doc) else: members[doc.pointsto].overwrite_docs(doc) return True else: return False
<SYSTEM_TASK:> Converts the specified xml list to a list of docstring elements. <END_TASK> <USER_TASK:> Description: def to_doc(self, xmllist, decorates): """Converts the specified xml list to a list of docstring elements."""
result = [] for xitem in xmllist: if xitem.tag != "group": #The docstring allows a single string to point to multiple #names in a comma-separated list in the names attribute. if "name" in list(xitem.keys()): names = re.split("[\s,]+", xitem.get("name")) for name in names: #Once we have created the DocElement, we need to override #its name attribute (which will have the comma-separated #list) with the single name docel = DocElement(xitem, self, decorates) docel.attributes["name"] = name result.append(docel) else: #This docstring doesn't have a name attribute, just add it result.append(DocElement(xitem, self, decorates)) else: docel = DocGroup(xitem, decorates) result.append(docel) return result
<SYSTEM_TASK:> Parses all the docstrings out of the specified string. <END_TASK> <USER_TASK:> Description: def _parse_docblocks(self, string, container): """Parses all the docstrings out of the specified string. Returns a dictionary of docstrings with the key as parent.code_element_name and the value a list of XML elements that contain docstrings. """
#The easiest way to do this is to look at one line at a time and see if it is a docstring #When we find a group of docstrings that suddenly ends, the next item is the code element #that they were decorating (which may or may not be pertinent). from fortpy.utility import XML current = [] docblocks = {} docstart = 0 for line in string.split("\n"): match = self.RE_DOCS.match(line) if match is not None: current.append(match.group("docstring")) if len(current) == 1: #This was the first docstring of a new documentation block. docend = docstart + len(line) + 1 # +1 for \n removed by split() else: #We already have some docstrings in the block, update start/end docend += len(line) + 1 else: #See if we were previously working on a docstring block or not. if len(current) > 0: #Save all the current docstrings in the blocks dictionary #under the name of the code element in this line. key = self._parse_docline(line, container) #If the docblock has multiple XML tags at the same depth, the XML #parser will scream. Wrap everything in a doc tag. doctext = "<doc>{}</doc>".format(" ".join(current)) try: #Let the docstart and docend *always* be absolute character references. tabsstart, tabsend = container.module.absolute_charindex(string, docstart, docend-len(line)) emsg="module '{0}' docstring starting @ {1[0]}:{1[1]}" emsg=emsg.format(container.module.name, container.module.linenum(tabsstart)) docs = XML(doctext, emsg) if not key in docblocks: absstart, absend = tabsstart, tabsend docblocks[key] = [list(docs), absstart, absend] else: docblocks[key][0].extend(list(docs)) except ET.ParseError as err: msg.err(err.msg) #Reset the list of current docstrings current = [] docstart = docend + len(line) + 1 else: #We need to keep track of the line lengths for docstart/end. docstart += len(line) + 1 return docblocks
<SYSTEM_TASK:> Parses a single line of code following a docblock to see if <END_TASK> <USER_TASK:> Description: def _parse_docline(self, line, container): """Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so, return the name of the code element."""
match = self.RE_DECOR.match(line) if match is not None: return "{}.{}".format(container.name, match.group("name")) else: return container.name
<SYSTEM_TASK:> Parses the docstrings out of the specified xml file. <END_TASK> <USER_TASK:> Description: def parsexml(self, xmlstring, modules, source=None): """Parses the docstrings out of the specified xml file. :arg source: the path to the file from which the XML string was extracted. """
result = {} from fortpy.utility import XML_fromstring xmlroot = XML_fromstring(xmlstring, source) if xmlroot.tag == "fortpy" and "mode" in xmlroot.attrib and \ xmlroot.attrib["mode"] == "docstring": #First, cycle through the kids to find the <global> tag (if any #exist). It's children will apply to any of the other tags we find #and we will have to update their attributes accordingly. xmlglobals = {} for child in xmlroot.iterfind("globals"): _update_globals(list(child), xmlglobals) _set_global_defaults(xmlglobals) #We fill the dictionary with decorates names as keys and lists #of the xml docstring elements as values. for child in xmlroot: if child.tag == "globals": continue xmltags = [] if child.tag == "decorates" and "name" in child.attrib: decorates = child.attrib["name"] xmltags.extend(list(child)) elif "decorates" in child.attrib: decorates = child.attrib["decorates"] xmltags.append(child) for xtag in xmltags: _update_from_globals(xtag, xmlglobals, child) if decorates in result: result[decorates].extend(xmltags) else: result[decorates] = xmltags #Loop through all the docstrings we found and team them up with #their respective module members. self._xml_update_modules(result, modules)
<SYSTEM_TASK:> Updates the docstrings in the specified modules by looking for <END_TASK> <USER_TASK:> Description: def _xml_update_modules(self, xmldict, modules): """Updates the docstrings in the specified modules by looking for docstrings in the xmldict."""
for kdecor in xmldict: modname, memname = kdecor.split(".") if modname in modules: module = modules[modname] #We only need to check the members, types and executables memname = memname.lower() if memname in module.members: docs = self.to_doc(xmldict[kdecor], modname) self.process_memberdocs(docs, module) elif memname in module.types: member = module.types[memname] docs = self.to_doc(xmldict[kdecor], memname) member.docstring.extend(docs) elif memname in module.executables: member = module.executables[memname] docs = self.to_doc(xmldict[kdecor], memname) self.process_execdocs(docs, member, kdecor) else: msg.warn("orphaned docstring. No member {} in module {}.".format( memname, modname)) else: msg.warn("orphaned docstring from XML docfile for {}".format(kdecor))
<SYSTEM_TASK:> Updates the members, executables and types in the specified module <END_TASK> <USER_TASK:> Description: def rt_update_module(self, xmldict, module): """Updates the members, executables and types in the specified module to have the latest docstring information from the xmldict. """
#This keeps track of how many character were added/removed by #updating the docstrings in xmldict. delta = 0 for kdecor in xmldict: if "." in kdecor: modname, memname = kdecor.split(".") else: modname, memname = module.name, None if module.name == modname: #This tag is relevant to the specified module. Continue xlist, docstart, docend = xmldict[kdecor] #We only need to check the members, types and executables #For executables and types, we need to update the docstart and #docend attributes since their docstrings must come as a single #block immediately preceding the signature, so that our values #from the updater will be correct. if memname in module.types: member = module.types[memname] docs = self.to_doc(xlist, memname) member.docstring = docs delta += self._rt_update_docindices(member, docstart, docend) elif memname in module.executables: member = module.executables[memname] docs = self.to_doc(xlist, memname) self.process_execdocs(docs, member, kdecor, False) delta += self._rt_update_docindices(member, docstart, docend) else: #Since it didn't point to anything else, it must be for the #members of the module. docs = self.to_doc(xlist, modname) self.process_memberdocs(docs, module, False) return delta
<SYSTEM_TASK:> Updates the docstart, docend, start and end attributes for the <END_TASK> <USER_TASK:> Description: def _rt_update_docindices(self, element, docstart, docend): """Updates the docstart, docend, start and end attributes for the specified element using the new limits for the docstring."""
#see how many characters have to be added/removed from the end #of the current doc limits. delta = element.docend - docend element.docstart = docstart element.docend = docend element.start += delta element.end += delta return delta
<SYSTEM_TASK:> Paint the table on terminal <END_TASK> <USER_TASK:> Description: def paint(self, tbl): """ Paint the table on terminal Currently only print out basic string format """
if not isinstance(tbl, Table): logging.error("unable to paint table: invalid object") return False self.term.stream.write(self.term.clear) self.term.stream.write(str(tbl)) return True
<SYSTEM_TASK:> Fortpy caches many things, that should be completed after each completion <END_TASK> <USER_TASK:> Description: def clear_caches(delete_all=False): """Fortpy caches many things, that should be completed after each completion finishes. :param delete_all: Deletes also the cache that is normally not deleted, like parser cache, which is important for faster parsing. """
global _time_caches if delete_all: _time_caches = [] _parser = { "default": CodeParser() } else: # normally just kill the expired entries, not all for tc in _time_caches: # check time_cache for expired entries for key, (t, value) in list(tc.items()): if t < time.time(): # delete expired entries del tc[key]
<SYSTEM_TASK:> This function calculates the cache key. <END_TASK> <USER_TASK:> Description: def cache_call_signatures(source, user_pos, stmt): """This function calculates the cache key."""
index = user_pos[0] - 1 lines = source.splitlines() or [''] if source and source[-1] == '\n': lines.append('') before_cursor = lines[index][:user_pos[1]] other_lines = lines[stmt.start_pos[0]:index] whole = '\n'.join(other_lines + [before_cursor]) before_bracket = re.match(r'.*\(', whole, re.DOTALL) module_path = stmt.get_parent_until().path return None if module_path is None else (module_path, before_bracket, stmt.start_pos)
<SYSTEM_TASK:> Make a new node from an existing one. <END_TASK> <USER_TASK:> Description: def make_new_node(self, distance, angle): """Make a new node from an existing one. This method creates a new node with a distance and angle given. The position of the new node is calculated with: x2 = cos(-angle)*distance+x1 y2 = sin(-angle)*distance+y1 Args: distance (float): The distance of the original node to the new node. angle (rad): The angle between the old and new node, relative to the horizont. Returns: object: The node with calculated poistion. """
return Node((cos(-angle)*distance+self.pos[0], sin(-angle)*distance+self.pos[1]))
<SYSTEM_TASK:> Get the angle beetween 2 nodes relative to the horizont. <END_TASK> <USER_TASK:> Description: def get_node_angle(self, node): """Get the angle beetween 2 nodes relative to the horizont. Args: node (object): The other node. Returns: rad: The angle """
return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2
<SYSTEM_TASK:> Get the distance beetween 2 nodes <END_TASK> <USER_TASK:> Description: def get_distance(self, node): """Get the distance beetween 2 nodes Args: node (object): The other node. """
delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1]) return sqrt(delta[0]**2+delta[1]**2)
<SYSTEM_TASK:> Move the node. <END_TASK> <USER_TASK:> Description: def move(self, delta): """Move the node. Args: delta (tupel): A tupel, holding the adjustment of the position. """
self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1])
<SYSTEM_TASK:> Checks the specified executable for the pointer condition that not <END_TASK> <USER_TASK:> Description: def _exec_check_pointers(executable): """Checks the specified executable for the pointer condition that not all members of the derived type have had their values set. Returns (list of offending members, parameter name). """
oparams = [] pmembers = {} xassigns = map(lambda x: x.lower().strip(), executable.external_assignments()) def add_offense(pname, member): """Adds the specified member as an offender under the specified parameter.""" if pname not in oparams: oparams.append(pname) if pname not in pmembers: pmembers[pname] = [member] else: pmembers[pname].append(member) def check_buried(executable, pname, member): """Checks whether the member has its value changed by one of the dependency subroutines in the executable. """ for d in executable.dependencies: if pname in d.argnames: pindex = d.argnames.index(pname) dtarget = d.target if dtarget is not None: mparam = dtarget.ordered_parameters[pindex] for pname, param in executable.parameters.items(): if param.direction == "(out)" and param.is_custom: utype = param.customtype if utype is None: continue for mname, member in utype.members.items(): key = "{}%{}".format(pname, mname).lower().strip() if key not in xassigns: #We also need to check the dependency calls to other, buried subroutines. compname = "{}%{}".format(pname, mname).lower() if executable.changed(compname) is None: add_offense(pname, member) return (oparams, pmembers)
<SYSTEM_TASK:> Checks the user-derived type for non-nullified pointer array declarations <END_TASK> <USER_TASK:> Description: def _type_check_pointers(utype): """Checks the user-derived type for non-nullified pointer array declarations in its base definition. Returns (list of offending members). """
result = [] for mname, member in utype.members.items(): if ("pointer" in member.modifiers and member.D > 0 and (member.default is None or "null" not in member.default)): result.append(member) return result
<SYSTEM_TASK:> Returns the json string from the Hydrawise server after calling <END_TASK> <USER_TASK:> Description: def status_schedule(token): """ Returns the json string from the Hydrawise server after calling statusschedule.php. :param token: The users API token. :type token: string :returns: The response from the controller. If there was an error returns None. :rtype: string or None """
url = 'https://app.hydrawise.com/api/v1/statusschedule.php' payload = { 'api_key': token, 'hours': 168} get_response = requests.get(url, params=payload, timeout=REQUESTS_TIMEOUT) if get_response.status_code == 200 and \ 'error_msg' not in get_response.json(): return get_response.json() return None
<SYSTEM_TASK:> Controls the zone relays to turn sprinklers on and off. <END_TASK> <USER_TASK:> Description: def set_zones(token, action, relay=None, time=None): """ Controls the zone relays to turn sprinklers on and off. :param token: The users API token. :type token: string :param action: The action to perform. Available actions are: run, runall, stop, stopall, suspend, and suspendall. :type action: string :param relay: The zone to take action on. If no zone is specified then the action will be on all zones. :type relay: int or None :param time: The number of seconds to run or unix epoch time to suspend. :type time: int or None :returns: The response from the controller. If there was an error returns None. :rtype: string or None """
# Actions must be one from this list. action_list = [ 'run', # Run a zone for an amount of time. 'runall', # Run all zones for an amount of time. 'stop', # Stop a zone. 'stopall', # stop all zones. 'suspend', # Suspend a zone for an amount of time. 'suspendall' # Suspend all zones. ] # Was a valid action specified? if action not in action_list: return None # Set the relay id if we are operating on a single relay. if action in ['runall', 'stopall', 'suspendall']: if relay is not None: return None else: relay_cmd = '' else: relay_cmd = '&relay_id={}'.format(relay) # Add a time argument if the action requires it. if action in ['run', 'runall', 'suspend', 'suspendall']: if time is None: return None else: custom_cmd = '&custom={}'.format(time) period_cmd = '&period_id=999' else: custom_cmd = '' period_cmd = '' # If action is on a single relay then make sure a relay is specified. if action in ['stop', 'run', 'suspend'] and relay is None: return None get_response = requests.get('https://app.hydrawise.com/api/v1/' 'setzone.php?' '&api_key={}' '&action={}{}{}{}' .format(token, action, relay_cmd, period_cmd, custom_cmd), timeout=REQUESTS_TIMEOUT) if get_response.status_code == 200 and \ 'error_msg' not in get_response.json(): return get_response.json() return None
<SYSTEM_TASK:> The workhorse function for the admin action functions that follow. <END_TASK> <USER_TASK:> Description: def update_status(modeladmin, request, queryset, status): """The workhorse function for the admin action functions that follow."""
# We loop over the objects here rather than use queryset.update() for # two reasons: # # 1. No one should ever be updating zillions of Topics or Questions, so # performance is not an issue. # 2. To be tidy, we want to log what the user has done. # for obj in queryset: obj.status = status obj.save() # Now log what happened. # Use ugettext_noop() 'cause this is going straight into the db. log_message = ugettext_noop(u'Changed status to \'%s\'.' % obj.get_status_display()) modeladmin.log_change(request, obj, log_message) # Send a message to the user telling them what has happened. message_dict = { 'count': queryset.count(), 'object': modeladmin.model._meta.verbose_name, 'verb': dict(STATUS_CHOICES)[status], } if not message_dict['count'] == 1: message_dict['object'] = modeladmin.model._meta.verbose_name_plural user_message = ungettext( u'%(count)s %(object)s was successfully %(verb)s.', u'%(count)s %(object)s were successfully %(verb)s.', message_dict['count']) % message_dict modeladmin.message_user(request, user_message) # Return None to display the change list page again and allow the user # to reload the page without getting that nasty "Send the form again ..." # warning from their browser. return None
<SYSTEM_TASK:> Adds the dependency calls from the specified executable instance <END_TASK> <USER_TASK:> Description: def _exec_callers(xinst, result): """Adds the dependency calls from the specified executable instance to the results dictionary. """
for depkey, depval in xinst.dependencies.items(): if depval.target is not None: if depval.target.name in result: if xinst not in result[depval.target.name]: result[depval.target.name].append(xinst) else: result[depval.target.name] = [xinst] for xname, xvalue in xinst.executables: _exec_callers(xvalue, result)
<SYSTEM_TASK:> Adds any calls to executables contained in the specified module. <END_TASK> <USER_TASK:> Description: def _module_callers(parser, modname, result): """Adds any calls to executables contained in the specified module. """
if modname in result: #We have already processed this module. return module = parser.get(modname) mresult = {} if module is not None: for xname, xinst in module.executables(): _exec_callers(xinst, mresult) result[modname] = mresult for depkey in module.dependencies: depmod = depkey.split('.')[0].lower() _module_callers(parser, depmod, result)
<SYSTEM_TASK:> Appends a list of callees to the branch for each parent <END_TASK> <USER_TASK:> Description: def _call_fan(branch, calls, executable): """Appends a list of callees to the branch for each parent in the call list that calls this executable. """
#Since we don't keep track of the specific logic in the executables #it is possible that we could get a infinite recursion of executables #that keep calling each other. if executable in branch: return branch.append(executable) if executable.name in calls: for caller in calls[executable.name]: twig = [] _call_fan(twig, calls, caller) branch
<SYSTEM_TASK:> Returns the full docstring information for the element suggested <END_TASK> <USER_TASK:> Description: def description(self): """Returns the full docstring information for the element suggested as a completion."""
result = "" if isinstance(self._element, ValueElement): if self._element.kind is not None: result = "{}({}) | {}".format(self._element.dtype, self._element.kind, self._element.summary) else: result = "{} | {}".format(self._element.dtype, self._element.summary) elif isinstance(self._element, Executable): result = "({})".format(self._element.parameters_as_string()) elif isinstance(self._element, str): result = "Intrinsic Fortran Symbol" elif isinstance(self._element, TypeExecutable): result = self._type_description() #Clean off any line breaks from the XML and excessive whitespace. cleaned = re.sub("\s+", " ", result.replace("\n", " ")) return cleaned
<SYSTEM_TASK:> Raises an ``AttributeError``if the definition is not callable. <END_TASK> <USER_TASK:> Description: def params(self): """ Raises an ``AttributeError``if the definition is not callable. Otherwise returns a list of `ValueElement` that represents the params. """
if self.context.el_type in [Function, Subroutine]: return self.evaluator.element.parameters
<SYSTEM_TASK:> Gets the completion description for a TypeExecutable. <END_TASK> <USER_TASK:> Description: def _type_description(self): """Gets the completion description for a TypeExecutable."""
#This is a little tricker because the docstring is housed #inside of the module that contains the actual executable. #These TypeExecutables are just pointers. iexec = self._element.target if iexec is not None: result = "method() | " + iexec.summary else: result = "Type Method: points to executable in module." return result
<SYSTEM_TASK:> Adds the specified DocElement to the docstring list. However, if an <END_TASK> <USER_TASK:> Description: def overwrite_docs(self, doc): """Adds the specified DocElement to the docstring list. However, if an element with the same xml tag and pointsto value already exists, it will be overwritten."""
for i in range(len(self.docstring)): if (self.docstring[i].doctype == doc.doctype and self.docstring[i].pointsto == doc.pointsto): del self.docstring[i] break self.docstring.append(doc)
<SYSTEM_TASK:> Sets the pointers for the docstrings that have groups. <END_TASK> <USER_TASK:> Description: def unpickle_docs(self): """Sets the pointers for the docstrings that have groups."""
for doc in self.docstring: if (doc.parent_name is not None and doc.parent_name in self.groups): doc.group = self.groups[doc.parent_name]
<SYSTEM_TASK:> Returns the absolute start of the element by including docstrings <END_TASK> <USER_TASK:> Description: def absstart(self): """Returns the absolute start of the element by including docstrings outside of the element definition if applicable."""
if hasattr(self, "docstart") and self.docstart > 0: return self.docstart else: return self.start
<SYSTEM_TASK:> Returns the module that this code element belongs to. <END_TASK> <USER_TASK:> Description: def module(self): """Returns the module that this code element belongs to."""
if self._module is None: root = self while self._module is None and root is not None: if isinstance(root, Module): self._module = root else: root = root.parent return self._module
<SYSTEM_TASK:> Returns the docstring summary for the code element if it exists. <END_TASK> <USER_TASK:> Description: def summary(self): """Returns the docstring summary for the code element if it exists."""
if self._summary is None: self._summary = "No summary for element." for doc in self.docstring: if doc.doctype == "summary": self._summary = doc.contents break #If a parameter, member or local tag has dimensions or other children, #then the inner-text is not the right thing to use; find a grand-child #summary tag instead. if self._summary == "No summary for element." and len(self.docstring) > 0: summary = self.doc_children("summary") if len(summary) > 0: self._summary = summary[0].contents else: self._summary = self.docstring[0].contents return self._summary
<SYSTEM_TASK:> Returns the full name of this element by visiting every <END_TASK> <USER_TASK:> Description: def full_name(self): """Returns the full name of this element by visiting every non-None parent in its ancestor chain."""
if self._full_name is None: ancestors = [ self.name ] current = self.parent while current is not None and type(current).__name__ != "CodeParser": ancestors.append(current.name) current = current.parent self._full_name = ".".join(reversed(ancestors)) return self._full_name
<SYSTEM_TASK:> Finds all grand-children of this element's docstrings that match <END_TASK> <USER_TASK:> Description: def doc_children(self, doctype, limiters=[]): """Finds all grand-children of this element's docstrings that match the specified doctype. If 'limiters' is specified, only docstrings with those doctypes are searched. """
result = [] for doc in self.docstring: if len(limiters) == 0 or doc.doctype in limiters: result.extend(doc.children(doctype)) return result
<SYSTEM_TASK:> Checks this code element for documentation related problems. <END_TASK> <USER_TASK:> Description: def warn(self, collection): """Checks this code element for documentation related problems."""
if not self.has_docstring(): collection.append("WARNING: no docstring on code element {}".format(self.name))
<SYSTEM_TASK:> Returns True if the two ValueElement instances differ only by name, <END_TASK> <USER_TASK:> Description: def matched(self, other): """Returns True if the two ValueElement instances differ only by name, default value or some other inconsequential modifier. """
mods = ["allocatable", "pointer"] return (self.kind.lower() == other.kind.lower() and self.dtype.lower() == other.dtype.lower() and self.D == other.D and all([m in other.modifiers for m in self.modifiers if m in mods]))
<SYSTEM_TASK:> Returns a string representing the type and kind of this value element. <END_TASK> <USER_TASK:> Description: def strtype(self): """Returns a string representing the type and kind of this value element."""
if self.kind is not None: return "{}({})".format(self.dtype, self.kind) else: return self.dtype
<SYSTEM_TASK:> Returns a formatted name for the ctypes Fortran wrapper module. <END_TASK> <USER_TASK:> Description: def _get_ctypes_name(self, index=None): """Returns a formatted name for the ctypes Fortran wrapper module. :arg index: the index of the array to return a name for. None for the new parameter, otherwise the index for the integer variable name of that dimension. """
if index is None: if ("allocatable" not in self.modifiers and "pointer" not in self.modifiers and self.dtype != "logical"): #The fortan logical has type 4 by default, whereas c_bool only has 1 return self.name else: return "{}_c".format(self.name) else: return "{0}_{1:d}_c".format(self.name, index)
<SYSTEM_TASK:> Returns the parameter list for this ValueElement adjusted for interoperability <END_TASK> <USER_TASK:> Description: def ctypes_parameter(self): """Returns the parameter list for this ValueElement adjusted for interoperability with the ctypes module. """
if self._ctypes_parameter is None: #Essentially, we just need to check if we are an array that doesn't have explicitly #defined bounds. Assumed-shape arrays have to be 'pointer' or 'allocatable'. However, #the deffered/assumed shape arrays always use ':' as the array dimension. if self.dimension is not None and ":" in self.dimension: result = [self._get_ctypes_name()] result.extend([self._get_ctypes_name(i+1) for i in range(self.D)]) if self.direction == "(inout)" and ("allocatable" in self.modifiers or "pointer" in self.modifiers): result.append("{}_o".format(self.name)) self._ctypes_parameter = result elif self.dtype == "logical": self._ctypes_parameter = [self._get_ctypes_name()] elif hasattr(self, "parameters"): #This is the handler for the function return types that are simple self._ctypes_parameter = [self.name + "_f"] else: #Nothing special, just return the standard name. self._ctypes_parameter = [self.name] return self._ctypes_parameter
<SYSTEM_TASK:> Returns the fortran code string that would define this value element. <END_TASK> <USER_TASK:> Description: def definition(self, suffix = "", local=False, ctype=None, optionals=True, customdim=None, modifiers=None): """Returns the fortran code string that would define this value element. :arg suffix: an optional suffix to append to the name of the variable. Useful for re-using definitions with new names. :arg local: when True, the parameter definition is re-cast as a local variable definition that has the "intent" and "optional" modifiers removed. :arg ctype: if a ctype should be used as the data type of the variable instead of the original type, specify that string here. :arg optionals: removes the "optional" modifier from the definition before generating it. :arg customdim: if the dimension string needs to be changed, specify the new one here. :arg modifiers: specify an additional list of modifiers to add to the variable definition. """
kind = "({})".format(self.kind) if self.kind is not None else "" cleanmods = [m for m in self.modifiers if m != "" and m != " " and not (local and ("intent" in m or m == "optional")) and not (not optionals and m == "optional")] if modifiers is not None: cleanmods.extend(modifiers) if len(cleanmods) > 0: mods = ", " + ", ".join(cleanmods) + " " else: mods = " " if customdim is not None: dimension = "({})".format(customdim) else: dimension = "({})".format(self.dimension) if self.dimension is not None else "" if self.default is None: default = "" else: if ">" in self.default: #We have a pointer, don't add an extra space. default = " ={}".format(self.default) if self.default is not None else "" else: default = " = {}".format(self.default) if self.default is not None else "" name = "{}{}".format(self.name, suffix) stype = self.dtype if ctype is None else ctype return "{}{}{}:: {}{}{}".format(stype, kind, mods, name, dimension, default)
<SYSTEM_TASK:> Returns the ctypes argtypes for use with the method.argtypes assignment for <END_TASK> <USER_TASK:> Description: def argtypes(self): """Returns the ctypes argtypes for use with the method.argtypes assignment for an executable loaded from a shared library. """
if self.dimension is not None: result = [] if "in" in self.direction: #The only complication here is that the 'known' dimensionality could actually #be a function like "size" that needs information about other variables. #If we choose to ignore known shapes, we lose the error checking for the passed #in variables from the python side. if self.direction == "(inout)" and ":" not in self.dimension: wstr = ", writeable" else: wstr = "" if ":" in self.dimension or "size" in self.dimension: template = 'ndpointer(dtype={}, ndim={}, flags="F{}")' result.append(template.format(self.pytype, self.D, wstr)) else: template = 'ndpointer(dtype={}, ndim={}, shape=({}), flags="F{}")' sdim = self.dimension + ("" if self.D > 1 else ",") result.append(template.format(self.pytype, self.D, sdim, wstr)) elif self.direction == "(out)": result.append("c_void_p") if self.D > 0 and ":" in self.dimension: result.extend(["c_int_p" for i in range(self.D)]) if (self.direction == "(inout)" and ":" in self.dimension and ("allocatable" in self.modifiers or "pointer" in self.modifiers)): result.append("c_void_p") return result else: ctype = self.ctype if ctype is not None: return ["{}_p".format(ctype.lower())]
<SYSTEM_TASK:> Returns the name of the c_type from iso_c_binding to use when declaring <END_TASK> <USER_TASK:> Description: def ctype(self): """Returns the name of the c_type from iso_c_binding to use when declaring the output parameter for interaction with python ctypes. """
if self.dtype == "logical": return "C_BOOL" elif self.dtype == "complex": #We don't actually know what the precision of the complex numbers is because #it is defined by the developer when they construct the number with CMPLX() #We just return double to be safe; it is a widening conversion, so there #shouldn't be any issues. return "C_DOUBLE_COMPLEX" elif self.dtype == "character": return "C_CHAR" elif self.dtype in ["integer", "real"]: if self.kind is None: if self.dtype == "integer": return "C_INT" else: return "C_FLOAT" if self._kind_module is None and self.kind is not None: self.dependency() if self._kind_module is None and self.kind is not None: raise ValueError("Can't find the c-type for {}".format(self.definition())) elif self._kind_module is not None: #We look up the parameter in the kind module to find out its #precision etc. import re default = self._kind_module.members[self.kind].default vals = default.split("(")[1].replace(")", "") ints = list(map(int, re.split(",\s*", vals))) if self.dtype == "integer" and len(ints) == 1: if ints[0] <= 15: return "C_SHORT" elif ints[0] <= 31: return "C_INT" elif ints[0] <= 63: return "C_LONG" elif self.dtype == "real" and len(ints) == 2: if ints[0] <= 24 and ints[1] < 127: return "C_FLOAT" elif ints[0] <= 53 and ints[1] < 1023: return "C_DOUBLE"
<SYSTEM_TASK:> If this variable is a user-derivedy type, return the CustomType instance that <END_TASK> <USER_TASK:> Description: def customtype(self): """If this variable is a user-derivedy type, return the CustomType instance that is its kind. """
result = None if self.is_custom: #Look for the module that declares this variable's kind in its public list. self.dependency() if self._kind_module is not None: if self.kind.lower() in self._kind_module.types: result = self._kind_module.types[self.kind.lower()] return result
<SYSTEM_TASK:> Returns the modulename.executable string that uniquely identifies <END_TASK> <USER_TASK:> Description: def external_name(self): """Returns the modulename.executable string that uniquely identifies the executable that this dependency points to."""
target = self.target if target is not None: return "{}.{}".format(target.name.lower(), self.name) else: return "{}.{}".format(self.module.name.lower(), self.name)
<SYSTEM_TASK:> Returns the executable code element that this dependency points to <END_TASK> <USER_TASK:> Description: def target(self): """Returns the executable code element that this dependency points to if it can be found. """
if self._target is None: if '%' in self.name: parts = self.name.split('%') base = self.module.parent.type_search(parts[0], self.name, self.module) if base is not None: self._target = base.target else: self._target = False else: found, foundmod = self.module.parent.tree_find(self.name, self.module, "executables") if found is not None: self._target = found else: self._target = False if isinstance(self._target, Executable): return self._target else: return None
<SYSTEM_TASK:> Cleans the argslist. <END_TASK> <USER_TASK:> Description: def clean(self, argslist): """Cleans the argslist."""
result = [] for arg in argslist: if type(arg) == type([]): if len(result) > 0: result[-1] = result[-1] + "(*{})".format(len(self.clean(arg))) elif "/" not in arg[0]: msg.warn("argument to function call unrecognized. {}".format(arg)) else: cleaner = re.sub("[:,]+", "", arg).strip() if len(cleaner) > 0: result.append(cleaner) return result
<SYSTEM_TASK:> Returns a value indicating whether the specified character index <END_TASK> <USER_TASK:> Description: def find_section(self, charindex): """Returns a value indicating whether the specified character index is owned by the current object."""
#All objects instances of decorable also inherit from CodeElement, #so we should have no problem accessing the start and end attributes. result = None if hasattr(self, "start") and hasattr(self, "end"): #The 8 seems arbitrary, but it is the length of type::b\n for a #really short type declaration with one character name. if charindex > self.docend and charindex - self.start < 8: result = "signature" elif charindex >= self.start and charindex <= self.end: result = "body" if (result is None and charindex >= self.docstart and charindex <= self.docend): result = "docstring" return result