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 generate(self): """ Generates a new token for this column based on its bit length. This method will not ensure uniqueness in the model itself, that should be...
try: model = self.schema().model() except AttributeError: return os.urandom(self.__bits).encode('hex') else: while True: token = os.urandom(self.__bits).encode('hex') if model.select(where=orb.Query(self) == token).count() == 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 start_monitoring(seconds_frozen=SECONDS_FROZEN, test_interval=TEST_INTERVAL): """Start monitoring for hanging threads. seconds_frozen - How much time should ...
thread = StoppableThread(target=monitor, args=(seconds_frozen, test_interval)) thread.daemon = True thread.start() return thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monitor(seconds_frozen, test_interval): """Monitoring thread function. Checks if thread is hanging for time defined by ``seconds_frozen`` parameter every ``t...
current_thread = threading.current_thread() hanging_threads = set() old_threads = {} # Threads found on previous iteration. while not current_thread.is_stopped(): new_threads = get_current_frames() # Report died threads. for thread_id in old_threads.keys(): if thr...
<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_current_frames(): """Return current threads prepared for further processing. """
return dict( (thread_id, {'frame': thread2list(frame), 'time': None}) for thread_id, frame in sys._current_frames().items() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frame2string(frame): """Return info about frame. Keyword arg: frame Return string in format: File {file name}, line {line number}, in {name of parent of code...
lineno = frame.f_lineno # or f_lasti co = frame.f_code filename = co.co_filename name = co.co_name s = '\tFile "{0}", line {1}, in {2}'.format(filename, lineno, name) line = linecache.getline(filename, lineno, frame.f_globals).lstrip() return s + '\n\t\t' + 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 thread2list(frame): """Return list with string frame representation of each frame of thread. """
l = [] while frame: l.insert(0, frame2string(frame)) frame = frame.f_back return l
<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_log(title, message=''): """Write formatted log message to stderr."""
sys.stderr.write(''.join([ title.center(40).center(60, '-'), '\n', 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 execute_input_middleware_stream(self, request, controller): """ Request comes from the controller. Returned is a request. controller arg is the name of the c...
start_request = request # either 'http' or 'cmd' or 'irc' controller_name = "".join(controller.get_controller_name().split('-')[:1]) middlewares = list(self.pre_input_middleware) + list(self.input_middleware) for m in middlewares: to_execute = getattr(m(controller), ...
<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_suggestions(self, filter_word=None): """ This only gets caled internally from the get_suggestion method. """
keys = self.manifest.keys() words = [] for key in keys: if isinstance(self.manifest[key], Manifest): # if this key is another manifest, append a slash to the # suggestion so the user knows theres more items under this 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 get_suggestion(self, front_path): """ Returns suggestions for a path. Used in tab completion from the command line. """
if '/' in front_path: # transverse the manifest, return the new manifest, then # get those suggestions with the remaining word splitted = front_path.split('/') new_manifest = self.manifest pre_path = '' for item in splitted: ...
<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_invocation(self, invocation, controller_tag): """ Given an invocation string, determine which part is the path, the program, and the args. """
if invocation.endswith('/'): invocation = invocation[:-1] if not invocation.startswith('/'): invocation = '/' + invocation if invocation == '': invocation = '/' all_programs = self.get_urls(controllers=[controller_tag]) matching_paths = set(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Returns a new instance copy of this column. :return: <orb.Column> """
out = type(self)( name=self.__name, field=self.__field, display=self.__display, flags=self.__flags, default=self.__default, defaultOrder=self.__defaultOrder, getter=self.__gettermethod, setter=self.__settermethod, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dbMath(self, typ, field, op, value): """ Performs some database math on the given field. This will be database specific implementations and should return the...
ops = orb.Query.Math(op) format = self.MathMap.get(typ, {}).get(ops) or self.MathMap.get('Default').get(ops) or '{field}' return format.format(field=field, value=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 dbType(self, typ): """ Returns the database object type based on the given connection type. :param typ: <str> :return: <str> """
return self.TypeMap.get(typ, self.TypeMap.get('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 default(self): """ Returns the default value for this column to return when generating new instances. :return <variant> """
if isinstance(self.__default, (str, unicode)): return self.valueFromString(self.__default) else: return self.__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 field(self): """ Returns the field name that this column will have inside the database. :return <str> """
if not self.__field: default_field = inflection.underscore(self.__name) if isinstance(self, orb.ReferenceColumn): default_field += '_id' self.__field = default_field return self.__field or default_field
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def firstMemberSchema(self, schemas): """ Returns the first schema within the list that this column is a member of. :param schemas | [<orb.TableSchema>, ..] :ret...
for schema in schemas: if schema.hasColumn(self): return schema return self.schema()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isMemberOf(self, schemas): """ Returns whether or not this column is a member of any of the given schemas. :param schemas | [<orb.TableSchema>, ..] || <orb.T...
if type(schemas) not in (tuple, list, set): schemas = (schemas,) for schema in schemas: if schema.hasColumn(self): 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 loadJSON(self, jdata): """ Initializes the information for this class from the given JSON data blob. :param jdata: <dict> """
# required params self.__name = jdata['name'] self.__field = jdata['field'] # optional fields self.__display = jdata.get('display') or self.__display self.__flags = jdata.get('flags') or self.__flags self.__defaultOrder = jdata.get('defaultOrder') or self.__defa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setFlag(self, flag, state=True): """ Sets whether or not this flag should be on. :param flag | <Column.Flags> state | <bool> """
if state: self.__flags |= flag else: self.__flags &= ~flag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, value): """ Validates the inputted value against this columns rules. If the inputted value does not pass, then a validation error will be rais...
# check for the required flag if self.testFlag(self.Flags.Required) and not self.testFlag(self.Flags.AutoAssign): if self.isNull(value): msg = '{0} is a required column.'.format(self.name()) raise orb.errors.ColumnValidationError(self, msg) # otherwi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromJSON(cls, jdata): """ Generates a new column from the given json data. This should be already loaded into a Python dictionary, not a JSON string. :param ...
cls_type = jdata.get('type') col_cls = cls.byName(cls_type) if not col_cls: raise orb.errors.ColumnTypeNotFound(cls_type) else: col = col_cls() col.loadJSON(jdata) return col
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ancestry(self): """ Returns the different inherited schemas for this instance. :return [<TableSchema>, ..] """
if not self.inherits(): return [] schema = orb.system.schema(self.inherits()) if not schema: return [] return schema.ancestry() + [schema]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addColumn(self, column): """ Adds the inputted column to this table schema. :param column | <orb.Column> """
column.setSchema(self) self.__columns[column.name()] = column
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addIndex(self, index): """ Adds the inputted index to this table schema. :param index | <orb.Index> """
index.setSchema(self) self.__indexes[index.name()] = index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCollector(self, collector): """ Adds the inputted collector reference to this table schema. :param collector | <orb.Collector> """
collector.setSchema(self) self.__collectors[collector.name()] = collector
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collector(self, name, recurse=True): """ Returns the collector that matches the inputted name. :return <orb.Collector> || None """
return self.collectors(recurse=recurse).get(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collectors(self, recurse=True, flags=0): """ Returns a list of the collectors for this instance. :return {<str> name: <orb.Collector>, ..} """
output = {} if recurse and self.inherits(): schema = orb.system.schema(self.inherits()) if not schema: raise orb.errors.ModelNotFound(schema=self.inherits()) else: iflags = (flags & ~orb.Collector.Flags.Virtual) if flags else ~orb.Coll...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inheritanceTree(self): """ Returns the inheritance tree for this schema, traversing up the hierarchy for the inherited schema instances. :return: <generator>...
inherits = self.inherits() while inherits: ischema = orb.system.schema(inherits) if not ischema: raise orb.errors.ModelNotFound(schema=inherits) yield ischema inherits = ischema.inherits()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def namespace(self, **context): """ Returns the namespace that should be used for this schema, when specified. :return: <str> """
context = orb.Context(**context) if context.forceNamespace: return context.namespace or self.__namespace else: return self.__namespace or context.namespace
<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_kwargs(kwargs): """ Convert a list of kwargs into a dictionary. Duplicates of the same keyword get added to an list within the dictionary. {'var1': [1,...
d = defaultdict(list) for k, v in ((k.lstrip('-'), v) for k,v in (a.split('=') for a in kwargs)): d[k].append(v) ret = {} for k, v in d.items(): # replace single item lists with just the item. if len(v) == 1 and type(v) is list: ret[k] = v[0] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def htmlize_list(items): """ Turn a python list into an html list. """
out = ["<ul>"] for item in items: out.append("<li>" + htmlize(item) + "</li>") out.append("</ul>") return "\n".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre_process_json(obj): """ Preprocess items in a dictionary or list and prepare them to be json serialized. """
if type(obj) is dict: new_dict = {} for key, value in obj.items(): new_dict[key] = pre_process_json(value) return new_dict elif type(obj) is list: new_list = [] for item in obj: new_list.append(pre_process_json(item)) return new_list ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_error_page(code, exc, mimetype='text/html', traceback=''): """ Render the error page """
from giotto.views import get_jinja_template if 'json' in mimetype: return json.dumps({ 'code': code, 'exception': exc.__class__.__name__, 'message': str(exc), }) et = get_config('error_template') if not et: return "%s %s\n%s" % (code, str(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 initialize(module_name=None): """ Build the giotto settings object. This function gets called at the very begining of every request cycle. """
import giotto from giotto.utils import random_string, switchout_keyvalue from django.conf import settings setattr(giotto, '_config', GiottoSettings()) if not module_name: # For testing. No settings will be set. return project_module = importlib.import_module(module_name) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(item, default=None): """ Use this function to get values from the config object. """
import giotto return getattr(giotto._config, item, default) or 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 has_object_permission(self, request, view, obj): """ check filter permissions """
user = request.user if not user.is_superuser and not user.is_anonymous(): valid = False try: ct = ContentType.objects.get_for_model(obj) fpm = FilterPermissionModel.objects.get(user=user, 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 displayHelp(self): """ Output help message of twistedchecker. """
self.outputStream.write(self.linter.help()) sys.exit(32)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregisterChecker(self, checker): """ Remove a checker from the list of registered checkers. @param checker: the checker to remove """
self.linter._checkers[checker.name].remove(checker) if checker in self.linter._reports: del self.linter._reports[checker] if checker in self.linter.options_providers: self.linter.options_providers.remove(checker)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findUselessCheckers(self, allowedMessages): """ Find checkers which generate no allowed messages. @param allowedMessages: allowed messages @return: useless c...
uselessCheckers = [] for checkerName in self.linter._checkers: for checker in list(self.linter._checkers[checkerName]): messagesOfChecker = set(checker.msgs) if not messagesOfChecker.intersection(allowedMessages): uselessCheckers.append(ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restrictCheckers(self, allowedMessages): """ Unregister useless checkers to speed up twistedchecker. @param allowedMessages: output messages allowed in twist...
uselessCheckers = self.findUselessCheckers(allowedMessages) # Unregister these checkers for checker in uselessCheckers: self.unregisterChecker(checker)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCheckerByName(self, checkerType): """ Get checker by given name. @checkerType: type of the checker """
for checker in sum(list(self.linter._checkers.values()), []): if isinstance(checker, checkerType): return checker 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 allowPatternsForNameChecking(self, patternsFunc, patternsClass): """ Allow name exceptions by given patterns. @param patternsFunc: patterns of special functi...
cfgParser = self.linter.cfgfile_parser nameChecker = self.getCheckerByName(NameChecker) if not nameChecker: return if patternsFunc: regexFuncAdd = "|((%s).+)$" % "|".join(patternsFunc) else: regexFuncAdd = "" if patternsClass: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPathList(self, filesOrModules): """ Transform a list of modules to path. @param filesOrModules: a list of modules (may be foo/bar.py or foo.bar) """
pathList = [] for fileOrMod in filesOrModules: if not os.path.exists(fileOrMod): # May be given module is not not a path, # then transform it to a path. try: filepath = file_from_modpath(fileOrMod.split('.')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setNameExceptions(self, filesOrModules): """ Find name exceptions in codes and allow them to be ignored in checking. @param filesOrModules: a list of modules...
pathList = self.getPathList(filesOrModules) for path in pathList: patternsFunc, patternsClass = findAllExceptions(path) self.allowPatternsForNameChecking(patternsFunc, patternsClass)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, args): """ Setup the environment, and run pylint. @param args: arguments will be passed to pylint @type args: list of string """
# set output stream. if self.outputStream: self.linter.reporter.set_output(self.outputStream) try: args = self.linter.load_command_line_configuration(args) except SystemExit as exc: if exc.code == 2: # bad options exc.code = 32 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepareDiff(self): """ Prepare to run the checker and get diff results. """
self.streamForDiff = NativeStringIO() self.linter.reporter.set_output(self.streamForDiff)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showDiffResults(self): """ Show results when diff option on. """
try: oldWarnings = self.parseWarnings(self._readDiffFile()) except: sys.stderr.write(self.errorResultRead % self.diffOption) return 1 newWarnings = self.parseWarnings(self.streamForDiff.getvalue()) diffWarnings = self.generateDiff(oldWarnings, newWa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _readDiffFile(self): """ Read content of diff file. This is here to help with testing. @return: File content. @rtype: c{str} """
with open(self.diffOption) as f: content = f.read() return 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 generateDiff(self, oldWarnings, newWarnings): """ Generate diff between given two lists of warnings. @param oldWarnings: parsed old warnings @param newWarnin...
diffWarnings = {} for modulename in newWarnings: diffInModule = ( newWarnings[modulename] - oldWarnings.get(modulename, set())) if diffInModule: diffWarnings[modulename] = diffInModule return diffWarnings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseWarnings(self, result): """ Transform result in string to a dict object. @param result: a list of warnings in string @return: a dict of warnings """
warnings = {} currentModule = None warningsCurrentModule = [] for line in result.splitlines(): if line.startswith(self.prefixModuleName): # Save results for previous module if currentModule: warnings[currentModule] = set(wa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatWarnings(self, warnings): """ Format warnings to a list of results. @param warnings: a dict of warnings produced by parseWarnings @return: a list of wa...
lines = [] for modulename in sorted(warnings): lines.append(self.prefixModuleName + modulename) lines.extend(sorted(warnings[modulename], key=lambda x: x.split(":")[1])) 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 get_N50(readlengths): """Calculate read length N50. Based on https://github.com/PapenfussLab/Mungo/blob/master/bin/fasta_stats.py """
return readlengths[np.where(np.cumsum(readlengths) >= 0.5 * np.sum(readlengths))[0][0]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_length_outliers(df, columnname): """Remove records with length-outliers above 3 standard deviations from the median."""
return df[df[columnname] < (np.median(df[columnname]) + 3 * np.std(df[columnname]))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ave_qual(quals, qround=False, tab=errs_tab(128)): """Calculate average basecall quality of a read. Receive the integer quality scores of a read and return th...
if quals: mq = -10 * log(sum([tab[q] for q in quals]) / len(quals), 10) if qround: return round(mq) else: return mq else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_stats(datadfs, outputfile, names=[]): """Call calculation functions and write stats file. This function takes a list of DataFrames, and will create a c...
if outputfile == 'stdout': output = sys.stdout else: output = open(outputfile, 'wt') stats = [Stats(df) for df in datadfs] features = { "Number of reads": "number_of_reads", "Total bases": "number_of_bases", "Total bases aligned": "number_of_bases_aligned", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errorRecorder(self, lineNumber, offset, text, check): """ A function to override report_error in pycodestyle. And record output warnings. @param lineNumber: ...
code = text.split(" ")[0] lineOffset = self.report.line_offset self.warnings.append((lineOffset + lineNumber, offset + 1, code, 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 run(self): """ Run pycodestyle checker and record warnings. """
# Set a stream to replace stdout, and get results in it stdoutBak = sys.stdout streamResult = StringIO() sys.stdout = streamResult try: pycodestyle.Checker.check_all(self) finally: sys.stdout = stdoutBak
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _outputMessages(self, warnings, node): """ Map pycodestyle results to messages in pylint, then output them. @param warnings: it should be a list of tuple inc...
if not warnings: # No warnings were found return for warning in warnings: linenum, offset, msgidInPyCodeStyle, text = warning if text.startswith(msgidInPyCodeStyle): # If the PyCodeStyle code is at the start of the text, trim it out ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_level_from_string(str_level): """ Returns the proper log level core based on a given string :param str_level: Log level string :return: The log level cod...
levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, } try: return levels[str_level.upper()] except KeyError: pass except AttributeError: if str_leve...
<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_config_from_package(package): """ Breaks a package string in module and class. :param package: A package string. :return: A config dict with class and mo...
package_x = package.split('.') package_conf = {} package_conf['class'] = package_x[-1] package_conf['module'] = '.'.join(package_x[:-1][:]) return package_conf
<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_class_from_module(module, class_name): """ Returns a class from a module and a class name parameters. This function is used by get_class_from_config and ...
import importlib module = importlib.import_module(module) return getattr(module, 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 load_yaml_config_file(path): """ Returns the parsed structure from a yaml config file. :param path: Path where the yaml file is located. :return: The yaml co...
result = None with open(path, 'r') as steam: result = yaml.safe_load(steam) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_config(config, config_data): """ Populates config with data from the configuration data dict. It handles components, data, log, management and sessio...
if 'components' in config_data: process_components_config_section(config, config_data['components']) if 'data' in config_data: process_data_config_section(config, config_data['data']) if 'log' in config_data: process_log_config_section(config, config_data['log']) if 'management'...
<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_app_config(config, config_data): """ Populates config with data from the configuration data dict. It handles everything that process_config does plus...
process_config(config, config_data) # If apps is on config data, this is running o multi app mode if 'apps' in config_data: config.app['multi'] = True process_apps_config_session(config, config_data['apps']) else: # If not the app definition is on the firenado config file ...
<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_app_config_section(config, app_config): """ Processes the app section from a configuration data dict. :param config: The config reference of the obje...
if 'addresses' in app_config: config.app['addresses'] = app_config['addresses'] if 'component' in app_config: config.app['component'] = app_config['component'] if 'data' in app_config: if 'sources' in app_config['data']: config.app['data']['sources'] = app_config['data']...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_components_config_section(config, components_config): """ Processes the components section from a configuration data dict. :param config: The config ...
for component_config in components_config: if 'id' not in component_config: raise Exception('The component %s was defined without an id.' % component_config) component_id = component_config['id'] if component_id not in config.components: 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 process_data_config_section(config, data_config): """ Processes the data configuration section from the configuration data dict. :param config: The config re...
if 'connectors' in data_config: for connector in data_config['connectors']: config.data['connectors'][ connector['name']] = get_config_from_package( connector['class']) if 'sources' in data_config: if data_config['sources']: for source in ...
<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_log_config_section(config, log_config): """ Processes the log section from a configuration data dict. :param config: The config reference of the obje...
if 'format' in log_config: config.log['format'] = log_config['format'] if 'level' in log_config: config.log['level'] = log_level_from_string(log_config['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 process_management_config_section(config, management_config): """ Processes the management section from a configuration data dict. :param config: The config ...
if 'commands' in management_config: for command in management_config['commands']: config.management['commands'].append(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 process_session_config_section(config, session_config): """ Processes the session section from the configuration data dict. :param config: The config referen...
# Setting session type as file by default config.session['type'] = 'file' if 'enabled' in session_config: config.session['enabled'] = session_config['enabled'] if 'type' in session_config: config.session['type'] = session_config['type'] if config.session['type'] == 'file': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open(self, db, writeAccess=False): """ Handles simple, SQL specific connection creation. This will not have to manage thread information as it is already ma...
if not pymysql: raise orb.errors.BackendNotFound('psycopg2 is not installed.') # create the python connection try: return pymysql.connect(db=db.name(), user=db.username(), passwd=db.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 run_script(script_path, session, handle_command=None, handle_line=None): """ Run a script file using a valid sqlalchemy session. Based on https://bit.ly/2CTo...
logger.debug("Opening script %s." % script_path) with open(script_path, "r") as stream: sql_command = "" for line in stream: # Ignore commented lines if not line.startswith("--") and line.strip("\n"): # Append line to the command string if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_from_command_line(): """ Run Firenado's management commands from a command line """
for commands_conf in firenado.conf.management['commands']: logger.debug("Loading %s commands from %s." % ( commands_conf['name'], commands_conf['module'] )) exec('import %s' % commands_conf['module']) command_index = 1 for arg in sys.argv[1:]: 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 get_command_header(parser, usage_message="", usage=False): """ Return the command line header :param parser: :param usage_message: :param usage: :return: The...
loader = template.Loader(os.path.join( firenado.conf.ROOT, 'management', 'templates', 'help')) return loader.load("header.txt").generate( parser=parser, usage_message=usage_message, usage=usage, firenado_version=".".join(map(str, firenado.__version__))).decode( sys.stdout.encodi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_command_line_usage(parser, usage=False): """ Show the command line help """
help_header_message = get_command_header(parser, "command", usage) loader = template.Loader(os.path.join( firenado.conf.ROOT, 'management', 'templates', 'help')) command_template = " {0.name:15}{0.description:40}" help_message = loader.load("main_command_help.txt").generate( command_ca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_exists(command): """ Check if the given command was registered. In another words if it exists. """
for category, commands in iteritems(command_categories): for existing_command in commands: if existing_command.match(command): 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 run_command(command, args): """ Run all tasks registered in a command. """
for category, commands in iteritems(command_categories): for existing_command in commands: if existing_command.match(command): existing_command.run(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 check(self, value, namespace): """ See whether the TypeVar is bound for the first time or is met with _exactly_ the same type as previously. That type must a...
return namespace.is_compatible(self.typevar, type(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 check_lines(self, lines, i): """ check lines have less than a maximum number of characters. It ignored lines with long URLs. """
maxChars = self.config.max_line_length for line in lines.splitlines(): if len(line) > maxChars: if 'http://' in line or 'https://' in line: continue self.add_message('C0301', line=i, args=(len(line), maxChars)) i += 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 to_representation(self, obj): """ Represent data for the field. """
many = isinstance(obj, collections.Iterable) \ or isinstance(obj, models.Manager) \ and not isinstance(obj, dict) assert self.serializer is not None \ and issubclass(self.serializer, serializers.ModelSerializer), ( "Bad serializer defined %s" % 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 setRemoveAction(self, action): """ Sets the remove action that should be taken when a model is removed from the collection generated by this reverse lookup. ...
if action not in ('unset', 'delete'): raise orb.errors.ValidationError('The remove action must be either "unset" or "delete"') else: self.__removeAction = action
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, typevar, its_type): """ Binds typevar to the type its_type. Binding occurs on the instance if the typevar is a TypeVar of the generic type of the ...
assert type(typevar) == tg.TypeVar if self.is_generic_in(typevar): self.bind_to_instance(typevar, its_type) else: self._ns[typevar] = its_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 binding_of(self, typevar): """Returns the type the typevar is bound to, or None."""
if typevar in self._ns: return self._ns[typevar] if self._instance_ns and typevar in self._instance_ns: return self._instance_ns[typevar] 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 _checkCopyright(self, text, node): """ Check whether the module has copyright header. @param text: codes of the module @param node: node of the module """
if not re.search(br"%s\s*\n\s*%s" % self.commentsCopyright, text): self.add_message('W9001', node=node)
<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_message(self, msg): """ Manage message of different type and in the context of path. """
if msg.msg_id in self.messagesAllowed: super(LimitedReporter, self).handle_message(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 unregister(self, obj=None): """ Unregisters the object from the system. If None is supplied, then all objects will be unregistered :param obj: <str> or <orb....
if obj is None: self.__databases.clear() self.__schemas.clear() elif isinstance(obj, orb.Schema): self.__schemas.pop(obj.name(), None) elif isinstance(obj, orb.Database): if obj == self.__current_db: self.__current_db = 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 page(self, number, **context): """ Returns the records for the current page, or the specified page number. If a page size is not specified, then this record ...
size = max(0, self.context(**context).pageSize) if not size: return self.copy() else: return self.copy(page=number, pageSize=size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load(self, event): """ Processes a load event by setting the properties of this record to the data restored from the database. :param event: <orb.events.Loa...
if not event.data: return context = self.context() schema = self.schema() dbname = schema.dbname() clean = {} for col, value in event.data.items(): try: model_dbname, col_name = col.split('.') except ValueError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changes(self, columns=None, recurse=True, flags=0, inflated=False): """ Returns a dictionary of changes that have been made to the data from this record. :re...
output = {} is_record = self.isRecord() schema = self.schema() columns = [schema.column(c) for c in columns] if columns else \ schema.columns(recurse=recurse, flags=flags).values() context = self.context(inflated=inflated) with ReadLocker(self.__dataL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context(self, **context): """ Returns the lookup options for this record. This will track the options that were used when looking this record up from the dat...
output = orb.Context(context=self.__context) if self.__context is not None else orb.Context() output.update(context) 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 delete(self, **context): """ Removes this record from the database. If the dryRun \ flag is specified then the command will be logged and \ not executed. :no...
if not self.isRecord(): return 0 event = orb.events.DeleteEvent(record=self, context=self.context(**context)) if self.processEvent(event): self.onDelete(event) if event.preventDefault: return 0 if self.__delayed: self.__delayed ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markLoaded(self, *columns): """ Tells the model to treat the given columns as though they had been loaded from the database. :param columns: (<str>, ..) """
schema = self.schema() columns = {schema.column(col) for col in columns} column_names = {col.name() for col in columns} with WriteLocker(self.__dataLock): for key, (old_value, new_value) in self.__values.items(): if key in column_names: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isRecord(self, db=None): """ Returns whether or not this database table record exists in the database. :return <bool> """
if db is not None: same_db = db == self.context().db if db is None or same_db: col = self.schema().idColumn() with ReadLocker(self.__dataLock): return (col in self.__loaded) and (self.__values[col.name()][0] is not None) else: 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 save(self, values=None, after=None, before=None, **context): """ Commits the current change set information to the database, or inserts this object as a new ...
# specify that this save call should be performed after the save of # another record, useful for chaining events if after is not None: callback = orb.events.Callback(self.save, values=values, **context) after.addCallback(orb.events.PostSaveEvent, callback, record=after, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, values, **context): """ Updates the model with the given dictionary of values. :param values: <dict> :param context: <orb.Context> :return: <int...
schema = self.schema() column_updates = {} other_updates = {} for key, value in values.items(): try: column_updates[schema.column(key)] = value except orb.errors.ColumnNotFound: other_updates[key] = value # update the colu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, columns=None): """ Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is...
schema = self.schema() if not columns: ignore_flags = orb.Column.Flags.Virtual | orb.Column.Flags.ReadOnly columns = schema.columns(flags=~ignore_flags).values() use_indexes = True else: use_indexes = False # validate the column values ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCallback(cls, eventType, func, record=None, once=False): """ Adds a callback method to the class. When an event of the given type is triggered, any regist...
callbacks = cls.callbacks() callbacks.setdefault(eventType, []) callbacks[eventType].append((func, record, once))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callbacks(cls, eventType=None): """ Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <li...
key = '_{0}__callbacks'.format(cls.__name__) try: callbacks = getattr(cls, key) except AttributeError: callbacks = {} setattr(cls, key, callbacks) return callbacks.get(eventType, []) if eventType is not None else callbacks
<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(cls, values, **context): """ Shortcut for creating a new record for this table. :param values | <dict> :return <orb.Table> """
schema = cls.schema() model = cls # check for creating inherited classes from a sub class polymorphic_columns = schema.columns(flags=orb.Column.Flags.Polymorphic) if polymorphic_columns: polymorphic_column = polymorphic_columns.values()[0] schema_name = ...