text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def policyChange(self, updateParams, func): """ update defaultPolicy dict """
for k,v in updateParams.items(): k = k.replace('-','_') c = globals()[k](v) try: self.defaultPolicies[k] = getattr(c,func)(self.defaultPolicies[k]) except Exception, e: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tag_html(tag_id): """ Returns the Django HTML to load the tag library and render the tag. Args: tag_id (str): The tag id for the to return the HTML for. """
tag_data = get_lazy_tag_data(tag_id) tag = tag_data['tag'] args = tag_data['args'] kwargs = tag_data['kwargs'] lib, tag_name = get_lib_and_tag_name(tag) args_str = '' if args: for arg in args: if isinstance(arg, six.string_types): args_str += "'{0}' ".format(arg) else: args_str += "{0} ".format(arg) kwargs_str = '' if kwargs: for name, value in kwargs.items(): if isinstance(value, six.string_types): kwargs_str += "{0}='{1}' ".format(name, value) else: kwargs_str += "{0}={1} ".format(name, value) html = '{{% load {lib} %}}{{% {tag_name} {args}{kwargs}%}}'.format( lib=lib, tag_name=tag_name, args=args_str, kwargs=kwargs_str) return html
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def topic_detail(request, slug): """ A detail view of a Topic Templates: :template:`faq/topic_detail.html` Context: topic An :model:`faq.Topic` object. question_list A list of all published :model:`faq.Question` objects that relate to the given :model:`faq.Topic`. """
extra_context = { 'question_list': Question.objects.published().filter(topic__slug=slug), } return object_detail(request, queryset=Topic.objects.published(), extra_context=extra_context, template_object_name='topic', slug=slug)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_dependencies(self): """Returns a list of modules that this executable needs in order to run properly. This includes special kind declarations for precision or derived types, but not dependency executable calls. """
#It is understood that this executable's module is obviously required. Just #add any additional modules from the parameters. result = [p.dependency() for p in self.ordered_parameters] result.extend([v.dependency() for k, v in list(self.members.items())]) for ekey, anexec in list(self.executables.items()): result.extend(anexec.search_dependencies()) return [m for m in result if m is not None and m != self.module.name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unpickle_collection(self, collection): """Unpickles all members of the specified dictionary."""
for mkey in collection: if isinstance(collection[mkey], list): for item in collection[mkey]: item.unpickle(self) else: collection[mkey].unpickle(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rt_update(self, statement, linenum, mode, xparser): """Uses the specified line parser to parse the given line. :arg statement: a string of lines that are part of a single statement. :arg linenum: the line number of the first line in the list relative to the entire module contents. arg mode: either 'insert', 'replace' or 'delete' :arg xparser: an instance of the executable parser from the real time update module's line parser. """
section = self.find_section(self.module.charindex(linenum, 1)) if section == "body": xparser.parse_line(statement, self, mode) elif section == "signature": if mode == "insert": xparser.parse_signature(statement, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_name(self, name): """Changes the name of this executable and the reference to it in the parent module."""
if name != self.name: self.parent.executables[name] = self del self.parent.executables[self.name] self.name = name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_type_target(self): """Returns the CustomType instance if this executable is an embedded procedure in a custom type declaration; else False. """
if self._is_type_target is None: #All we need to do is search through the custom types in the parent #module and see if any of their executables points to this method. self._is_type_target = False for tkey in self.module.types: custype = self.module.types[tkey] for execkey, execinst in custype.executables.items(): if execinst.target is self: self._is_type_target = custype break if self._is_type_target: break return self._is_type_target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_assignments_in(self, filterlist, symbol = ""): """Returns a list of code elements whose names are in the specified object. :arg filterlist: the list of symbols to check agains the assignments. :arg symbol: when specified, return true if that symbol has its value changed via an assignment."""
if symbol != "": lsymbol = symbol for assign in self._assignments: target = assign.split("%")[0].lower() if target == lsymbol: return True else: result = [] for assign in self._assignments: target = assign.split("%")[0].lower() if target in filterlist: result.append(assign) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parameter(self, index): """Returns the ValueElement corresponding to the parameter at the specified index."""
result = None if index < len(self.paramorder): key = self.paramorder[index] if key in self._parameters: result = self._parameters[key] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_parameter(self, parameter): """Adds the specified parameter value to the list."""
if parameter.name.lower() not in self.paramorder: self.paramorder.append(parameter.name.lower()) self._parameters[parameter.name.lower()] = parameter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_parameter(self, parameter_name): """Removes the specified parameter from the list."""
if parameter_name in self.paramorder: index = self.paramorder.index(parameter_name) del self.paramorder[index] if parameter_name in self._parameters: del self._parameters[parameter_name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parameters_as_string(self): """Returns a comma-separated list of the parameters in the executable definition."""
params = ", ".join([ p.name for p in self.ordered_parameters ]) return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_dependency(self, value): """Adds the specified executable dependency to the list for this executable."""
if value.name in self.dependencies: self.dependencies[value.name.lower()].append(value) else: self.dependencies[value.name.lower()] = [ value ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, name, modifiers, dtype, kind): """Updates the attributes for the function instance, handles name changes in the parent module as well."""
self.update_name(name) self.modifiers = modifiers self.dtype = dtype self.kind = kind self.update_dtype()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def returns(self): """Gets a string showing the return type and modifiers for the function in a nice display format."""
kind = "({}) ".format(self.kind) if self.kind is not None else "" mods = ", ".join(self.modifiers) + " " dtype = self.dtype if self.dtype is not None else "" return "{}{}{}".format(dtype, kind, mods)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signature(self): """Returns the signature definition for the subroutine."""
mods = ", ".join(self.modifiers) return "{} SUBROUTINE {}({})".format(mods, self.name, self.parameters_as_string())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, name, modifiers): """Updates the attributes for the subroutine instance, handles name changes in the parent module as well."""
self.update_name(name) self.modifiers = modifiers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def target(self): """Returns the code element that is the actual executable that this type executable points to."""
if self.pointsto is not None: #It is in the format of module.executable. xinst = self.module.parent.get_executable(self.pointsto.lower()) return xinst else: #The executable it points to is the same as its name. fullname = "{}.{}".format(self.module.name, self.name) return self.module.parent.get_executable(fullname.lower())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixedvar(self): """Returns the name of a member in this type that is non-custom so that it would terminate the auto-class variable context chain. """
possible = [m for m in self.members.values() if not m.is_custom] #If any of the possible variables is not allocatable or pointer, it will always #have a value and we can just use that. sufficient = [m for m in possible if "allocatable" not in m.modifiers and "pointer" not in m.modifiers] if len(sufficient) > 0: return [sufficient[0].name] else: return [m.name for m in possible]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recursive(self): """When True, this CustomType has at least one member that is of the same type as itself. """
for m in self.members.values(): if m.kind is not None and m.kind.lower() == self.name.lower(): return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_name(self, name): """Updates the name of the custom type in this instance and its parent reference."""
if name != self.name: self.parent.types[name] = self del self.parent.types[self.name] self.name = name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parameter(self, index): """Gets the list of parameters at the specified index in the calling argument list for each of the module procedures in the interface. :arg index: the 0-based index of the parameter in the argument list. """
result = [] for target in self.targets: if target is not None: result.append(target.get_parameter(index)) return result