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 load_clubs(self): """Fetches the MAL character clubs page and sets the current character's clubs attributes. :rtype: :class:`.Character` :return: Current character object. """
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/clubs').text self.set(self.parse_clubs(utilities.get_clean_dom(character))) return 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 generate(self, minlen, maxlen): """ Generates words of different length without storing them into memory, enforced by itertools.product """
if minlen < 1 or maxlen < minlen: raise ValueError() for cur in range(minlen, maxlen + 1): # string product generator str_generator = product(self.charset, repeat=cur) for each in str_generator: # yield the produced word yield ''.join(each)+self.delimiter
<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_username_from_user_id(session, user_id): """Look up a MAL username's user ID. :type session: :class:`myanimelist.session.Session` :param session: A valid MAL session. :type user_id: int :param user_id: The user ID for which we want to look up a username. :raises: :class:`.InvalidUserError` :rtype: str :return: The given user's username. """
comments_page = session.session.get(u'http://myanimelist.net/comments.php?' + urllib.urlencode({'id': int(user_id)})).text comments_page = bs4.BeautifulSoup(comments_page) username_elt = comments_page.find('h1') if "'s Comments" not in username_elt.text: raise InvalidUserError(user_id, message="Invalid user ID given when looking up username") return username_elt.text.replace("'s Comments", "")
<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_reviews(self, reviews_page): """Parses the DOM and returns user reviews attributes. :type reviews_page: :class:`bs4.BeautifulSoup` :param reviews_page: MAL user reviews page's DOM :rtype: dict :return: User reviews attributes. """
user_info = self.parse_sidebar(reviews_page) second_col = reviews_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: user_info[u'reviews'] = {} reviews = second_col.find_all(u'div', {u'class': u'borderDark'}, recursive=False) if reviews: for row in reviews: review_info = {} try: (meta_elt, review_elt) = row.find_all(u'div', recursive=False)[0:2] except ValueError: raise meta_rows = meta_elt.find_all(u'div', recursive=False) review_info[u'date'] = utilities.parse_profile_date(meta_rows[0].find(u'div').text) media_link = meta_rows[0].find(u'a') link_parts = media_link.get(u'href').split(u'/') # of the form /(anime|manga)/9760/Hoshi_wo_Ou_Kodomo media = getattr(self.session, link_parts[1])(int(link_parts[2])).set({u'title': media_link.text}) helpfuls = meta_rows[1].find(u'span', recursive=False) helpful_match = re.match(r'(?P<people_helped>[0-9]+) of (?P<people_total>[0-9]+)', helpfuls.text).groupdict() review_info[u'people_helped'] = int(helpful_match[u'people_helped']) review_info[u'people_total'] = int(helpful_match[u'people_total']) consumption_match = re.match(r'(?P<media_consumed>[0-9]+) of (?P<media_total>[0-9?]+)', meta_rows[2].text).groupdict() review_info[u'media_consumed'] = int(consumption_match[u'media_consumed']) if consumption_match[u'media_total'] == u'?': review_info[u'media_total'] = None else: review_info[u'media_total'] = int(consumption_match[u'media_total']) review_info[u'rating'] = int(meta_rows[3].find(u'div').text.replace(u'Overall Rating: ', '')) for x in review_elt.find_all([u'div', 'a']): x.extract() review_info[u'text'] = review_elt.text.strip() user_info[u'reviews'][media] = review_info except: if not self.session.suppress_parse_exceptions: raise return user_info
<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_recommendations(self, recommendations_page): """Parses the DOM and returns user recommendations attributes. :type recommendations_page: :class:`bs4.BeautifulSoup` :param recommendations_page: MAL user recommendations page's DOM :rtype: dict :return: User recommendations attributes. """
user_info = self.parse_sidebar(recommendations_page) second_col = recommendations_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: recommendations = second_col.find_all(u"div", {u"class": u"spaceit borderClass"}) if recommendations: user_info[u'recommendations'] = {} for row in recommendations[1:]: anime_table = row.find(u'table') animes = anime_table.find_all(u'td') liked_media_link = animes[0].find(u'a', recursive=False) link_parts = liked_media_link.get(u'href').split(u'/') # of the form /anime|manga/64/Rozen_Maiden liked_media = getattr(self.session, link_parts[1])(int(link_parts[2])).set({u'title': liked_media_link.text}) recommended_media_link = animes[1].find(u'a', recursive=False) link_parts = recommended_media_link.get(u'href').split(u'/') # of the form /anime|manga/64/Rozen_Maiden recommended_media = getattr(self.session, link_parts[1])(int(link_parts[2])).set({u'title': recommended_media_link.text}) recommendation_text = row.find(u'p').text recommendation_menu = row.find(u'div', recursive=False) utilities.extract_tags(recommendation_menu) recommendation_date = utilities.parse_profile_date(recommendation_menu.text.split(u' - ')[1]) user_info[u'recommendations'][liked_media] = {link_parts[1]: recommended_media, 'text': recommendation_text, 'date': recommendation_date} except: if not self.session.suppress_parse_exceptions: raise return user_info
<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_clubs(self, clubs_page): """Parses the DOM and returns user clubs attributes. :type clubs_page: :class:`bs4.BeautifulSoup` :param clubs_page: MAL user clubs page's DOM :rtype: dict :return: User clubs attributes. """
user_info = self.parse_sidebar(clubs_page) second_col = clubs_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: user_info[u'clubs'] = [] club_list = second_col.find(u'ol') if club_list: clubs = club_list.find_all(u'li') for row in clubs: club_link = row.find(u'a') link_parts = club_link.get(u'href').split(u'?cid=') # of the form /clubs.php?cid=10178 user_info[u'clubs'].append(self.session.club(int(link_parts[1])).set({u'name': club_link.text})) except: if not self.session.suppress_parse_exceptions: raise return user_info
<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_friends(self, friends_page): """Parses the DOM and returns user friends attributes. :type friends_page: :class:`bs4.BeautifulSoup` :param friends_page: MAL user friends page's DOM :rtype: dict :return: User friends attributes. """
user_info = self.parse_sidebar(friends_page) second_col = friends_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: user_info[u'friends'] = {} friends = second_col.find_all(u'div', {u'class': u'friendHolder'}) if friends: for row in friends: block = row.find(u'div', {u'class': u'friendBlock'}) cols = block.find_all(u'div') friend_link = cols[1].find(u'a') friend = self.session.user(friend_link.text) friend_info = {} if len(cols) > 2 and cols[2].text != u'': friend_info[u'last_active'] = utilities.parse_profile_date(cols[2].text.strip()) if len(cols) > 3 and cols[3].text != u'': friend_info[u'since'] = utilities.parse_profile_date(cols[3].text.replace(u'Friends since', '').strip()) user_info[u'friends'][friend] = friend_info except: if not self.session.suppress_parse_exceptions: raise return user_info
<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(self): """Fetches the MAL user page and sets the current user's attributes. :rtype: :class:`.User` :return: Current user object. """
user_profile = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username)).text self.set(self.parse(utilities.get_clean_dom(user_profile))) return 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 load_reviews(self): """Fetches the MAL user reviews page and sets the current user's reviews attributes. :rtype: :class:`.User` :return: Current user object. """
page = 0 # collect all reviews over all pages. review_collection = [] while True: user_reviews = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/reviews&' + urllib.urlencode({u'p': page})).text parse_result = self.parse_reviews(utilities.get_clean_dom(user_reviews)) if page == 0: # only set attributes once the first time around. self.set(parse_result) if len(parse_result[u'reviews']) == 0: break review_collection.append(parse_result[u'reviews']) page += 1 # merge the review collections into one review dict, and set it. self.set({ 'reviews': {k: v for d in review_collection for k,v in d.iteritems()} }) return 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 load_recommendations(self): """Fetches the MAL user recommendations page and sets the current user's recommendations attributes. :rtype: :class:`.User` :return: Current user object. """
user_recommendations = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/recommendations').text self.set(self.parse_recommendations(utilities.get_clean_dom(user_recommendations))) return 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 load_clubs(self): """Fetches the MAL user clubs page and sets the current user's clubs attributes. :rtype: :class:`.User` :return: Current user object. """
user_clubs = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/clubs').text self.set(self.parse_clubs(utilities.get_clean_dom(user_clubs))) return 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 load_friends(self): """Fetches the MAL user friends page and sets the current user's friends attributes. :rtype: :class:`.User` :return: Current user object. """
user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text self.set(self.parse_friends(utilities.get_clean_dom(user_friends))) return 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 arb(text, cols, split): """Prints a line of text in arbitrary colors specified by the numeric values contained in msg.cenum dictionary. """
stext = text if text[-1] != split else text[0:-1] words = stext.split(split) for i, word in enumerate(words): col = icols[cols[i]] printer(word, col, end="") if i < len(words)-1: printer(split, end="") else: printer(split)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def will_print(level=1): """Returns True if the current global status of messaging would print a message using any of the printing functions in this module. """
if level == 1: #We only affect printability using the quiet setting. return quiet is None or quiet == False else: return ((isinstance(verbosity, int) and level <= verbosity) or (isinstance(verbosity, bool) and verbosity == 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 warn(msg, level=0, prefix=True): """Prints the specified message as a warning; prepends "WARNING" to the message, so that can be left off. """
if will_print(level): printer(("WARNING: " if prefix else "") + msg, "yellow")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def err(msg, level=-1, prefix=True): """Prints the specified message as an error; prepends "ERROR" to the message, so that can be left off. """
if will_print(level) or verbosity is None: printer(("ERROR: " if prefix else "") + msg, "red")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getenvar(self, envar): from os import getenv """Retrieves the value of an environment variable if it exists."""
if getenv(envar) is not None: self._vardict[envar] = getenv(envar)
<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_isense(self, tag): """Loads isense configuration as a dict of dicts into vardict."""
isense = {} for child in tag: if child.tag in isense: isense[child.tag].update(child.attrib) else: isense[child.tag] = child.attrib self._vardict["isense"] = isense
<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_ssh(self, tag): """Loads the SSH configuration into the vardict."""
for child in tag: if child.tag == "server": self._vardict["server"] = child.attrib elif child.tag == "codes": self._load_codes(child, True) elif child.tag == "mappings": self._load_mapping(child, True) elif child.tag == "libraries": self._load_includes(child, 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 _load_includes(self, tag, ssh=False): """Extracts all additional libraries that should be included when linking the unit testing executables. """
import re includes = [] for child in tag: if child.tag == "include" and "path" in child.attrib: incl = { "path": child.attrib["path"] } if "modules" in child.attrib: incl["modules"] = re.split(",\s*", child.attrib["modules"].lower()) includes.append(incl) if ssh == False: self._vardict["includes"] = includes else: self._vardict["ssh.includes"] = includes
<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_codes(self, tag, ssh=False): """Extracts all the paths to additional code directories to be considered. :arg tag: the ET tag for the <codes> element."""
codes = [] for code in tag: if code.tag == "trunk": codes.append(code.attrib["value"]) if ssh == False: self._vardict["codes"] = codes else: self._vardict["ssh.codes"] = codes
<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_mapping(self, tag, ssh=False): """Extracts all the alternate module name mappings to be considered. :arg tag: the ET tag for the <mappings> element."""
mappings = {} for mapping in tag: if mapping.tag == "map": mappings[mapping.attrib["module"]] = mapping.attrib["file"] if ssh == False: self._vardict["mappings"] = mappings else: self._vardict["ssh.mappings"] = mappings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copytree(src, dst): """Recursively copies the source directory to the destination only if the files are newer or modified by using rsync. """
from os import path, waitpid from subprocess import Popen, PIPE #Append any trailing / that we need to get rsync to work correctly. source = path.join(src, "") desti = path.join(dst, "") if not path.isdir(desti): from os import mkdir mkdir(desti) prsync = Popen("rsync -t -u -r {} {}".format(source, desti), close_fds=True, shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE) waitpid(prsync.pid, 0) #Redirect the output and errors so that we don't pollute stdout. #output = prsync.stdout.readlines() error = prsync.stderr.readlines() prsync.stderr.close() prsync.stdout.close() if len(error) > 0: from fortpy.msg import warn warn("Error while copying {} using rsync.\n\n{}".format(source, '\n'.join(error)))
<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_fortpy_templates_dir(): """Gets the templates directory from the fortpy package."""
import fortpy from os import path fortdir = path.dirname(fortpy.__file__) return path.join(fortdir, "templates")
<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_fortpy_templates(obj, fortpy_templates=None): """Sets the directory path for the fortpy templates. If no directory is specified, use the default one that shipped with the package. """
#If they didn't specify a custom templates directory, use the default #one that shipped with the package. from os import path if fortpy_templates is not None: obj.fortpy_templates = path.abspath(path.expanduser(fortpy_templates)) else: from fortpy.utility import get_fortpy_templates_dir obj.fortpy_templates = get_fortpy_templates_dir()
<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_dir_relpath(base, relpath): """Returns the absolute path to the 'relpath' taken relative to the base directory. :arg base: the base directory to take the path relative to. :arg relpath: the path relative to 'base' in terms of '.' and '..'. """
from os import path xbase = path.abspath(path.expanduser(base)) if not path.isdir(xbase): return path.join(xbase, relpath) if relpath[0:2] == "./": return path.join(xbase, relpath[2::]) else: from os import chdir, getcwd cd = getcwd() chdir(xbase) result = path.abspath(relpath) chdir(cd) 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 wrap_line(line, limit=None, chars=80): """Wraps the specified line of text on whitespace to make sure that none of the lines' lengths exceeds 'chars' characters. """
result = [] builder = [] length = 0 if limit is not None: sline = line[0:limit] else: sline = line for word in sline.split(): if length <= chars: builder.append(word) length += len(word) + 1 else: result.append(' '.join(builder)) builder = [word] length = 0 result.append(' '.join(builder)) 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 x_parse_error(err, content, source): """Explains the specified ParseError instance to show the user where the error happened in their XML. """
lineno, column = err.position if "<doc>" in content: #Adjust the position since we are taking the <doc> part out of the tags #since we may have put that in ourselves. column -= 5 start = lineno - (1 if lineno == 1 else 2) lines = [] tcontent = content.replace("<doc>", "").replace("</doc>", "").split('\n') for context in IT.islice(tcontent, start, lineno): lines.append(context.strip()) last = wrap_line(lines.pop(), column) lines.extend(last) caret = '{:=>{}}'.format('^', len(last[-1])) if source is not None: err.msg = '\nIn: {}\n{}\n{}\n{}'.format(source, err, '\n'.join(lines), caret) else: err.msg = '{}\n{}\n{}'.format(err, '\n'.join(lines), caret) raise err
<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(content, source=None): """Parses the XML text using the ET.XML function, but handling the ParseError in a user-friendly way. """
try: tree = ET.XML(content) except ET.ParseError as err: x_parse_error(err, content, source) return tree
<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_fromstring(content, source=None): """Parses the XML string into a node tree. If an ParseError exception is raised, the error message is formatted nicely to show the badly formed XML to the user. """
try: tree = ET.fromstring(content) except ET.ParseError as err: x_parse_error(err, content, source) return tree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(element): """Formats all of the docstrings in the specified element and its children into a user-friendly paragraph format for printing. :arg element: an instance of fortpy.element.CodeElement. """
result = [] if type(element).__name__ in ["Subroutine", "Function"]: _format_executable(result, element) elif type(element).__name__ == "CustomType": _format_type(result, element) elif isinstance(element, ValueElement): _format_value_element(result, element) return '\n'.join(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 _format_executable(lines, element, spacer=""): """Performs formatting specific to a Subroutine or Function code element for relevant docstrings. """
rlines = [] rlines.append(element.signature) _format_summary(rlines, element) rlines.append("") rlines.append("PARAMETERS") for p in element.ordered_parameters: _format_value_element(rlines, p) rlines.append("") _format_generic(rlines, element, ["summary"]) #Subroutines can have embedded types and functions which need to be handled. if len(element.types) > 0: rlines.append("\nEMBEDDED TYPES") for key, value in list(element.types.items()): _format_type(rlines, value, " ") if len(element.executables) > 0: rlines.append("\nEMBEDDED EXECUTABLES") for key, value in list(element.executables.items()): _format_executable(rlines, value, " ") lines.extend([spacer + l for l in rlines])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_type(lines, element, spacer=""): """Formats a derived type for full documentation output."""
rlines = [] rlines.append(element.signature) _format_summary(rlines, element) rlines.append("") _format_generic(rlines, element, ["summary"]) if len(element.executables) > 0: rlines.append("\nEMBEDDED PROCEDURES") for key, value in list(element.executables.items()): rlines.append(" {}".format(value.__str__())) target = value.target if target is not None: _format_executable(rlines, target, " ") if len(element.members) > 0: rlines.append("\nEMBEDDED MEMBERS") for key, value in list(element.members.items()): _format_value_element(rlines, value, " ") lines.extend([spacer + l for l in rlines])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_value_element(lines, element, spacer=""): """Formats a member or parameter for full documentation output."""
lines.append(spacer + element.definition()) _format_summary(lines, element) _format_generic(lines, element, ["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 _format_summary(lines, element, spacer=" "): """Adds the element's summary tag to the lines if it exists."""
summary = spacer + element.summary if element.summary == "": summary = spacer + "No description given in XML documentation for this element." lines.append(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 _format_generic(lines, element, printed, spacer=""): """Generically formats all remaining docstrings and custom XML tags that don't appear in the list of already printed documentation. :arg printed: a list of XML tags for the element that have already been handled by a higher method. """
for doc in element.docstring: if doc.doctype.lower() not in printed: lines.append(spacer + doc.__str__())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_ex_argtype(executable): """Returns the code to create the argtype to assign to the methods argtypes attribute. """
result = [] for p in executable.ordered_parameters: atypes = p.argtypes if atypes is not None: result.extend(p.argtypes) else: print(("No argtypes for: {}".format(p.definition()))) if type(executable).__name__ == "Function": result.extend(executable.argtypes) 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 _py_ctype(parameter): """Returns the ctypes type name for the specified fortran parameter. """
ctype = parameter.ctype if ctype is None: raise ValueError("Can't bind ctypes py_parameter for parameter" " {}".format(parameter.definition())) return 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 _py_code_clean(lines, tab, executable): """Appends all the code lines needed to create the result class instance and populate its keys with all output variables. """
count = 0 allparams = executable.ordered_parameters if type(executable).__name__ == "Function": allparams = allparams + [executable] for p in allparams: value = _py_clean(p, tab) if value is not None: count += 1 lines.append(value) return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_ftype(parameter, tab): """Returns the code to declare an Ftype object that handles memory deallocation for Fortran return arrays that were allocated by the method called in ctypes. """
splice = ', '.join(["{0}_{1:d}".format(parameter.lname, i) for i in range(parameter.D)]) return "{2}{0}_ft = Ftype({0}_o, [{1}], libpath)".format(parameter.lname, splice, tab)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_clean(parameter, tab): """Returns the code line to clean the output value of the specified parameter. """
if "out" in parameter.direction: if parameter.D > 0: if ":" in parameter.dimension and ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers): if parameter.D == 1: clarray = "as_array({0}_o, ({0}_0.value,))".format(parameter.lname) else: #We have to reverse the order of the indices because of the way that #fortran orders the array elements. We undo this using a transpose in #the ftypes.as_array() so that the elements are ordered correctly. splice = ', '.join(reversed(["{0}_{1:d}.value".format(parameter.lname, i) for i in range(parameter.D)])) clarray = "as_array({0}_o, ({1}))".format(parameter.lname, splice) assign = '{0}result.add("{1}", {2}, {1}_ft)'.format(tab, parameter.lname, clarray) fstr = _py_ftype(parameter, tab) #For optional out parameters, we won't necessarily have anything to report. return _py_check_optional(parameter, tab, [fstr, assign]) else: return '{1}result.add("{0}", {0}_a)'.format(parameter.lname, tab) else: #This handles scalar (inout) and (out) variables. return '{1}result.add("{0}", {0}_c.value)'.format(parameter.lname, tab)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_code_variables(lines, executable, lparams, tab): """Adds the variable code lines for all the parameters in the executable. :arg lparams: a list of the local variable declarations made so far that need to be passed to the executable when it is called. """
allparams = executable.ordered_parameters if type(executable).__name__ == "Function": allparams = allparams + [executable] for p in allparams: _py_code_parameter(lines, p, "invar", lparams, tab) if p.direction == "(out)": #We need to reverse the order of the indices to match the fortran code #generation of the wrapper. _py_code_parameter(lines, p, "outvar", lparams, tab) _py_code_parameter(lines, p, "indices", lparams, tab) else: _py_code_parameter(lines, p, "indices", lparams, tab) _py_code_parameter(lines, p, "outvar", lparams, tab)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_code_parameter(lines, parameter, position, lparams, tab): """Appends the code to produce the parameter at the specified position in the executable. :arg position: one of ['invar', 'outvar', 'indices']. :arg lparams: a list of the local variable declarations made so far that need to be passed to the executable when it is called. """
mdict = { "invar": _py_invar, "outvar": _py_outvar, "indices": _py_indices } line = mdict[position](parameter, lparams, tab) if line is not None: value, blank = line lines.append(tab + value) if blank: lines.append("")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_invar(parameter, lparams, tab): """Returns the code to create the local input parameter that is coerced to have the correct type for ctypes interaction. """
if ("in" in parameter.direction and parameter.D > 0): if parameter.direction == "(inout)" and ":" not in parameter.dimension: wstr = ", writeable" else: wstr = "" pytype = _py_pytype(parameter) lparams.append("{}_a".format(parameter.lname)) return ('{0}_a = require({0}, {1}, "F{2}")'.format(parameter.lname, pytype, wstr), False) elif parameter.D == 0: #Even for scalar outvars, we need to initialize a variable to pass by reference. lparams.append("byref({}_c)".format(parameter.lname)) if parameter.direction == "(out)": initval = parameter.py_initval return ("{0}_c = {1}({2})".format(parameter.lname, _py_ctype(parameter), initval), False) else: return ("{0}_c = {1}({0})".format(parameter.lname, _py_ctype(parameter)), 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 _py_outvar(parameter, lparams, tab): """Returns the code to produce a ctypes output variable for interacting with fortran. """
if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)): lparams.append("byref({}_o)".format(parameter.lname)) blank = True if parameter.direction == "(inout)" else False return ("{0}_o = POINTER({1})()".format(parameter.lname, _py_ctype(parameter)), blank)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _py_indices(parameter, lparams, tab): """Returns the code to produce py ctypes for the indices of the specified parameter that has D > 0. """
if parameter.D > 0 and ":" in parameter.dimension: if "in" in parameter.direction: indexstr = "{0}_{1:d} = c_int({0}_a.shape[{1:d}])" else: indexstr = "{0}_{1:d} = c_int(0)" lparams.extend(["byref({}_{})".format(parameter.lname, i) for i in range(parameter.D)]) joinstr = "\n" + tab blank = True if parameter.direction == "(out)" else False return (joinstr.join([indexstr.format(parameter.lname, i) for i in range(parameter.D)]), blank)
<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_code_parameter(lines, parameter, position): """Returns the code for the specified parameter being written into a subroutine wrapper. :arg position: one of ['indices', 'variable', 'out', 'regular', 'saved', 'assign', 'clean'] """
mdict = { 'indices': _ctypes_indices, 'variable': _ctypes_variables, 'out': _ctypes_out, 'regular': _ctypes_regular, 'saved': _ctypes_saved, 'assign': _ctypes_assign, 'clean': _ctypes_clean } line = mdict[position](parameter) if line is not None: value, blank = line lines.append(value) if blank: lines.append("")
<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_dtype(parameter): """Determines the ISO_C data type to use for describing the specified parameter. """
ctype = parameter.ctype if ctype is None: if parameter.kind is not None: return "{}({})".format(parameter.dtype, parameter.kind) else: return parameter.dtype else: return"{}({})".format(parameter.dtype, ctype)
<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_splice(parameter): """Returns a list of variable names that define the size of each dimension. """
params = parameter.ctypes_parameter() if parameter.direction == "(inout)" and ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers): return ', '.join(params[1:-1]) else: return ', '.join(params[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 _ctypes_indices(parameter): """Returns code for parameter variable declarations specifying the size of each dimension in the specified parameter. """
if (parameter.dimension is not None and ":" in parameter.dimension): splice = _ctypes_splice(parameter) if "out" in parameter.direction: #Even for pure out variables, the ctypes pointer is passed in and will #have a value already. return ("integer, intent(inout) :: {}".format(splice), False) else: return ("integer, intent(in) :: {}".format(splice), 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 _ctypes_variables(parameter): """Returns the local parameter definition for implementing a Fortran wrapper subroutine for this parameter's parent executable. """
if parameter.dimension is not None and ":" in parameter.dimension: #For arrays that provide input (including 'inout'), we pass the output separately #through a c-pointer. They will always be input arrays. For pure (out) parameters #we use *only* a c-ptr, but it needs intent (inout) since it is created by ctypes. if "in" in parameter.direction or parameter.direction == "": #We have to get the ctypes-compatible data type for the parameters. #stype = _ctypes_dtype(parameter) splice = _ctypes_splice(parameter) name = parameter.ctypes_parameter()[0] if parameter.direction == "(inout)" and not ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers): return (parameter.definition(optionals=False, customdim=splice), False) else: return ("{}, intent(in) :: {}({})".format(parameter.strtype, name, splice), False) else: if parameter.dtype == "logical": stype = _ctypes_dtype(parameter) suffix = "_c" modifiers = None elif hasattr(parameter, "parameters"): stype = None suffix = "_f" modifiers = ["intent(out)"] else: stype = None suffix = "" modifiers = None return (parameter.definition(ctype=stype, optionals=False, suffix=suffix, modifiers=modifiers), 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 _ctypes_out(parameter): """Returns a parameter variable declaration for an output variable for the specified parameter. """
if (parameter.dimension is not None and ":" in parameter.dimension and "out" in parameter.direction and ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)): if parameter.direction == "(inout)": return ("type(C_PTR), intent(inout) :: {}_o".format(parameter.name), True) else: #self.direction == "(out)" since that is the only other option. return ("type(C_PTR), intent(inout) :: {}_c".format(parameter.name), 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 _ctypes_saved(parameter): """Returns local variable declarations that create allocatable variables that can persist long enough to return their value through ctypes. """
if ("out" in parameter.direction and parameter.dimension is not None and ":" in parameter.dimension and ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)): stype = _ctypes_dtype(parameter) name = "{}_t({})".format(parameter.name, parameter.dimension) return ("{}, allocatable, target, save :: {}".format(stype, name), 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 _ctypes_clean(parameter): """Returns the lines of code required to assign the correct values to the integers representing the indices of the output arrays in the ctypes wrapper subroutine. """
if ("out" in parameter.direction and parameter.dimension is not None and ":" in parameter.dimension and ("pointer" in parameter.modifiers or "allocatable" in parameter.modifiers)): params = parameter.ctypes_parameter() result = [] spacer = " " #We get segfaults if we try to assign c-pointers to unallocated pointers or arrays. if "optional" in parameter.modifiers: if "pointer" in parameter.modifiers: result.append("{}if (associated({})) then".format(spacer, parameter.name)) spacer += " " elif "allocatable" in parameter.modifiers: result.append("{}if (allocated({})) then".format(spacer, parameter.name)) spacer += " " #We have to copy the values or at least update the pointer to access the #variables with 'target' and 'save' attributes. result.append("{0}{1}_t = {1}".format(spacer, parameter.name)) if parameter.direction == "(inout)": result.append("{1}{0}_o = C_LOC({0}_t)".format(parameter.name, spacer)) #Update the index variables for the dimensions of the output variable. for i, p in enumerate(params[1:-1]): result.append("{}{} = size({}, {})".format(spacer, p, parameter.name, i+1)) else: #This is the case for intent(out) result.append("{1}{0}_c = C_LOC({0}_t)".format(parameter.name, spacer)) for i, p in enumerate(params[1::]): result.append("{}{} = size({}, {})".format(spacer, p, parameter.name, i+1)) if ("optional" in parameter.modifiers and ("pointer" in parameter.modifiers or "allocatable" in parameter.modifiers)): result.append(" end if") return ('\n'.join(result), True) elif parameter.dtype == "logical" and "out" in parameter.direction: return (" {0}_c = {0}".format(parameter.name), 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 _ctypes_ex_parameters(executable): """Returns a list of the parameters to form the wrapper executable to interact with ctypes. """
result = [] for p in executable.ordered_parameters: result.extend(p.ctypes_parameter()) if type(executable).__name__ == "Function": result.extend(executable.ctypes_parameter()) #This method inherits from ValueElement. 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 _ctypes_ex_variables(executable): """Returns a list of the local variable definitions required to construct the ctypes interop wrapper. """
result = [] for p in executable.ordered_parameters: _ctypes_code_parameter(result, p, "indices") _ctypes_code_parameter(result, p, "variable") _ctypes_code_parameter(result, p, "out") if type(executable).__name__ == "Function": #For functions, we still create a subroutine-type interface and then just add an extra #output-type parameter for the function's return type. _ctypes_code_parameter(result, executable, "indices") _ctypes_code_parameter(result, executable, "variable") _ctypes_code_parameter(result, executable, "out") 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 _ctypes_ex_compatvars(executable): """Returns a list of code lines for signature matching variables, and pointer saving variables. """
result = [] for p in executable.ordered_parameters: _ctypes_code_parameter(result, p, "regular") _ctypes_code_parameter(result, p, "saved") if type(executable).__name__ == "Function": _ctypes_code_parameter(result, executable, "regular") _ctypes_code_parameter(result, executable, "saved") 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 _ctypes_ex_assign(executable): """Return a list of code lines to allocate and assign the local parameter definitions that match those in the signature of the wrapped executable. """
result = [] for p in executable.ordered_parameters: _ctypes_code_parameter(result, p, "assign") if type(executable).__name__ == "Function": _ctypes_code_parameter(result, executable, "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 _ctypes_ex_clean(executable): """Return a list of code lines to take care of assigning pointers for output variables interacting with ctypes. """
result = [] for p in executable.ordered_parameters: _ctypes_code_parameter(result, p, "clean") if type(executable).__name__ == "Function": _ctypes_code_parameter(result, executable, "clean") 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 libname(self): """Returns the name of the shared library file compiled for the wrapper subroutines coded in fortran. """
if self.library is not None: return "ftypes.{}.so".format(self.library) else: return "{}.so".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 _check_lib(self, remake, compiler, debug, profile): """Makes sure that the linked library with the original code exists. If it doesn't the library is compiled from scratch. """
from os import path if self.link is None or not path.isfile(self.link): self.makelib(remake, True, compiler, debug, profile)
<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(self, dirpath, makename, compiler, debug, profile): """Compiles the makefile at the specified location with 'compiler'. :arg dirpath: the full path to the directory where the makefile lives. :arg compiler: one of ['ifort', 'gfortran']. :arg makename: the name of the make file to compile. """
from os import path options = "" if debug: options += " DEBUG=true" if profile: options += " GPROF=true" from os import system codestr = "cd {}; make -f '{}' F90={} FAM={}" + options code = system(codestr.format(dirpath, makename, compiler, compiler[0])) #It turns out that the compiler still returns a code of zero, even if the compile #failed because the actual compiler didn't fail; it did its job properly. We need to #check for the existence of errors in the 'compile.log' file. lcount = 0 errors = [] log = path.join(dirpath, "compile.log") with open(log) as f: for line in f: lcount += 1 if lcount > 21 and lcount < 32: errors.append(line) elif lcount > 21: break if len(errors) > 0: #There are 21 lines in the compile.log file when everything runs correctly #Overwrite code with a bad exit value since we have some other problems. code = 1 #We want to write the first couple of errors to the console and give them the #option to still execute if the compile only generated warnings. msg.warn("compile generated some errors or warnings:") msg.blank() msg.info(''.join(errors)) return code
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makelib(self, remake=False, full=True, compiler="gfortran", debug=False, profile=False): """Generates a makefile for the code files that reside in the same directory as the source that was parsed by the code parser. :arg full: when True, the shared library is compiled for *all* the code files in the directory not just the one's that are dependencies of the source module. """
if self.link is None or remake: from os import path if self.library is not None: outpath = path.join(self.dirpath, "{}.a".format(self.library)) else: outpath = path.join(self.dirpath, "{}.a".format(self.name)) if not remake and path.isfile(outpath): #No need to recompile self.link = outpath return dependencies = self._get_lib_modules(full) makepath = path.join(path.dirname(self.module.filepath), "Makefile.ftypes") if full: compileid = "ftypes.all_libs" identifier = self.library else: compileid = "ftypes.{}_c".format(self.module.name) identifier = self.module.name makefile(identifier, dependencies, makepath, compileid, self.module.precompile, False, self.module.parent, "a") code = self._compile(path.dirname(self.module.filepath), "Makefile.ftypes", compiler, debug, profile) if code == 0: self.link = path.join(path.dirname(self.module.filepath), "{}.a".format(identifier)) self._copy_so(outpath) self.link = outpath else: #Just make sure it is copied over into the directory where we want to compile the wrapper #module for ftypes. self._copy_so(self.dirpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_so(self, outpath): """Copies the shared library in self.so into the working directory for the wrapper module if it doesn't already exist. """
from os import path if not path.isfile(outpath) and path.isfile(self.link): from shutil import copy copy(self.link, outpath)
<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_modules(self, full): """Returns a list of the modules in the same folder as the one being wrapped for compilation as a linked library. :arg full: when True, all the code files in the source file's directory are considered as dependencies; otherwise only those explicitly needed are kept. """
#The only complication with the whole process is that we need to get the list of #dependencies for the current module. For full lib, we compile *all* the files in #the directory, otherwise only those that are explicitly required. result = [] if full: found = {} from os import path mypath = path.dirname(self.module.filepath) self.module.parent.scan_path(mypath, found) for codefile in found: self.module.parent.load_dependency(codefile.replace(".f90", ""), True, True, False) for modname, module in list(self.module.parent.modules.items()): if path.dirname(module.filepath).lower() == mypath.lower(): result.append(modname) else: result.extend(self.module.search_dependencies()) return self._process_module_needs(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_dependencies(self): """Gets a list of the module names that should be included in the shared lib compile as dependencies for the current wrapper module. """
#The only complication with the whole process is that we need to get the list of #dependencies for the current module. For full lib, we compile *all* the files in #the directory, otherwise only those that are explicitly required. from os import path modules = self.module.search_dependencies() result = {} for module in modules: self.module.parent.load_dependency(module, True, True, False) for modname, module in list(self.module.parent.modules.items()): pathkey = path.dirname(module.filepath).lower() if pathkey not in result: result[pathkey] = path.dirname(module.filepath) 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_executables(self): """Finds the list of executables that pass the requirements necessary to have a wrapper created for them. """
if len(self.needs) > 0: return for execname, executable in list(self.module.executables.items()): skip = False #At the moment we can't handle executables that use special derived types. if not execname in self.module.publics or not executable.primitive: msg.info("Skipping {}.{} because it is not public.".format(self.module.name, execname)) skip = True #Check that all the parameters have intent specified, otherwise we won't handle them well.ha if any([p.direction == "" for p in executable.ordered_parameters]): msg.warn("Some parameters in {}.{} have no intent".format(self.module.name, execname) + " specified. Can't wrap that executable.") skip = True if not skip: self.uses.append(execname) for depmod in executable.search_dependencies(): if depmod not in self.needs: self.needs.append(depmod)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_dir(self): """Makes sure that the working directory for the wrapper modules exists. """
from os import path, mkdir if not path.isdir(self.dirpath): mkdir(self.dirpath) #Copy the ftypes.py module shipped with fortpy to the local directory. ftypes = path.join(get_fortpy_templates(), "ftypes.py") from shutil import copy copy(ftypes, self.dirpath) #Create the __init__.py file so that the library becomes a package for #its module contents. with open(path.join(self.dirpath, "__init__.py"), 'w') as f: f.write("# Auto-generated for package structure by fortpy.") #We also need to make sure that the fortpy deallocator module is present for #compilation in the shared library. if not path.isdir(self.f90path): mkdir(self.f90path) #Copy the ftypes.py module shipped with fortpy to the local directory. ftypes = path.join(get_fortpy_templates(), "ftypes_dealloc.f90") from shutil import copy copy(ftypes, self.f90path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_py(self): """Writes a python module file to the current working directory for the library. """
self._check_dir() #We make it so that the write py method can be called independently (as opposed #to first needing the F90 write method to be called). self._find_executables() lines = [] lines.append('"""Auto-generated python module for interaction with Fortran shared library\n' 'via ctypes. Generated for module {}.\n'.format(self.module.name) + '"""') lines.append("from ctypes import *") lines.append("from ftypes import *") lines.append("from numpy.ctypeslib import load_library, ndpointer") lines.append("from numpy import require") lines.append("from os import path") lines.append("") for execkey in self.uses: self._write_executable_py(execkey, lines) from os import path pypath = path.join(self.dirpath, "{}.py".format(self.module.name.lower())) with open(pypath, 'w') as f: f.write('\n'.join(lines))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_f90(self): """Writes the F90 module file to the specified directory. """
from os import path self._check_dir() #Find the list of executables that we actually need to write wrappers for. self._find_executables() lines = [] lines.append("!!<summary>Auto-generated Fortran module for interaction with ctypes\n" "!!through python. Generated for module {}.</summary>".format(self.module.name)) lines.append("MODULE {}_c".format(self.module.name)) #Some of the variables and parameters will have special kinds that need to be imported. #Check each of the executables to find additional dependencies. lines.append(" use {}".format(self.module.name)) lines.append(" use ISO_C_BINDING") for modname in self.needs: lines.append(" use {}".format(modname)) lines.append(" implicit none") lines.append("CONTAINS") #We want everything in these wrapper modules to be public, so we just exclude the 'private'. for execkey in self.uses: self._write_executable_f90(execkey, lines) lines.append("END MODULE {}_c".format(self.module.name)) fullpath = path.join(self.f90path, "{}_c.f90".format(self.module.name)) with open(fullpath, 'w') as f: f.write('\n'.join(lines))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_executable_f90(self, execname, lines): """Appends the Fortran code to write the wrapper executable to the specified 'lines' list. :arg execname: the name of the executable in the self.module.executables to write. """
executable = self.module.executables[execname] #The 14 in the formatting indent comes from 4 spaces, 2 from "_c", 1 from the spacing #between 'subroutine' and name of the executable, 10 from subroutine, 1 from the (" cparams = present_params(_ctypes_ex_parameters(executable), len(execname) + 14) lines.append(" subroutine {}_c({}) BIND(C)".format(execname, cparams)) #Next, we add the variables declarations, the call to the original executable and then #the handling of the output variables. lines.append(" " + "\n ".join(_ctypes_ex_variables(executable))) lines.append(" " + "\n ".join(_ctypes_ex_compatvars(executable))) #Add assignment/allocate statements for the intent(in*) paramaters *local* variable #declarations so that we can match the signature exactly. lines.extend(_ctypes_ex_assign(executable)) if type(executable).__name__ == "Subroutine": prefix = "call " else: prefix = "{}_f = ".format(execname) spacing = len(list(prefix)) + len(list(execname)) + 4 lines.append(" {}{}({})".format(prefix, execname, present_params(executable.paramorder, spacing, 90))) lines.append("") lines.extend(_ctypes_ex_clean(executable)) lines.append(" end subroutine {}_c\n".format(execname))
<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_module_needs(self, modules): """Adds the module and its dependencies to the result list in dependency order."""
result = list(modules) for i, module in enumerate(modules): #It is possible that the parser couldn't find it, if so #we can't create the executable! if module in self.module.parent.modules: modneeds = self.module.parent.modules[module].needs for modn in modneeds: if modn not in result: #Since this module depends on the other, insert the other #above it in the list. result.insert(i, modn) else: x = result.index(modn) if x > i: #We need to move this module higher up in the food chain #because it is needed sooner. result.remove(modn) result.insert(i, modn) newi = result.index(modn) else: raise ValueError("Unable to find module {}.".format(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 coderelpath(coderoot, relpath): """Returns the absolute path of the 'relpath' relative to the specified code directory."""
from os import chdir, getcwd, path cd = getcwd() chdir(coderoot) result = path.abspath(relpath) chdir(cd) 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 _setup_ssh(self): """Initializes the connection to the server via SSH."""
global paramiko if paramiko is none: import paramiko self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(self.server, username=self.user, pkey=self.pkey)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abspath(self, path): """Returns the absolute path to the specified relative or user-relative path. For ssh paths, just return the full ssh path."""
if self.is_ssh(path): return path else: return os.path.abspath(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirname(self, path): """Returns the full path to the parent directory of the specified file path."""
if self.is_ssh(path): remotepath = self._get_remote(path) remotedir = os.path.dirname(remotepath) return self._get_tramp_path(remotedir) else: return os.path.dirname(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def touch(self, filepath): """Touches the specified file so that its modified time changes."""
if self.is_ssh(filepath): self._check_ssh() remotepath = self._get_remote(filepath) stdin, stdout, stderr = self.ssh.exec_command("touch {}".format(remotepath)) stdin.close() else: os.system("touch {}".format(filepath))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expanduser(self, filepath, ssh=False): """Replaces the user root ~ with the full path on the file system. Works for local disks and remote servers. For remote servers, set ssh=True."""
if ssh: self._check_ssh() stdin, stdout, stderr = self.ssh.exec_command("cd; pwd") stdin.close() remotepath = filepath.replace("~", stdout.read().split()[0]) return self._get_tramp_path(remotepath) else: return os.path.expanduser(filepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getmtime(self, filepath): """Gets the last time that the file was modified."""
if self.is_ssh(filepath): self._check_ftp() source = self._get_remote(filepath) mtime = self.ftp.stat(source).st_mtime else: mtime = os.path.getmtime(filepath) return mtime
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, filepath): """Returns the entire file as a string even if it is on a remote server."""
target = self._read_check(filepath) if os.path.isfile(target): with open(target) as f: string = f.read() #If we got this file via SSH, delete it from the temp folder if self.is_ssh(filepath): os.remove(target) else: string = "" return 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 walk(self, dirpath): """Performs an os.walk on a local or SSH filepath."""
if self.is_ssh(dirpath): self._check_ftp() remotepath = self._get_remote(dirpath) return self._sftp_walk(remotepath) else: return os.walk(dirpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sftp_walk(self, remotepath): """Performs the same function as os.walk but over the SSH channel."""
#Get all the files and folders in the current directory over SFTP. path = remotepath # We need this instance of path for the yield to work. files=[] folders=[] for f in self.ftp.listdir_attr(remotepath): if S_ISDIR(f.st_mode): folders.append(self._get_tramp_path(f.filename)) else: files.append(f.filename) #We use yield so that if there are really large folders with #complicated structures, we don't wait forever while the SFTP #keeps traversing down the tree. yield path, folders, files #Now call this method recursively for each of sub-directories. for folder in folders: new_path = os.path.join(remotepath, folder) for x in self._sftp_walk(new_path): yield x
<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_hashed_path(self, path): """Returns an md5 hash for the specified file path."""
return self._get_path('%s.pkl' % hashlib.md5(path.encode("utf-8")).hexdigest())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pkey(self): """Returns the private key for quick authentication on the SSH server."""
if self._pkey is None: self._pkey = self._get_pkey() return self._pkey
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metarate(self, func, name='values'): """ Set the values object to the function object's namespace """
setattr(func, name, self.values) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exit(self, status=0, message=None): """ Delegates to `ArgumentParser.exit` """
if status: self.logger.error(message) if self.__parser__: # pylint: disable-msg=E1101 self.__parser__.exit(status, message) # pylint: disable-msg=E1101 else: sys.exit(status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, message=None): """ Delegates to `ArgumentParser.error` """
if self.__parser__: # pylint: disable-msg=E1101 self.__parser__.error(message) # pylint: disable-msg=E1101 else: self.logger.error(message) sys.exit(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 run(self, args=None): """ Runs the main command or sub command based on user input """
if not args: args = self.parse(sys.argv[1:]) if getattr(args, 'verbose', False): self.logger.setLevel(logging.DEBUG) try: if hasattr(args, 'run'): args.run(self, args) else: self.__main__(args) # pylint: disable-msg=E1101 except Exception as e: # pylint: disable-msg=W0703 import traceback self.logger.debug(traceback.format_exc()) self.logger.error(str(e)) if self.raise_exceptions: raise sys.exit(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 nvalues(self): """Returns the number of values recorded on this single line. If the number is variable, it returns -1."""
if self._nvalues is None: self._nvalues = 0 for val in self.values: if type(val) == type(int): self._nvalues += val else: self._nvalues = -1 break return self._nvalues
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, valuedict): """Returns the lines that this template line should add to the input file."""
if self.identifier in valuedict: value = valuedict[self.identifier] elif self.default is not None: value = self.default elif self.fromtag is not None and self.fromtag in valuedict: if self.operator == "count": value = len(valuedict[self.fromtag]) else: msg.err("referenced 'from' attribute/operator {} not in xml dictionary.".format(self.fromtag)) exit(1) else: msg.err("a required line {} had no value or default specified.".format(self.identifier)) exit(1) #Before we generate the result, validate the choices if they exist if len(self.choices) > 0: for single in value: if str(single) not in self.choices: msg.warn("failed choices validation for {} in {} (line {})".format( single, self.choices, self.identifier)) result = [] #Get the string representation of the value if isinstance(value, list): sval = " ".join([ str(val) for val in value]) else: sval = str(value) if self.comment != "" and (self.nvalues < 0 or self.nvalues > 5): #We will put the comments on a separate line from the actual values. result.append(self.comment) result.append(sval) else: result.append("{} {}".format(sval, self.comment)) 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(self, element): """Parses the contents of the specified XML element using template info. :arg element: the XML element from the input file being converted. """
result = [] if element.text is not None and element.tag == self.identifier: l, k = (0, 0) raw = element.text.split() while k < len(self.values): dtype = self.dtype[k] if isinstance(self.values[k], int): for i in range(self.values[k]): result.append(self._caster[dtype](raw[i + l])) l += self.values[k] k += 1 else: #This is a variable argument line, just use up the rest #of them as the type of the current line rest = [ self._caster[dtype](val) for val in raw[l::] ] result.extend(rest) break else: msg.warn("no results for parsing {} using line {}".format(element.tag, self.identifier)) 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 _cast_int(self, value): """Returns the specified value as int if possible."""
try: return int(value) except ValueError: msg.err("Cannot convert {} to int for line {}.".format(value, self.identifier)) exit(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 _cast_float(self, value): """Returns the specified value as float if possible."""
try: return float(value) except ValueError: msg.err("Cannot convert {} to float for line {}.".format(value, self.identifier)) exit(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 _load(self, element, commentchar): """Loads all the child line elements from the XML group element."""
for child in element: if "id" in child.attrib: tline = TemplateLine(child, self, commentchar) self.order.append(tline.identifier) self.lines[tline.identifier] = tline else: msg.warn("no id element in {}. Ignored. (group._load)".format(child))
<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, element): """Extracts the values from the specified XML element that is being converted."""
#All the children of this element are what we are trying to parse. result = [] for child in element: if child.tag in self.lines: values = { child.tag: self.lines[child.tag].parse(child) } result.append(values) 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 write(self, valuedict): """Generates the lines for the converted input file using the specified value dictionary."""
result = [] if self.identifier in valuedict: values = valuedict[self.identifier] else: return result if self.comment != "": result.append(self.comment) if self.repeat is not None and type(values) == type([]): if self.repeat.isdigit(): for i in range(int(self.repeat)): result.extend(self._write_iterate(values[i])) else: #We are repeating for as many values as we have in the value #entry for the group in the dictionary. for value in values: result.extend(self._write_iterate(value)) elif type(values) == type({}): #This group doesn't get repeated, so the values variable must #be a dictionary, just run it once. result = self._write_iterate(values) 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 _write_iterate(self, values): """Generates the lines for a single pass through the group."""
result = [] for key in self.order: result.append(self.lines[key].write(values)) if len(result) > 1: return result else: return result[0]
<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(self): """Extracts the XML template data from the file."""
if os.path.exists(self.path): root = ET.parse(self.path).getroot() if (root.tag == "fortpy" and "mode" in root.attrib and root.attrib["mode"] == "template" and "direction" in root.attrib and root.attrib["direction"] == self.direction): #First, we need instances of the template contents for each of the #versions listed in the fortpy tag. for v in _get_xml_version(root): self.versions[v] = TemplateContents() #Now we can update the contents objects using the XML data. self._load_entries(root) #See if a custom name was specified for the auto-converted #files. if "autoname" in root.attrib: self.name = root.attrib["autoname"] else: msg.err("the specified template {} ".format(self.path) + "is missing the mode and direction attributes.") exit(1) else: msg.err("could not find the template {}.".format(self.path)) exit(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 write(self, valuedict, version): """Generates the lines for the converted input file from the valuedict. :arg valuedict: a dictionary of values where the keys are ids in the template and the values obey their template rules. :arg version: the target version of the output file. """
result = [] if version in self.versions: for tag in self.versions[version].order: entry = self.versions[version].entries[tag] result.extend(entry.write(valuedict)) 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 _load_entries(self, root): """Loads all the child entries of the input template from the specified root element."""
mdict = { "comments": self._comment, "line": self._line, "group": self._group } for entry in root: mdict[entry.tag](entry)