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 string_avg(strings, binary=True): """ Takes a list of strings of equal length and returns a string containing the most common value from each index in the string. Optional argument: binary - a boolean indicating whether or not to treat strings as binary numbers (fill in leading zeros if lengths differ). """
if binary: # Assume this is a binary number and fill leading zeros strings = deepcopy(strings) longest = len(max(strings, key=len)) for i in range(len(strings)): while len(strings[i]) < longest: split_string = strings[i].split("b") strings[i] = "0b0" + split_string[1] avg = "" for i in (range(len(strings[0]))): opts = [] for s in strings: opts.append(s[i]) avg += max(set(opts), key=opts.count) return avg
<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_world_dimensions(gridfile, delim=" "): """ This function takes the name of a file in grid_task format and returns the dimensions of the world it represents. """
infile = open(gridfile) lines = infile.readlines() infile.close() world_x = len(lines[0].strip().split(delim)) world_y = len(lines) return (world_x, world_y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_config(path): """ Context manager to modify a flit config file. Will read the config file, validate the config, yield the config object, validate and write back the config to the file on exit """
if isinstance(path, str): path = Path(path) config = _read_pkg_ini(path) _validate_config(config, path) # don't catch exception, we won't write the new config. yield config _validate_config(config, path) with path.open('w') as f: config.write(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 pformat(self): '''
and supress escaping apostrophe ''' result = "{\n" indent1 = " " * 4 indent2 = " " * 8 for line_no, code_objects in sorted(self.items()): result += '%s%i: [\n' % (indent1, line_no) for code_object in code_objects: result += '%s"""<%s:%s>""",\n' % ( indent2, code_object.PART_TYPE, code_object.content ) result += '%s],\n' % indent1 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_string(self, line): """ Consume the complete string until next " or \n """
log.debug("*** parse STRING: >>>%r<<<", line) parts = self.regex_split_string.split(line, maxsplit=1) if len(parts) == 1: # end return parts[0], None pre, match, post = parts log.debug("\tpre: >>>%r<<<", pre) log.debug("\tmatch: >>>%r<<<", match) log.debug("\tpost: >>>%r<<<", post) pre = pre + match log.debug("Parse string result: %r,%r", pre, post) return pre, post
<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_code(self, line): """ parse the given BASIC line and branch into DATA, String and consume a complete Comment """
log.debug("*** parse CODE: >>>%r<<<", line) parts = self.regex_split_all.split(line, maxsplit=1) if len(parts) == 1: # end self.line_data.append(BASIC_Code(parts[0])) return pre, match, post = parts log.debug("\tpre: >>>%r<<<", pre) log.debug("\tmatch: >>>%r<<<", match) log.debug("\tpost: >>>%r<<<", post) if match == '"': log.debug("%r --> parse STRING", match) self.line_data.append(BASIC_Code(pre)) string_part, rest = self._parse_string(post) self.line_data.append(BASIC_String(match + string_part)) if rest: self._parse_code(rest) return self.line_data.append(BASIC_Code(pre + match)) if match == "DATA": log.debug("%r --> parse DATA", match) data_part, rest = self._parse_data(post) self.line_data.append(BASIC_Data(data_part)) if rest: self._parse_code(rest) return elif match in ("'", "REM"): log.debug("%r --> consume rest of the line as COMMENT", match) if post: self.line_data.append(BASIC_Comment(post)) return raise RuntimeError("Wrong Reg.Exp.? match is: %r" % match)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(correlation_id, components): """ Closes multiple components. To be closed components must implement [[ICloseable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed. """
if components == None: return for component in components: Closer.close_one(correlation_id, component)
<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(app, url = None, path = None, endpoint=None, decorate=None, index='index.html', **options): """Adds static files endpoint with optional directory index."""
url = url or app.static_url_path or '' path = os.path.abspath(path or app.static_folder or '.') endpoint = endpoint or 'static_' + os.path.basename(path) decorate = decorate or (lambda f: f) endpoints = {} if path == app.static_folder: raise ValueError('Files in `{}` path are already automatically served on `{}` URL by Flask.' ' Set Flask app static_folder to None, if you want to serve them using Flask Ecstatic at `{}` URL' .format(path, app.static_url_path, url)) @app.route(url + '/<path:filename>', endpoint = endpoint) @handle404 @decorate def static_files(filename): if index: filename = safe_join(path, filename) if os.path.isdir(filename): filename = os.path.join(filename, index) return send_file(filename, **options) else: return send_from_directory(path, filename, **options) endpoints[endpoint] = static_files if index: @app.route(url + '/', endpoint = endpoint + '_index') @handle404 @decorate def static_index(): return send_from_directory(path, index, **options) endpoints[endpoint + '_index'] = static_index if url: @app.route(url, endpoint = endpoint + '_index_bare') @handle404 @decorate def static_index_bare(): return send_from_directory(path, index, **options) endpoints[endpoint + '_index_bare'] = static_index_bare return endpoints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def program_dump2ascii_lines(self, dump, program_start=None): """ convert a memory dump of a tokensized BASIC listing into ASCII listing list. """
dump = bytearray(dump) # assert isinstance(dump, bytearray) if program_start is None: program_start = self.DEFAULT_PROGRAM_START return self.listing.program_dump2ascii_lines(dump, program_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 ascii_listing2program_dump(self, basic_program_ascii, program_start=None): """ convert a ASCII BASIC program listing into tokens. This tokens list can be used to insert it into the Emulator RAM. """
if program_start is None: program_start = self.DEFAULT_PROGRAM_START basic_lines = self.ascii_listing2basic_lines(basic_program_ascii, program_start) program_dump=self.listing.basic_lines2program_dump(basic_lines, program_start) assert isinstance(program_dump, bytearray), ( "is type: %s and not bytearray: %s" % (type(program_dump), repr(program_dump)) ) return program_dump
<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_gaf_format(self): """Return a GAF 2.0-compatible string representation of the annotation. Parameters Returns ------- str The formatted string. """
sep = '\t' return sep.join( [self.gene, self.db_ref, self.term.id, self.evidence, '|'.join(self.db_ref), '|'.join(self.with_)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ahead(self, i, j=None): '''Raising stopiteration with end the parse. ''' if j is None: return self._stream[self.i + i] else: return self._stream[self.i + i: self.i + j]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def method_name(func): """Method wrapper that adds the name of the method being called to its arguments list in Pascal case """
@wraps(func) def _method_name(*args, **kwargs): name = to_pascal_case(func.__name__) return func(name=name, *args, **kwargs) return _method_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 to_pascal_case(s): """Transform underscore separated string to pascal case """
return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())
<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_underscore(s): """Transform camel or pascal case to underscore separated string """
return re.sub( r'(?!^)([A-Z]+)', lambda m: "_{0}".format(m.group(1).lower()), re.sub(r'(?!^)([A-Z]{1}[a-z]{1})', lambda m: "_{0}".format(m.group(1).lower()), s) ).lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, correlation_id, args): """ Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with. """
for listener in self._listeners: try: listener.on_event(correlation_id, self, args) except Exception as ex: raise InvocationException( correlation_id, "EXEC_FAILED", "Raising event " + self._name + " failed: " + str(ex) ).with_details("event", self._name).wrap(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 _parseIsTag(self): """ Detect whether the element is HTML tag or not. Result is saved to the :attr:`_istag` property. """
el = self._element self._istag = el and el[0] == "<" and el[-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 _parseIsComment(self): """ Detect whether the element is HTML comment or not. Result is saved to the :attr:`_iscomment` property. """
self._iscomment = ( self._element.startswith("<!--") and self._element.endswith("-->") )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseTagName(self): """ Parse name of the tag. Result is saved to the :attr:`_tagname` property. """
for el in self._element.split(): el = el.replace("/", "").replace("<", "").replace(">", "") if el.strip(): self._tagname = el.rstrip() 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 _parseParams(self): """ Parse parameters from their string HTML representation to dictionary. Result is saved to the :attr:`params` property. """
# check if there are any parameters if " " not in self._element or "=" not in self._element: return # remove '<' & '>' params = self._element.strip()[1:-1].strip() # remove tagname offset = params.find(self.getTagName()) + len(self.getTagName()) params = params[offset:].strip() # parser machine next_state = 0 key = "" value = "" end_quote = "" buff = ["", ""] for c in params: if next_state == 0: # key if c.strip() != "": # safer than list space, tab and all if c == "=": # possible whitespaces in UTF next_state = 1 else: key += c elif next_state == 1: # value decisioner if c.strip() != "": # skip whitespaces if c == "'" or c == '"': next_state = 3 end_quote = c else: next_state = 2 value += c elif next_state == 2: # one word parameter without quotes if c.strip() == "": next_state = 0 self.params[key] = value key = "" value = "" else: value += c elif next_state == 3: # quoted string if c == end_quote and (buff[0] != "\\" or (buff[0]) == "\\" and buff[1] == "\\"): next_state = 0 self.params[key] = unescape(value, end_quote) key = "" value = "" end_quote = "" else: value += c buff = _rotate_buff(buff) buff[0] = c if key: if end_quote and value.strip(): self.params[key] = unescape(value, end_quote) else: self.params[key] = value if "/" in self.params.keys(): del self.params["/"] self._isnonpairtag = 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 isOpeningTag(self): """ Detect whether this tag is opening or not. Returns: bool: True if it is opening. """
if self.isTag() and \ not self.isComment() and \ not self.isEndTag() and \ not self.isNonPairTag(): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entropy(dictionary): """ Helper function for entropy calculations. Takes a frequency dictionary and calculates entropy of the keys. """
total = 0.0 entropy = 0 for key in dictionary.keys(): total += dictionary[key] for key in dictionary.keys(): entropy += dictionary[key]/total * log(1.0/(dictionary[key]/total), 2) return entropy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqrt_shannon_entropy(filename): """ Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability. """
data = load_grid_data(filename, "int") data = agg_grid(data, mode) phenotypes = {} for r in data: for c in r: if c in phenotypes: phenotypes[c] += 1 else: phenotypes[c] = 1 for key in phenotypes.keys(): phenotypes[key] = sqrt(phenotypes[key]) return entropy(phenotypes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _composed_doc(fs): """ Generate a docstring for the composition of fs. """
if not fs: # Argument name for the docstring. return 'n' return '{f}({g})'.format(f=fs[0].__name__, g=_composed_doc(fs[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 update_model(self, idx=None): """Updates the value of property at given index. If idx is None, all controlled indices will be updated. This method should be called directly by the user in very unusual conditions."""
if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) try: val = self._read_widget(idx) except ValueError: pass else: self._write_property(val, idx) pass pass else: try: val = self._read_widget(idx) except ValueError: pass else: self._write_property(val, idx) 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 update_widget(self, idx=None): """Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions."""
if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) self._write_widget(self._read_property(idx), idx) pass else: self._write_widget(self._read_property(idx), idx) 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 _on_wid_changed(self, wid): """Called when the widget is changed"""
if self._itsme: return self.update_model(self._get_idx_from_widget(wid)) 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 fetch_url(url): """ Fetch the given url, strip formfeeds and decode it into the defined encoding """
with closing(urllib.urlopen(url)) as f: if f.code is 200: response = f.read() return strip_formfeeds(response).decode(ENCODING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ): """Does a regex match of the mount entry string"""
match_obj = regex_obj.match(str_to_match) if not match_obj: error_message = ('Line "%s" is unrecognized by overlay4u. ' 'This is only meant for use with Ubuntu Linux.') raise UnrecognizedMountEntry(error_message % str_to_match) return match_obj.groupdict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_list(self, fs_type=None): """List mount entries"""
entries = self._entries if fs_type: entries = filter(lambda a: a.fs_type == fs_type, entries) return entries
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, f_buf=None): """ Definitely render the workbook :param obj f_buf: A file buffer supporting the write and seek methods """
if f_buf is None: f_buf = StringIO.StringIO() with odswriter.writer(f_buf) as writer: default_sheet = writer.new_sheet(self.title) self._render_headers(default_sheet) self._render_rows(default_sheet) # abstract_sheet require the same attributes as our current writer for abstract_sheet in self.sheets: sheet = writer.new_sheet(name=abstract_sheet.title) abstract_sheet._render_headers(sheet) abstract_sheet._render_rows(sheet) f_buf.seek(0) return f_buf
<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_related_exporter(self, related_obj, column): """ returns an SqlaOdsExporter for the given related object and stores it in the column object as a cache """
result = column.get('sqla_ods_exporter') if result is None: result = column['sqla_ods_exporter'] = SqlaOdsExporter( related_obj.__class__, is_root=False, title=column.get('label', column['key']), ) self.add_sheet(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 _get_relationship_cell_val(self, obj, column): """ Return the value to insert in a relationship cell Handle the case of complex related datas we want to handle """
val = SqlaExporter._get_relationship_cell_val(self, obj, column) if val == "": related_key = column.get('related_key', None) if column['__col__'].uselist and related_key is None and \ self.is_root: # on récupère les objets liés key = column['key'] related_objects = getattr(obj, key, None) if not related_objects: return "" else: exporter = self._get_related_exporter( related_objects[0], column, ) for rel_obj in related_objects: exporter.add_row(rel_obj) return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raster(times, indices, max_time=None, max_index=None, x_label="Timestep", y_label="Index", **kwargs): """Plots a raster plot given times and indices of events."""
# set default size to 1 if 's' not in kwargs: kwargs['s'] = 1 scatter(times, indices, **kwargs) if max_time is None: max_time = max(times) if max_index is None: max_index = max(indices) axis((0, max_time, 0, max_index)) if x_label is not None: xlabel(x_label) if y_label is not None: ylabel(y_label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def query(query): ''' Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results. ''' # send the query to the Gaia archive with warnings.catch_warnings() : warnings.filterwarnings("ignore") _gaia_job = astroquery.gaia.Gaia.launch_job(query) # return the table of results return _gaia_job.get_results()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectionMade(self): """ Initializes the protocol. """
self._buffer = b'' self._queue = {} self._stopped = None self._tag = 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 dataReceived(self, data): """ Parses chunks of bytes into responses. Whenever a complete response is received, this method extracts its payload and calls L{responseReceived} to process it. @param data: A chunk of data representing a (possibly partial) response @type data: C{bytes} """
size = len(self._buffer) + len(data) if size > self.MAX_LENGTH: self.lengthLimitExceeded(size) self._buffer += data start = 0 for match in self._pattern.finditer(self._buffer): # The start of the sentinel marks the end of the response. end = match.start() tag = int(match.group(1)) self.responseReceived(self._buffer[start:end], tag) # Advance start position to the beginning of the next line start = match.end() + 1 if start: self._buffer = self._buffer[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 responseReceived(self, response, tag): """ Receives some characters of a netstring. Whenever a complete response is received, this method calls the deferred associated with it. @param response: A complete response generated by exiftool. @type response: C{bytes} @param tag: The tag associated with the response @type tag: C{int} """
self._queue.pop(tag).callback(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 execute(self, *args): """ Pass one command to exiftool and return a deferred which is fired as soon as the command completes. @param *args: Command line arguments passed to exiftool @type *args: C{unicode} @rtype: C{Deferred} @return: A deferred whose callback will be invoked when the command completed. """
result = defer.Deferred() if self.connected and not self._stopped: self._tag += 1 args = tuple(args) + ('-execute{:d}'.format(self._tag), '') safe_args = [fsencode(arg) for arg in args] self.transport.write(b'\n'.join(safe_args)) result = defer.Deferred() self._queue[self._tag] = result else: result.errback(error.ConnectionClosed('Not connected to exiftool')) 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 loseConnection(self): """ Close the connection and terminate the exiftool process. @rtype: C{Deferred} @return: A deferred whose callback will be invoked when the connection was closed. """
if self._stopped: result = self._stopped elif self.connected: result = defer.Deferred() self._stopped = result self.transport.write(b'\n'.join((b'-stay_open', b'False', b''))) else: # Already disconnected. result = defer.succeed(self) 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 connectionLost(self, reason=protocol.connectionDone): """ Check whether termination was intended and invoke the deferred. If the connection terminated unexpectedly, reraise the failure. @type reason: L{twisted.python.failure.Failure} """
self.connected = 0 for pending in self._queue.values(): pending.errback(reason) self._queue.clear() if self._stopped: result = self if reason.check(error.ConnectionDone) else reason self._stopped.callback(result) self._stopped = None else: reason.raiseException()
<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_next_character(code, position, char): """Find next char and return its first and last positions"""
end = LineCol(code, *position) while not end.eof and end.char() in WHITESPACE: end.inc() if not end.eof and end.char() == char: return end.tuple(), inc_tuple(end.tuple()) return None, 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 from_value(value = None): """ Converts specified value into ProjectionParams. :param value: value to be converted :return: a newly created ProjectionParams. """
if isinstance(value, ProjectionParams): return value array = AnyValueArray.from_value(value) if value != None else AnyValueArray() return ProjectionParams(array)
<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_string(self): """ Gets a string representation of the object. The result is a comma-separated list of projection fields "field1,field2.field21,field2.field22.field221" :return: a string representation of the object. """
builder = "" index = 0 while index < self.__len__(): if index > 0: builder = builder + ',' builder = builder + super(ProjectionParams, self).__getitem__(index) index = index + 1 return builder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snake_case_backend_name(self): """ CamelCase -> camel_case """
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', type(self).__name__) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_setting(self, key, default=NOT_SET): """ Gets a setting for the key. :raise KeyError: If the key is not set and default isn't provided. """
if self._arca is None: raise LazySettingProperty.SettingsNotReady return self._arca.settings.get(*self.get_settings_keys(key), default=default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash_file_contents(requirements_option: RequirementsOptions, path: Path) -> str: """ Returns a SHA256 hash of the contents of ``path`` combined with the Arca version. """
return hashlib.sha256(path.read_bytes() + bytes( requirements_option.name + arca.__version__, "utf-8" )).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_requirements_information(self, path: Path) -> Tuple[RequirementsOptions, Optional[str]]: """ Returns the information needed to install requirements for a repository - what kind is used and the hash of contents of the defining file. """
if self.pipfile_location is not None: pipfile = path / self.pipfile_location / "Pipfile" pipfile_lock = path / self.pipfile_location / "Pipfile.lock" pipfile_exists = pipfile.exists() pipfile_lock_exists = pipfile_lock.exists() if pipfile_exists and pipfile_lock_exists: option = RequirementsOptions.pipfile return option, self.hash_file_contents(option, pipfile_lock) elif pipfile_exists: raise BuildError("Only the Pipfile is included in the repository, Arca does not support that.") elif pipfile_lock_exists: raise BuildError("Only the Pipfile.lock file is include in the repository, Arca does not support that.") if self.requirements_location: requirements_file = path / self.requirements_location if requirements_file.exists(): option = RequirementsOptions.requirements_txt return option, self.hash_file_contents(option, requirements_file) return RequirementsOptions.no_requirements, 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 serialized_task(self, task: Task) -> Tuple[str, str]: """ Returns the name of the task definition file and its contents. """
return f"{task.hash}.json", task.json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path) -> Result: # pragma: no cover """ Executes the script and returns the result. Must be implemented by subclasses. :param repo: Repo URL :param branch: Branch name :param task: The requested :class:`Task` :param git_repo: A :class:`Repo <git.repo.base.Repo>` of the repo/branch :param repo_path: :class:`Path <pathlib.Path>` to the location where the repo is stored. :return: The output of the task in a :class:`Result` instance. """
raise NotImplementedError
<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_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: # pragma: no cover """ Abstract method which must be implemented in subclasses, which must return a str path to a Python executable which will be used to run the script. See :meth:`BaseBackend.run <arca.BaseBackend.run>` to see arguments description. """
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quote_names(db, names): """psycopg2 doesn't know how to quote identifier names, so we ask the server"""
c = db.cursor() c.execute("SELECT pg_catalog.quote_ident(n) FROM pg_catalog.unnest(%s::text[]) n", [list(names)]) return [name for (name,) in 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 execute_catch(c, sql, vars=None): """Run a query, but ignore any errors. For error recovery paths where the error handler should not raise another."""
try: c.execute(sql, vars) except Exception as err: cmd = sql.split(' ', 1)[0] log.error("Error executing %s: %s", cmd, err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_copy(): settings. When used with --force, an existing database with the same name as DEST is replaced, the original is renamed out of place in the form DEST_old_YYYYMMDD (unless --no-backup is specified). """
db = connect() if args.force and db_exists(db, args.dest): tmp_db = generate_alt_dbname(db, args.dest, 'tmp') pg_copy(db, args.src, tmp_db) pg_move_extended(db, tmp_db, args.dest) else: pg_copy(db, args.src, args.dest)
<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_move(db=None): """Rename a database within a server. When used with --force, an existing database with the same name as DEST is replaced, the original is renamed out of place in the form DEST_old_YYYYMMDD (unless --no-backup is specified). """
if db is None: db = connect() pg_move_extended(db, args.src, args.dest)
<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_reindex(): """Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original. The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until the rename succeeds. """
db = connect(args.database) for idx in args.indexes: pg_reindex(db, idx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def align(s1, s2, gap=' ', eq=operator.eq): '''aligns two strings >>> print(*align('pharmacy', 'farmácia', gap='_'), sep='\\n') pharmac_y _farmácia >>> print(*align('advantage', 'vantagem', gap='_'), sep='\\n') advantage_ __vantagem ''' # first we compute the dynamic programming table m, n = len(s1), len(s2) table = [] # the table is extended lazily, one row at a time row = list(range(n+1)) # the first row is 0, 1, 2, ..., n table.append(list(row)) # copy row and insert into table for i in range(m): p = i row[0] = i+1 for j in range(n): t = 0 if eq(s1[i], s2[j]) else 1 p, row[j+1] = row[j+1], min(p+t, row[j]+1, row[j+1]+1) table.append(list(row)) # copy row and insert into table # now we trace the best alignment path from cell [m][n] to cell [0],[0] s1_, s2_ = '', '' i, j = m, n while i != 0 and j != 0: _, i, j, s1_, s2_ = min( (table[i-1][j-1], i-1, j-1, s1[i-1]+s1_, s2[j-1]+s2_), (table[i-1][j], i-1, j, s1[i-1]+s1_, gap+s2_), (table[i][j-1], i, j-1, gap+s1_, s2[j-1]+s2_) ) if i != 0: s1_ = s1[:i]+s1_ s2_ = gap*i+s2_ if j != 0: s1_ = gap*j+s1_ s2_ = s2[:j]+s2_ return s1_, s2_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mismatches(s1, s2, context=0, eq=operator.eq): '''extract mismatched segments from aligned strings >>> list(mismatches(*align('pharmacy', 'farmácia'), context=1)) [('pha', ' fa'), ('mac', 'mác'), ('c y', 'cia')] >>> list(mismatches(*align('constitution', 'constituição'), context=1)) [('ution', 'uição')] >>> list(mismatches(*align('idea', 'ideia'), context=1)) [('e a', 'eia')] >>> list(mismatches(*align('instructed', 'instruído'), context=1)) [('ucted', 'u ído')] >>> list(mismatches(*align('concluded', 'concluído'), context=1)) [('uded', 'uído')] ''' n = len(s1) assert(len(s2) == n) lct, rct = context, context if isinstance(context, int) else context i = None for j in range(n): if eq(s1[j], s2[j]): if i is not None: # report mismatch segment [i:j] with lct chars of left context # and rct chars of right context p, q = max(0, i-lct), min(j+rct, n) yield s1[p:q], s2[p:q] i = None elif i is None: i = j if i is not None: p = max(i-lct, 0) yield s1[p:], s2[p:]
<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(): """ build connection and init it"""
connection.connect() # start track # all services were provided here: # https://android.googlesource.com/platform/system/core/+/jb-dev/adb/SERVICES.TXT ready_data = utils.encode_data('host:track-devices') connection.adb_socket.send(ready_data) # get status status = connection.adb_socket.recv(4) # make sure track is ready if status != b'OKAY': raise RuntimeError('adb server return "{}", not OKAY'.format(str(status)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_comment_group_for_path(self, pathname, default_content_type=None): """ Obtains the comment group for a specified pathname. :param pathname: The path for which the comment group will be obtained. :return: Returns the comment group for the specified pathname or raises a ``ValueError`` if a content type is not found or raises a ``KeyError`` if a comment group is not found. Usage: [['#', '']] [['/*', '*/'], ['//', '']] Traceback (most recent call last): KeyError: 'No comment groups for content type `structured-text` for file `foobar.rst` found' # If the content type cannot be determined, we assume the content # type to be ``python`` in this case. [['#', '']] Traceback (most recent call last): ValueError: No content type defined for file path: foobar.f37993ajdha73 Traceback (most recent call last): ValueError: No content type defined for file path: foobar.f37993ajdha73 """
content_type = self.guess_content_type(pathname) if not content_type: # Content type is not found. if default_content_type: content_type = default_content_type return self.get_comment_group(content_type) else: raise ValueError( "No content type defined for file path: %s" % pathname) else: try: return self.get_comment_group(content_type) except KeyError: raise KeyError( "No comment groups for content type `%s` for file `%s` found" % ( content_type, pathname))
<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_config_file(self, config_filename): """ Parses the content.types file and updates the content types database. :param config_filename: The path to the configuration file. """
with open(config_filename, 'rb') as f: content = f.read() config = yaml.load(content) self.add_config(config, config_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 guess_content_type(self, pathname): """Guess the content type for the given path. :param path: The path of file for which to guess the content type. :return: Returns the content type or ``None`` if the content type could not be determined. Usage: """
file_basename = os.path.basename(pathname) content_type = None # Try to determine from the path. if not content_type and self._filename_map.has_key(file_basename): content_type = self._filename_map[file_basename] #logger.debug("Content type of '%s' is '%s' (determined from full "\ # "path).", pathname, content_type) # Try to determine from the suffix. if not content_type and '.' in file_basename: extension = "." + file_basename.split(".")[-1] extension = extension_case_transform_func(extension) try: content_type = self._extension_map[extension] #logger.debug("Content type of '%s' is '%s' (determined from "\ # "suffix '%s').", pathname, content_type, extension) except KeyError: pass # Try to determine from the registered set of regular expression patterns. if not content_type: for regexp, _content_type in self._regexp_map.iteritems(): if regexp.search(file_basename): content_type = _content_type #logger.debug( # "Content type of '%s' is '%s' (matches regexp '%s')", # pathname, content_type, regexp.pattern) break # Try to determine from the file contents. if os.path.exists(pathname): with open(pathname, 'rb') as f: content = f.read() if content.startswith("<?xml"): # cheap XML sniffing content_type = "XML" # TODO: Try to determine from mime-type. return content_type
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(): """ create socket and connect to adb server """
global adb_socket if adb_socket is not None: raise RuntimeError('connection already existed') host, port = config.HOST, config.PORT connection = socket.socket() try: connection.connect((host, port)) except ConnectionError as _: warn_msg = 'failed when connecting to adb server: {}:{}, retrying ...'.format(host, port) warnings.warn(warn_msg) reboot_adb_server() connect() return adb_socket = connection
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reboot_adb_server(): """ execute 'adb devices' to start adb server """
_reboot_count = 0 _max_retry = 1 def _reboot(): nonlocal _reboot_count if _reboot_count >= _max_retry: raise RuntimeError('fail after retry {} times'.format(_max_retry)) _reboot_count += 1 return_code = subprocess.call(['adb', 'devices'], stdout=subprocess.DEVNULL) if bool(return_code): warnings.warn('return not zero, execute "adb version" failed') raise EnvironmentError('adb did not work :(') return _reboot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape_string(value): """Converts a string to its S-expression representation, adding quotes and escaping funny characters. """
res = StringIO() res.write('"') for c in value: if c in CHAR_TO_ESCAPE: res.write(f'\\{CHAR_TO_ESCAPE[c]}') elif c.isprintable(): res.write(c) elif ord(c) < 0x100: res.write(f'\\x{ord(c):02x}') elif ord(c) < 0x10000: res.write(f'\\u{ord(c):04x}') else: res.write(f'\\U{ord(c):06x}') res.write('"') return res.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(value1, operation, value2): """ Perform comparison operation over two arguments. The operation can be performed over values of any type. :param value1: the first argument to compare :param operation: the comparison operation: "==" ("=", "EQ"), "!= " ("<>", "NE"); "<"/">" ("LT"/"GT"), "<="/">=" ("LE"/"GE"); "LIKE". :param value2: the second argument to compare :return: result of the comparison operation """
if operation == None: return False operation = operation.upper() if operation in ["=", "==", "EQ"]: return ObjectComparator.are_equal(value1, value2) if operation in ["!=", "<>", "NE"]: return ObjectComparator.are_not_equal(value1, value2) if operation in ["<", "LT"]: return ObjectComparator.less(value1, value2) if operation in ["<=", "LE"]: return ObjectComparator.are_equal(value1, value2) or ObjectComparator.less(value1, value2) if operation in [">", "GT"]: return ObjectComparator.more(value1, value2) if operation in [">=", "GE"]: return ObjectComparator.are_equal(value1, value2) or ObjectComparator.more(value1, value2) if operation == "LIKE": return ObjectComparator.match(value1, value2) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def are_equal(value1, value2): """ Checks if two values are equal. The operation can be performed over values of any type. :param value1: the first value to compare :param value2: the second value to compare :return: true if values are equal and false otherwise """
if value1 == None or value2 == None: return True if value1 == None or value2 == None: return False return value1 == value2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def less(value1, value2): """ Checks if first value is less than the second one. The operation can be performed over numbers or strings. :param value1: the first value to compare :param value2: the second value to compare :return: true if the first value is less than second and false otherwise. """
number1 = FloatConverter.to_nullable_float(value1) number2 = FloatConverter.to_nullable_float(value2) if number1 == None or number2 == None: return False return number1 < number2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def more(value1, value2): """ Checks if first value is greater than the second one. The operation can be performed over numbers or strings. :param value1: the first value to compare :param value2: the second value to compare :return: true if the first value is greater than second and false otherwise. """
number1 = FloatConverter.to_nullable_float(value1) number2 = FloatConverter.to_nullable_float(value2) if number1 == None or number2 == None: return False return number1 > number2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(value1, value2): """ Checks if string matches a regular expression :param value1: a string value to match :param value2: a regular expression string :return: true if the value matches regular expression and false otherwise. """
if value1 == None and value2 == None: return True if value1 == None or value2 == None: return False string1 = str(value1) string2 = str(value2) return re.match(string2, string1) != 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 register_view(self, view): """Loads the text taking it from the model, then starts a timer to scroll it."""
self.view.set_text(self.model.credits) gobject.timeout_add(1500, self.on_begin_scroll) 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 on_scroll(self): """Called to scroll text"""
try: sw = self.view['sw_scroller'] except KeyError: return False # destroyed! vadj = sw.get_vadjustment() if vadj is None: return False val = vadj.get_value() # is scrolling over? if val >= vadj.upper - vadj.page_size: self.view.show_vscrollbar() return False vadj.set_value(val+0.5) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card', identity_document=None, billing_address=None, additional_details=None): """ When creating a Token, remember to use the public-key header instead of the private-key header, and do not include the app-id header. Args: holder_name: Name of the credit card holder. card_number: Credit card number. credit_card_cvv: The CVV number on the card (3 or 4 digits) to be encrypted. expiration_date: Credit card expiration date. Possible formats: mm-yyyy, mm-yy, mm.yyyy, mm.yy, mm/yy, mm/yyyy, mm yyyy, or mm yy. token_type: The type of token billing_address: Address. identity_document: National identity document of the card holder. additional_details: Optional additional data stored with your token in key/value pairs. Returns: """
headers = self.client._get_public_headers() payload = { "token_type": token_type, "credit_card_cvv": credit_card_cvv, "card_number": card_number, "expiration_date": expiration_date, "holder_name": holder_name, "identity_document": identity_document, "billing_address": billing_address, "additional_details": additional_details, } endpoint = '/tokens' return self.client._post(self.client.URL_BASE + endpoint, json=payload, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_token(self, token): """ Retrieve Token details for a specific Token. Args: token: The identifier of the token. Returns: """
headers = self.client._get_private_headers() endpoint = '/tokens/{}'.format(token) return self.client._get(self.client.URL_BASE + endpoint, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prj_created_data(project, role): """Return the data for created :param project: the project that holds the data :type project: :class:`jukeboxcore.djadapter.models.Project` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the created :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole: return project.date_created.isoformat(' ')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prj_fps_data(project, role): """Return the data for fps :param project: the project that holds the data :type project: :class:`jukeboxcore.djadapter.models.Project` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the fps :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole: return str(project.framerate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prj_resolution_data(project, role): """Return the data for resolution :param project: the project that holds the data :type project: :class:`jukeboxcore.djadapter.models.Project` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the resolution :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole: return '%s x %s' % (project.resx, project.resy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shot_duration_data(shot, role): """Return the data for duration :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Shot` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the duration :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole: return str(shot.duration)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shot_start_data(shot, role): """Return the data for startframe :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Shot` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the start :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole: return str(shot.startframe)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shot_end_data(shot, role): """Return the data for endframe :param shot: the shot that holds the data :type shot: :class:`jukeboxcore.djadapter.models.Shot` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the end :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole: return str(shot.endframe)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def note_content_data(note, role): """Return the data for content :param note: the note that holds the data :type note: :class:`jukeboxcore.djadapter.models.Note` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the created date :rtype: depending on role :raises: None """
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole: return note.content
<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_adapter(widget_class, flavour=None): """Removes the given widget class information from the default set of adapters. If widget_class had been previously added by using add_adapter, the added adapter will be removed, restoring possibly previusly existing adapter(s). Notice that this function will remove only *one* adapter about given wiget_class (the first found in order), even if many are currently stored. @param flavour has to be used when the entry was added with a particular flavour. Returns True if one adapter was removed, False if no adapter was removed."""
for it,tu in enumerate(__def_adapter): if (widget_class == tu[WIDGET] and flavour == tu[FLAVOUR]): del __def_adapter[it] return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key): """ Gets a map element specified by its key. The key can be defined using dot notation and allows to recursively access elements of elements. :param key: a key of the element to get. :return: the value of the map element. """
if key == None or key == '': return None elif key.find('.') > 0: return RecursiveObjectReader.get_property(self, key) else: return super(Parameters, self).get(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, key, value): """ Puts a new value into map element specified by its key. The key can be defined using dot notation and allows to recursively access elements of elements. :param key: a key of the element to put. :param value: a new value for map element. """
if key == None or key == '': return None elif key.find('.') > 0: RecursiveObjectWriter.set_property(self, key, value) return value else: self[key] = value return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_parameters(self, key): """ Converts map element into an Parameters or returns null if conversion is not possible. :param key: a key of element to get. :return: Parameters value of the element or null if conversion is not supported. """
value = self.get_as_nullable_map(key) return Parameters(value) if value != 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_as_parameters_with_default(self, key, default_value): """ Converts map element into an Parameters or returns default value if conversion is not possible. :param key: a key of element to get. :param default_value: the default value :return: Parameters value of the element or default value if conversion is not supported. """
result = self.get_as_nullable_parameters(key) return result if result != None else default_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override(self, parameters, recursive = False): """ Overrides parameters with new values from specified Parameters and returns a new Parameters object. :param parameters: Parameters with parameters to override the current values. :param recursive: (optional) true to perform deep copy, and false for shallow copy. Default: false :return: a new Parameters object. """
result = Parameters() if recursive: RecursiveObjectWriter.copy_properties(result, self) RecursiveObjectWriter.copy_properties(result, parameters) else: ObjectWriter.set_properties(result, self) ObjectWriter.set_properties(result, parameters) 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 set_defaults(self, default_values, recursive = False): """ Set default values from specified Parameters and returns a new Parameters object. :param default_values: Parameters with default parameter values. :param recursive: (optional) true to perform deep copy, and false for shallow copy. Default: false :return: a new Parameters object. """
result = Parameters() if recursive: RecursiveObjectWriter.copy_properties(result, default_values) RecursiveObjectWriter.copy_properties(result, self) else: ObjectWriter.set_properties(result, default_values) ObjectWriter.set_properties(result, self) 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 pick(self, *props): """ Picks select parameters from this Parameters and returns them as a new Parameters object. :param props: keys to be picked and copied over to new Parameters. :return: a new Parameters object. """
result = Parameters() for prop in props: if self.contains_key(prop): result.put(prop, self.get(prop)) 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 omit(self, *props): """ Omits selected parameters from this Parameters and returns the rest as a new Parameters object. :param props: keys to be omitted from copying over to new Parameters. :return: a new Parameters object. """
result = Parameters(self) for prop in props: del result[prop] 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 from_value(value): """ Creates a new Parameters object filled with key-value pairs from specified object. :param value: an object with key-value pairs used to initialize a new Parameters. :return: a new Parameters object. """
map = value if isinstance(value, dict) else RecursiveObjectReader.get_properties(value) return Parameters(map)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_config(config): """ Creates new Parameters from ConfigMap object. :param config: a ConfigParams that contain parameters. :return: a new Parameters object. """
result = Parameters() if config == None or len(config) == 0: return result for (key, value) in config.items(): result.put(key, value) 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 execute(correlation_id, components, args = None): """ Executes multiple components. To be executed components must implement [[IExecutable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: a list of components that are to be executed. :param args: execution arguments. :return: execution result """
results = [] if components == None: return args = args if args != None else Parameters() for component in components: result = Executor.execute_one(correlation_id, component, args) results.append(result) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorator(func): """A function timer decorator."""
def function_timer(*args, **kwargs): """A nested function for timing other functions.""" # Capture start time start = time.time() # Execute function with arguments value = func(*args, **kwargs) # Capture end time end = time.time() # Calculate run time runtime = end - start if runtime < 60: runtime = str('sec: ' + str('{:f}'.format(runtime))) else: runtime = str('min: ' + str('{:f}'.format(runtime / 60))) print('{func:50} --> {time}'.format(func=func.__qualname__, time=runtime)) return value return function_timer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def populateImagesFromSurveys(self, surveys=dss2 + twomass): ''' Load images from archives. ''' # what's the coordinate center? coordinatetosearch = '{0.ra.deg} {0.dec.deg}'.format(self.center) # query sky view for those images paths = astroquery.skyview.SkyView.get_images( position=coordinatetosearch, radius=self.radius, survey=surveys) # populate the images for each of these self.images = [Image(p[0], s) for p, s in zip(paths, surveys)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def global_instance(cls): """Return a per-thread global batcher instance."""
try: return GLOBAL_BATCHER.instance except AttributeError: instance = PrioritizedBatcher( **getattr(settings, 'PRIORITIZED_BATCHER', {}) ) GLOBAL_BATCHER.instance = instance return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self): """Commit a batch."""
assert self.batch is not None, "No active batch, call start() first" logger.debug("Comitting batch from %d sources...", len(self.batch)) # Determine item priority. by_priority = [] for name in self.batch.keys(): priority = self.priorities.get(name, self.default_priority) by_priority.append((priority, name)) for priority, name in sorted(by_priority, key=lambda key: key[0]): logger.debug("Processing items from '%s' (priority=%d)...", name, priority) items = self.batch[name] for handlers in items.values(): for agg, handler in handlers: try: if agg is None: handler() else: handler(agg) except Exception as error: # Log errors and proceed to evaluate the next handler. logger.exception("Error while invoking handler.") self.batch = None logger.debug("Batch committed.")
<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, name, handler, group_by=None, aggregator=None): """Add a new handler to the current batch."""
assert self.batch is not None, "No active batch, call start() first" items = self.batch.setdefault(name, collections.OrderedDict()) if group_by is None: # None is special as it means no grouping. In this case we must store all # the different handlers and call them all. items.setdefault(group_by, []).append((None, handler)) elif aggregator is not None: agg = items.get(group_by, [(None, None)])[0][0] items[group_by] = [(aggregator(agg), handler)] else: items[group_by] = [(None, handler)]
<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(name, path=None): """ Configure logging and return a logger and the location of its logging configuration file. This function expects: + A Splunk app directory structure:: <app-root> bin default local + The current working directory is *<app-root>***/bin**. Splunk guarantees this. If you are running the app outside of Splunk, be sure to set the current working directory to *<app-root>***/bin** before calling. This function looks for a logging configuration file at each of these locations, loading the first, if any, logging configuration file that it finds:: local/{name}.logging.conf default/{name}.logging.conf local/logging.conf default/logging.conf The current working directory is set to *<app-root>* before the logging configuration file is loaded. Hence, paths in the logging configuration file are relative to *<app-root>*. The current directory is reset before return. You may short circuit the search for a logging configuration file by providing an alternative file location in `path`. Logging configuration files must be in `ConfigParser format`_. #Arguments: :param name: Logger name :type name: str :param path: Location of an alternative logging configuration file or `None` :type path: str or NoneType :returns: A logger and the location of its logging configuration file .. _ConfigParser format: http://goo.gl/K6edZ8 """
app_directory = os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))) if path is None: probing_path = [ 'local/%s.logging.conf' % name, 'default/%s.logging.conf' % name, 'local/logging.conf', 'default/logging.conf'] for relative_path in probing_path: configuration_file = os.path.join(app_directory, relative_path) if os.path.exists(configuration_file): path = configuration_file break elif not os.path.isabs(path): found = False for conf in 'local', 'default': configuration_file = os.path.join(app_directory, conf, path) if os.path.exists(configuration_file): path = configuration_file found = True break if not found: raise ValueError( 'Logging configuration file "%s" not found in local or default ' 'directory' % path) elif not os.path.exists(path): raise ValueError('Logging configuration file "%s" not found') if path is not None: working_directory = os.getcwd() os.chdir(app_directory) try: splunk_home = os.path.normpath(os.path.join(working_directory, os.environ['SPLUNK_HOME'])) except KeyError: splunk_home = working_directory # reasonable in debug scenarios try: path = os.path.abspath(path) fileConfig(path, {'SPLUNK_HOME': splunk_home}) finally: os.chdir(working_directory) if len(root.handlers) == 0: root.addHandler(StreamHandler()) logger = getLogger(name) return logger, 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 expand_user(path, user=None): """Roughly the same as os.path.expanduser, but you can pass a default user."""
def _replace(m): m_user = m.group(1) or user return pwd.getpwnam(m_user).pw_dir if m_user else pwd.getpwuid(os.getuid()).pw_dir return re.sub(r'~(\w*)', _replace, path)