text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_property_names(obj): """ Recursively gets names of all properties implemented in specified object and its subobjects. The object can be a user defined ob...
property_names = [] if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_property_names(obj, None, property_names, cycle_detect) return property_names
<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_properties(obj): """ Get values of all properties in specified object and its subobjects and returns them as a map. The object can be a user defined obje...
properties = {} if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_properties(obj, None, properties, cycle_detect) return properties
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hookable(cls): """ Initialise hookery in a class that declares hooks by decorating it with this decorator. This replaces the class with another one which has...
assert isinstance(cls, type) # For classes that won't have descriptors initialised by metaclass, need to do it here. hook_definitions = [] if not issubclass(cls, Hookable): for k, v in list(cls.__dict__.items()): if isinstance(v, (ClassHook, InstanceHook)): delattr(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _triggering_ctx(self): """ Context manager that ensures that a hook is not re-triggered by one of its handlers. """
if self._is_triggering: raise RuntimeError('{} cannot be triggered while it is being handled'.format(self)) self._is_triggering = True try: yield self finally: self._is_triggering = 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 unregister_handler(self, handler_or_func): """ Remove the handler from this hook's list of handlers. This does not give up until the handler is found in the ...
index = -1 for i, handler in enumerate(self._direct_handlers): if handler is handler_or_func or handler._original_func is handler_or_func: index = i break if index >= 0: self._direct_handlers.pop(index) self._cached_handlers = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notifySolved(self, identifier, title): """Notifies the user that a particular exercise has been solved. """
notify(self.workbench, u"Congratulations", u"Congratulations! You " "have completed the '{title}' exercise.".format(title=title)) return {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_urls(self): """ Add the following array of urls to the Tileset base urls """
return [ url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/generate%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('generate'), name="api_tileset_generate"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$" % (s...
<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, request, **kwargs): """ proxy for the tileset.generate method """
# method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) # using the primary key defined in the url, obtain the tileset tileset = 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 download(self, request, **kwargs): """ proxy for the helpers.tileset_download method """
# method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) # using the primary key defined in the url, obtain the tileset tileset = 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 configure(self, config): """ Configures the component with specified parameters. :param config: configuration parameters to set. """
dependencies = config.get_section("dependencies") names = dependencies.get_key_names() for name in names: locator = dependencies.get(name) if locator == None: continue try: descriptor = Descriptor.from_string(locat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _locate(self, name): """ Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if...
if name == None: raise Exception("Dependency name cannot be null") if self._references == None: raise Exception("References shall be set") return self._dependencies.get(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_optional(self, name): """ Gets all optional dependencies by their name. :param name: the dependency name to locate. :return: a list with found dependenci...
locator = self._locate(name) return self._references.get_optional(locator) if locator != None else 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 get_one_optional(self, name): """ Gets one optional dependency by its name. :param name: the dependency name to locate. :return: a dependency reference or nu...
locator = self._locate(name) return self._references.get_one_optional(locator) if locator != None else 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 find(self, name, required): """ Finds all matching dependencies by their name. :param name: the dependency name to locate. :param required: true to raise an ...
if name == None: raise Exception("Name cannot be null") locator = self._locate(name) if locator == None: if required: raise ReferenceException(None, name) return None return self._references.find(locator, required)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obtain_to(filename): """ Return the digital elevation map projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf fi...
root, _ = nc.open(filename) lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:] nc.close(root) return obtain(lat, lon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(config, config_as_default = False): """ Resolves an "options" configuration section from component configuration parameters. :param config: configura...
options = config.get_section("options") if len(options) == 0 and config_as_default: options = config return options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_form_view(self, view, opts): """Checks if the form referenced in the view exists or attempts to create it by parsing the template """
name = opts.get("name", opts.get("form")) if isinstance(name, Form): return template = opts.get("template", getattr(view, "template", None)) if not template: if not name: raise NoFormError("No form name specified in the form action and no templat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populate_obj(self, obj=None, form=None): """Populates an object with the form's data """
if not form: form = current_context.data.form if obj is None: obj = AttrDict() form.populate_obj(obj) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlap(self, feature, stranded: bool=False): """Determine if a feature's position overlaps with the entry Args: feature (class): GFF3Entry object stranded ...
# Allow features to overlap on different strands feature_strand = feature.strand strand = self.strand if stranded and ((strand == '.') or (strand == '+' and \ feature_strand in ['-', '.']) or (strand == '-' and \ feature_strand in ['+', '.'])): retu...
<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): """Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry """
none_type = type(None) # Format attributes for writing attrs = self.attribute_string() # Place holder if field value is NoneType for attr in self.__dict__.keys(): if type(attr) == none_type: setattr(self, attr, '.') # Format entry for writ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attribute_string(self): """Restore an entries attributes in original format, escaping reserved characters when necessary Returns: str: escaped attributes as ...
escape_map = {ord('='): '%3D', ord(','): '%2C', ord(';'): '%3B', ord('&'): '%26', ord('\t'): '%09', } list_type = type(list()) attrs = self.attributes if type(attrs) is Ordered...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterate(self, start_line=None, parse_attr=True, headers=False, comments=False): """Iterate over GFF3 file, returning GFF3 entries Args: start_line (str): Ne...
handle = self.handle # Speed tricks: reduces function calls split = str.split strip = str.strip if start_line is None: line = next(handle) # Read first GFF3 else: line = start_line # Set header to given header # Check if input is tex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, locator = None, component = None): """ Puts a new reference into this reference map. :param locator: a component reference to be added. :param comp...
if component == None: raise Exception("Component cannot be null") self._lock.acquire() try: self._references.append(Reference(locator, component)) finally: self._lock.release()
<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_all(self, locator): """ Removes all component references that match the specified locator. :param locator: a locator to remove reference by. :return: ...
components = [] if locator == None: return components self._lock.acquire() try: for reference in reversed(self._references): if reference.match(locator): self._references.remove(reference) components.appen...
<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_all_locators(self): """ Gets locators for all registered component references in this reference map. :return: a list with component locators. """
locators = [] self._lock.acquire() try: for reference in self._references: locators.append(reference.get_locator()) finally: self._lock.release() return locators
<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_all(self): """ Gets all component references registered in this reference map. :return: a list with component references. """
components = [] self._lock.acquire() try: for reference in self._references: components.append(reference.get_component()) finally: self._lock.release() return components
<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_one_optional(self, locator): """ Gets an optional component reference that matches specified locator. :param locator: the locator to find references by. ...
try: components = self.find(locator, False) return components[0] if len(components) > 0 else None except Exception as ex: 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 get_one_required(self, locator): """ Gets a required component reference that matches specified locator. :param locator: the locator to find a reference by. ...
components = self.find(locator, True) return components[0] if len(components) > 0 else 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 initialize(**kwargs): """ Loads the globally shared YAML configuration """
global config config_opts = kwargs.setdefault('config',{}) if isinstance(config_opts,basestring): config_opts = {'config_filename':config_opts} kwargs['config'] = config_opts if 'environment' in kwargs: config_opts['environment'] = kwargs['environment'] config.load_config...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_amend_key_(self,key,value): """ This will take a stringified key representation and value and load it into the configuration file for furthur usage. T...
cfg_i = self._cfg keys = key.split('.') last_key = keys.pop() trail = [] for e in keys: cfg_i.setdefault(e,{}) cfg_i = cfg_i[e] trail.append(e) if not isinstance(cfg_i,dict): raise Exception('.'.join(trail) + ' has ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_amend_(self,config_amend): """ This will take a YAML or dict configuration and load it into the configuration file for furthur usage. The good part ab...
if not isinstance(config_amend,dict): config_amend = yaml.load(config_amend) def merge_dicts(source,target,breadcrumbs=None): """ Function to update the configuration if required. Returns True if a change was made. """ changed = ...
<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_string(self, input_string): """ Return string type user input """
if input_string in ('--input', '--outname', '--framework'): # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn't, so if it's required, exit if input_string in self.required: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_executor(elem, doc): """Determines the executor for the code in `elem.text`. The elem attributes and classes select the executor in this order (highes...
executor = EXECUTORS['default'] if 'cmd' in elem.attributes.keys(): executor = elem.attributes['cmd'] elif 'runas' in elem.attributes.keys(): executor = EXECUTORS[elem.attributes['runas']] elif elem.classes[0] != 'exec': executor = EXECUTORS[elem.classes[0]] return executo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_code_block(elem, doc): """Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of t...
command = select_executor(elem, doc).split(' ') code = elem.text if 'plt' in elem.attributes or 'plt' in elem.classes: code = save_plot(code, elem) command.append(code) if 'args' in elem.attributes: for arg in elem.attributes['args'].split(): command.append(arg) cwd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_interactive_code(elem, doc): """Executes code blocks for a python shell. Parses the code in `elem.text` into blocks and executes them. Args: elem The...
code_lines = [l[4:] for l in elem.text.split('\n')] code_blocks = [[code_lines[0]]] for line in code_lines[1:]: if line.startswith(' ') or line == '': code_blocks[-1].append(line) else: code_blocks.append([line]) final_code = [] try: child = replwra...
<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_file(filename): """Reads a file which matches the pattern `filename`. Args: filename The filename pattern Returns: The file content or the empty string,...
hits = glob.glob('**/{}'.format(filename), recursive=True) if not len(hits): pf.debug('No file "{}" found.'.format(filename)) return '' elif len(hits) > 1: pf.debug('File pattern "{}" ambiguous. Using first.'.format(filename)) with open(hits[0], 'r') as f: return f.read...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_lines(code, line_spec): """Removes all lines not matching the line_spec. Args: code The code to filter line_spec The line specification. This should b...
code_lines = code.splitlines() line_specs = [line_denom.strip() for line_denom in line_spec.split(',')] single_lines = set(map(int, filter(lambda line: '-' not in line, line_specs))) line_ranges = set(filter(lambda line: '-' in line, line_specs)) for line_range in line_ranges: begin, end...
<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_import_statements(code): """Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import ...
new_code = [] for line in code.splitlines(): if not line.lstrip().startswith('import ') and \ not line.lstrip().startswith('from '): new_code.append(line) while new_code and new_code[0] == '': new_code.pop(0) while new_code and new_code[-1] == '': new_cod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_plot(code, elem): """Converts matplotlib plots to tikz code. If elem has either the plt attribute (format: plt=width,height) or the attributes width=wid...
if 'plt' in elem.attributes: figurewidth, figureheight = elem.attributes['plt'].split(',') else: try: figureheight = elem.attributes['height'] except KeyError: figureheight = '4cm' try: figurewidth = elem.attributes['width'] except Ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trimpath(attributes): """Simplifies the given path. If pathdepth is in attributes, the last pathdepth elements will be returned. If pathdepth is "full", the ...
if 'pathdepth' in attributes: if attributes['pathdepth'] != 'full': pathelements = [] remainder = attributes['file'] limit = int(attributes['pathdepth']) while len(pathelements) < limit and remainder: remainder, pe = os.path.split(remainder) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(doc): """Sets the caption_found and plot_found variables to False."""
doc.caption_found = False doc.plot_found = False doc.listings_counter = 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 maybe_center_plot(result): """Embeds a possible tikz image inside a center environment. Searches for matplotlib2tikz last commend line to detect tikz images....
begin = re.search('(% .* matplotlib2tikz v.*)', result) if begin: result = ('\\begin{center}\n' + result[begin.end():] + '\n\\end{center}') 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 action(elem, doc): # noqa """Processes pf.CodeBlocks. For details and a specification of how each command should behave, check the example files (especially ...
if isinstance(elem, pf.CodeBlock): doc.listings_counter += 1 elems = [elem] if 'hide' not in elem.classes else [] if 'file' in elem.attributes: elem.text = read_file(elem.attributes['file']) filename = trimpath(elem.attributes) prefix = pf.Emph(pf.Str('F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(doc): """Adds the pgfplots and caption packages to the header-includes if needed. """
if doc.plot_found: pgfplots_inline = pf.MetaInlines(pf.RawInline( r'''% \makeatletter \@ifpackageloaded{pgfplots}{}{\usepackage{pgfplots}} \makeatother \usepgfplotslibrary{groupplots} ''', format='tex')) try: doc.metadata['header-includes'].append(pgfplots_inline) ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rescue(f, on_success, on_error=reraise, on_complete=nop): ''' Functional try-except-finally :param function f: guarded function :param function on_succes: called when f is executed without error :param function on_error: called with `error` parameter when f failed :param function on_complet...
<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_file(self, location): """Read in a yaml file and return as a python object"""
try: return yaml.load(open(location)) except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error: raise self.BadFileErrorKls("Failed to read yaml", location=location, error_type=error.__class__.__name__, error="{0}{1}".format(error.problem, error.problem_mark))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trigger_job(job): """ trigger a job """
if job.api_instance().is_running(): return "{0}, {1} is already running".format(job.host, job.name) else: requests.get(job.api_instance().get_build_triggerurl()) return "triggering {0}, {1}...".format(job.host, job.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 observed(cls, _func): """ Decorate methods to be observable. If they are called on an instance stored in a property, the model will emit before and after not...
def wrapper(*args, **kwargs): self = args[0] assert(isinstance(self, Observable)) self._notify_method_before(self, _func.__name__, args, kwargs) res = _func(*args, **kwargs) self._notify_method_after(self, _func.__name__, res, 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 emit(self, arg=None): """Emits the signal, passing the optional argument"""
for model,name in self.__get_models__(): model.notify_signal_emit(name, 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 _linearize(cls, inst_list): """ A generator function which performs linearization of the list of instructions; that is, each instruction which should be exec...
for inst in inst_list: # Check if we need to recurse if isinstance(inst, Instructions): for sub_inst in cls._linearize(inst.instructions): yield sub_inst else: yield inst
<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_to_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Add the remote host SSH public key to the `known_hosts` file. :param hosts: ...
to_add = [] with open(known_hosts) as fh: known_hosts_set = set(line.strip() for line in fh.readlines()) cmd = ['ssh-keyscan'] + [host.hostname for host in hosts] logger.debug('Call: %s', ' '.join(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subpr...
<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_from_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Remove the remote host SSH public key to the `known_hosts` file. :param...
for host in hosts: logger.info('[%s] Removing the remote host SSH public key from [%s]...', host.hostname, known_hosts) cmd = ['ssh-keygen', '-f', known_hosts, '-R', host.hostname] logger.debug('Call: %s', ' '.join(cmd)) if not dry: try: ...
<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_requests(self): """ Loop that runs in a thread to process requests synchronously. """
while True: id, args, kwargs = self.request_queue.get() try: response = self._make_request(*args, **kwargs) except Exception as e: response = e self.results[id] = response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_from_address(self): """ Cache the coinbase address so that we don't make two requests for every single transaction. """
if self._coinbase_cache_til is not None: if time.time - self._coinbase_cache_til > 30: self._coinbase_cache_til = None self._coinbase_cache = None if self._coinbase_cache is None: self._coinbase_cache = self.get_coinbase() return self._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 find_pulls(self, testpulls=None): """Finds a list of new pull requests that need to be processed. :arg testpulls: a list of tserver.FakePull instances so we ...
#We check all the repositories installed for new (open) pull requests. #If any exist, we check the pull request number against our archive to #see if we have to do anything for it. result = {} for lname, repo in self.repositories.items(): if lname not in self.archive...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_archive(self): """Saves the JSON archive of processed pull requests. """
import json from utility import json_serial with open(self.archpath, 'w') as f: json.dump(self.archive, f, default=json_serial)
<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_repos(self): """Gets a list of all the installed repositories in this server. """
result = {} for xmlpath in self.installed: repo = RepositorySettings(self, xmlpath) result[repo.name.lower()] = repo return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_installed(self): """Gets a list of the file paths to repo settings files that are being monitored by the CI server. """
from utility import get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the script's database that tracks #the user's interactions with it. fulldata = get_json(self.instpath, {}) if "installed" in fullda...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uninstall(self, xmlpath): """Uninstalls the repository with the specified XML path from the server. """
from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if fullpath in self.installed: repo = RepositorySettings(self, fullpath) if repo.name.lower() in self.repositories: del self.repositories[repo.name.lower()] if repo.name.low...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self, xmlpath): """Installs the repository at the specified XML path as an additional repo to monitor pull requests for. """
#Before we can install it, we need to make sure that none of the existing #installed paths point to the same repo. from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if path.isfile(fullpath): repo = RepositorySettings(self, fullpath) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_installed(self): """Saves the list of installed repo XML settings files."""
import json from utility import json_serial, get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the script's database that tracks #the user's interactions with it. fulldata = get_json(self.instpath, {})...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self, archive): """Creates the repo folder locally, copies the static files and folders available locally, initalizes the repo with git so it has the co...
from os import makedirs, path, chdir, system, getcwd self.repodir = path.abspath(path.expanduser(self.repo.staging)) if ("stage" in archive and path.isdir(archive["stage"]) and self.repodir != archive["stage"] and archive["stage"] is not None): #We have a previous attem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fields_common(self): """Returns a dictionary of fields and values that are common to all events for which fields dictionaries are created. """
result = {} if not self.testmode: result["__reponame__"] = self.repo.repo.full_name result["__repodesc__"] = self.repo.repo.description result["__repourl__"] = self.repo.repo.html_url result["__repodir__"] = self.repodir if self.organization ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wiki(self): """Returns the wiki markup describing the details of the github pull request as well as a link to the details on github. """
date = self.pull.created_at.strftime("%m/%d/%Y %H:%M") return "{} {} ({} [{} github])\n".format(self.pull.avatar_url, self.pull.body, date, self.pull.html_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fields_general(self, event): """Appends any additional fields to the common ones and returns the fields dictionary. """
result = self._fields_common() basic = { "__test_html__": self.repo.testing.html(False), "__test_text__": self.repo.testing.text(False)} full = { "__test_html__": self.repo.testing.html(), "__test_text__": self.repo.testing.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 _get_site(self): """Returns the mwclient.Site for accessing and editing the wiki pages. """
import mwclient parts = self.server.settings.wiki.replace("http", "").replace("://", "").split("/") self.url = parts[0] if len(parts) > 1 and parts[1].strip() != "": self.relpath = '/' + '/'.join(parts[1:len(parts)]) #The API expects us to have a trailing forward...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _site_login(self, repo): """Logs the user specified in the repo into the wiki. :arg repo: an instance of config.RepositorySettings with wiki credentials. """
try: if not self.testmode: self.site.login(repo.wiki["user"], repo.wiki["password"]) except LoginError as e: print(e[1]['result']) self.basepage = repo.wiki["basepage"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, request): """Creates a new wiki page for the specified PullRequest instance. The page gets initialized with basic information about the pull req...
self._site_login(request.repo) self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) #We add the link to the main repo page during this creation; we also create #the full unit test report page here. self._edit_main(request) return sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, request): """Updates the wiki page with the results of the unit tests run for the pull request. :arg percent: the percent success rate of the un...
from os import path self._site_login(request.repo) self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) #Before we can update the results from stdout, we first need to upload them to the #server. The files can be quite big sometimes;...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_new(self, request): """Creates the new wiki page that houses the details of the unit testing runs. """
self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) head = list(self._newpage_head) head.append(request.repo.testing.wiki(False)) if not self.testmode: page = self.site.Pages[self.newpage] result = page.save('\n'.join(head), 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 _edit_main(self, request): """Adds the link to the new unit testing results on the repo's main wiki page. """
self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) if not self.testmode: page = site.pages[self.basepage] text = page.text() else: text = "This is a fake wiki page.\n\n<!--@CI:Placeholder-->" self.newpage = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def email(self, repo, event, fields, dryrun=False): """Sends an email to the configured recipients for the specified event. :arg repo: the name of the repository...
tcontents = self._get_template(event, "txt", fields) hcontents = self._get_template(event, "html", fields) if tcontents is not None and hcontents is not None: return Email(self.server, repo, self.settings[repo], tcontents, hcontents, dryrun)
<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_sys(): """Tries to identify your python platform :returns: a dict with the gathered information :rtype: dict :raises: None the returned dict has these...
system = platform.system() bit = platform.architecture()[0] compiler = platform.python_compiler() ver = platform.python_version_tuple() return {'system': system, 'bit': bit, 'compiler': compiler, 'python_version_tuple': ver}
<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_maya_location(self, ): """ Return the installation path to maya :returns: path to maya :rtype: str :raises: errors.SoftwareNotFoundError """
import _winreg # query winreg entry # the last flag is needed, if we want to test with 32 bit python! # Because Maya is an 64 bit key! for ver in MAYA_VERSIONS: try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, ...
<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_maya_envpath(self): """Return the PYTHONPATH neccessary for running mayapy If you start native mayapy, it will setup these paths. You might want to prepe...
opj = os.path.join ml = self.get_maya_location() mb = self.get_maya_bin() msp = self.get_maya_sitepackage_dir() pyzip = opj(mb, "python27.zip") pydir = opj(ml, "Python") pydll = opj(pydir, "DLLs") pylib = opj(pydir, "lib") pyplat = opj(pylib, "pla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sort(self): """ Sort the response dictionaries priority levels for ordered iteration """
self._log.debug('Sorting responses by priority') self._responses = OrderedDict(sorted(list(self._responses.items()), reverse=True)) self.sorted = 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 register_blueprints(app, application_package_name=None, blueprint_directory=None): """Register Flask blueprints on app object"""
if not application_package_name: application_package_name = 'app' if not blueprint_directory: blueprint_directory = os.path.join(os.getcwd(), application_package_name) blueprint_directories = get_child_directories(blueprint_directory) for directory in blueprint_directories: a...
<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_child_directories(path): """Return names of immediate child directories"""
if not _is_valid_directory(path): raise exceptions.InvalidDirectory entries = os.listdir(path) directory_names = [] for entry in entries: abs_entry_path = os.path.join(path, entry) if _is_valid_directory(abs_entry_path): directory_names.append(entry) return di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """ Deletes all the keys from redis along with emptying the objects internal `_data` dict, then deleting itself at the end of it all. """
redis_search_key = ":".join([self.namespace, self.key, "*"]) keys = self.conn.keys(redis_search_key) if keys: for key in keys: part = key.split(":")[-1] self._data.pop(part) self.conn.delete(part) del 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 get(self, part): """ Retrieves a part of the model from redis and stores it. :param part: The part of the model to retrieve. :raises RedisORMException: If th...
redis_key = ':'.join([self.namespace, self.key, part]) objectType = self.conn.type(redis_key) if objectType == "string": self._data[part] = self.conn.get(redis_key) elif objectType == "list": self._data[part] = RedisList(redis_key, self.conn) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(client, source_dir): """Upload inappproducts to play store."""
print('') print('upload inappproducs') print('---------------------') products_folder = os.path.join(source_dir, 'products') product_files = filter(os.path.isfile, list_dir_abspath(products_folder)) current_product_skus = map(lambda product: product['sku'], client.list_inappproducts()) pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(client, target_dir): """Download inappproducts from play store."""
print('') print("download inappproducts") print('---------------------') products = client.list_inappproducts() for product in products: path = os.path.join(target_dir, 'products') del product['packageName'] mkdir_p(path) with open(os.path.join(path, product['sku'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dataset_exists(dataset_name): '''If a dataset with the given name exists, return its absolute path; otherwise return None''' dataset_dir = os.path.join(LIB_DIR, 'datasets') dataset_path = os.path.join(dataset_dir, dataset_name) return dataset_path if os.path.isdir(dataset_path) else 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 run_script(self, args, event_writer, input_stream): """Handles all the specifics of running a modular input :param args: List of command line arguments passe...
try: if len(args) == 1: # This script is running as an input. Input definitions will be # passed on stdin as XML, and the script will write events on # stdout and log entries on stderr. self._input_definition = InputDefinition.parse(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 money(s, thousand_sep=".", decimal_sep=","): """Converts money amount in string to a Decimal object. With the default arguments, the format is expected to be...
s = s.replace(thousand_sep, "") s = s.replace(decimal_sep, ".") return Decimal(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csv_row_to_transaction(index, row, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses a row of strings to a ``T...
xfer, posted, message, amount, total = row xfer = Parse.date(xfer) posted = Parse.date(posted) message = Parse.to_utf8(message, source_encoding) amount = Parse.money(amount) total = Parse.money(total) return Transaction(index, xfer, posted, message, amount, total...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csv_to_transactions(handle, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses CSV data from stream and returns...
trans = Transactions() rows = csv.reader(handle, delimiter=";", quotechar="\"") for index, row in enumerate(rows): trans.append(Parse.csv_row_to_transaction(index, row)) return trans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_sqlite3(self, location=":memory:"): """Returns an SQLITE3 connection to a database containing the transactions."""
def decimal_to_sqlite3(n): return int(100*n) def sqlite3_to_decimal(s): return Decimal(s)/100 sqlite3.register_adapter(Decimal, decimal_to_sqlite3) sqlite3.register_converter("decimal", sqlite3_to_decimal) con = sqlite3.connect(location, detect_types=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_by(self, key, field=lambda x: x.xfer): """Returns all transactions whose given ``field`` matches ``key``. Returns: A ``Transactions`` object. """
return Transactions([t for t in self.trans if field(t) == 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 range(self, start_date=None, stop_date=None, field=lambda x: x.xfer): """Return a ``Transactions`` object in an inclusive date range. Args: start_date: A ``d...
assert start_date <= stop_date, \ "Start date must be earlier than end date." out = Transactions() for t in self.trans: date = field(t) if (start_date is not None) and not (date >= start_date): continue if (stop_date is not None)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agg_grid(grid, agg=None): """ Many functions return a 2d list with a complex data type in each cell. For instance, grids representing environments have a set...
grid = deepcopy(grid) if agg is None: if type(grid[0][0]) is list and type(grid[0][0][0]) is str: agg = string_avg else: agg = mode for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = agg(grid[i][j]) return grid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """
grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_zeros_to_lists(ls): """ Takes a list of lists and appends 0s to the beggining of each sub_list until they are all the same length. Used for sign-exte...
longest = max([len(l) for l in ls]) for i in range(len(ls)): while len(ls[i]) < longest: ls[i].insert(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 squared_toroidal_dist(p1, p2, world_size=(60, 60)): """ Separated out because sqrt has a lot of overhead """
halfx = world_size[0]/2.0 if world_size[0] == world_size[1]: halfy = halfx else: halfy = world_size[1]/2.0 deltax = p1[0] - p2[0] if deltax < -halfx: deltax += world_size[0] elif deltax > halfx: deltax -= world_size[0] deltay = p1[1] - p2[1] if deltay <...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def phenotype_to_res_set(phenotype, resources): """ Converts a binary string to a set containing the resources indicated by the bits in the string. Inputs: pheno...
assert(phenotype[0:2] == "0b") phenotype = phenotype[2:] # Fill in leading zeroes while len(phenotype) < len(resources): phenotype = "0" + phenotype res_set = set() for i in range(len(phenotype)): if phenotype[i] == "1": res_set.add(resources[i]) assert(phenot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def res_set_to_phenotype(res_set, full_list): """ Converts a set of strings indicating resources to a binary string where the positions of 1s indicate which reso...
full_list = list(full_list) phenotype = len(full_list) * ["0"] for i in range(len(full_list)): if full_list[i] in res_set: phenotype[i] = "1" assert(phenotype.count("1") == len(res_set)) # Remove uneceesary leading 0s while phenotype[0] == "0" and len(phenotype) > 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 weighted_hamming(b1, b2): """ Hamming distance that emphasizes differences earlier in strings. """
assert(len(b1) == len(b2)) hamming = 0 for i in range(len(b1)): if b1[i] != b2[i]: # differences at more significant (leftward) bits # are more important if i > 0: hamming += 1 + 1.0/i # This weighting is completely arbitrary r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def n_tasks(dec_num): """ Takes a decimal number as input and returns the number of ones in the binary representation. This translates to the number of tasks bei...
bitstring = "" try: bitstring = dec_num[2:] except: bitstring = bin(int(dec_num))[2:] # cut off 0b # print bin(int(dec_num)), bitstring return bitstring.count("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 convert_to_pysal(data): """ Pysal expects a distance matrix, and data formatted in a numpy array. This functions takes a data grid and returns those things. ...
w = pysal.lat2W(len(data[0]), len(data)) data = np.array(data) data = np.reshape(data, (len(data)*len(data[0]), 1)) return w, data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median(ls): """ Takes a list and returns the median. """
ls = sorted(ls) return ls[int(floor(len(ls)/2.0))]