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 _collapse_default(self, entry): """Collapses the list structure in entry to a single string representing the default value assigned to a variable or its dimensions. """
if isinstance(entry, tuple) or isinstance(entry, list): sets = [] i = 0 while i < len(entry): if isinstance(entry[i], str) and i+1 < len(entry) and isinstance(entry[i+1], list): sets.append((entry[i], entry[i+1])) i += 2 elif isinstance(entry[i], str) and entry[i] == ",": i += 1 else: sets.append((entry[i],)) i += 1 result = [] for s in sets: if isinstance(s[0], str): name = s[0].strip(",") elif len(s) == 1: name = self._collapse_default(s[0]) if len(s) > 1: args = self._collapse_default(s[1]) else: args = [] if len(args) > 0: result.append("{}({})".format(name, args)) else: result.append(name) return ', '.join(result) else: if "," in entry: return entry.split(",")[0].strip() else: return entry.strip()
<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_multiple_def(self, ready): """Cleans the list of variable definitions extracted from the definition text to get hold of the dimensions and default values. """
result = [] for entry in ready: if isinstance(entry, list): #This variable declaration has a default value specified, which is in the #second slot of the list. default = self._collapse_default(entry[1]) #For hard-coded array defaults, add the parenthesis back in. if default[0] == "/": default = "({})".format(default) namedim = entry[0] else: default = None namedim = entry if isinstance(namedim, str): name = namedim.strip().strip(",") dimension = None D = 0 else: #Namedim is a tuple of (name, dimension) name = namedim[0].strip() D = count_dimensions(namedim[1]) dimension = self._collapse_default(namedim[1]) result.append((name, dimension, default, D)) 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 char_range(starting_char, ending_char): """ Create a range generator for chars """
assert isinstance(starting_char, str), 'char_range: Wrong argument/s type' assert isinstance(ending_char, str), 'char_range: Wrong argument/s type' for char in range(ord(starting_char), ord(ending_char) + 1): yield chr(char)
<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_charset(charset): """ Finds out whether there are intervals to expand and creates the charset """
import re regex = r'(\w-\w)' pat = re.compile(regex) found = pat.findall(charset) result = '' if found: for element in found: for char in char_range(element[0], element[-1]): result += char return result return charset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """Return the viewable size of the Table as @tuple (x,y)"""
width = max( map(lambda x: x.size()[0], self.sections.itervalues())) height = sum( map(lambda x: x.size()[1], self.sections.itervalues())) return width, height
<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_ftr(self): """ Process footer and return the processed string """
if not self.ftr: return self.ftr width = self.size()[0] return re.sub( "%time", "%s\n" % time.strftime("%H:%M:%S"), self.ftr).rjust(width)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_help(self, arg): """Sets up the header for the help command that explains the background on how to use the script generally. Help for each command then stands alone in the context of this documentation. Although we could have documented this on the wiki, it is better served when shipped with the shell. """
if arg == "": lines = [("The fortpy unit testing analysis shell makes it easy to analyze the results " "of multiple test cases, make plots of trends and tabulate values for use in " "other applications. This documentation will provide an overview of the basics. " "Use 'help <command>' to get specific command help."), ("Each fortpy shell session can hold the results of multiple unit tests. You can " "load a unit test's results into the session using one of the 'parse' commands. " "Once the test is loaded you can tabulate and plot results by setting test case " "filters ('filter'), and independent and dependent variables ('indep', 'dep')." "Switch between different unit tests loaded into the session using 'set'."), ("To make multiple plots/tables for the same unit test, create new analysis " "groups ('group'). " "Each group has its own set of properties that can be set (e.g. variables, plot " "labels for axes, filters for test cases, etc.) The possible properties that affect " "each command are listed in the specific help for that command."), ("You can save the state of a shell session using 'save' and then recover it at " "a later time using 'load'. When a session is re-loaded, all the variables and " "properties/settings for plots/tables are maintained and the latest state of the " "unit test's results are used. A console history is also maintained with bash-like " "commands (e.g. Ctrl-R for reverse history search, etc.) across sessions. You can " "manipulate its behavior with 'history'.")] self._fixed_width_info(lines) cmd.Cmd.do_help(self, arg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fixed_width_info(self, lines): """Prints the specified string as information with fixed width of 80 chars."""
for string in lines: for line in [string[i:i+80] for i in range(0, len(string), 80)]: msg.info(line) msg.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 _redirect_output(self, value, filename=None, append=None, printfun=None): """Outputs the specified value to the console or a file depending on the redirect behavior specified. :arg value: the string text to print or save. :arg filename: the name of the file to save the text to. :arg append: when true, the text is appended to the file if it exists. """
if filename is None: if printfun is None: print(value) else: printfun(value) else: if append: mode = 'a' else: mode = 'w' from os import path fullpath = path.abspath(filename) with open(filename, mode) as f: f.write(value + '\n')
<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_cases(self, text, line, istart, iend): """Returns the completion list of possible test cases for the active unit test."""
if text == "": return list(self.live.keys()) else: return [c for c in self.live if c.startswith(text)]
<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_arg_generic(self, argid, arg, cast=str): """Sets the value of the argument with the specified id using the argument passed in from the shell session. """
usable, filename, append = self._redirect_split(arg) if usable != "": self.curargs[argid] = cast(usable) if argid in self.curargs: result = "{}: '{}'".format(argid.upper(), self.curargs[argid]) self._redirect_output(result, filename, append, msg.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 _print_map_dict(self, argkey, filename, append): """Prints a dictionary that has variable => value mappings."""
result = [] skeys = list(sorted(self.curargs[argkey].keys())) for key in skeys: result.append("'{}' => {}".format(key, self.curargs[argkey][key])) self._redirect_output('\n'.join(result), filename, append, msg.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 do_postfix(self, arg): """Sets the function to apply to the values of a specific variable before plotting or tabulating values. """
usable, filename, append = self._redirect_split(arg) sargs = usable.split() if len(sargs) == 1 and sargs[0] == "list": self._print_map_dict("functions", filename, append) elif len(sargs) >= 2: defvars = self._postfix_varlist("postfix " + arg) for var in defvars.values(): if not self._validate_var(var): msg.err("Variable '{}' is not a valid variable|property combination.") return fxn = arg.split()[-1] if ":" not in fxn: msg.err("{} is not a valid postfix function expression.") self.help_postfix() return modvar = fxn.split(":")[0] if modvar not in defvars: msg.err("Invalid postfix function: variable '{}' not defined.".format(modvar)) return defvars["lambda"] = fxn self.curargs["functions"][defvars[modvar]] = defvars #Give the user some feedback so that they know it was successful. self.do_postfix("list")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_rmpostfix(self, arg): """Removes a postfix function from a variable. See 'postfix'."""
altered = False if arg in self.curargs["functions"]: del self.curargs["functions"][arg] altered = True elif arg == "*": for varname in list(self.curargs["functions"].keys()): del self.curargs["functions"][varname] altered = True if altered: self.do_postfix("list")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_rmfit(self, arg): """Removes a fit function from a variable. See 'fit'."""
if arg in self.curargs["fits"]: del self.curargs["fits"][arg] #We also need to remove the variable entry if it exists. if "timing" in arg: fitvar = "{}|fit".format(arg) else: fitvar = "{}.fit".format(arg) if fitvar in self.curargs["dependents"]: self.curargs["dependents"].remove(fitvar)
<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_matplot_dict(self, option, prop, defdict): """Returns a copy of the settings dictionary for the specified option in curargs with update values where the value is replaced by the key from the relevant default dictionary. :arg option: the key in self.curargs to update. :arg defdict: the default dictionary whose keys should be used when values match. """
cargs = self.curargs[option] result = cargs.copy() for varname in cargs: if prop in cargs[varname]: name = cargs[varname][prop] for key, val in list(defdict.items()): if val == name: cargs[varname][prop] = key break 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 _plot_generic(self, filename=None): """Plots the current state of the shell, saving the value to the specified file if specified. """
#Since the filename is being passed directly from the argument, check its validity. if filename == "": filename = None if "x" not in self.curargs["labels"]: #Set a default x-label since we know what variable is being plotted. self.curargs["labels"]["x"] = "Value of '{}' (unknown units)".format(self.curargs["independent"]) args = self.curargs a = self.tests[self.active] self._make_fits() #Before we can pass the markers in, we need to translate from keys to values so #that matplotlib understands. markdict = self._get_matplot_dict("markers", "marker", self._possible_markers) linedict = self._get_matplot_dict("lines", "style", self._possible_linestyles) #Set the remaining arguments to have the right keyword name. args["savefile"] = filename args["markers"] = markdict args["lines"] = linedict a.plot(**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 do_plot(self, arg): """Plots the current state of the shell's independent vs. dependent variables on the same set of axes. Give filename to save to as argument or leave blank to show. """
usable, filename, append = self._redirect_split(arg) self.curargs["xscale"] = None self.curargs["yscale"] = None self._plot_generic(filename)
<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_def_prompt(self): """Sets the default prompt to match the currently active unit test."""
if len(self.active) > 15: ids = self.active.split(".") if len(ids) > 2: module, executable, compiler = ids else: module, executable = ids compiler = "g" self.prompt = "({}*.{}*.{}:{})".format(module[0:6], executable[0:6], compiler, self.group) else: self.prompt = "({}:{})".format(self.active, self.group)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_set(self, arg): """Sets the specified 'module.executable' to be the active test result to interact with. """
if arg in self.tests: self.active = arg #Create a default argument set and analysis group for the current plotting if arg not in self.args: self.args[arg] = {"default": dict(self._template_args)} self.group = "default" else: self.group = list(self.curargs.keys())[0] #Change the prompt so that they know which unit test is being edited. self._set_def_prompt() else: msg.err("The test case '{}' is not valid.".format(arg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_load(self, arg): """Loads a saved session variables, settings and test results to the shell."""
from os import path import json fullpath = path.expanduser(arg) if path.isfile(fullpath): with open(fullpath) as f: data = json.load(f) #Now, reparse the staging directories that were present in the saved session. for stagepath in data["tests"]: self.do_parse(stagepath) self.args = data["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 do_reparse(self, arg): """Reparses the currently active unit test to get the latest test results loaded to the console. """
#We just get the full path of the currently active test and hit reparse. full = arg == "full" from os import path fullpath = path.abspath(self.tests[self.active].stagedir) self.tests[self.active] = Analysis(fullpath, full)
<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_fits(self): """Generates the data fits for any variables set for fitting in the shell."""
a = self.tests[self.active] args = self.curargs #We need to generate a fit for the data if there are any fits specified. if len(args["fits"]) > 0: for fit in list(args["fits"].keys()): a.fit(args["independent"], fit, args["fits"][fit], args["threshold"], args["functions"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_table(self, arg): """Prints the set of values for the independent vs. dependent variables in the active unit test and analysis group as a table. """
usable, filename, append = self._redirect_split(arg) a = self.tests[self.active] args = self.curargs self._make_fits() result = a.table(args["independent"], args["dependents"], args["threshold"], args["headings"], args["functions"]) if result is not None: self._redirect_output(result, filename, append, msg.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 do_failures(self, arg): """Prints a list of test cases that failed for the current unit test and analysis group settings. To only check failure on specific output files, set the list of files to check as arguments. """
usable, filename, append = self._redirect_split(arg) a = self.tests[self.active] args = self.curargs splitargs = usable.split() if len(splitargs) > 0: tfilter = splitargs[0] else: tfilter = "*" outfiles = None if len(splitargs) > 1: outfiles = splitargs[1:len(splitargs)] result = a.failures(outfiles, args["threshold"], tfilter) self._redirect_output(result, filename, append, msg.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 histpath(self): """Returns the full path to the console history file."""
from os import path from fortpy import settings return path.join(settings.cache_directory, "history")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _store_lasterr(self): """Stores the information about the last unhandled exception."""
from sys import exc_info from traceback import format_exception e = exc_info() self.lasterr = '\n'.join(format_exception(e[0], e[1], e[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 precmd(self, line): """Makes sure that the command specified in the line is valid given the current status of loaded unit tests and analysis group. """
if line == "": return "" command = line.split()[0] if "!" in command: value = command.split("!")[1] try: ihist = int(value) import readline if ihist <= readline.get_current_history_length(): return readline.get_history_item(ihist) else: msg.warn("The specified history item {} ".format(ihist) + "does not exist in the history.") return "" except ValueError: #This clearly isn't a bash style recursion of a past history item. #Just run the command as it was originally entered. return line else: if command in self._test_cmds or command in self._group_cmds: #We have to test the active unit test for both the test commands and the #group commands, since the group commands rely on the active unit test. if self.active is None or self.active not in self.tests: msg.err("The specified command '{}' requires an ".format(command) + "active unit test to be loaded. Use 'parse' or 'load'.") return "" elif (command in self._group_cmds and (self.group is None or self.group not in self.args[self.active])): msg.err("No valid analysis group is active. Use 'group' to create " "one or mark an existing one as active.") return "" else: return line if command in self._var_cmds: #We need to make sure that we have variables set. if self.curargs["independent"] is None or len(self.curargs["dependents"]) == 0: msg.err("This command requires an independent variable to be set and " "at least one dependent variable.\n See 'dep' and 'indep' commands.") return "" else: return line else: return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_cd(self, arg): """Imitates the bash shell 'cd' command."""
from os import chdir, path fullpath = path.abspath(path.expanduser(arg)) if path.isdir(fullpath): chdir(fullpath) else: msg.err("'{}' is not a valid directory.".format(arg))
<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_branches(scales=None, angles=None, shift_angle=0): """Generates branches with alternative system. Args: scales (tuple/array): Indicating how the branch/es length/es develop/s from age to age. angles (tuple/array): Holding the branch and shift angle in radians. shift_angle (float): Holding the rotation angle for all branches. Returns: branches (2d-array): A array constits of arrays holding scale and angle for every branch. """
branches = [] for pos, scale in enumerate(scales): angle = -sum(angles)/2 + sum(angles[:pos]) + shift_angle branches.append([scale, angle]) return branches
<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_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """
rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node.pos[i]: rec[2+i] = node.pos[i] return tuple(rec)
<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_size(self): """Get the size of the tree. Returns: tupel: (width, height) """
rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[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_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: length * scale^age. Args: age (int): The age, for which you want to know the branch length. Returns: float: The length of the branch """
if age is None: age = self.age return self.length * pow(self.branches[pos][0], age)
<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_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the given branch length. """
return log(length/self.length, min(self.branches[0][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 get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """
if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 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_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """
if age is None: age = self.age return pow(self.comp, age)
<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_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [(20, 80), (100, 30)], ] """
nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes
<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_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10, 40, 90, 30)], [(90, 30, 100, 40), (90, 30, 300, 60)], ] """
branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) branches[age].append(p_node.get_tuple() + node.get_tuple()) return branches
<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 tree. Args: delta (tupel): The adjustment of the position. """
pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(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 grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """
self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(self.comp): tot_angle = self.__get_total_angle(angle, i) length = self.__get_total_length(self.age+1, i) self.nodes[self.age+1].append(node.make_new_node(length, tot_angle)) self.age += 1 if times > 1: self.grow(times-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 draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the tree on. Supported canvases: svgwrite.Drawing and PIL.Image (You can also add your custom libraries.) stem_color (tupel): Color or gradient for the stem of the tree. leaf_color (tupel): Color for the leaf (= the color for last iteration). thickness (int): The start thickness of the tree. """
if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw()
<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_total_angle(self, angle, pos): """Get the total angle."""
tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle
<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_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """
return self.nodes[age][int(pos / self.comp)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _field_lookups(model, status=None): """ Abstraction of field lookups for managers. Returns a dictionary of field lookups for a queryset. The lookups will always filter by site. Optionally, if ``status`` is passed to the function the objects will also be filtered by the given status. This function saves from having to make two different on-site and published Managers each for `Topic` and `Question`, and having to move Managers out of the `FAQBase` model and into each of the `Topic` and `Question` models. """
# Import models here to avoid circular import fail. from faq.models import Topic, Question field_lookups = {} if model == Topic: field_lookups['sites__pk'] = settings.SITE_ID if model == Question: field_lookups['topic__sites__pk'] = settings.SITE_ID if status: field_lookups['topic__status'] = status # Both Topic & Question have a status field. if status: field_lookups['status'] = status return field_lookups
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_compiler(libpath): """Determines the compiler used to compile the specified shared library by using the system utilities. :arg libpath: the full path to the shared library *.so file. """
from os import waitpid, path from subprocess import Popen, PIPE command = "nm {0}".format(path.abspath(libpath)) child = Popen(command, shell=True, executable="/bin/bash", stdout=PIPE) # Need to do this so that we are sure the process is done before moving on waitpid(child.pid, 0) contents = child.stdout.readlines() i = 0 found = False while i < len(contents) and found == False: if "_MOD_" in contents[i]: found = "gfortran" elif "_mp_" in contents[i]: found = "ifort" i += 1 return found
<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): """Deallocates the fortran-managed memory that this ctype references. """
if not self.deallocated: #Release/deallocate the pointer in fortran. method = self._deallocator() if method is not None: dealloc = static_symbol("ftypes_dealloc", method, self.libpath, True) if dealloc is None: return arrtype = ndpointer(dtype=int, ndim=1, shape=(len(self.indices),), flags="F") dealloc.argtypes = [c_void_p, c_int_p, arrtype] nindices = require(array([i.value for i in self.indices]), int, "F") dealloc(byref(self.pointer), c_int(len(self.indices)), nindices) self.deallocated = 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 _deallocator(self): """Returns the name of the subroutine in ftypes_dealloc.f90 that can deallocate the array for this Ftype's pointer. :arg ctype: the string c-type of the variable. """
lookup = { "c_bool": "logical", "c_double": "double", "c_double_complex": "complex", "c_char": "char", "c_int": "int", "c_float": "float", "c_short": "short", "c_long": "long" } ctype = type(self.pointer).__name__.replace("LP_", "").lower() if ctype in lookup: return "dealloc_{0}_{1:d}d".format(lookup[ctype], len(self.indices)) 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 add(self, varname, result, pointer=None): """Adds the specified python-typed result and an optional Ftype pointer to use when cleaning up this object. :arg result: a python-typed representation of the result. :arg pointer: an instance of Ftype with pointer information for deallocating the c-pointer. """
self.result[varname] = result setattr(self, varname, result) if pointer is not None: self._finalizers[varname] = pointer
<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_python_object(name): """ Loads a python module from string """
logger = getLoggerWithNullHandler('commando.load_python_object') (module_name, _, object_name) = name.rpartition(".") if module_name == '': (module_name, object_name) = (object_name, module_name) try: logger.debug('Loading module [%s]' % module_name) module = __import__(module_name) except ImportError: raise CommandoLoaderException( "Module [%s] cannot be loaded." % module_name) if object_name == '': return module try: module = sys.modules[module_name] except KeyError: raise CommandoLoaderException( "Error occured when loading module [%s]" % module_name) try: logger.debug('Getting object [%s] from module [%s]' % (object_name, module_name)) return getattr(module, object_name) except AttributeError: raise CommandoLoaderException( "Cannot load object [%s]. " "Module [%s] does not contain object [%s]. " "Please fix the configuration or " "ensure that the module is installed properly" % ( name, module_name, object_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 getLoggerWithConsoleHandler(logger_name=None): """ Gets a logger object with a pre-initialized console handler. """
logger = logging.getLogger(logger_name) logger.setLevel(logging.INFO) if not logger.handlers: handler = logging.StreamHandler(sys.stdout) if sys.platform == 'win32': formatter = logging.Formatter( fmt="%(asctime)s %(name)s %(message)s", datefmt='%H:%M:%S') else: formatter = ColorFormatter(fmt="$RESET %(asctime)s " "$BOLD$COLOR%(name)s$RESET " "%(message)s", datefmt='%H:%M:%S') handler.setFormatter(formatter) logger.addHandler(handler) return logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLoggerWithNullHandler(logger_name): """ Gets the logger initialized with the `logger_name` and a NullHandler. """
logger = logging.getLogger(logger_name) if not logger.handlers: logger.addHandler(NullHandler()) return logger
<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(self, *args, **kwargs): """ Delegates to `subprocess.check_call`. """
args, kwargs = self.__process__(*args, **kwargs) return check_call(args, **kwargs)
<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(self, *args, **kwargs): """ Delegates to `subprocess.check_output`. """
args, kwargs = self.__process__(*args, **kwargs) return check_output(args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, *args, **kwargs): """ Delegates to `subprocess.Popen`. """
args, kwargs = self.__process__(*args, **kwargs) return Popen(args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag(request, tag_id=None): """ The view used to render a tag after the page has loaded. """
html = get_tag_html(tag_id) t = template.Template(html) c = template.RequestContext(request) return HttpResponse(t.render(c))
<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_color(self, age): """Get the fill color depending on age. Args: age (int): The age of the branch/es Returns: tuple: (r, g, b) """
if age == self.tree.age: return self.leaf_color color = self.stem_color tree = self.tree if len(color) == 3: return color diff = [color[i+3]-color[i] for i in range(3)] per_age = [diff[i]/(tree.age-1) for i in range(3)] return tuple([int(color[i]+per_age[i]*age) for i in range(3)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the tree. Args: ages (array): Contains the ages you want to draw. """
for age, level in enumerate(self.tree.get_branches()): if age in self.ages: thickness = self._get_thickness(age) color = self._get_color(age) for branch in level: self._draw_branch(branch, color, thickness, age)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cmd_create(self): """Create a migration in the current or new revision folder """
assert self._message, "need to supply a message for the \"create\" command" if not self._revisions: self._revisions.append("1") # get the migration folder rev_folder = self._revisions[-1] full_rev_path = os.path.join(self._migration_path, rev_folder) if not os.path.exists(full_rev_path): os.mkdir(full_rev_path) else: count = len(glob.glob(os.path.join(full_rev_path, "*"))) # create next revision folder if needed if count and self._rev and int(self._rev) == 0: rev_folder = str(int(rev_folder) + 1) full_rev_path = os.path.join(self._migration_path, rev_folder) os.mkdir(full_rev_path) self._revisions.append(rev_folder) # format file name filename = '_'.join([s.lower() for s in self._message.split(' ') if s.strip()]) for p in string.punctuation: if p in filename: filename = filename.replace(p, '_') filename = "%s_%s" % (datetime.utcnow().strftime("%Y%m%d%H%M%S"), filename.replace('__', '_')) # create the migration files self._log(0, "creating files: ") for s in ('up', 'down'): file_path = os.path.join(full_rev_path, "%s.%s.sql" % (filename, s)) with open(file_path, 'a+') as w: w.write('\n'.join([ '-- *** %s ***' % s.upper(), '-- file: %s' % os.path.join(rev_folder, filename), '-- comment: %s' % self._message])) self._log(0, file_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 _cmd_up(self): """Upgrade to a revision"""
revision = self._get_revision() if not self._rev: self._log(0, "upgrading current revision") else: self._log(0, "upgrading from revision %s" % revision) for rev in self._revisions[int(revision) - 1:]: sql_files = glob.glob(os.path.join(self._migration_path, rev, "*.up.sql")) sql_files.sort() self._exec(sql_files, rev) self._log(0, "done: upgraded revision to %s\n" % rev)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cmd_down(self): """Downgrade to a revision"""
revision = self._get_revision() if not self._rev: self._log(0, "downgrading current revision") else: self._log(0, "downgrading to revision %s" % revision) # execute from latest to oldest revision for rev in reversed(self._revisions[int(revision) - 1:]): sql_files = glob.glob(os.path.join(self._migration_path, rev, "*.down.sql")) sql_files.sort(reverse=True) self._exec(sql_files, rev) self._log(0, "done: downgraded revision to %s" % rev)
<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_revision(self): """Validate and return the revision to use for current command """
assert self._revisions, "no migration revision exist" revision = self._rev or self._revisions[-1] # revision count must be less or equal since revisions are ordered assert revision in self._revisions, "invalid revision specified" return revision
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newest(cls, session): """Fetches the latest media added to MAL. :type session: :class:`myanimelist.session.Session` :param session: A valid MAL session :rtype: :class:`.Media` :return: the newest media on MAL :raises: :class:`.MalformedMediaPageError` """
media_type = cls.__name__.lower() p = session.session.get(u'http://myanimelist.net/' + media_type + '.php?o=9&c[]=a&c[]=d&cv=2&w=1').text soup = utilities.get_clean_dom(p) latest_entry = soup.find(u"div", {u"class": u"hoverinfo"}) if not latest_entry: raise MalformedMediaPageError(0, p, u"No media entries found on recently-added page") latest_id = int(latest_entry[u'rel'][1:]) return getattr(session, media_type)(latest_id)
<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, media_page): """Parses the DOM and returns media attributes in the main-content area. :type media_page: :class:`bs4.BeautifulSoup` :param media_page: MAL media page's DOM :rtype: dict :return: media attributes. """
media_info = self.parse_sidebar(media_page) try: synopsis_elt = media_page.find(u'h2', text=u'Synopsis').parent utilities.extract_tags(synopsis_elt.find_all(u'h2')) media_info[u'synopsis'] = synopsis_elt.text.strip() except: if not self.session.suppress_parse_exceptions: raise try: related_title = media_page.find(u'h2', text=u'Related ' + self.__class__.__name__) if related_title: related_elt = related_title.parent utilities.extract_tags(related_elt.find_all(u'h2')) related = {} for link in related_elt.find_all(u'a'): href = link.get(u'href').replace(u'http://myanimelist.net', '') if not re.match(r'/(anime|manga)', href): break curr_elt = link.previous_sibling if curr_elt is None: # we've reached the end of the list. break related_type = None while True: if not curr_elt: raise MalformedAnimePageError(self.id, related_elt, message="Prematurely reached end of related anime listing") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match(u'(?P<type>[a-zA-Z\ \-]+):', curr_elt) if type_match: related_type = type_match.group(u'type') break curr_elt = curr_elt.previous_sibling title = link.text # parse link: may be manga or anime. href_parts = href.split(u'/') # sometimes links on MAL are broken, of the form /anime// if href_parts[2] == '': continue # of the form: /(anime|manga)/1/Cowboy_Bebop obj_id = int(href_parts[2]) new_obj = getattr(self.session, href_parts[1])(obj_id).set({'title': title}) if related_type not in related: related[related_type] = [new_obj] else: related[related_type].append(new_obj) media_info[u'related'] = related else: media_info[u'related'] = None except: if not self.session.suppress_parse_exceptions: raise return media_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_characters(self, character_page): """Parses the DOM and returns media character attributes in the sidebar. :type character_page: :class:`bs4.BeautifulSoup` :param character_page: MAL character page's DOM :rtype: dict :return: character attributes. """
media_info = self.parse_sidebar(character_page) try: character_title = filter(lambda x: u'Characters' in x.text, character_page.find_all(u'h2')) media_info[u'characters'] = {} if character_title: character_title = character_title[0] curr_elt = character_title.find_next_sibling(u'table') while curr_elt: curr_row = curr_elt.find(u'tr') # character in second col. character_col = curr_row.find_all(u'td', recursive=False)[1] character_link = character_col.find(u'a') character_name = ' '.join(reversed(character_link.text.split(u', '))) link_parts = character_link.get(u'href').split(u'/') # of the form /character/7373/Holo character = self.session.character(int(link_parts[2])).set({'name': character_name}) role = character_col.find(u'small').text media_info[u'characters'][character] = {'role': role} curr_elt = curr_elt.find_next_sibling(u'table') except: if not self.session.suppress_parse_exceptions: raise return media_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 media page and sets the current media's attributes. :rtype: :class:`.Media` :return: current media object. """
media_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id)).text self.set(self.parse(utilities.get_clean_dom(media_page))) 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_stats(self): """Fetches the MAL media statistics page and sets the current media's statistics attributes. :rtype: :class:`.Media` :return: current media object. """
stats_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/stats').text self.set(self.parse_stats(utilities.get_clean_dom(stats_page))) 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_characters(self): """Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current media object. """
characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/characters').text self.set(self.parse_characters(utilities.get_clean_dom(characters_page))) 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(parser, serializer): """Returns a dictionary of builtin functions for Fortran. Checks the cache first to see if we have a serialized version. If we don't, it loads it from the XML file. :arg parser: the DocParser instance for parsing the XML tags. :arg serializer: a Serializer instance from the CodeParser to cache the loaded XML file. """
fortdir = os.path.dirname(fortpy.__file__) xmlpath = os.path.join(fortdir, "isense", "builtin.xml") if not os.path.isfile(xmlpath): return {} changed_time = os.path.getmtime(xmlpath) cached = serializer.load_module("builtin.xml", changed_time) if cached is None: result = _load_builtin_xml(xmlpath, parser) serializer.save_module("builtin.xml", result, changed_time) else: result = cached 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_builtin_xml(xmlpath, parser): """Loads the builtin function specifications from the builtin.xml file. :arg parser: the DocParser instance for parsing the XML tags. """
#First we need to get hold of the fortpy directory so we can locate #the isense/builtin.xml file. result = {} el = ET.parse(xmlpath).getroot() if el.tag == "builtin": for child in el: anexec = _parse_xml(child, parser) result[anexec.name.lower()] = anexec 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_xml(child, parser): """Parses the specified child XML tag and creates a Subroutine or Function object out of it."""
name, modifiers, dtype, kind = _parse_common(child) #Handle the symbol modification according to the isense settings. name = _isense_builtin_symbol(name) if child.tag == "subroutine": parent = Subroutine(name, modifiers, None) elif child.tag == "function": parent = Function(name, modifiers, dtype, kind, None) if parent is not None: for kid in child: if kid.tag == "parameter": _parse_parameter(kid, parser, parent) elif kid.tag == "summary": _parse_summary(kid, parser, parent) elif kid.tag == "usage": _parse_usage(kid, parser, parent) return parent
<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_request(self, url, params, auth=None): """ Prepares a request from a url, params, and optionally authentication. """
req = urllib2.Request(url + urllib.urlencode(params)) if auth: req.add_header('AUTHORIZATION', 'Basic ' + auth) return urllib2.urlopen(req)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fpy_interface(fpy, static, interface, typedict): """Splices the full list of subroutines and the module procedure list into the static.f90 file. :arg static: the string contents of the static.f90 file. :arg interface: the name of the interface *field* being replaced. :arg typedict: the dictionary of dtypes and their kind and suffix combos. """
modprocs = [] subtext = [] for dtype, combos in list(typedict.items()): for tcombo in combos: kind, suffix = tcombo xnames, sub = fpy_interface_sub(fpy, dtype, kind, suffix) modprocs.extend(xnames) subtext.append(sub) subtext.append("\n") #Next, chunk the names of the module procedures into blocks of five #so that they display nicely for human readability. from fortpy.printing.formatting import present_params splice = static.replace(interface, present_params(modprocs, 21)) return splice.replace(interface.replace("py", "xpy"), ''.join(subtext))
<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(): """Parses the specified Fortran source file from which the wrappers will be constructed for ctypes. """
if not args["reparse"]: settings.use_filesystem_cache = False c = CodeParser() if args["verbose"]: c.verbose = True if args["reparse"]: c.reparse(args["source"]) else: c.parse(args["source"]) return c
<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 compiled regex objects for parsing code elements."""
#Regex for extracting modules from the code self._RX_MODULE = r"(\n|^)\s*module\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*module" self.RE_MODULE = re.compile(self._RX_MODULE, re.I | re.DOTALL) self._RX_PROGRAM = r"(\n|^)\s*program\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*program" self.RE_PROGRAM = re.compile(self._RX_PROGRAM, re.I | re.DOTALL) #Regex for use statements in a module self._RX_USE = r"^\s*use\s+(?P<name>[^,]+?)(\s*,\s+only\s*:(?P<only>[A-Za-z0-9_\s,]+?))?$" self.RE_USE = re.compile(self._RX_USE, re.I | re.M) #Regex for finding if the module is private self._RX_PRIV = "private.+?(type|contains)" self.RE_PRIV = re.compile(self._RX_PRIV, re.DOTALL | re.I) #Regex for finding publcily labeled members declared using public keyword. self._RX_PUBLIC = r"\n\s*public\s+(?P<methods>[A-Za-z0-9_,\s&\n]+)" self.RE_PUBLIC = re.compile(self._RX_PUBLIC, re.I) #Regex for finding text before type or contains declarations that may contian members. self._RX_MEMBERS = "(?P<preamble>.+?)(\s+type[,\s]|contains)" self.RE_MEMBERS = re.compile(self._RX_MEMBERS, re.DOTALL | re.I) self._RX_PRECOMP = r"#endif" self.RE_PRECOMP = re.compile(self._RX_PRECOMP, 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_programs(self, string, parent, filepath=None): """Extracts a PROGRAM from the specified fortran code file."""
#First, get hold of the docstrings for all the modules so that we can #attach them as we parse them. moddocs = self.docparser.parse_docs(string) #Now look for modules in the file and then match them to their decorators. matches = self.RE_PROGRAM.finditer(string) result = [] for rmodule in matches: name = rmodule.group("name").lower() contents = re.sub("&[ ]*\n", "", rmodule.group("contents")) module = self._process_module(name, contents, parent, rmodule, filepath) #Check whether the docparser found docstrings for the module. if name in moddocs: module.docstring = self.docparser.to_doc(moddocs[name][0], name) module.docstart, module.docend = module.absolute_charindex(string, moddocs[name][1], moddocs[name][2]) result.append(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 _process_publics(self, contents): """Extracts a list of public members, types and executables that were declared using the public keyword instead of a decoration."""
matches = self.RE_PUBLIC.finditer(contents) result = {} start = 0 for public in matches: methods = public.group("methods") #We need to keep track of where the public declarations start so that the unit #testing framework can insert public statements for those procedures being tested #who are not marked as public if start == 0: start = public.start("methods") for item in re.split(r"[\s&\n,]+", methods.strip()): if item.lower() in ["interface", "type", "use"]: #We have obviously reached the end of the actual public #declaration in this regex match. break self._dict_increment(result, item.lower()) return (result, 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 _process_module(self, name, contents, parent, match, filepath=None): """Processes a regex match for a module to create a CodeElement."""
#First, get hold of the name and contents of the module so that we can process the other #parts of the module. modifiers = [] #We need to check for the private keyword before any type or contains declarations if self.RE_PRIV.search(contents): modifiers.append("private") #The only other modifier for modules ought to be implicit none if re.search("implicit\s+none", contents): modifiers.append("implicit none") #Next, parse out the dependencies of the module on other modules dependencies = self._parse_use(contents) publics, pubstart = self._process_publics(match.string) #We can now create the CodeElement result = Module(name, modifiers, dependencies, publics, contents, parent) if filepath is not None: result.filepath = filepath.lower() result.start = match.start() result.end = match.end() result.refstring = match.string result.set_public_start(pubstart) if self.RE_PRECOMP.search(contents): result.precompile = True self.xparser.parse(result) self.tparser.parse(result) #It is possible for the module to have members, parse those self._parse_members(contents, result) self.iparser.parse(result) #Now we can update the docstrings for the types. They rely on data #extracted during parse_members() which is why they have to run #separately over here. for t in result.types: self.tparser.update_docs(result.types[t], result) 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_use(self, string): """Extracts use dependencies from the innertext of a module."""
result = {} for ruse in self.RE_USE.finditer(string): #We also handle comments for individual use cases, the "only" section #won't pick up any comments. name = ruse.group("name").split("!")[0].strip() if name.lower() == "mpi": continue if ruse.group("only"): only = ruse.group("only").split(",") for method in only: key = "{}.{}".format(name, method.strip()) self._dict_increment(result, key) else: self._dict_increment(result, name) 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 _dict_increment(self, dictionary, key): """Increments the value of the dictionary at the specified key."""
if key in dictionary: dictionary[key] += 1 else: dictionary[key] = 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 _parse_members(self, contents, module): """Extracts any module-level members from the code. They must appear before any type declalations."""
#We need to get hold of the text before the module's main CONTAINS keyword #so that we don't find variables from executables and claim them as #belonging to the module. icontains = module.contains_index ichar = module.charindex(icontains, 0) module.preamble = module.refstring[:ichar] #Get a dictionary of all the members in this module body #We only want to look at variable definitions before the first type lowest = ichar remove = [] #Will use later below, see next comment for t in module.types: remove.append((module.types[t].start, module.types[t].end)) if module.types[t].start < lowest: lowest = module.types[t].start module.members.update(self.vparser.parse(contents[:lowest-(module.start + 10 + len(module.name))], module)) #The docstrings for these members will appear as member tags in the same #preamble text. We can't use the entire preamble for this because member #docs inside of a type declaration will show up as belonging to the #module, when in fact, they don't. remove.sort(key=lambda tup: tup[0]) retain = [] cur_end = 0 for rem in remove: signature = module.refstring[rem[0]+1:rem[1]].index("\n") + 2 keep = module.refstring[cur_end:rem[0] + signature] cur_end = rem[1] retain.append(keep) #If there weren't any types in the module, we still want to get at the docs in #the preamble. if len(remove) == 0: retain = module.preamble docsearch = "".join(retain) module.predocs = self.docparser.parse_docs(docsearch, module) if module.name in module.predocs: #We can only do member docstrings if the module had internal docstrings #that may to members. memdocs = self.docparser.to_doc(module.predocs[module.name][0], module.name) remainingdocs = self.docparser.process_memberdocs(memdocs, module) module.predocs[module.name] = 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 setup_regex(self): """Sets up compiled regex objects for parsing the executables from a module."""
self._RX_CONTAINS = r"^\s*contains[^\n]*?$" self.RE_CONTAINS = re.compile(self._RX_CONTAINS, re.M | re.I) #Setup a regex that can extract information about both functions and subroutines self._RX_EXEC = r"\n[ \t]*((?P<type>character|real|type|logical|integer|complex)?" + \ r"(?P<kind>\([a-z0-9_]+\))?)?((?P<modifiers>[\w, \t]+?))?[ \t]*" + \ r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \ r"\s*\((?P<parameters>[^)]*)\)(?P<result>\sresult\([a-z0-9_]+\))?" + \ r"(?P<contents>.+?)end\s*(?P=codetype)\s+(?P=name)" self.RE_EXEC = re.compile(self._RX_EXEC, re.DOTALL | re.I) #Regex for the signature is almost identical to the full executable, but it doesn't #look for any contents after the parameter list. self._RX_SIG = r"((?P<type>character|real|type|logical|integer|complex)?" + \ r"(?P<kind>\([a-z0-9_]+\))?)?(,?(?P<modifiers>[^\n]+?))?\s*" + \ r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \ r"\s*\((?P<parameters>[^)]*)\)" self.RE_SIG = re.compile(self._RX_SIG, re.I) #The contents of the executable already have any & line continuations #removed, so we can use a simple multiline regex. self._RX_ASSIGN = r"^(?P<assignee>[^!<=\n/]+?)=[^\n]+?$" self.RE_ASSIGN = re.compile(self._RX_ASSIGN, re.M) self._RX_DEPEND = r"^\s*(?P<sub>call\s+)?(?P<exec>[a-z0-9_%]+\s*\([^\n]+)$" self.RE_DEPEND = re.compile(self._RX_DEPEND, re.M | re. I) self._RX_DEPCLEAN = r"(?P<key>[a-z0-9_%]+)\(" self.RE_DEPCLEAN = re.compile(self._RX_DEPCLEAN, re.I) self._RX_CONST = '[^"\']+(?P<const>["\'][^\'"]+["\'])' self.RE_CONST = re.compile(self._RX_CONST) self._RX_COMMENTS = r'\s*![^\n"]+?\n' self.RE_COMMENTS = re.compile(self._RX_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(self, module): """Extracts all the subroutine and function definitions from the specified module."""
#Because of embedded types, we have to examine the entire module for #executable definitions. self.parse_block(module.refstring, module, module, 0) #Now we can set the value of module.contains as the text after the start of #the *first* non-embedded executable. min_start = len(module.refstring) for x in module.executables: if module.executables[x].start < min_start: min_start = module.executables[x].start module.contains = module.refstring[min_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 parse_block(self, contents, parent, module, depth): """Extracts all executable definitions from the specified string and adds them to the specified parent."""
for anexec in self.RE_EXEC.finditer(contents): x = self._process_execs(anexec, parent, module) parent.executables[x.name.lower()] = x if isinstance(parent, Module) and "public" in x.modifiers: parent.publics[x.name.lower()] = 1 #To handle the embedded executables, run this method recursively self.parse_block(x.contents, x, module, depth + 1) #Now that we have the executables, we can use them to compile a string #that includes only documentation *external* to the executable definitions #Because we enforce adding the name to 'end subroutine' statements etc. #all the embedded executables haven't been parsed yet. if len(parent.executables) > 0: remove = [] for x in parent.executables: remove.append((parent.executables[x].start, parent.executables[x].end)) remove.sort(key=lambda tup: tup[0]) retain = [] cur_end = 0 for rem in remove: if "\n" in contents[rem[0]+1:rem[1]]: signature = contents[rem[0]+1:rem[1]].index("\n") + 2 keep = contents[cur_end:rem[0] + signature] cur_end = rem[1] retain.append(keep) #Now we have a string of documentation segments and the signatures they #decorate that only applies to the non-embedded subroutines docsearch = "".join(retain) docblocks = self.docparser.parse_docs(docsearch, parent) #Process the decorating documentation for the executables including the #parameter definitions. for x in parent.executables: self._process_docs(parent.executables[x], docblocks, parent, module, docsearch)
<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_execs(self, execmatch, parent, module): """Processes the regex match of an executable from the match object."""
#Get the matches that must be present for every executable. name = execmatch.group("name").strip() modifiers = execmatch.group("modifiers") if modifiers is None: modifiers = [] else: modifiers = re.split(",[ \t]*", modifiers) codetype = execmatch.group("codetype") params = re.split("[\s,]+", execmatch.group("parameters")) contents = execmatch.group("contents") #If the exec is a function, we also may have a type and kind specified. if codetype.lower() == "function": dtype = execmatch.group("type") kind = execmatch.group("kind") result = Function(name, modifiers, dtype, kind, parent) else: result = Subroutine(name, modifiers, parent) #Set the regex start and end char indices result.start, result.end = module.absolute_charindex(execmatch.string, execmatch.start(), execmatch.end()) result.contents = contents #Now we can handle the rest which is common to both types of executable #Extract a list of local variables self._parse_members(contents, result, params) if isinstance(result, Function): #We need to handle the syntax for defining a function with result(variable) #to specify the return type of the function. if execmatch.group("result") is not None: resvar = execmatch.group("result").lower().split("result(")[1].replace(")", "") else: resvar = None result.update_dtype(resvar) #Fortran allows lines to be continued using &. The easiest way #to deal with this is to remove all of those before processing #any of the regular expressions decommented = "\n".join([ self._depend_exec_clean(l) for l in contents.split("\n") ]) cleaned = re.sub("&\s*", "", decommented) #Finally, process the dependencies. These are calls to functions and #subroutines from within the executable body self._process_dependencies(result, cleaned) self._process_assignments(result, cleaned) 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_assignments(self, anexec, contents, mode="insert"): """Extracts all variable assignments from the body of the executable. :arg mode: for real-time update; either 'insert', 'delete' or 'replace'. """
for assign in self.RE_ASSIGN.finditer(contents): assignee = assign.group("assignee").strip() target = re.split(r"[(%\s]", assignee)[0].lower() #We only want to include variables that we know are in the scope of the #current executable. This excludes function calls etc. with optional params. if target in self._intrinsic: continue if target in anexec.members or \ target in anexec.parameters or \ (isinstance(anexec, Function) and target.lower() == anexec.name.lower()): if mode == "insert": anexec.add_assignment(re.split(r"[(\s]", assignee)[0]) elif mode == "delete": #Remove the first instance of this assignment from the list try: index = element.assignments.index(assign) del element.assignments[index] except ValueError: #We didn't have anything to remove, but python pass
<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_dependencies(self, anexec, contents, mode="insert"): """Extracts a list of subroutines and functions that are called from within this executable. :arg mode: specifies whether the matches should be added, removed or merged into the specified executable. """
#At this point we don't necessarily know which module the executables are #in, so we just extract the names. Once all the modules in the library #have been parsed, we can do the associations at that level for linking. for dmatch in self.RE_DEPEND.finditer(contents): isSubroutine = dmatch.group("sub") is not None if "!" in dmatch.group("exec"): execline = self._depend_exec_clean(dmatch.group("exec")) else: execline = "(" + dmatch.group("exec").split("!")[0].replace(",", ", ") + ")" if not "::" in execline: try: dependent = self.nester.parseString(execline).asList()[0] except: msg.err("parsing executable dependency call {}".format(anexec.name)) msg.gen("\t" + execline) #Sometimes the parameter passed to a subroutine or function is #itself a function call. These are always the first elements in #their nested lists. self._process_dependlist(dependent, anexec, isSubroutine, mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _depend_exec_clean(self, text): """Cleans any string constants in the specified dependency text to remove embedded ! etc. that break the parsing. """
#First remove the escaped quotes, we will add them back at the end. unquoted = text.replace('""', "_FORTPYDQ_").replace("''", "_FORTPYSQ_") for cmatch in self.RE_CONST.finditer(unquoted): string = cmatch.string[cmatch.start():cmatch.end()] newstr = string.replace("!", "_FORTPYEX_") unquoted = unquoted.replace(string, newstr) requote = unquoted.split("!")[0].replace("_FORTPYDQ_", '""').replace("_FORTPYSQ_", "''") result = "(" + requote.replace("_FORTPYEX_", "!").replace(",", ", ") + ")" 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_dependlist(self, dependlist, anexec, isSubroutine, mode="insert"): """Processes a list of nested dependencies recursively."""
for i in range(len(dependlist)): #Since we are looping over all the elements and some will #be lists of parameters, we need to skip any items that are lists. if isinstance(dependlist[i], list): continue key = dependlist[i].lower() if len(dependlist) > i + 1: has_params = isinstance(dependlist[i + 1], list) else: has_params = False #Clean the dependency key to make sure we are only considering valid #executable symbols. cleanmatch = self.RE_DEPCLEAN.match(key + "(") if not cleanmatch: continue else: key = cleanmatch.group("key") #We need to handle if and do constructs etc. separately if key not in ["then", ",", "", "elseif"] and has_params \ and not "=" in key and not ">" in key: if key in ["if", "do"]: self._process_dependlist(dependlist[i + 1], anexec, False, mode) else: #This must be valid call to an executable, add it to the list #with its parameters and then process its parameters list #to see if there are more nested executables if mode == "insert": self._add_dependency(key, dependlist, i, isSubroutine, anexec) elif mode == "delete": #Try and find a dependency already in the executable that #has the same call signature; then remove it. self._remove_dependency(dependlist, i, isSubroutine, anexec) self._process_dependlist(dependlist[i + 1], anexec, False, mode)
<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_dependency(self, dependlist, i, isSubroutine, anexec): """Removes the specified dependency from the executable if it exists and matches the call signature."""
if dependlist[i] in anexec.dependencies: all_depends = anexec.dependencies[dependlist[i]] if len(all_depends) > 0: clean_args = all_depends[0].clean(dependlist[i + 1]) for idepend in range(len(all_depends)): #Make sure we match across all relevant parameters if (all_depends[idepend].argslist == clean_args and all_depends[idepend].isSubroutine == isSubroutine): del anexec.dependencies[dependlist[i]][idepend] #We only need to delete one, even if there are multiple #identical calls from elsewhere in the body. break
<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, key, dependlist, i, isSubroutine, anexec): """Determines whether the item in the dependency list is a valid function call by excluding local variables and members."""
#First determine if the reference is to a derived type variable lkey = key.lower() if "%" in key: #Find the type of the base variable and then perform a tree #search at the module level to determine if the final reference #is a valid executable base = key.split("%")[0] ftype = None if base in anexec.members and anexec.members[base].is_custom: ftype = anexec.members[base].kind elif base in anexec.parameters and anexec.parameters[base].is_custom: ftype = anexec.parameters[base].kind if ftype is not None: end = anexec.module.type_search(ftype, key) if end is not None and isinstance(end, TypeExecutable): #We have to overwrite the key to include the actual name of the type #that is being referenced instead of the local name of its variable. tname = "{}%{}".format(ftype, '%'.join(key.split('%')[1:])) d = Dependency(tname, dependlist[i + 1], isSubroutine, anexec) anexec.add_dependency(d) elif lkey not in ["for", "forall", "do"]: #This is a straight forward function/subroutine call, make sure that #the symbol is not a local variable or parameter, then add it if not lkey in anexec.members and not lkey in anexec.parameters \ and not lkey in self._intrinsic: #One issue with the logic until now is that some one-line statements #like "if (cond) call subroutine" don't trigger the subroutine flag #of the dependency. if dependlist[i-1] == "call": isSubroutine = True d = Dependency(dependlist[i], dependlist[i + 1], isSubroutine, anexec) anexec.add_dependency(d)
<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_docs(self, anexec, docblocks, parent, module, docsearch): """Associates the docstrings from the docblocks with their parameters."""
#The documentation for the parameters is stored outside of the executable #We need to get hold of them from docblocks from the parent text key = "{}.{}".format(parent.name, anexec.name) if key in docblocks: docs = self.docparser.to_doc(docblocks[key][0], anexec.name) anexec.docstart, anexec.docend = (docblocks[key][1], docblocks[key][2]) self.docparser.process_execdocs(docs, anexec, 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 _parse_members(self, contents, anexec, params, mode="insert"): """Parses the local variables for the contents of the specified executable."""
#First get the variables declared in the body of the executable, these can #be either locals or parameter declarations. members = self.vparser.parse(contents, anexec) #If the name matches one in the parameter list, we can connect them for param in list(params): lparam = param.lower() if lparam in members: if mode == "insert" and not lparam in anexec.parameters: anexec.add_parameter(members[lparam]) elif mode == "delete": anexec.remove_parameter(members[lparam]) #The remaining members that aren't in parameters are the local variables for key in members: if mode == "insert": if not key.lower() in anexec.parameters: anexec.members[key] = members[key] elif mode == "delete" and key in anexec.members: del anexec.members[key] #Next we need to get hold of the docstrings for these members if mode == "insert": memdocs = self.docparser.parse_docs(contents, anexec) if anexec.name in memdocs: docs = self.docparser.to_doc(memdocs[anexec.name][0], anexec.name) self.docparser.process_memberdocs(docs, anexec) #Also process the embedded types and executables who may have #docstrings just like regular executables/types do. self.docparser.process_embedded(memdocs, anexec)
<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_sidebar(self, character_page): """Parses the DOM and returns character attributes in the sidebar. :type character_page: :class:`bs4.BeautifulSoup` :param character_page: MAL character page's DOM :rtype: dict :return: Character attributes :raises: :class:`.InvalidCharacterError`, :class:`.MalformedCharacterPageError` """
character_info = {} error_tag = character_page.find(u'div', {'class': 'badresult'}) if error_tag: # MAL says the character does not exist. raise InvalidCharacterError(self.id) try: full_name_tag = character_page.find(u'div', {'id': 'contentWrapper'}).find(u'h1') if not full_name_tag: # Page is malformed. raise MalformedCharacterPageError(self.id, html, message="Could not find title div") character_info[u'full_name'] = full_name_tag.text.strip() except: if not self.session.suppress_parse_exceptions: raise info_panel_first = character_page.find(u'div', {'id': 'content'}).find(u'table').find(u'td') try: picture_tag = info_panel_first.find(u'img') character_info[u'picture'] = picture_tag.get(u'src').decode('utf-8') except: if not self.session.suppress_parse_exceptions: raise try: # assemble animeography for this character. character_info[u'animeography'] = {} animeography_header = info_panel_first.find(u'div', text=u'Animeography') if animeography_header: animeography_table = animeography_header.find_next_sibling(u'table') for row in animeography_table.find_all(u'tr'): # second column has anime info. info_col = row.find_all(u'td')[1] anime_link = info_col.find(u'a') link_parts = anime_link.get(u'href').split(u'/') # of the form: /anime/1/Cowboy_Bebop anime = self.session.anime(int(link_parts[2])).set({'title': anime_link.text}) role = info_col.find(u'small').text character_info[u'animeography'][anime] = role except: if not self.session.suppress_parse_exceptions: raise try: # assemble mangaography for this character. character_info[u'mangaography'] = {} mangaography_header = info_panel_first.find(u'div', text=u'Mangaography') if mangaography_header: mangaography_table = mangaography_header.find_next_sibling(u'table') for row in mangaography_table.find_all(u'tr'): # second column has manga info. info_col = row.find_all(u'td')[1] manga_link = info_col.find(u'a') link_parts = manga_link.get(u'href').split(u'/') # of the form: /manga/1/Cowboy_Bebop manga = self.session.manga(int(link_parts[2])).set({'title': manga_link.text}) role = info_col.find(u'small').text character_info[u'mangaography'][manga] = role except: if not self.session.suppress_parse_exceptions: raise try: num_favorites_node = info_panel_first.find(text=re.compile(u'Member Favorites: ')) character_info[u'num_favorites'] = int(num_favorites_node.strip().split(u': ')[1]) except: if not self.session.suppress_parse_exceptions: raise return character_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(self, character_page): """Parses the DOM and returns character attributes in the main-content area. :type character_page: :class:`bs4.BeautifulSoup` :param character_page: MAL character page's DOM :rtype: dict :return: Character attributes. """
character_info = self.parse_sidebar(character_page) second_col = character_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] name_elt = second_col.find(u'div', {'class': 'normal_header'}) try: name_jpn_node = name_elt.find(u'small') if name_jpn_node: character_info[u'name_jpn'] = name_jpn_node.text[1:-1] else: character_info[u'name_jpn'] = None except: if not self.session.suppress_parse_exceptions: raise try: name_elt.find(u'span').extract() character_info[u'name'] = name_elt.text.rstrip() except: if not self.session.suppress_parse_exceptions: raise try: description_elts = [] curr_elt = name_elt.nextSibling while True: if curr_elt.name not in [None, u'br']: break description_elts.append(unicode(curr_elt)) curr_elt = curr_elt.nextSibling character_info[u'description'] = ''.join(description_elts) except: if not self.session.suppress_parse_exceptions: raise try: character_info[u'voice_actors'] = {} voice_actors_header = second_col.find(u'div', text=u'Voice Actors') if voice_actors_header: voice_actors_table = voice_actors_header.find_next_sibling(u'table') for row in voice_actors_table.find_all(u'tr'): # second column has va info. info_col = row.find_all(u'td')[1] voice_actor_link = info_col.find(u'a') name = ' '.join(reversed(voice_actor_link.text.split(u', '))) link_parts = voice_actor_link.get(u'href').split(u'/') # of the form: /people/82/Romi_Park person = self.session.person(int(link_parts[2])).set({'name': name}) language = info_col.find(u'small').text character_info[u'voice_actors'][person] = language except: if not self.session.suppress_parse_exceptions: raise return character_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_favorites(self, favorites_page): """Parses the DOM and returns character favorites attributes. :type favorites_page: :class:`bs4.BeautifulSoup` :param favorites_page: MAL character favorites page's DOM :rtype: dict :return: Character favorites attributes. """
character_info = self.parse_sidebar(favorites_page) second_col = favorites_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: character_info[u'favorites'] = [] favorite_links = second_col.find_all('a', recursive=False) for link in favorite_links: # of the form /profile/shaldengeki character_info[u'favorites'].append(self.session.user(username=link.text)) except: if not self.session.suppress_parse_exceptions: raise return character_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_pictures(self, picture_page): """Parses the DOM and returns character pictures attributes. :type picture_page: :class:`bs4.BeautifulSoup` :param picture_page: MAL character pictures page's DOM :rtype: dict :return: character pictures attributes. """
character_info = self.parse_sidebar(picture_page) second_col = picture_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: picture_table = second_col.find(u'table', recursive=False) character_info[u'pictures'] = [] if picture_table: character_info[u'pictures'] = map(lambda img: img.get(u'src').decode('utf-8'), picture_table.find_all(u'img')) except: if not self.session.suppress_parse_exceptions: raise return character_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 character clubs attributes. :type clubs_page: :class:`bs4.BeautifulSoup` :param clubs_page: MAL character clubs page's DOM :rtype: dict :return: character clubs attributes. """
character_info = self.parse_sidebar(clubs_page) second_col = clubs_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: clubs_header = second_col.find(u'div', text=u'Related Clubs') character_info[u'clubs'] = [] if clubs_header: curr_elt = clubs_header.nextSibling while curr_elt is not None: if curr_elt.name == u'div': link = curr_elt.find(u'a') club_id = int(re.match(r'/clubs\.php\?cid=(?P<id>[0-9]+)', link.get(u'href')).group(u'id')) num_members = int(re.match(r'(?P<num>[0-9]+) members', curr_elt.find(u'small').text).group(u'num')) character_info[u'clubs'].append(self.session.club(club_id).set({'name': link.text, 'num_members': num_members})) curr_elt = curr_elt.nextSibling except: if not self.session.suppress_parse_exceptions: raise return character_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 character page and sets the current character's attributes. :rtype: :class:`.Character` :return: Current character object. """
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id)).text self.set(self.parse(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 load_favorites(self): """Fetches the MAL character favorites page and sets the current character's favorites 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'/favorites').text self.set(self.parse_favorites(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 load_pictures(self): """Fetches the MAL character pictures page and sets the current character's pictures 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'/pictures').text self.set(self.parse_pictures(utilities.get_clean_dom(character))) return self