text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_confirmation_url(email, request, name="email_registration_confirm", **kwargs): """ Returns the confirmation URL """
return request.build_absolute_uri( reverse(name, kwargs={"code": get_confirmation_code(email, request, **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 _retrieve_stack_host_zone_name(awsclient, default_stack_name=None): """ Use service discovery to get the host zone name from the default stack :return: Host ...
global _host_zone_name if _host_zone_name is not None: return _host_zone_name env = get_env() if env is None: print("Please set environment...") # TODO: why is there a sys.exit in library code used by cloudformation!!! sys.exit() if default_stack_name is 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 delete_log_group(awsclient, log_group_name): """Delete the specified log group :param log_group_name: log group name :return: """
client_logs = awsclient.get_client('logs') response = client_logs.delete_log_group( logGroupName=log_group_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 put_retention_policy(awsclient, log_group_name, retention_in_days): """Sets the retention of the specified log group if the log group does not yet exist than...
try: # Note: for AWS Lambda the log_group is created once the first # log event occurs. So if the log_group does not exist we create it create_log_group(awsclient, log_group_name) except GracefulExit: raise except Exception: # TODO check that it is really a ResourceA...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_log_group(awsclient, log_group_name): """Get info on the specified log group :param log_group_name: log group name :return: """
client_logs = awsclient.get_client('logs') request = { 'logGroupNamePrefix': log_group_name, 'limit': 1 } response = client_logs.describe_log_groups(**request) if response['logGroups']: return response['logGroups'][0] else: return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_log_stream(awsclient, log_group_name, log_stream_name): """Get info on the specified log stream :param log_group_name: log group name :param log_str...
client_logs = awsclient.get_client('logs') response = client_logs.describe_log_streams( logGroupName=log_group_name, logStreamNamePrefix=log_stream_name, limit=1 ) if response['logStreams']: return response['logStreams'][0] else: return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_log_group(awsclient, log_group_name): """Creates a log group with the specified name. :param log_group_name: log group name :return: """
client_logs = awsclient.get_client('logs') response = client_logs.create_log_group( logGroupName=log_group_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 create_log_stream(awsclient, log_group_name, log_stream_name): """Creates a log stream for the specified log group. :param log_group_name: log group name :pa...
client_logs = awsclient.get_client('logs') response = client_logs.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_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 put_log_events(awsclient, log_group_name, log_stream_name, log_events, sequence_token=None): """Put log events for the specified log group and stream. :param...
client_logs = awsclient.get_client('logs') request = { 'logGroupName': log_group_name, 'logStreamName': log_stream_name, 'logEvents': log_events } if sequence_token: request['sequenceToken'] = sequence_token response = client_logs.put_log_events(**request) if '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 get_log_events(awsclient, log_group_name, log_stream_name, start_ts=None): """Get log events for the specified log group and stream. this is used in tenkai o...
client_logs = awsclient.get_client('logs') request = { 'logGroupName': log_group_name, 'logStreamName': log_stream_name } if start_ts: request['startTime'] = start_ts # TODO exhaust the events! # TODO use all_pages ! response = client_logs.get_log_events(**request)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self): """Reload the configuration from disk returning True if the configuration has changed from the previous values. """
config = self._default_configuration() if self._file_path: config.update(self._load_config_file()) if config != self._values: self._values = config 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 _load_config_file(self): """Load the configuration file into memory, returning the content. """
LOGGER.info('Loading configuration from %s', self._file_path) if self._file_path.endswith('json'): config = self._load_json_config() else: config = self._load_yaml_config() for key, value in [(k, v) for k, v in config.items()]: if key.title() != 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 _load_json_config(self): """Load the configuration file in JSON format :rtype: dict """
try: return json.loads(self._read_config()) except ValueError as error: raise ValueError( 'Could not read configuration file: {}'.format(error))
<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(self): """Loads the configuration file from a .yaml or .yml file :type: dict """
try: config = self._read_config() except OSError as error: raise ValueError('Could not read configuration file: %s' % error) try: return yaml.safe_load(config) except yaml.YAMLError as error: message = '\n'.join([' > %s' % 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 _normalize_file_path(file_path): """Normalize the file path value. :param str file_path: The file path as passed in :rtype: str """
if not file_path: return None elif file_path.startswith('s3://') or \ file_path.startswith('http://') or \ file_path.startswith('https://'): return file_path return path.abspath(file_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_config(self): """Read the configuration from the various places it may be read from. :rtype: str :raises: ValueError """
if not self._file_path: return None elif self._file_path.startswith('s3://'): return self._read_s3_config() elif self._file_path.startswith('http://') or \ self._file_path.startswith('https://'): return self._read_remote_config() elif ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_remote_config(self): """Read a remote config via URL. :rtype: str :raises: ValueError """
try: import requests except ImportError: requests = None if not requests: raise ValueError( 'Remote config URL specified but requests not installed') result = requests.get(self._file_path) if not result.ok: raise Va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_s3_config(self): """Read in the value of the configuration file in Amazon S3. :rtype: str :raises: ValueError """
try: import boto3 import botocore.exceptions except ImportError: boto3, botocore = None, None if not boto3: raise ValueError( 's3 URL specified for configuration but boto3 not installed') parsed = parse.urlparse(self._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 update(self, configuration, debug=None): """Update the internal configuration values, removing debug_only handlers if debug is False. Returns True if the con...
if self.config != dict(configuration) and debug != self.debug: self.config = dict(configuration) self.debug = debug self.configure() 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 configure(self): """Configure the Python stdlib logger"""
if self.debug is not None and not self.debug: self._remove_debug_handlers() self._remove_debug_only() logging.config.dictConfig(self.config) try: logging.captureWarnings(True) except AttributeError: pass
<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_debug_handlers(self): """Remove any handlers with an attribute of debug_only that is True and remove the references to said handlers from any loggers...
remove = list() for handler in self.config[self.HANDLERS]: if self.config[self.HANDLERS][handler].get('debug_only'): remove.append(handler) for handler in remove: del self.config[self.HANDLERS][handler] for logger in self.config[self.LOGGERS]....
<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_debug_only(self): """Iterate through each handler removing the invalid dictConfig key of debug_only. """
LOGGER.debug('Removing debug only from handlers') for handler in self.config[self.HANDLERS]: if self.DEBUG_ONLY in self.config[self.HANDLERS][handler]: del self.config[self.HANDLERS][handler][self.DEBUG_ONLY]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_dictionary(self): """ Convert this object to a dictionary with formatting appropriate for a PIF. :returns: Dictionary with the content of this object form...
return {to_camel_case(i): Serializable._convert_to_dictionary(self.__dict__[i]) for i in self.__dict__ if self.__dict__[i] 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 _convert_to_dictionary(obj): """ Convert obj to a dictionary with formatting appropriate for a PIF. This function attempts to treat obj as a Pio object and o...
if isinstance(obj, list): return [Serializable._convert_to_dictionary(i) for i in obj] elif hasattr(obj, 'as_dictionary'): return obj.as_dictionary() else: return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_object(class_, obj): """ Helper function that returns an object, or if it is a dictionary, initializes it from class_. :param class_: Class to use to in...
if isinstance(obj, list): return [Serializable._get_object(class_, i) for i in obj] elif isinstance(obj, dict): return class_(**keys_to_snake_case(obj)) else: return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def total_level(source_levels): """ Calculates the total sound pressure level based on multiple source levels """
sums = 0.0 for l in source_levels: if l is None: continue if l == 0: continue sums += pow(10.0, float(l) / 10.0) level = 10.0 * math.log10(sums) return 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 total_rated_level(octave_frequencies): """ Calculates the A-rated total sound pressure level based on octave band frequencies """
sums = 0.0 for band in OCTAVE_BANDS.keys(): if band not in octave_frequencies: continue if octave_frequencies[band] is None: continue if octave_frequencies[band] == 0: continue sums += pow(10.0, ((float(octave_frequencies[band]) + OCTAVE_BANDS...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distant_level(reference_level, distance, reference_distance=1.0): """ Calculates the sound pressure level in dependence of a distance where a perfect ball-sh...
rel_dist = float(reference_distance) / float(distance) level = float(reference_level) + 20.0 * (math.log(rel_dist) / math.log(10)) return 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 distant_total_damped_rated_level( octave_frequencies, distance, temp, relhum, reference_distance=1.0): """ Calculates the damped, A-rated total sound pressur...
damping_distance = distance - reference_distance sums = 0.0 for band in OCTAVE_BANDS.keys(): if band not in octave_frequencies: continue if octave_frequencies[band] is None: continue # distance-adjusted level per band distant_val = distant_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 getLogger(name): """This is used by gcdt plugins to get a logger with the right level."""
logger = logging.getLogger(name) # note: the level might be adjusted via '-v' option logger.setLevel(logging_config['loggers']['gcdt']['level']) return logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keep_session_alive(self): """If the session expired, logs back in."""
try: self.resources() except xmlrpclib.Fault as fault: if fault.faultCode == 5: self.login() else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def help(self): """Prints discovered resources and their associated methods. Nice when noodling in the terminal to wrap your head around Magento's insanity. """
print('Resources:') print('') for name in sorted(self._resources.keys()): methods = sorted(self._resources[name]._methods.keys()) print('{}: {}'.format(bold(name), ', '.join(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 run(self): """Import the controller and run it. This mimics the processing done by :func:`helper.start` when a controller is run in the foreground. A new ins...
segments = self.controller.split('.') controller_class = reduce(getattr, segments[1:], __import__('.'.join(segments[:-1]))) cmd_line = ['-f'] if self.configuration is not None: cmd_line.extend(['-c', self.configuration]) args = parse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info_hash_base32(self): """ Returns the base32 info hash of the torrent. Useful for generating magnet links. .. note:: ``generate()`` must be called first. "...
if getattr(self, '_data', None): return b32encode(sha1(bencode(self._data['info'])).digest()) else: raise exceptions.TorrentNotGeneratedException
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy(awsclient, applicationName, deploymentGroupName, deploymentConfigName, bucket, bundlefile): """Upload bundle and deploy to deployment group. This incl...
etag, version = upload_file_to_s3(awsclient, bucket, _build_bundle_key(applicationName), bundlefile) client_codedeploy = awsclient.get_client('codedeploy') response = client_codedeploy.create_deployment( applicationName=ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_deployment_status(awsclient, deployment_id, iterations=100): """Wait until an deployment is in an steady state and output information. :param deployme...
counter = 0 steady_states = ['Succeeded', 'Failed', 'Stopped'] client_codedeploy = awsclient.get_client('codedeploy') while counter <= iterations: response = client_codedeploy.get_deployment(deploymentId=deployment_id) status = response['deploymentInfo']['status'] if status no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_deployment(awsclient, deployment_id): """stop tenkai deployment. :param awsclient: :param deployment_id: """
log.info('Deployment: %s - stopping active deployment.', deployment_id) client_codedeploy = awsclient.get_client('codedeploy') response = client_codedeploy.stop_deployment( deploymentId=deployment_id, autoRollbackEnabled=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 _list_deployment_instances(awsclient, deployment_id): """list deployment instances. :param awsclient: :param deployment_id: """
client_codedeploy = awsclient.get_client('codedeploy') instances = [] next_token = None # TODO refactor generic exhaust_function from this while True: request = { 'deploymentId': deployment_id } if next_token: request['nextToken'] = next_token ...
<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_deployment_instance_summary(awsclient, deployment_id, instance_id): """instance summary. :param awsclient: :param deployment_id: :param instance_id: ret...
client_codedeploy = awsclient.get_client('codedeploy') request = { 'deploymentId': deployment_id, 'instanceId': instance_id } response = client_codedeploy.get_deployment_instance(**request) return response['instanceSummary']['status'], \ response['instanceSummary']['lifec...
<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_deployment_instance_diagnostics(awsclient, deployment_id, instance_id): """Gets you the diagnostics details for the first 'Failed' event. :param awsclie...
client_codedeploy = awsclient.get_client('codedeploy') request = { 'deploymentId': deployment_id, 'instanceId': instance_id } response = client_codedeploy.get_deployment_instance(**request) # find first 'Failed' event for i, event in enumerate(response['instanceSummary']['lifecy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def directive_SPACE(self, label, params): """ label SPACE num Allocate space on the stack. `num` is the number of bytes to allocate """
# TODO allow equations params = params.strip() try: self.convert_to_integer(params) except ValueError: warnings.warn("Unknown parameters; {}".format(params)) return self.labels[label] = self.space_pointer if params in self.equates: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instance_ik_model_receiver(fn): """ A method decorator that filters out sign_original_specals coming from models that don't have fields that function as Imag...
@wraps(fn) def receiver(self, sender, **kwargs): # print 'inspect.isclass(sender? %s'%(inspect.isclass(sender)) if not inspect.isclass(sender): return for src in self._source_groups: if issubclass(sender, src.model_class): fn(self, sender=sender, ...
<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_source_fields(self, instance): """ Returns a list of the source fields for the given instance. """
return set(src.image_field for src in self._source_groups if isinstance(instance, src.model_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 check_hook_mechanism_is_intact(module): """Check if the hook configuration is absent or has both register AND deregister. :param module: :return: True if val...
result = True if check_register_present(module): result = not result if check_deregister_present(module): result = not result return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfn_viz(template, parameters={}, outputs={}, out=sys.stdout): """Render dot output for cloudformation.template in json format. """
known_sg, open_sg = _analyze_sg(template['Resources']) (graph, edges) = _extract_graph(template.get('Description', ''), template['Resources'], known_sg, open_sg) graph['edges'].extend(edges) _handle_terminals(template, graph, 'Parameters', 'source', parameters) _...
<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(controller_class): """Start the Helper controller either in the foreground or as a daemon process. :param controller_class: The controller class handle...
args = parser.parse() obj = controller_class(args, platform.operating_system()) if args.foreground: try: obj.start() except KeyboardInterrupt: obj.stop() else: try: with platform.Daemon(obj) as daemon: daemon.start() 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 _validate_type(self, name, obj, *args): """ Helper function that checks the input object type against each in a list of classes. This function also allows th...
if obj is None: return for arg in args: if isinstance(obj, arg): return raise TypeError(self.__class__.__name__ + '.' + name + ' is of type ' + type(obj).__name__ + '. Must be equal to None or one of the following types: ' + str(ar...
<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_list_type(self, name, obj, *args): """ Helper function that checks the input object type against each in a list of classes, or if the input object ...
if obj is None: return if isinstance(obj, list): for i in obj: self._validate_type_not_null(name, i, *args) else: self._validate_type(name, obj, *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 _validate_nested_list_type(self, name, obj, nested_level, *args): """ Helper function that checks the input object as a list then recursively until nested_le...
if nested_level <= 1: self._validate_list_type(name, obj, *args) else: if obj is None: return if not isinstance(obj, list): raise TypeError(self.__class__.__name__ + '.' + name + ' contains value of 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 get_version(version): """ Returns a PEP 440-compliant version number from VERSION. Created by modifying django.utils.version.get_version """
# Now build the two parts of the version number: # major = X.Y[.Z] # sub = .devN - for development releases # | {a|b|rc}N - for alpha, beta and rc releases # | .postN - for post-release releases assert len(version) == 5 version_parts = version[:2] if version[2] == 0 else version[...
<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_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. ...
repo_dir = os.path.dirname(os.path.abspath(__file__)) git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True) timestamp = git_lo...
<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_cloudformation_template(path=None): """Load cloudformation template from path. :param path: Absolute or relative path of cloudformation template. Defaul...
if not path: path = os.path.abspath('cloudformation.py') else: path = os.path.abspath(path) if isinstance(path, six.string_types): try: sp = sys.path # temporarily add folder to allow relative path sys.path.append(os.path.abspath(os.path.dirname(p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parameter_diff(awsclient, config): """get differences between local config and currently active config """
client_cf = awsclient.get_client('cloudformation') try: stack_name = config['stack']['StackName'] if stack_name: response = client_cf.describe_stacks(StackName=stack_name) if response['Stacks']: stack_id = response['Stacks'][0]['StackId'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_pre_hook(awsclient, cloudformation): """Invoke the pre_hook BEFORE the config is read. :param awsclient: :param cloudformation: """
# TODO: this is deprecated!! move this to glomex_config_reader # no config available if not hasattr(cloudformation, 'pre_hook'): # hook is not present return hook_func = getattr(cloudformation, 'pre_hook') if not hook_func.func_code.co_argcount: hook_func() # for compatibil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_stack(awsclient, context, conf, cloudformation, override_stack_policy=False): """Deploy the stack to AWS cloud. Does either create or update the stack...
stack_name = _get_stack_name(conf) parameters = _generate_parameters(conf) if stack_exists(awsclient, stack_name): exit_code = _update_stack(awsclient, context, conf, cloudformation, parameters, override_stack_policy) else: exit_code = _create_stack(aws...
<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_stack(awsclient, conf, feedback=True): """Delete the stack from AWS cloud. :param awsclient: :param conf: :param feedback: print out stack events (def...
client_cf = awsclient.get_client('cloudformation') stack_name = _get_stack_name(conf) last_event = _get_stack_events_last_timestamp(awsclient, stack_name) request = {} dict_selective_merge(request, conf['stack'], ['StackName', 'RoleARN']) response = client_cf.delete_stack(**request) if f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_stacks(awsclient): """Print out the list of stacks deployed at AWS cloud. :param awsclient: :return: """
client_cf = awsclient.get_client('cloudformation') response = client_cf.list_stacks( StackStatusFilter=[ 'CREATE_IN_PROGRESS', 'CREATE_COMPLETE', 'ROLLBACK_IN_PROGRESS', 'ROLLBACK_COMPLETE', 'DELETE_IN_PROGRESS', 'DELETE_FAILED', 'UPDATE_IN_PROGRESS', 'UPDATE_COMPLET...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_change_set(awsclient, change_set_name, stack_name): """Print out the change_set to console. This needs to run create_change_set first. :param awscli...
client = awsclient.get_client('cloudformation') status = None while status not in ['CREATE_COMPLETE', 'FAILED']: response = client.describe_change_set( ChangeSetName=change_set_name, StackName=stack_name) status = response['Status'] # print('##### %s' % stat...
<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_change_set(awsclient, change_set_name, stack_name): """Delete specified change set. Currently we only use this during automated regression testing. Bu...
client = awsclient.get_client('cloudformation') response = client.delete_change_set( ChangeSetName=change_set_name, StackName=stack_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 write_template_to_file(conf, template_body): """Writes the template to disk """
template_file_name = _get_stack_name(conf) + '-generated-cf-template.json' with open(template_file_name, 'w') as opened_file: opened_file.write(template_body) print('wrote cf-template for %s to disk: %s' % ( get_env(), template_file_name)) return template_file_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 info(awsclient, config, format=None): """ collect info and output to console :param awsclient: :param config: :param json: True / False to use json format as...
if format is None: format = 'tabular' stack_name = _get_stack_name(config) client_cfn = awsclient.get_client('cloudformation') resources = all_pages( client_cfn.list_stack_resources, {'StackName': stack_name}, lambda x: [(r['ResourceType'], r['LogicalResourceId'], r['Re...
<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_queryset(self, request): """Shows one entry per distinct metric name"""
queryset = super(MetricGroupAdmin, self).get_queryset(request) # poor-man's DISTINCT ON for Sqlite3 qs_values = queryset.values('id', 'name') # 2.7+ only :( # = {metric['name']: metric['id'] for metric in qs_values} distinct_names = {} for metric in qs_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 save_model(self, request, obj, form, change): """Updates all metrics with the same name"""
like_metrics = self.model.objects.filter(name=obj.name) # 2.7+ only :( # = {key: form.cleaned_data[key] for key in form.changed_data} updates = {} for key in form.changed_data: updates[key] = form.cleaned_data[key] like_metrics.update(**updates)
<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_lines(self, code): """ Return a list of the parsed code For each line, return a three-tuple containing: 1. The label 2. The instruction 3. Any argument...
remove_comments = re.compile(r'^([^;@\n]*);?.*$', re.MULTILINE) code = '\n'.join(remove_comments.findall(code)) # TODO can probably do this better # TODO labels with spaces between pipes is allowed `|label with space| INST OPER` parser = re.compile(r'^(\S*)?[\s]*(\S*)([^\n]*)$', re.MUL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rule_low_registers(self, arg): """Low registers are R0 - R7"""
r_num = self.check_register(arg) if r_num > 7: raise iarm.exceptions.RuleError( "Register {} is not a low register".format(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 get_two_parameters(self, regex_exp, parameters): """ Get two parameters from a given regex expression Raise an exception if more than two were found :param r...
Rx, Ry, other = self.get_parameters(regex_exp, parameters) if other is not None and other.strip(): raise iarm.exceptions.ParsingError("Extra arguments found: {}".format(other)) if Rx and Ry: return Rx.upper(), Ry.upper() elif not Rx: raise iarm.except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rule_special_registers(self, arg): """Raises an exception if the register is not a special register"""
# TODO is PSR supposed to be here? special_registers = "PSR APSR IPSR EPSR PRIMASK FAULTMASK BASEPRI CONTROL" if arg not in special_registers.split(): raise iarm.exceptions.RuleError("{} is not a special register; Must be [{}]".format(arg, special_registers))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version(): """Output version of gcdt tools and plugins."""
log.info('gcdt version %s' % __version__) tools = get_plugin_versions('gcdttool10') if tools: log.info('gcdt tools:') for p, v in tools.items(): log.info(' * %s version %s' % (p, v)) log.info('gcdt plugins:') for p, v in get_plugin_versions().items(): log.info(' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retries(max_tries, delay=1, backoff=2, exceptions=(Exception,), hook=None): """Function decorator implementing retrying logic. delay: Sleep this many seconds...
""" def example_hook(tries_remaining, exception, delay): '''Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised. ''' print >> sys.stderr, "Caught '%s', %d tries remain...
<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_context(awsclient, env, tool, command, arguments=None): """This assembles the tool context. Private members are preceded by a '_'. :param tool: :param co...
# TODO: elapsed, artifact(stack, depl-grp, lambda, api) if arguments is None: arguments = {} context = { '_awsclient': awsclient, 'env': env, 'tool': tool, 'command': command, '_arguments': arguments, # TODO clean up arguments -> args 'version': __ve...
<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(arguments): """Extract the first argument from arguments parsed by docopt. :param arguments parsed by docopt: :return: command """
return [k for k, v in arguments.items() if not k.startswith('-') and v is True][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 check_gcdt_update(): """Check whether a newer gcdt is available and output a warning. """
try: inst_version, latest_version = get_package_versions('gcdt') if inst_version < latest_version: log.warn('Please consider an update to gcdt version: %s' % latest_version) except GracefulExit: raise except Exception: log.warn('P...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_selective_merge(a, b, selection, path=None): """Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selectio...
if path is None: path = [] for key in b: if key in selection: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): dict_selective_merge(a[key], b[key], b[key].keys(), path + [str(key)]) elif a[key] != b[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 are_credentials_still_valid(awsclient): """Check whether the credentials have expired. :param awsclient: :return: exit_code """
client = awsclient.get_client('lambda') try: client.list_functions() except GracefulExit: raise except Exception as e: log.debug(e) log.error(e) return 1 return 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 flatten(lis): """Given a list, possibly nested to any level, return it flattened."""
new_lis = [] for item in lis: if isinstance(item, collections.Sequence) and not isinstance(item, basestring): new_lis.extend(flatten(item)) else: new_lis.append(item) return new_lis
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_string(length=6): """Create a random 6 character string. note: in case you use this function in a test during test together with an awsclient then thi...
return ''.join([random.choice(string.ascii_lowercase) for i in range(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_template(): """Bail out if template is not found. """
cloudformation, found = load_cloudformation_template() if not found: print(colored.red('could not load cloudformation.py, bailing out...')) sys.exit(1) return cloudformation
<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_argument_parser(): """Creates the argument parser for haas. """
parser = argparse.ArgumentParser(prog='haas') parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(haas.__version__)) verbosity = parser.add_mutually_exclusive_group() verbosity.add_argument('-v', '--verbose', action='store_const', default=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 run(self, plugin_manager=None): """Run the haas test runner. This will load and configure the selected plugins, set up the environment and begin test discove...
if plugin_manager is None: plugin_manager = PluginManager() plugin_manager.add_plugin_arguments(self.parser) args = self.parser.parse_args(self.argv[1:]) environment_plugins = plugin_manager.get_enabled_hook_plugins( plugin_manager.ENVIRONMENT_HOOK, 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 cache_request_user(user_cls, request, user_id): """ Helper function to cache currently logged in user. User is cached at `request._user`. Caching happens onl...
pk_field = user_cls.pk_field() user = getattr(request, '_user', None) if user is None or getattr(user, pk_field, None) != user_id: request._user = user_cls.get_item(**{pk_field: user_id})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_authuser_by_userid(cls, request): """ Get user by ID. Used by Ticket-based auth. Is added as request method to populate `request.user`. """
userid = authenticated_userid(request) if userid: cache_request_user(cls, request, userid) return request._user
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_authuser_by_name(cls, request): """ Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. """
username = authenticated_userid(request) if username: return cls.get_item(username=username)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def includeme(config): """ Set up event subscribers. """
from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=AuthUserMixin, field='username') add_proc([lower_strip], model=AuthUserMixin, 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 _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthed...
if self.blocked_until is not None and \ datetime.datetime.utcnow() < self.blocked_until: raise SlackError("Too many requests - wait until {0}" \ .format(self.blocked_until)) url = "%s/%s" % (SlackClient.BASE_URL, method) params['token'] = self.to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channels_list(self, exclude_archived=True, **params): """channels.list This method returns a list of all channels in the team. This includes channels the cal...
method = 'channels.list' params.update({'exclude_archived': exclude_archived and 1 or 0}) return self._make_request(method, 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 channel_name_to_id(self, channel_name, force_lookup=False): """Helper name for getting a channel's id from its name """
if force_lookup or not self.channel_name_id_map: channels = self.channels_list()['channels'] self.channel_name_id_map = {channel['name']: channel['id'] for channel in channels} channel = channel_name.startswith('#') and channel_name[1:] or channel_name return self.channe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessag...
method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, }) return self._make_request(method, 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 chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containi...
method = 'chat.update' if self._channel_is_name(channel): # chat.update only takes channel ids (not channel names) channel = self.channel_name_to_id(channel) params.update({ 'channel': channel, 'text': text, 'ts': timestamp, })...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def includeme(config): """ Connect view to route that catches all URIs like """
root = config.get_root_resource() root.add('nef_polymorphic', '{collections:.+,.+}', view=PolymorphicESView, factory=PolymorphicACL)
<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_collections(self): """ Get names of collections from request matchdict. :return: Names of collections :rtype: list of str """
collections = self.request.matchdict['collections'].split('/')[0] collections = [coll.strip() for coll in collections.split(',')] return set(collections)
<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_least_permissions_aces(self, resources): """ Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, u...
factories = [res.view._factory for res in resources] contexts = [factory(self.request) for factory in factories] for ctx in contexts: if not self.request.has_permission('view', ctx): return else: return [ (Allow, principal, 'view')...
<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_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. ""...
acl = [(Allow, 'g:admin', ALL_PERMISSIONS)] collections = self.get_collections() resources = self.get_resources(collections) aces = self._get_least_permissions_aces(resources) if aces is not None: for ace in aces: acl.append(ace) acl.append(DE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its ...
from nefertari.elasticsearch import ES collections = self.get_collections() resources = self.get_resources(collections) models = set([res.view.Model for res in resources]) es_models = [mdl for mdl in models if mdl and getattr(mdl, '_index_enabled', False)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command(domain_name, command_name): """Returns a closure function that dispatches message to the WebSocket."""
def send_command(self, **kwargs): return self.ws.send_message( '{0}.{1}'.format(domain_name, command_name), kwargs ) return send_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 DomainFactory(domain_name, cmds): """Dynamically create Domain class and set it's methods."""
klass = type(str(domain_name), (BaseDomain,), {}) for c in cmds: command = get_command(domain_name, c['name']) setattr(klass, c['name'], classmethod(command)) return klass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """The entrypoint for the hairball command installed via setup.py."""
description = ('PATH can be either the path to a scratch file, or a ' 'directory containing scratch files. Multiple PATH ' 'arguments can be provided.') parser = OptionParser(usage='%prog -p PLUGIN_NAME [options] PATH...', description=description,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key_to_path(self, key): """Return the fullpath to the file with sha1sum key."""
return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
<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, filename): """Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. """
# Compute sha1 hash (key) with open(filename) as fp: key = sha1(fp.read()).hexdigest() path = self.key_to_path(key) # Return the cached file if available if key in self.hashes: try: with open(path) as fp: return cPickle...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hairball_files(self, paths, extensions): """Yield filepath to files with the proper extension within paths."""
def add_file(filename): return os.path.splitext(filename)[1] in extensions while paths: arg_path = paths.pop(0) if os.path.isdir(arg_path): found = False for path, dirs, files in os.walk(arg_path): dirs.sort() # T...
<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_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """
for plugin_name in self.options.plugin: parts = plugin_name.split('.') if len(parts) > 1: module_name = '.'.join(parts[:-1]) class_name = parts[-1] else: # Use the titlecase format of the module name as the class name ...