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 process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the ...
for filename in self.hairball_files(self.paths, self.extensions): if not self.options.quiet: print(filename) try: if self.cache: scratch = self.cache.load(filename) else: scratch = kurt.Project.load(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maybe_dotted(module, throw=True): """ If ``module`` is a dotted string pointing to the module, imports and returns the module object. """
try: return Configurator().maybe_dotted(module) except ImportError as e: err = '%s not found. %s' % (module, e) if throw: raise ImportError(err) else: log.error(err) 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 issequence(arg): """Return True if `arg` acts as a list and does not look like a string."""
string_behaviour = ( isinstance(arg, six.string_types) or isinstance(arg, six.text_type)) list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__') return not string_behaviour and list_behaviour
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop_reserved_params(params): """ Drops reserved params """
from nefertari import RESERVED_PARAMS params = params.copy() for reserved_param in RESERVED_PARAMS: if reserved_param in params: params.pop(reserved_param) return params
<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_results(tmp_): """Return a 3 tuple for something."""
# TODO: Fix this to work with more meaningful names if tmp_['t'] > 0: if tmp_['l'] > 0: if tmp_['rr'] > 0 or tmp_['ra'] > 1: print 1, 3, tmp_ return 3 elif tmp_['cr'] > 0 or tmp_['ca'] > 1: print 2, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_animation(self, last, last_level, gen): """Internal helper function to check the animation."""
tmp_ = Counter() results = Counter() name, level, block = last, last_level, last others = False while name in self.ANIMATION and level >= last_level: if name in self.LOOP: if block != last: count = self.check_results(tmp_) ...
<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(self, scratch, **kwargs): """Run and return the results from the Animation plugin."""
results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' level = None while name != '': if name in self.ANIMATION: gen, count = self._check_animation(name, 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 get_receive(self, script_list): """Return a list of received events contained in script_list."""
events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() events[event].add(script) return events
<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(self, scratch, **kwargs): """Run and return the results from the BroadcastReceive plugin."""
all_scripts = list(self.iter_scripts(scratch)) results = defaultdict(set) broadcast = dict((x, self.get_broadcast_events(x)) # Events by script for x in all_scripts) correct = self.get_receive(all_scripts) results['never broadcast'] = set(correct.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 analyze(self, scratch, **kwargs): """Categorize instances of attempted say and sound synchronization."""
errors = Counter() for script in self.iter_scripts(scratch): prev_name, prev_depth, prev_block = '', 0, script.blocks[0] gen = self.iter_blocks(script.blocks) for name, depth, block in gen: if prev_depth == depth: if prev_name in s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self, gen): """Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play...
retval = Counter() name, _, block = next(gen, ('', 0, '')) if name in self.SAY_THINK: if self.is_blank(block.args[0]): retval[self.CORRECT] += 1 else: name, _, block = next(gen, ('', 0, '')) if name == 'play sound %s until ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """
if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_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 _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """
if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(ST...
<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_result_handler(self, handler): """Register a new result handler. """
self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = 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 addError(self, test, exception): """Register that a test ended in an error. Parameters test : unittest.TestCase The test that has completed. exception : tupl...
result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.errors.append(result) self._mirror_output = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters test : unittest.TestCase The test that has completed. exception :...
result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) self.failures.append(result) self._mirror_output = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSkip(self, test, reason): """Register that a test that was skipped. Parameters test : unittest.TestCase The test that has completed. reason : str The reas...
result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(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 addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters test : unittest.TestCase The test that ha...
result = self._handle_result( test, TestCompletionStatus.expected_failure, exception=exception) self.expectedFailures.append(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 addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters test : unittest.TestCase The test that has completed. """
result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master...
if encrypted_key: try: new_key = bytes.fromhex(encrypted_key) if len(self.terminal_key) != len(new_key): # The keys must have equal length return False self.terminal_key = self.tmk_cipher.decrypt(new_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_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """
if not self.terminal_key: print('Terminal key is not set') return '' if self.pinblock_format == '01': try: pinblock = bytes.fromhex(get_pinblock(clear_pin, card_number)) #print('PIN block: {}'.format(raw2str(pinblock))) 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 is_url(string, allowed_schemes=None): """ Check if a string is a valid url. :param string: String to check. :return: True if url, false otherwise :rtype: boo...
if not is_full_string(string): return False valid = bool(URL_RE.search(string)) if allowed_schemes: return valid and any([string.startswith(s) for s in allowed_schemes]) return valid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, oth...
if not is_full_string(string): return False if card_type: if card_type not in CREDIT_CARDS: raise KeyError( 'Invalid card type "{}". Valid types are: {}'.format(card_type, ', '.join(CREDIT_CARDS.keys())) ) return bool(CREDIT_CARDS[card_type].searc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool...
if not is_full_string(string): return False if bool(JSON_WRAPPER_RE.search(string)): try: return isinstance(json.loads(string), dict) except (TypeError, ValueError, OverflowError): return False 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 is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug....
if not is_full_string(string): return False rex = r'^([a-z\d]+' + re.escape(sign) + r'?)*[a-z\d]$' return re.match(rex, string) is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str "...
s = sorted(string) # turn the string into a list of chars random.shuffle(s) # shuffle the list return ''.join(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :par...
r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', 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 parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.Noteb...
link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname(env.doc2path(env.docname)) abs_path = os.path.normpath(os.path.join(source_dir, link['path'])) path = utils.relative_path(None, abs_path) path = nodes.reprunicode(path) docu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """Output the duplicate scripts detected."""
if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
<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(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. ""...
scripts_set = set() for script in self.iter_scripts(scratch): if script[0].type.text == 'define %s': continue # Ignore user defined scripts blocks_list = [] for name, _, _ in self.iter_blocks(script.blocks): blocks_list.append(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 _set_content_type(self, system): """ Set response content type """
request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'application/json'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_response(self, value, system): """ Render a response """
view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
<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_common_kwargs(self, system): """ Get kwargs common for all methods. """
enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request'], 'encoder': enc_class, }
<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_create_update_kwargs(self, value, common_kw): """ Get kwargs common to create, update, replace. """
kw = common_kw.copy() kw['body'] = value if '_self' in value: kw['headers'] = [('Location', value['_self'])] return kw
<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_response(self, value, system): """ Handle response rendering. Calls mixin methods according to request.action value. """
super_call = super(DefaultResponseRendererMixin, self)._render_response try: method_name = 'render_{}'.format(system['request'].action) except (KeyError, AttributeError): return super_call(value, system) method = getattr(self, method_name, None) if method...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remember(self, request, username, **kw): """ Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header. """
if self.credentials_callback: token = self.credentials_callback(username, request) api_key = 'ApiKey {}:{}'.format(username, token) return [('WWW-Authenticate', 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 _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """
authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except ValueError: # not enough values to unpack return None if authmeth.lower() != 'apikey': ...
<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_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing...
request = view_obj.request view_method = getattr(view_obj, request.action) do_trigger = not ( getattr(view_method, '_silent', False) or getattr(view_obj, '_silent', False)) if do_trigger: event_kwargs = { 'view': view_obj, 'model': view_obj.Model, ...
<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_event_cls(view_obj, events_map): """ Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map...
request = view_obj.request view_method = getattr(view_obj, request.action) event_action = ( getattr(view_method, '_event_action', None) or request.action) return events_map[event_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 subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :pa...
kwargs = {} if model is not None: kwargs['model'] = model for evt in events: config.add_subscriber(subscriber, evt, **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 add_field_processors(config, processors, model, field): """ Add processors for model field. Under the hood, regular nefertari event subscribed is created whi...
before_change_events = ( BeforeCreate, BeforeUpdate, BeforeReplace, BeforeUpdateMany, BeforeRegister, ) def wrapper(event, _processors=processors, _field=field): proc_kw = { 'new_value': event.field.new_value, 'instance': event.instan...
<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_field_value(self, field_name, value): """ Set value of request field named `field_name`. Use this method to apply changes to object which is affected by ...
self.view._json_params[field_name] = value if field_name in self.fields: self.fields[field_name].new_value = value return fields = FieldData.from_dict({field_name: value}, self.model) self.fields.update(fields)
<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_field_value(self, field_name, value): """ Set value of response field named `field_name`. If response contains single item, its field is set. If response...
if self.response is None: return if 'data' in self.response: items = self.response['data'] else: items = [self.response] for item in items: item[field_name] = 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 process_fields_param(fields): """ Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value i...
if not fields: return fields if isinstance(fields, six.string_types): fields = split_strip(fields) if '_type' not in fields: fields.append('_type') return { '_source_include': fields, '_source': True, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _catch_index_error(self, response): """ Catch and raise index errors which are not critical and thus not raised by elasticsearch-py. """
code, headers, raw_data = response if not raw_data: return data = json.loads(raw_data) if not data or not data.get('errors'): return try: error_dict = data['items'][0]['index'] message = error_dict['error'] except (KeyError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup...
if getattr(cls, '_mappings_setup', False) and not force: log.debug('ES mappings have been already set up for currently ' 'running application. Call `setup_mappings` with ' '`force=True` to perform mappings set up again.') return log.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_chunks(self, documents, operation): """ Apply `operation` to chunks of `documents` of size `self.chunk_size`. """
chunk_size = self.chunk_size start = end = 0 count = len(documents) while count: if count < chunk_size: chunk_size = count end += chunk_size bulk = documents[start:end] operation(documents_actions=bulk) 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 index_missing_documents(self, documents, request=None): """ Index documents that are missing from ES index. Determines which documents are missing using ES `...
log.info('Trying to index documents of type `{}` missing from ' '`{}` index'.format(self.doc_type, self.index_name)) if not documents: log.info('No documents to index') return query_kwargs = dict( index=self.index_name, doc_type=s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version(path="src/devpy/__init__.py"): """ Return the version of by with regex intead of importing it"""
init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(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 add_plugin_arguments(self, parser): """Add plugin arguments to argument parser. Parameters parser : argparse.ArgumentParser The main haas ArgumentParser. """
for manager in self.hook_managers.values(): if len(list(manager)) == 0: continue manager.map(self._add_hook_extension_arguments, parser) for namespace, manager in self.driver_managers.items(): choices = list(sorted(manager.names())) if len...
<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_enabled_hook_plugins(self, hook, args, **kwargs): """Get enabled plugins for specified hook name. """
manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_hook_plugin, args, **kwargs) if plugin is not None ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """
option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = self.driver_managers[namespace][driver_name] return driver_extension.plugin.from_args( parsed_args, dest_prefi...
<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_amount(self, amount): """ Set transaction amount """
if amount: try: self.IsoMessage.FieldData(4, int(amount)) except ValueError: self.IsoMessage.FieldData(4, 0) self.rebuild()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """Output the aggregate block count results."""
for name, count in sorted(self.blocks.items(), key=lambda x: x[1]): print('{:3} {}'.format(count, name)) print('{:3} total'.format(sum(self.blocks.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 analyze(self, scratch, **kwargs): """Run and return the results from the BlockCounts plugin."""
file_blocks = Counter() for script in self.iter_scripts(scratch): for name, _, _ in self.iter_blocks(script.blocks): file_blocks[name] += 1 self.blocks.update(file_blocks) # Update the overall count return {'types': file_blocks}
<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(self, scratch, **kwargs): """Run and return the results form the DeadCode plugin. The variable_event indicates that the Scratch file contains at leas...
self.total_instances += 1 sprites = {} for sprite, script in self.iter_sprite_scripts(scratch): if not script.reachable: sprites.setdefault(sprite, []).append(script) if sprites: self.dead_code_instances += 1 import pprint ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """Output the number of instances that contained dead code."""
if self.total_instances > 1: print('{} of {} instances contained dead code.' .format(self.dead_code_instances, self.total_instances))
<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_help(name): """ Show help and basic usage """
print('Usage: python3 {} [OPTIONS]... '.format(name)) print('ISO8583 message client') print(' -v, --verbose\t\tRun transactions verbosely') print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default') print(' -s, --server=[IP]\t\tIP of the ISO host to connect to, 127.0.0.1 by 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 find_top_level_directory(start_directory): """Finds the top-level directory of a project given a start directory inside the project. Parameters start_directo...
top_level = start_directory while os.path.isfile(os.path.join(top_level, '__init__.py')): top_level = os.path.dirname(top_level) if top_level == os.path.dirname(top_level): raise ValueError("Can't find top level directory") return os.path.abspath(top_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 discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ...
logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(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 discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if ...
# If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters module : module The impo...
# Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters start_directory ...
start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, patte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters start_filepath : str The module file in ...
start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%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 _set_options_headers(self, methods): """ Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Argument...
request = self.request response = request.response response.headers['Allow'] = ', '.join(sorted(methods)) if 'Access-Control-Request-Method' in request.headers: response.headers['Access-Control-Allow-Methods'] = \ ', '.join(sorted(methods)) if 'Acc...
<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_handled_methods(self, actions_map): """ Get names of HTTP methods that can be used at requested URI. Arguments: :actions_map: Map of actions. Must have ...
methods = ('OPTIONS',) defined_actions = [] for action_name in actions_map.keys(): view_method = getattr(self, action_name, None) method_exists = view_method is not None method_defined = view_method != self.not_allowed_action if method_exists and...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def item_options(self, **kwargs): """ Handle collection OPTIONS request. Singular route requests are handled a bit differently because singular views may handle ...
actions = self._item_actions.copy() if self._resource.is_singular: actions['create'] = ('POST',) methods = self._get_handled_methods(actions) return self._set_options_headers(methods)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collection_options(self, **kwargs): """ Handle collection item OPTIONS request. """
methods = self._get_handled_methods(self._collection_actions) return self._set_options_headers(methods)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop_aggregations_params(self): """ Pop and return aggregation params from query string params. Aggregation params are expected to be prefixed(nested under) b...
from nefertari.view import BaseView self._query_params = BaseView.convert_dotted(self.view._query_params) for key in self._aggregations_keys: if key in self._query_params: return self._query_params.pop(key) else: raise KeyError('Missing aggregati...
<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_aggregations_fields(cls, params): """ Recursively get values under the 'field' key. Is used to get names of fields on which aggregations should be perfor...
fields = [] for key, val in params.items(): if isinstance(val, dict): fields += cls.get_aggregations_fields(val) if key == 'field': fields.append(val) return fields
<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_aggregations_privacy(self, aggregations_params): """ Check per-field privacy rules in aggregations. Privacy is checked by making sure user has access t...
fields = self.get_aggregations_fields(aggregations_params) fields_dict = dictset.fromkeys(fields) fields_dict['_type'] = self.view.Model.__name__ try: validate_data_privacy(self.view.request, fields_dict) except wrappers.ValidationError as ex: raise JHTT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate(self): """ Perform aggregation and return response. """
from nefertari.elasticsearch import ES aggregations_params = self.pop_aggregations_params() if self.view._auth_enabled: self.check_aggregations_privacy(aggregations_params) self.stub_wrappers() return ES(self.view.Model.__name__).aggregate( _aggregations...
<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_random_hex(length): """ Return random hex string of a given length """
if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0: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 load_case(self, testcase): """Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters testcase : type A subclass ...
tests = [self.load_test(testcase, name) for name in self.find_test_method_names(testcase)] return self.create_suite(tests)
<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_module(self, module): """Create and return a test suite containing all cases loaded from the provided module. Parameters module : module A module object...
cases = self.get_test_cases_from_module(module) suites = [self.load_case(case) for case in cases] return self.create_suite(suites)
<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, field, Value = None): ''' Add field to bitmap ''' if Value == None: try: return self.__Bitmap[field] except KeyError: return None elif Value == 1 or Value == 0: self.__Bitmap[field] = 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 FieldData(self, field, Value = None): ''' Add field data ''' if Value == None: try: return self.__FieldData[field] except KeyError: return None else: if len(str(Value)) > self.__IsoSpec.MaxLength(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 authenticated_userid(request): """Helper function that can be used in ``db_key`` to support `self` as a collection key. """
user = getattr(request, 'user', None) key = user.pk_field() return getattr(user, 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 iter_blocks(block_list): """A generator for blocks contained in a block list. Yields tuples containing the block name, the depth that the block was found at,...
# queue the block and the depth of the block queue = [(block, 0) for block in block_list if isinstance(block, kurt.Block)] while queue: block, depth = queue.pop(0) assert block.type.text yield block.type.text, depth, block for arg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def script_start_type(script): """Return the type of block the script begins with."""
if script[0].type.text == 'when @greenFlag clicked': return HairballPlugin.HAT_GREEN_FLAG elif script[0].type.text == 'when I receive %s': return HairballPlugin.HAT_WHEN_I_RECEIVE elif script[0].type.text == 'when this sprite clicked': return HairballPlugin.H...
<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_broadcast_events(cls, script): """Return a Counter of event-names that were broadcast. The Count will contain the key True if any of the broadcast blocks...
events = Counter() for name, _, block in cls.iter_blocks(script): if 'broadcast %s' in name: if isinstance(block.args[0], kurt.Block): events[True] += 1 else: events[block.args[0].lower()] += 1 return events
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag_reachable_scripts(cls, scratch): """Tag each script with attribute reachable. The reachable attribute will be set false for any script that does not begi...
if getattr(scratch, 'hairball_prepared', False): # Only process once return reachable = set() untriggered_events = {} # Initial pass to find reachable and potentially reachable scripts for script in cls.iter_scripts(scratch): if not isinstance(script, k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def description(self): """Attribute that returns the plugin description from its docstring."""
lines = [] for line in self.__doc__.split('\n')[2:]: line = line.strip() if line: lines.append(line) return ' '.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 _process(self, scratch, filename, **kwargs): """Internal hook that marks reachable scripts before calling analyze. Returns data exactly as returned by the an...
self.tag_reachable_scripts(scratch) return self.analyze(scratch, filename=filename, **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 _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys wi...
formats = {} formats['blk'] = ["blank"] formats['dft'] = ["default"] formats['hdr'] = ["header"] formats['hlp'] = ["help"] formats['msg'] = ["message"] formats['shw'] = ["show"] formats['vld'] = ["valid"] @wraps(func) def inner(*args, **kwargs): for k in formats.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 show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) ...
global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) 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 run_func(entry): """Runs the function associated with the given MenuEntry."""
if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(**entry.krgs) return entry.func()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append....
if not menu: menu = Menu(*args, **kwargs) for s in strs: menu.enum(s) return menu
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. O...
global _AUTO def print_help(): lst = [v for v in vld if not callable(v)] if blk: lst.remove("") for v in vld: if not callable(v): continue if int == v: lst.append("<int>") elif float == v: ls...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no."""
yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+no) in yes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer."""
vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float."""
vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string."""
vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_captcha(length=4): """Prompts the user for a random string."""
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=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 clear(): """Clears the console."""
if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function t...
def decor(func): @wraps(func) def wrapper(*args, **krgs): echo("[!] " + msg, end=" ", flush=True) result = func(*args, **krgs) echo(fin, flush=True) return result return wrapper fin = kwargs.pop('fin', "DONE.") args = list(args) 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 fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg."""
# NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FATAL] " + msg, **kwargs) if pause_before_exit: pause() sys.exit(exitcode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string."""
width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def title(msg): """Sets the title of the console window."""
if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(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 wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qp...
with Wrap(**kwargs): if callable(item): args = args or [] krgs = krgs or {} item(*args, **krgs) else: echo(item)