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 simple_filter(self, key, value): "Search keys whose values match with the searched values" searched = {key: value} return set([k for k, v in self.data.items() if intersect(searched, v) == searched])
<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(self, **kwargs): """ Filter data according to the given arguments. """
keys = self.filter_keys(**kwargs) return self.keys_to_values(keys)
<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_index(self, name, recreate=False, _type='default'): """ Create an index. If recreate is True, recreate even if already there. """
if name not in self.indexes or recreate: self.build_index(name, _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 build_index(self, idx_name, _type='default'): "Build the index related to the `name`." indexes = {} has_non_string_values = False for key, item in self.data.items(): if idx_name in item: value = item[idx_name] # A non-string index value switches it into a lazy one. if not isinstance(value, six.string_types): has_non_string_values = True if value not in indexes: indexes[value] = set([]) indexes[value].add(key) self.indexes[idx_name] = indexes if self._meta.lazy_indexes or has_non_string_values: # Every index is lazy _type = 'lazy' self.index_defs[idx_name] = {'type': _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 _clean_index(self): "Clean index values after loading." for idx_name, idx_def in self.index_defs.items(): if idx_def['type'] == 'lazy': self.build_index(idx_name) for index_name, values in self.indexes.items(): for value in values: if not isinstance(values[value], set): values[value] = set(values[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 make_command(tasks, *args, **kwargs): """ Create a TaskCommand with defined tasks. This is a helper function to avoid boiletplate when dealing with simple cases (e.g., all cli arguments can be handled by TaskCommand), with no special processing. In general, this means a command only needs to run established tasks. Arguments: tasks - the tasks to execute args - extra arguments to pass to the TargetCommand constructor kwargs - extra keyword arguments to pass to the TargetCommand constructor """
command = TaskCommand(tasks=tasks, *args, **kwargs) return command
<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_command(command, args): """ Runs the provided command with the given args. Exceptions, if any, are propogated to the caller. Arguments: command - something that extends the Command class args - A list of command line arguments. If args is None, sys.argv (without the first argument--assumed to be the command name) will be used. """
if args is None: args = sys.argv[1:] try: command.execute(args) except IOError as failure: if failure.errno == errno.EPIPE: # This probably means we were piped into something that terminated # (e.g., head). Might be a better way to handle this, but for now # silently swallowing the error isn't terrible. pass except _PartialFailureException as failed: for failure, skipped, message in failed.failed: print("\nTask {} failed".format(failure), file=sys.stderr) print("\tError: {}".format(message), file=sys.stderr) print("\tSkipped: {}".format(skipped), file=sys.stderr) sys.exit(1) except Exception as failure: # pylint: disable=broad-except print("Error: {}".format(str(failure)), file=sys.stderr) sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, *args, **kwargs): """ Initializes and runs the tool. This is shorhand to parse command line arguments, then calling: self.setup(parsed_arguments) self.process() """
args = self.parser.parse_args(*args, **kwargs) self.process(args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_targets(self, targets, full_config, arguments): """ Calls the tasks with the appropriate options for each of the targets. """
executor = _get_executor(arguments) resolver = _get_resolver(arguments) dep_manager = resolver(targets, full_config, self._task_order) task_queue = dep_manager.get_queue() config_info = devpipeline_core.configinfo.ConfigInfo(executor) try: failed = [] def _keep_going_on_failure(failure, task): skipped = task_queue.fail(task) failed.append((task, skipped, str(failure))) def _fail_immediately(failure, task): del task raise failure fail_fn = _fail_immediately if arguments.keep_going: fail_fn = _keep_going_on_failure self._execute_targets(task_queue, config_info, full_config, fail_fn) if failed: raise _PartialFailureException(failed) finally: full_config.write()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _user_input() -> str: """ A helper function which waits for user multi-line input. :return: A string input by user, separated by ``'\\n'``. """
lines = [] try: while True: line = input() if line != '': lines.append(line) else: break except (EOFError, KeyboardInterrupt): return '\n'.join(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infile_path(self) -> Optional[PurePath]: """ Read-only property. :return: A ``pathlib.PurePath`` object or ``None``. """
if not self.__infile_path: return Path(self.__infile_path).expanduser() 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 generator(self) -> Iterator[str]: """ Create a generate that iterates the whole content of the file or string. :return: An iterator iterating the lines of the text stream, separated by ``'\\n'`` or ``'\\r'``. """
stream = self.stream # In case that ``self.stream`` is changed. stream.seek(0) for line in stream: yield line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generator_telling_position(self) -> Iterator[Tuple[str, int]]: """ Create a generate that iterates the whole content of the file or string, and also tells which offset is now. separated by ``'\\n'`` or ``'\\r'``; and the offset (in bytes) of current line. """
stream = self.stream # In case that ``self.stream`` is changed. stream.seek(0) for line in stream: yield line, stream.tell()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_value(self, string, key, inline_code=True): """Extract strings from the docstrings .. code-block:: text * synopsis: ``%shorten{text, max_size}`` * example: ``%shorten{$title, 32}`` * description: Shorten “text” on word boundarys. """
regex = r'\* ' + key + ': ' if inline_code: regex = regex + '``(.*)``' else: regex = regex + '(.*)' value = re.findall(regex, string) if value: return value[0].replace('``', '') else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def underline(self, text, indent=4): """Underline a given text"""
length = len(text) indentation = (' ' * indent) return indentation + text + '\n' + indentation + ('-' * length)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, text, width=78, indent=4): """Apply textwrap to a given text string"""
return textwrap.fill( text, width=width, initial_indent=' ' * indent, subsequent_indent=' ' * indent, )
<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): """Retrieve a formated text string"""
output = '' for f in self.functions: output += self.underline(f) + '\n\n' if f in self.synopsises and isinstance(self.synopsises[f], str): output += self.format(self.synopsises[f]) + '\n' if f in self.descriptions and isinstance( self.descriptions[f], str ): output += self.format(self.descriptions[f], indent=8) + '\n' if f in self.examples and isinstance(self.examples[f], str): output += self.format(self.examples[f], indent=8) + '\n' output += '\n' return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def propagate(w, b, X, Y): """ Implement the cost function and its gradient for the propagation Arguments: w weights, a numpy array of size (dim, 1) b bias, a scalar X data of size (dim, number of examples) Y true "label" vector of size (1, number of examples) Return: cost negative log-likelihood cost for logistic regression dw gradient of the loss with respect to w, thus same shape as w db gradient of the loss with respect to b, thus same shape as b """
m = X.shape[1] A = sigmoid(np.dot(w.T, X) + b) cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) # BACKWARD PROPAGATION (TO FIND GRAD) dw = 1.0 / m * np.dot(X, (A - Y).T) db = 1.0 / m * np.sum(A - Y) assert (dw.shape == w.shape) assert (db.dtype == float) cost = np.squeeze(cost) assert (cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def LR_train(w, b, X, Y, num_iterations, learning_rate, print_cost=True): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w weights, a numpy array of size (dim, 1) b bias, a scalar X data of shape (dim, number of examples) Y true "label" vector, of shape (1, number of examples) num_iterations number of iterations of the optimization loop learning_rate learning rate of the gradient descent update rule print_cost True to print the loss every 100 steps Returns: params dictionary containing the weights w and bias b grads dictionary containing the gradients of the weights and bias with respect to the cost function costs list of all the costs computed during the optimization, this will be used to plot the learning curve. """
costs = [] for i in range(num_iterations): # Cost and gradient calculation grads, cost = propagate(w, b, X, Y) # Retrieve derivatives from grads dw = grads["dw"] db = grads["db"] # update rule w = w - learning_rate * dw b = b - learning_rate * db # Record the costs if i % 100 == 0: costs.append(cost) # Print the cost every 100 training examples if print_cost and i % 100 == 0: print("Cost after iteration %i: %f" % (i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=True): """ Builds the logistic regression model by calling the function implemented above Arguments: X_train training set represented by a numpy array of shape (dim, m_train) Y_train training labels represented by a numpy array (vector) of shape (1, m_train) X_test test set represented by a numpy array of shape (dim, m_test) Y_test test labels represented by a numpy array (vector) of shape (1, m_test) num_iterations hyperparameter representing the number of iterations to optimize the parameters learning_rate hyperparameter representing the learning rate used in the update rule of optimize() print_cost Set to true to print the cost every 100 iterations Returns: d -- dictionary containing information about the model. """
print('X_train shape:', X_train.shape) # initialize parameters with zeros w, b = initialize_with_zeros(X_train.shape[0]) print('w shape:', w.shape) # Gradient descent parameters, grads, costs = LR_train(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) # Retrieve parameters w and b from dictionary "parameters" w = parameters["w"] b = parameters["b"] print('w shape params:', w.shape) Y_prediction_test = LR_predict(w, b, X_test) Y_prediction_train = LR_predict(w, b, X_train) # Print train/test Errors print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train": Y_prediction_train, "w": w, "b": b, "learning_rate": learning_rate, "num_iterations": num_iterations} return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_lc(d): """plot learning curve Arguments: d Returned by model function. Dictionary containing information about the model. """
costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLogLevelNo(level): """Return numerical log level or raise ValueError. A valid level is either an integer or a string such as WARNING etc."""
if isinstance(level,(int,long)): return level try: return(int(logging.getLevelName(level.upper()))) except: raise ValueError('illegal loglevel %s' % level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmdLine(useBasename=False): """Return full command line with any necessary quoting."""
qargv = [] cmdwords = list(sys.argv) if useBasename: cmdwords[0] = os.path.basename(cmdwords[0]) for s in cmdwords: # any white space or special characters in word so we need quoting? if re.search(r'\s|\*|\?', s): if "'" in s: qargv.append('"%s"' % re.sub('"', "'", s)) else: qargv.append("'%s'" % re.sub("'", '"', s)) else: qargv.append(s) cmd = ' '.join(qargv) return cmd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handleError(exception, debugFlag=False, abortFlag=True): """Error handling utility. Print more or less error information depending on debug flag. Unless abort is set False, exits with error code 1."""
if isinstance(exception, CmdError) or not debugFlag: error(str(exception)) else: import traceback traceback.print_exc() error(str(exception)) # or log complete traceback as well? if abortFlag: sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confirm(msg, acceptByDefault=False, exitCodeOnAbort=1, batch=False): """Get user confirmation or abort execution. confirm returns True (if user confirms) or False (if user declines and exitCodeOnAbort is None) or aborts with sys.exit(exitCodeOnAbort) (if user declines and exitCodeOnAbort is not None). Depending on acceptByDefault, the default answer (if user presses Return only), is to accept or abort. " - are you sure [y] ?" or " - are you sure [n] ?" will be appended to msg, depending on the value of acceptByDefault. If batch is True, returns immediately."""
if batch: return if acceptByDefault: msg += ' - are you sure [y] ? ' else: msg += ' - are you sure [n] ? ' while True: reply = raw_input(msg).lower() print if reply == '': reply = 'y' if acceptByDefault else 'n' if reply == 'y': return True elif reply == 'n': if exitCodeOnAbort is None: return False else: error('Program execution aborted by user') sys.exit(exitCodeOnAbort) else: print "ERROR: Invalid reply - please enter either 'y' or 'n', or press just enter to accept default\n"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, text): """Write text. An additional attribute terminator with a value of None is added to the logging record to indicate that StreamHandler should not add a newline."""
self.logger.log(self.loglevel, text, extra={'terminator': 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 emit(self, record): """Emit a record. Unless record.terminator is set, a trailing newline will be written to the output stream."""
try: msg = self.format(record) if isinstance(msg,unicode): if hasattr(self.stream, "encoding") and self.stream.encoding: # Stream should take care of encoding, but do it explicitly to # prevent bug in Python 2.6 - see # https://stackoverflow.com/questions/8016236/python-unicode-handling-differences-between-print-and-sys-stdout-write self.stream.write(msg.encode(self.stream.encoding)) else: self.stream.write(msg.encode(encoding)) else: self.stream.write(msg) terminator = getattr(record, 'terminator', '\n') if terminator is not None: self.stream.write(terminator) self.flush() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """Flush the stream. In contrast to StreamHandler, errors are not caught so the program doesn't iterate through tons of logging errors e.g. in case of a broken pipe."""
# See /usr/lib64/python2.7/logging/__init__.py, StreamHander.flush() self.acquire() try: if self.stream and hasattr(self.stream, "flush"): self.stream.flush() except IOError as e: if self.abortOnIOError: sys.exit('IOError: %s' % e) else: raise e finally: self.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 emit(self, record): """Emit record after checking if message triggers later sending of e-mail."""
if self.triggerLevelNo is not None and record.levelno>=self.triggerLevelNo: self.triggered = True logging.handlers.BufferingHandler.emit(self,record)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """Send messages by e-mail. The sending of messages is suppressed if a trigger severity level has been set and none of the received messages was at that level or above. In that case the messages are discarded. Empty e-mails are discarded."""
if self.triggered and len(self.buffer) > 0: # Do not send empty e-mails text = [] for record in self.buffer: terminator = getattr(record, 'terminator', '\n') s = self.format(record) if terminator is not None: text.append(s + terminator) else: text.append(s) msg = MIMEText(''.join(text)) msg['From'] = self.fromAddr msg['To'] = self.toAddr msg['Subject'] = self.subject # print 'BufferingSMTPHandler' # print msg.as_string() smtp = smtplib.SMTP('localhost') smtp.sendmail(self.fromAddr, [self.toAddr], msg.as_string()) smtp.quit() self.buffer = []
<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_option(self, *args, **kwargs): """Add optparse or argparse option depending on CmdHelper initialization."""
if self.parseTool == 'argparse': if args and args[0] == '': # no short option args = args[1:] return self.parser.add_argument(*args, **kwargs) else: return self.parser.add_option(*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 make_string(seq): """ Don't throw an exception when given an out of range character. """
string = '' for c in seq: # Screen out non-printing characters try: if 32 <= c and c < 256: string += chr(c) except TypeError: pass # If no printing chars if not string: return str(seq) return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_file(file_path_name): """ Read the content of the specified file. @param file_path_name: path and name of the file to read. @return: content of the specified file. """
with io.open(os.path.join(os.path.dirname(__file__), file_path_name), mode='rt', encoding='utf-8') as fd: return fd.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 run(self, react=True, strict=True, roles=1): """Select a cast and perform the next scene. :param bool react: If `True`, then Property directives are executed at the point they are encountered. Pass `False` to skip them so they can be enacted later on. :param bool strict: Only fully-cast scripts to be performed. :param int roles: Maximum number of roles permitted each character. This method is a generator. It yields events from the performance. If a :py:class:`~turberfield.dialogue.model.Model.Condition` is encountered, it is evaluated. No events are generated while the most recent condition is False. A new :py:class:`~turberfield.dialogue.model.Model.Shot` resets the current condition. """
try: folder, index, self.script, self.selection, interlude = self.next( self.folders, self.ensemble, strict=strict, roles=roles ) except TypeError: raise GeneratorExit with self.script as dialogue: model = dialogue.cast(self.selection).run() for shot, item in model: if self.condition is not False: yield shot yield item if not self.shots or self.shots[-1][:2] != shot[:2]: self.shots.append(shot._replace(items=self.script.fP)) self.condition = None if isinstance(item, Model.Condition): self.condition = self.allows(item) if react: self.react(item) for key, value in model.metadata: if value not in self.metadata[key]: self.metadata[key].append(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 md5(self): """ Returns the md5-sum of this file. This is of course potentially expensive! """
hash_ = hashlib.md5() with self.open("rb") as inf: block = inf.read(4096) while block: hash_.update(block) block = inf.read(4096) return hash_.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 lock(self, fail_on_lock=False, cleanup=False): """ Allows to lock a file via abl.util.LockFile, with the same parameters there. Returns an opened, writable file. """
return self.connection.lock(self, fail_on_lock, cleanup)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _manipulate(self, *args, **kwargs): """ This is a semi-private method. It's current use is to manipulate memory file system objects so that you can create certain conditions, to provoke errors that otherwise won't occur. """
self.connection._manipulate(self, *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 move(self, source, destination): """ the semantic should be like unix 'mv' command """
if source.isfile(): source.copy(destination) source.remove() else: source.copy(destination, recursive=True) source.remove('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 parser(self): """ Instantiates the argparse parser """
if self._parser is None: apkw = { 'description': self.description, 'epilog': self.epilog, } self._parser = argparse.ArgumentParser(**apkw) # For Python 3 add version as a default command if self.version: self._parser.add_argument( '-v', '--version', action='version', version="%(prog)s {}".format(self.version), ) return self._parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subparsers(self): """ Insantiates the subparsers for all commands """
if self._subparsers is None: apkw = { 'title': 'commands', 'description': 'Commands for the %s program' % self.parser.prog, } self._subparsers = self.parser.add_subparsers(**apkw) return self._subparsers
<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(self, command): """ Registers a command with the program """
command = command() if command.name in self.commands: raise ConsoleError( "Command %s already registered!" % command.name ) command.create_parser(self.subparsers) self.commands[command.name] = command
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exit(self, code=0, message=None): """ Exit the console program sanely. """
## If we have a parser, use it to exit if self._parser: if code > 0: self.parser.error(message) else: self.parser.exit(code, message) ## Else we are exiting before parser creation else: if message is not None: if code > 0: sys.stderr.write(message) else: sys.stdout.write(message) sys.exit(code) ## If we're here we didn't exit for some reason? raise Exception("Unable to exit the %s" % self.__class__.__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 execute(self): """ Entry point to the execution of the program. """
# Ensure that we have commands registered if not self.commands or self._parser is None: raise NotImplementedError( "No commands registered with this program!" ) # Handle input from the command line args = self.parser.parse_args() # Parse the arguments try: handle_default_args(args) # Handle the default args if not hasattr(args, 'func'): # Handle no subcommands self.parser.print_help() self.exit(0) msg = args.func(args) # Call the default function msg = "{}\n".format(msg) if msg else '' # Format the message self.exit(0, msg) # Exit cleanly with message except Exception as e: if hasattr(args, 'traceback') and args.traceback: traceback.print_exc() msg = color.format(str(e), color.RED) self.exit(1, msg)
<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_lang_array(self): """gets supported langs as an array"""
r = self.yandex_translate_request("getLangs", "") self.handle_errors(r) return r.json()["dirs"]
<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_lang_dict(self): """gets supported langs as an dictionary"""
r = self.yandex_translate_request("getLangs") self.handle_errors(r) return r.json()["langs"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _browser_init(self): """ Init the browsing instance if not setup :rtype: None """
if self.session: return self.session = requests.Session() headers = {} if self.user_agent: headers['User-agent'] = self.user_agent self.session.headers.update(headers) if self._auth_method in [None, "", "HTTPBasicAuth"]: if self._auth_username is not None: self.session.auth = (self._auth_username, self._auth_password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_scrap(self, path): """ Load scraper settings from file :param path: Path to file :type path: str :rtype: None :raises WEBFileException: Failed to load settings :raises WEBParameterException: Missing parameters in file """
try: conf = self.load_settings(path) except: # Should only be IOError self.exception("Failed to load file") raise WEBFileException("Failed to load from {}".format(path)) if "scheme" not in conf: raise WEBParameterException("Missing scheme definition") if "url" not in conf: raise WEBParameterException("Missing url definition") version = conf.get('version', None) if version != "1.0": raise WEBParameterException( "Unsupported version {}".format(version) ) self.scheme = conf['scheme'] self.url = conf['url'] self.timeout = conf.get('timeout', self.timeout) if conf.get('html2text'): self._set_html2text(conf['html2text'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request( self, method, url, timeout=None, headers=None, data=None, params=None ): """ Make a request using the requests library :param method: Which http method to use (GET/POST) :type method: str | unicode :param url: Url to make request to :type url: str | unicode :param timeout: Timeout for request (default: None) None -> infinite timeout :type timeout: None | int | float :param headers: Headers to be passed along (default: None) :type headers: None | dict :param data: Data to be passed along (e.g. body in POST) (default: None) :type data: None | dict :param params: Parameters to be passed along (e.g. with url in GET) (default: None) :type params: None | dict :return: Response to the request :rtype: requests.Response :raises WEBConnectException: Loading failed """
if headers is None: headers = {} if not self.session: self._browser_init() try: response = self.session.request( method, url, timeout=timeout, allow_redirects=self._handle_redirect, headers=headers, data=data, params=params ) except SSLError as e: raise WEBConnectException(e) except HTTPError: raise WEBConnectException("Unable to load {}".format(url)) except (Timeout, socket.timeout): raise WEBConnectException("Timeout loading {}".format(url)) except ConnectionError: raise WEBConnectException("Failed to load {}".format(url)) except Exception: self.exception("Failed to load {}".format(url)) raise WEBConnectException( "Unknown failure loading {}".format(url) ) return 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 scrap(self, url=None, scheme=None, timeout=None, html_parser=None, cache_ext=None ): """ Scrap a url and parse the content according to scheme :param url: Url to parse (default: self._url) :type url: str :param scheme: Scheme to apply to html (default: self._scheme) :type scheme: dict :param timeout: Timeout for http operation (default: self._timout) :type timeout: float :param html_parser: What html parser to use (default: self._html_parser) :type html_parser: str | unicode :param cache_ext: External cache info :type cache_ext: floscraper.models.CacheInfo :return: Response data from url and parsed info :rtype: floscraper.models.Response :raises WEBConnectException: HTTP get failed :raises WEBParameterException: Missing scheme or url """
if not url: url = self.url if not scheme: scheme = self.scheme if not timeout: timeout = self.timeout if not html_parser: html_parser = self.html_parser if not scheme: raise WEBParameterException("Missing scheme definition") if not url: raise WEBParameterException("Missing url definition") resp = self.get(url, timeout, cache_ext=cache_ext) soup = BeautifulSoup(resp.html, html_parser) resp.scraped = self._parse_scheme(soup, scheme) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shrink_list(self, shrink): """ Shrink list down to essentials :param shrink: List to shrink :type shrink: list :return: Shrunk list :rtype: list """
res = [] if len(shrink) == 1: return self.shrink(shrink[0]) else: for a in shrink: temp = self.shrink(a) if temp: res.append(temp) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shrink_dict(self, shrink): """ Shrink dict down to essentials :param shrink: Dict to shrink :type shrink: dict :return: Shrunk dict :rtype: dict """
res = {} if len(shrink.keys()) == 1 and "value" in shrink: return self.shrink(shrink['value']) else: for a in shrink: res[a] = self.shrink(shrink[a]) if not res[a]: del res[a] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shrink(self, shrink): """ Remove unnecessary parts :param shrink: Object to shringk :type shrink: dict | list :return: Shrunk object :rtype: dict | list """
if isinstance(shrink, list): return self._shrink_list(shrink) if isinstance(shrink, dict): return self._shrink_dict(shrink) return shrink
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mode_name(mode): '''Tries best-effortly to get the right mode name''' if mode: l = mode.lower() if l in ('java', ): return ('clike', 'text/x-java') if l in ('c', ): return ('clike', 'text/x-csrc') if l in ('c++', 'cxx'): return ('clike', 'text/x-c++src') if l in ('csharp', 'c#'): return ('clike', 'text/x-csharp') if l in ('sh', 'bash', ): return ('shell', 'text/x-sh') if l in codemirror_modes: return (l, None) 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 simulate(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, grid_size=(80, 80), model="projection", pixel_size=None, center=None): """Simulate scattering at a sphere Parameters radius: float Radius of the sphere [m] sphere_index: float Refractive index of the object medium_index: float Refractive index of the surrounding medium wavelength: float Vacuum wavelength of the imaging light [m] grid_size: tuple of ints or int Resulting image size in x and y [px] model: str Sphere model to use (see :const:`available`) pixel_size: float or None Pixel size [m]; if set to `None` the pixel size is chosen such that the radius fits at least three to four times into the grid. center: tuple of floats or None Center position in image coordinates [px]; if set to None, the center of the image (grid_size - 1)/2 is used. Returns ------- qpi: qpimage.QPImage Quantitative phase data set """
if isinstance(grid_size, numbers.Integral): # default to square-shape grid grid_size = (grid_size, grid_size) if pixel_size is None: # select simulation automatically rl = radius / wavelength if rl < 5: # a lot of diffraction artifacts may occur; # use 4x radius to capture the full field fact = 4 elif rl >= 5 and rl <= 10: # linearly decrease towards 3x radius fact = 4 - (rl - 5) / 5 else: # not many diffraction artifacts occur; # 3x radius is enough and allows to # simulate larger radii with BHFIELD fact = 3 pixel_size = fact * radius / np.min(grid_size) if center is None: center = (np.array(grid_size) - 1) / 2 model = model_dict[model] qpi = model(radius=radius, sphere_index=sphere_index, medium_index=medium_index, wavelength=wavelength, pixel_size=pixel_size, grid_size=grid_size, center=center) return qpi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def params(self): """Current interpolation parameter dictionary"""
par = {"radius": self.radius, "sphere_index": self.sphere_index, "pha_offset": self.pha_offset, "center": [self.posx_offset, self.posy_offset] } return par
<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_n(self): """Current interpolation range of refractive index"""
return self.sphere_index - self.dn, self.sphere_index + self.dn
<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_r(self): """Current interpolation range of radius"""
return self.radius - self.dr, self.radius + self.dr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_qpi(self): """Compute model data with current parameters Returns ------- qpi: qpimage.QPImage Modeled phase data Notes ----- The model image might deviate from the fitted image because of interpolation during the fitting process. """
kwargs = self.model_kwargs.copy() kwargs["radius"] = self.radius kwargs["sphere_index"] = self.sphere_index kwargs["center"] = [self.posx_offset, self.posy_offset] qpi = self.sphere_method(**kwargs) # apply phase offset bg_data = np.ones(qpi.shape) * -self.pha_offset qpi.set_bg_data(bg_data=bg_data, which_data="phase") return qpi
<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_border_phase(self, idn=0, idr=0): """Return one of nine border fields Parameters idn: int Index for refractive index. One of -1 (left), 0 (center), 1 (right) idr: int Index for radius. One of -1 (left), 0 (center), 1 (right) """
assert idn in [-1, 0, 1] assert idr in [-1, 0, 1] n = self.sphere_index + self.dn * idn r = self.radius + self.dr * idr # convert to array indices idn += 1 idr += 1 # find out whether we need to compute a new border field if self._n_border[idn, idr] == n and self._r_border[idn, idr] == r: if self.verbose > 3: print("Using cached border phase (n{}, r{})".format(idn, idr)) # return previously computed field pha = self._border_pha[(idn, idr)] else: if self.verbose > 3: print("Computing border phase (n{}, r{})".format(idn, idr)) kwargs = self.model_kwargs.copy() kwargs["radius"] = r kwargs["sphere_index"] = n kwargs["center"] = [self.posx_offset, self.posy_offset] tb = time.time() pha = self.sphere_method(**kwargs).pha if self.verbose > 2: print("Border phase computation time:", self.sphere_method.__module__, time.time() - tb) self._border_pha[(idn, idr)] = pha self._n_border[idn, idr] = n self._r_border[idn, idr] = r return pha
<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_phase(self, nintp=None, rintp=None, delta_offset_x=0, delta_offset_y=0): """Interpolate from the border fields to new coordinates Parameters nintp: float or None Refractive index of the sphere rintp: float or None Radius of sphere [m] delta_offset_x: float Offset in x-direction [px] delta_offset_y: float Offset in y-direction [px] Returns ------- phase_intp: 2D real-valued np.ndarray Interpolated phase at the given parameters Notes ----- Not all combinations are poosible, e.g. - One of nintp or rintp must be None - The current interpolation range must include the values for rintp and nintp """
if nintp is None: nintp = self.sphere_index if rintp is None: rintp = self.radius assert (rintp == self.radius or nintp == self.sphere_index), "Only r or n can be changed at a time." assert rintp >= self.radius - self.dr assert rintp <= self.radius + self.dr assert nintp >= self.sphere_index - \ self.dn, "Out of range: {} !> {}".format( nintp, self.sphere_index - self.dn) assert nintp <= self.sphere_index + self.dn left = self.get_border_phase(0, 0) if rintp == self.radius: dist = nintp - self.sphere_index dmax = self.dn if dist < 0: righ = self.get_border_phase(-1, 0) else: righ = self.get_border_phase(1, 0) else: dist = rintp - self.radius dmax = self.dr if dist < 0: righ = self.get_border_phase(0, -1) else: righ = self.get_border_phase(0, 1) # make dist positive so that we are interpolating from left to right dist = np.abs(dist) # perform linear interpolation of data. phas = left + (righ - left) * dist / dmax # interpolation of lateral movement ti = time.time() ipphas = spintp.RectBivariateSpline(np.arange(phas.shape[0]), np.arange(phas.shape[1]), phas) if delta_offset_x != 0 or delta_offset_y != 0: # Shift the image. The offset values used here # are not self.posx_offset and self.posy_offset! # The offset values are added to the fields computed # with self.posx_offset and self.posy_offset. newx = np.arange(phas.shape[0]) + delta_offset_x newy = np.arange(phas.shape[1]) + delta_offset_y phas = ipphas(newx, newy) if self.verbose > 2: print("Interpolation time for {}: {}".format( self.model, time.time() - ti)) return phas + self.pha_offset
<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_empty_text(self): """Display the empty text """
self.buffer.insert_with_tags_by_name( self.buffer.get_start_iter(), self.empty_text, 'empty-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 buildMessage(headers, parts): """ Builds a message from some headers and MIME parts. """
message = multipart.MIMEMultipart('alternative') for name, value in headers.iteritems(): name = name.title() if name == "From": multipart[name] = _encodeAddress(value) elif name in ["To", "Cc", "Bcc"]: multipart[name] = _encodeAddresses(value) else: multipart[name] = _encodeHeader(value) for partType, part in parts.iteritems(): mimeText = text.MIMEText(part.encode("utf-8"), partType, "UTF-8") message.attach(mimeText.encode()) return message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encodeHeader(headerValue): """ Encodes a header value. Returns ASCII if possible, else returns an UTF-8 encoded e-mail header. """
try: return headerValue.encode('ascii', 'strict') except UnicodeError: encoded = headerValue.encode("utf-8") return header.Header(encoded, "UTF-8").encode()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def messageToFile(message): """ Flattens a message into a file-like object. """
outFile = StringIO() messageGenerator = generator.Generator(outFile, False) messageGenerator.flatten(message) outFile.seek(0, 0) return outFile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze(qpi, r0, edgekw={}, ret_center=False, ret_edge=False): """Determine refractive index and radius using Canny edge detection Compute the refractive index of a spherical phase object by detection of an edge in the phase image, a subsequent circle fit to the edge, and finally a weighted average over the phase image assuming a parabolic phase profile. Parameters qpi: QPImage Quantitative phase image information r0: float Approximate radius of the sphere [m] edgekw: dict Additional keyword arguments for :func:`contour_canny` ret_center: bool Return the center coordinate of the sphere Returns ------- n: float Computed refractive index r: float Computed radius [m] center: tuple of floats Center position of the sphere [px], only returned if `ret_center` is `True` """
nmed = qpi["medium index"] px_m = qpi["pixel size"] wl_m = qpi["wavelength"] px_wl = px_m / wl_m phase = qpi.pha # determine edge edge = contour_canny(image=phase, radius=r0 / px_m, verbose=False, **edgekw, ) # fit circle to edge center, r = circle_fit(edge) # compute average phase density avg_phase = average_sphere(phase, center, r) # convert phase average to refractive index n = nmed + avg_phase / (2 * np.pi * px_wl) # convert radius from pixels to meters ret = [n, r * px_m] if ret_center: ret.append(center) if ret_edge: ret.append(edge) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def average_sphere(image, center, radius, weighted=True, ret_crop=False): """Compute the weighted average phase from a phase image of a sphere Parameters image: 2d ndarray Quantitative phase image of a sphere center: tuble (x,y) Center of the sphere in `image` in ndarray coordinates radius: float Radius of the sphere in pixels weighted: bool If `True`, return average phase density weighted with the height profile obtained from the radius, otherwise return simple average phase density. Weighting gives data points at the center of the sphere more weight than those points at the boundary of the sphere, avoiding edge artifacts. ret_crop: bool Return the cropped image. Returns ------- average: float The average phase value of the sphere from which the refractive index can be computed cropped_image: 2d ndarray Returned if `ret_crop` is True """
sx, sy = image.shape x = np.arange(sx).reshape(-1, 1) y = np.arange(sy).reshape(1, -1) discsq = ((x - center[0])**2 + (y - center[1])**2) root = radius**2 - discsq # height of the cell for each x and y h = 2 * np.sqrt(root * (root > 0)) # compute phase density rho = np.zeros(image.shape) hbin = h != 0 # phase density [rad/px] rho[hbin] = image[hbin] / h[hbin] if weighted: # compute weighted average average = np.sum(rho * h) / np.sum(h) else: # compute simple average average = np.sum(rho) / np.sum(hbin) ret = average if ret_crop: ret = (ret, rho) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circle_fit(edge, ret_dev=False): """Fit a circle to a boolean edge image Parameters edge: 2d boolean ndarray Edge image ret_dev: bool Return the average deviation of the distance from contour to center of the fitted circle. Returns ------- center: tuple of (float, float) Coordinates of the circle center radius: float Radius of the circle [px] rdev: Only returned if `ret_dev` is True Average deviation of the radius from the circle """
sx, sy = edge.shape x = np.linspace(0, sx, sx, endpoint=False).reshape(-1, 1) y = np.linspace(0, sy, sy, endpoint=False).reshape(1, -1) params = lmfit.Parameters() # initial parameters sum_edge = np.sum(edge) params.add("cx", np.sum(x * edge) / sum_edge) params.add("cy", np.sum(y * edge) / sum_edge) # data xedge, yedge = np.where(edge) # minimize out = lmfit.minimize(circle_residual, params, args=(xedge, yedge)) center = (out.params["cx"].value, out.params["cy"].value) radii = circle_radii(out.params, xedge, yedge) radius = np.mean(radii) ret = [center, radius] if ret_dev: dev = np.average(np.abs(radii - radius)) ret.append(dev) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circle_radii(params, xedge, yedge): """Compute the distance to the center from cartesian coordinates This method is used for fitting a circle to a set of contour points. Parameters params: lmfit.Parameters Must contain the keys: - "cx": origin of x coordinate [px] - "cy": origin of y coordinate [px] xedge: 1D np.ndarray Edge coordinates x [px] yedge: 1D np.ndarray Edge coordinates y [px] Returns ------- radii: 1D np.ndarray Radii corresponding to edge coordinates relative to origin """
cx = params["cx"].value cy = params["cy"].value radii = np.sqrt((cx - xedge)**2 + (cy - yedge)**2) return radii
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circle_residual(params, xedge, yedge): """Residuals for circle fitting Parameters params: lmfit.Parameters Must contain the keys: - "cx": origin of x coordinate [px] - "cy": origin of y coordinate [px] xedge: 1D np.ndarray Edge coordinates x [px] yedge: 1D np.ndarray Edge coordinates y [px] Returns ------- rad_dev: 1D np.ndarray Deviation of radii from average radius """
radii = circle_radii(params, xedge, yedge) return radii - np.mean(radii)
<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_run_command_dialog(command, shell=False, title='', data_callback=None, parent=None, **kwargs): ''' Launch command in a subprocess and create a dialog window to monitor the output of the process. Parameters ---------- command : list or str Subprocess command to execute. shell : bool, optional If :data:`shell` is ``False``, :data:`command` **must** be a :class:`list`. If :data:`shell` is ``True``, :data:`command` **must** be a :class:`str`. title : str, optional Title for dialog window and initial contents of main label. data_callback : func(dialog, command_view, fd, data), optional Callback function called when data is available for one of the file descriptors. The :data:`fd` callback parameter is 1 for ``stdout`` and 2 for ``stderr``. **kwargs Additional keyword arguments are interpreted as dialog widget property values and are applied to the dialog widget. Returns ------- gtk.Dialog Dialog with a progress bar and an expandable text view to monitor the output of the specified :data:`command`. .. note:: Subprocess is launched before returning dialog. ''' dialog = gtk.Dialog(title=title or None, parent=parent) dialog.set_size_request(540, -1) for key, value in kwargs.iteritems(): setattr(dialog.props, key, value) dialog.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK) dialog.set_default_response(gtk.RESPONSE_OK) content_area = dialog.get_content_area() label = gtk.Label(title) label.props.xalign = .1 content_area.pack_start(label, expand=False, fill=True, padding=10) progress_bar = gtk.ProgressBar() expander = gtk.Expander('Details') # Resize window based on whether or not expander is open. expander.connect('activate', functools .partial(lambda w, e, *args: w.set_size_request(540, -1 if e.props.expanded else 480), dialog)) command_view = CommandTextView() if data_callback is not None: command_view.connect('data-written', functools.partial(data_callback, dialog)) expander.add(command_view.widget) content_area.pack_start(progress_bar, expand=False) content_area.pack_start(expander, expand=True, fill=True) button = dialog.get_action_area().get_children()[0] content_area.show_all() def _run_command(label, progress_bar, button, view, command, shell): button.props.sensitive = False text_buffer = command_view.text_view.get_buffer() text_buffer.delete(*text_buffer.get_bounds()) def _pulse(*args): progress_bar.pulse() return True timeout_id = gobject.timeout_add(250, _pulse) command_view.run(command, shell=shell) gobject.source_remove(timeout_id) progress_bar.set_fraction(1.) button.props.sensitive = True label.set_markup('{} <b>done</b>.'.format(title)) gobject.idle_add(_run_command, label, progress_bar, button, command_view, command, shell) return dialog
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_key_from_file(url): """ Check bugzillarc for an API key for this Bugzilla URL. """
path = os.path.expanduser('~/.config/python-bugzilla/bugzillarc') cfg = SafeConfigParser() cfg.read(path) domain = urlparse(url)[1] if domain not in cfg.sections(): return None if not cfg.has_option(domain, 'api_key'): return None return cfg.get(domain, 'api_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 call(self, action, payload): """ Make an XML-RPC call to the server. This method will automatically authenticate the call with self.api_key, if that is set. returns: deferred that when fired returns a dict with data from this XML-RPC call. """
if self.api_key: payload['Bugzilla_api_key'] = self.api_key d = self.proxy.callRemote(action, payload) d.addErrback(self._parse_errback) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign(self, bugids, user): """ Assign a bug to a user. param bugid: ``int``, bug ID number. param user: ``str``, the login name of the user to whom the bug is assigned returns: deferred that when fired returns True if the change succeeded, False if the change was unnecessary (because the user is already assigned.) """
payload = {'ids': (bugids,), 'assigned_to': user} d = self.call('Bug.update', payload) d.addCallback(self._parse_bug_assigned_callback) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_external_tracker(self, url, id_): """ Find a list of bugs by searching an external tracker URL and ID. param url: ``str``, the external ticket URL, eg "http://tracker.ceph.com". (Note this is the base URL.) param id_: ``str``, the external ticket ID, eg "18812". returns: deferred that when fired returns a list of ``AttrDict``s representing these bugs. """
payload = { 'include_fields': ['id', 'summary', 'status'], 'f1': 'external_bugzilla.url', 'o1': 'substring', 'v1': url, 'f2': 'ext_bz_bug_map.ext_bz_bug_id', 'o2': 'equals', 'v2': id_, } d = self.call('Bug.search', payload) d.addCallback(self._parse_bugs_callback) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_bugs_callback(self, value): """ Fires when we get bug information back from the XML-RPC server. param value: dict of data from XML-RPC server. The "bugs" dict element contains a list of bugs. returns: ``list`` of ``AttrDict`` """
return list(map(lambda x: self._parse_bug(x), value['bugs']))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onSettingsChange(self, plugin_name, data): """ The plugin has been changed by the frontend :param plugin_name: Name of plugin that changed :type plugin_name: str :param data: Complete data (changed and unchanged) :type data: dict :rtype: None """
logger.info(u"onSettingsChange: {}".format(data)) if not plugin_name: logger.error("Missing plugin name") return if not data: logger.error("Missing data") return logger.info(u"Sending data {}".format(data)) reactor.callFromThread(self._sendJSON, { 'msg': "plugin_data_set", 'plugin_name': plugin_name, 'data': data }) # trigger db update reactor.callFromThread(self._sendJSON, { 'msg': "plugin_data_get", 'plugin_name': plugin_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 onRefreshPluginData(self, plugin_name, data): """ Frontend requests a data refresh :param plugin_name: Name of plugin that changed :type plugin_name: str :param data: Additional data :type data: None :rtype: None """
logger.info(u"onRefreshPluginData: {}".format(plugin_name)) if not plugin_name: logger.error("Missing plugin name") return reactor.callFromThread(self._sendJSON, { 'msg': "plugin_data_get", 'plugin_name': plugin_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 connect(self,soft_reset=False,**options): """ This just creates the websocket connection """
self._state = STATE_CONNECTING logger.debug("About to connect to {}".format(self.url)) m = re.search('(ws+)://([\w\.]+)(:?:(\d+))?',self.url) options['subprotocols'] = ['wamp.2.json'] options['enable_multithread'] = True options.setdefault('timeout',self._loop_timeout) # Handle the weird issue in websocket that the origin # port will be always http://host:port even though connection is # wss. This causes some origin issues with demo.crossbar.io demo # so we ensure we use http or https appropriately depending on the # ws or wss protocol if m and m.group(1).lower() == 'wss': origin_port = ':'+m.group(3) if m.group(3) else '' options['origin'] = u'https://{}{}'.format(m.group(2),origin_port) # Attempt connection once unless it's autoreconnect in which # case we try and try again... while True: try: if self.sslopt: options.setdefault('sslopt',self.sslopt) # By default if no settings are chosen we apply # the looser traditional policy (makes life less # secure but less excruciating on windows) if options.get('sslopt') is None: options['sslopt'] = { "cert_reqs":ssl.CERT_NONE, "check_hostname": False } if self.sockopt: options.setdefault('sockopt',self.sockopt) self.ws = websocket.create_connection( self.url, **options ) self.handle_connect() except Exception as ex: if self.auto_reconnect: logger.debug( "Error connecting to {url}. Reconnection attempt in {retry} second(s). {err}".format( url=self.url, retry=self.auto_reconnect, err=ex ) ) time.sleep(self.auto_reconnect) continue else: raise break logger.debug("Connected to {}".format(self.url)) if not soft_reset: self._subscriptions = {} self._registered_calls = {} self._requests_pending = {} self._state = STATE_WEBSOCKET_CONNECTED # notify the threading.Conditional that restart can happen self._request_loop_notify_restart.acquire() self._request_loop_notify_restart.notify() self._request_loop_notify_restart.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 hello(self,details=None): """ Say hello to the server and wait for the welcome message before proceeding """
self._welcome_queue = queue.Queue() if details is None: details = {} if self.authid: details.setdefault('authid', self.authid) details.setdefault('agent', u'swampyer-1.0') details.setdefault('authmethods', self.authmethods or [u'anonymous']) details.setdefault('roles', { 'subscriber': {}, 'publisher': {}, 'caller': {}, 'callee': {}, }) self._state = STATE_AUTHENTICATING self.send_message(HELLO( realm = self.realm, details = details )) # Wait till we get a welcome message try: message = self._welcome_queue.get(block=True,timeout=self.timeout) except Exception as ex: raise ExWelcomeTimeout("Timed out waiting for WELCOME response") if message == WAMP_ABORT: raise ExAbort("Received abort when trying to connect: {}".format( message.details.get('message', message.reason))) self.session_id = message.session_id self.peer = message self._state = STATE_CONNECTED # And hook register/subscribe to anything that's required self.handle_join(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, uri, *args, **kwargs ): """ Sends a RPC request to the WAMP server """
if self._state == STATE_DISCONNECTED: raise Exception("WAMP is currently disconnected!") options = { 'disclose_me': True } uri = self.get_full_uri(uri) message = self.send_and_await_response(CALL( options=options, procedure=uri, args=args, kwargs=kwargs )) if message == WAMP_RESULT: return message.args[0] if message == WAMP_ERROR: if message.args: err = message.args[0] else: err = message.error raise ExInvocationError(err) return message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_message(self,message): """ Send awamp message to the server. We don't wait for a response here. Just fire out a message """
if self._state == STATE_DISCONNECTED: raise Exception("WAMP is currently disconnected!") message = message.as_str() logger.debug("SND>: {}".format(message)) if not self.ws: raise Exception("WAMP is currently disconnected!") self.ws.send(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_and_await_response(self,request): """ Used by most things. Sends out a request then awaits a response keyed by the request_id """
if self._state == STATE_DISCONNECTED: raise Exception("WAMP is currently disconnected!") wait_queue = queue.Queue() request_id = request.request_id self._requests_pending[request_id] = wait_queue; self.send_message(request) try: return wait_queue.get(block=True,timeout=self.timeout) except Exception as ex: raise Exception("Did not receive a 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 dispatch_to_awaiting(self,result): """ Send dat ato the appropriate queues """
# If we are awaiting to login, then we might also get # an abort message. Handle that here.... if self._state == STATE_AUTHENTICATING: # If the authentication message is something unexpected, # we'll just ignore it for now if result == WAMP_ABORT \ or result == WAMP_WELCOME \ or result == WAMP_GOODBYE: self._welcome_queue.put(result) return try: request_id = result.request_id if request_id in self._requests_pending: self._requests_pending[request_id].put(result) del self._requests_pending[request_id] except: raise Exception("Response does not have a request id. Do not know who to send data to. Data: {} ".format(result.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 handle_abort(self, reason): """ We're out? """
self._welcome_queue.put(reason) self.close() self.disconnect()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_invocation(self, message): """ Passes the invocation request to the appropriate callback. """
req_id = message.request_id reg_id = message.registration_id if reg_id in self._registered_calls: handler = self._registered_calls[reg_id][REGISTERED_CALL_CALLBACK] invoke = WampInvokeWrapper(self,handler,message) invoke.start() else: error_uri = self.get_full_uri('error.unknown.uri') self.send_message(ERROR( request_code = WAMP_INVOCATION, request_id = req_id, details = {}, error =error_uri ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_event(self, event): """ Send the event to the subclass or simply reject """
subscription_id = event.subscription_id if subscription_id in self._subscriptions: # FIXME: [1] should be a constant handler = self._subscriptions[subscription_id][SUBSCRIPTION_CALLBACK] WampSubscriptionWrapper(self,handler,event).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 subscribe(self,topic,callback=None,options=None): """ Subscribe to a uri for events from a publisher """
full_topic = self.get_full_uri(topic) result = self.send_and_await_response(SUBSCRIBE( options=options or {}, topic=full_topic )) if result == WAMP_SUBSCRIBED: if not callback: callback = lambda a: None self._subscriptions[result.subscription_id] = [topic,callback]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self,topic,options=None,args=None,kwargs=None): """ Publishes a messages to the server """
topic = self.get_full_uri(topic) if options is None: options = {'acknowledge':True} if options.get('acknowledge'): request = PUBLISH( options=options or {}, topic=topic, args=args or [], kwargs=kwargs or {} ) result = self.send_and_await_response(request) return result else: request = PUBLISH( options=options or {}, topic=topic, args=args or [], kwargs=kwargs or {} ) self.send_message(request) return request.request_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ Disconnect from the websocket and pause the process till we reconnect """
logger.debug("Disconnecting") # Close off the websocket if self.ws: try: if self._state == STATE_CONNECTED: self.handle_leave() self.send_message(GOODBYE( details={}, reason="wamp.error.system_shutdown" )) logger.debug("Closing Websocket") try: self.ws.close() except Exception as ex: logger.debug("Could not close websocket connection because: {}".format(ex)) except Exception as ex: logger.debug("Could not send Goodbye message because {}".format(ex)) pass # FIXME: Maybe do better handling here self.ws = None # Cleanup the state variables. By settings this # we're going to be telling the main loop to stop # trying to read from a websocket and await a notice # of restart via a threading.Condition object self._state = STATE_DISCONNECTED # Send a message to all queues that we have disconnected # Without this, any requests that are awaiting a response # will block until timeout needlessly for request_id, request_queue in self._requests_pending.items(): request_queue.put(GOODBYE( details={}, reason="wamp.error.system_shutdown" )) self._requests_pending = {} self.handle_disconnect()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shutdown(self): """ Request the system to shutdown the main loop and shutdown the system This is a one-way trip! Reconnecting requires a new connection to be made! """
self._request_shutdown = True for i in range(100): if self._state == STATE_DISCONNECTED: break time.sleep(0.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 start(self): """ Initialize websockets, say hello, and start listening for events """
self.connect() if not self.isAlive(): super(WAMPClient,self).start() self.hello() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Waits and receives messages from the server. This function somewhat needs to block so is executed in its own thread until self._request_shutdown is called. """
while not self._request_shutdown: # Find out if we have any data pending from the # server try: # If we've been asked to stop running the # request loop. We'll just sit and wait # till we get asked to run again if self._state not in [STATE_AUTHENTICATING,STATE_WEBSOCKET_CONNECTED,STATE_CONNECTED]: self._request_loop_notify_restart.acquire() self._request_loop_notify_restart.wait(self._loop_timeout) self._request_loop_notify_restart.release() continue # If we don't have a websocket defined. # we don't go further either elif not self.ws: logger.debug("No longer have a websocket. Marking disconnected") self._state = STATE_DISCONNECTED continue # Okay, we think we're okay so let's try and read some data data = self.ws.recv() except io.BlockingIOError: continue except websocket.WebSocketTimeoutException: continue except websocket.WebSocketConnectionClosedException as ex: logger.debug("WebSocketConnectionClosedException: Requesting disconnect:".format(ex)) self.disconnect() # If the server disconnected, let's try and reconnect # back to the service after a random few seconds if self.auto_reconnect: # As doing a reconnect would block and would then # prevent us from ticking the websoocket, we'll # go into a subthread to deal with the reconnection def reconnect(): self.reconnect() t = threading.Thread(target=reconnect) t.start() # FIXME: need to randomly wait time.sleep(1) if not data: continue except Exception as ex: logger.error("ERROR in main loop: {}".format(ex)) continue try: logger.debug("<RCV: {}".format(data)) message = WampMessage.loads(data) logger.debug("<RCV: {}".format(message.dump())) try: code_name = message.code_name.lower() handler_name = "handle_"+code_name handler_function = getattr(self,handler_name) handler_function(message) except AttributeError as ex: self.handle_unknown(message) except Exception as ex: logger.error("ERROR in main loop: {}".format(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 handle_challenge(self,data): """ Executed when the server requests additional authentication """
# Send challenge response self.send_message(AUTHENTICATE( signature = self.password, extra = {} ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def icevol_correction(age, proxyvalue, proxytype='d18o', timeunit='ya', benthic_stack=None): """Correct isotopic proxy data for ice-volume contribution This function uses the LR04 benthic stack [1]_ scaled such that the LGM-present change is assumed to be 1.0 ‰ in accordance with the pore-water estimate from [2]_. This correction method is adapted from [3]_. Parameters age: ndarray Age array associated with proxy data. proxyvalue: ndarray Isotopic proxy data to be corrected. proxytype: str, optional Type of proxy. Must be 'd18o' for δ18O or 'dd' for δD. Default is 'd18o'. timeunit: str, optional Time unit for 'age'. Must be 'ya' (for years BP), 'ka' (thousand years BP), or 'ma' (million years BP). Default is 'ya'. benthic_stack: obj, optional Benthic stack to use for ice-volume correction. Uses erebusfall.benthic_stacks.lr04 by default. This is derived from LR04. Returns ------- A numpy array giving the corrected isotope data. References .. [1] Lisiecki, L. E., & Raymo, M. E. (2005). A Pliocene-Pleistocene stack of 57 globally distributed benthic δ18O records: PLIOCENE-PLEISTOCENE BENTHIC STACK. Paleoceanography, 20(1). https://doi.org/10.1029/2004PA001071 .. [2] Schrag, D. P., Hampt, G., & Murray, D. W. (1996). Pore Fluid Constraints on the Temperature and Oxygen Isotopic Composition of the Glacial Ocean. Science, 272(5270), 1930–1932. https://doi.org/10.1126/science.272.5270.1930 .. [3] Tierney, J. E., deMenocal, P. B., & Zander, P. D. (2017). A climatic context for the out-of-Africa migration. Geology, 45(11), 1023–1026. https://doi.org/10.1130/G39457.1 Examples -------- """
age = np.array(age) proxyvalue = np.array(proxyvalue) assert len(age) == len(proxyvalue) proxytype = proxytype.lower() timeunit = timeunit.lower() assert proxytype in ['d18o', 'dd'] assert timeunit in ['ya', 'ka', 'ma'] if benthic_stack is None: benthic_stack = stacks.lr04 sage = benthic_stack.age.copy() if timeunit == 'ya': sage *= 1000 elif timeunit == 'ma': sage /= 1000 # Linearly interpolate the scaled benthic stack to the target data ages. interp_f = interp1d(sage, benthic_stack.delo_scaled, kind='linear', bounds_error=False) target = interp_f(age) # Find any ages that are negative (e.g., post-1950) and turn to 0 modern = age < 0 if any(modern): target[modern] = 0 # Find any ages that are greater than the end of the benthic stack and set # then to nan. ancient = age > max(sage) if any(ancient): target[ancient] = np.nan # adjust the isotope data if proxytype == 'dd': target = 8 * target corrected = ((1000 + proxyvalue) / (target / 1000 + 1)) - 1000 return corrected
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rehearse( folders, references, handler, repeat=0, roles=1, strict=False, loop=None ): """Cast a set of objects into a sequence of scene scripts. Deliver the performance. :param folders: A sequence of :py:class:`turberfield.dialogue.model.SceneScript.Folder` objects. :param references: A sequence of Python objects. :param handler: A callable object. This will be invoked with every event from the performance. :param int repeat: Extra repetitions of each folder. :param int roles: Maximum number of roles permitted each character. :param bool strict: Only fully-cast scripts to be performed. This function is a generator. It yields events from the performance. """
if isinstance(folders, SceneScript.Folder): folders = [folders] yield from handler(references, loop=loop) matcher = Matcher(folders) performer = Performer(folders, references) while True: folder, index, script, selection, interlude = performer.next( folders, references, strict=strict, roles=roles ) yield from handler(script, loop=loop) for item in performer.run(react=False, strict=strict, roles=roles): yield from handler(item, loop=loop) if isinstance(interlude, Callable): metadata = next(handler( interlude, folder, index, references, loop=loop ), None) yield metadata if metadata is None: return branch = next(matcher.options(metadata)) if branch != folder: performer = Performer([branch], references) if not repeat: break else: repeat -= 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 can_add_new_content(self, block, file_info): """ new content from file_info can be added into block iff - file count limit hasn't been reached for the block - there is enough space to completely fit the info into the block - OR the info can be split and some info can fit into the block """
return ((self._max_files_per_container == 0 or self._max_files_per_container > len(block.content_file_infos)) and (self.does_content_fit(file_info, block) or # check if we can fit some content by splitting the file # Note: if max size was unlimited, does_content_fit would have been True (block.content_size < self._max_container_content_size_in_bytes and (self._should_split_small_files or not self._is_small_file(file_info)))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_init(self, fs_settings, global_quota): fs_settings = deepcopy(fs_settings) # because we store some of the info, we need a deep copy ''' If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice ''' for sender_spec in fs_settings.sender_specs: restrictions = sender_spec.restrictions if restrictions in self.restriction_to_job: self.restriction_to_job[restrictions].add_destinations(sender_spec.destinations) else: compressor = _CompressorJob( next_task=self.get_next_task(), sender_spec=sender_spec, tmp_file_parts_basepath=fs_settings.tmp_file_parts_basepath, should_split_small_files=fs_settings.should_split_small_files, global_quota=global_quota) self.restriction_to_job[restrictions] = compressor compressor.register(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_last_nonce(app, key, nonce): """ Get the last_nonce used by the given key from the SQLAlchemy database. Update the last_nonce to nonce at the same time. :param str key: the public key the nonce belongs to :param int nonce: the last nonce used by this key """
uk = ses.query(um.UserKey).filter(um.UserKey.key==key)\ .filter(um.UserKey.last_nonce<nonce * 1000).first() if not uk: return None lastnonce = copy.copy(uk.last_nonce) # TODO Update DB record in same query as above, if possible uk.last_nonce = nonce * 1000 try: ses.commit() except Exception as e: current_app.logger.exception(e) ses.rollback() ses.flush() return lastnonce
<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_user_by_key(app, key): """ An SQLAlchemy User getting function. Get a user by public key. :param str key: the public key the user belongs to """
user = ses.query(um.User).join(um.UserKey).filter(um.UserKey.key==key).first() return user
<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_user(): """ Get your user object. Users may only get their own info, not others'. --- responses: '200': description: user response schema: $ref: '#/definitions/User' default: description: unexpected error schema: $ref: '#/definitions/errorModel' description: get your user record security: - kid: [] - typ: [] - alg: [] operationId: getUserList """
userdict = json.loads(jsonify2(current_user.dbuser, 'User')) return current_app.bitjws.create_response(userdict)