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 _longest_val_in_column(self, col): """ get size of longest value in specific column :param col: str, column name :return int """
try: # +2 is for implicit separator return max([len(x[col]) for x in self.table if x[col]]) + 2 except KeyError: logger.error("there is no column %r", col) 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 _init(self): """ initialize all values based on provided input :return: None """
self.col_count = len(self.col_list) # list of lengths of longest entries in columns self.col_longest = self.get_all_longest_col_lengths() self.data_length = sum(self.col_longest.values()) if self.terminal_width > 0: # free space is space which should be equeally dis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _count_sizes(self): """ count all values needed to display whole table <> HEADER | HEADER2 | HEADER3 <> kudos to PostgreSQL developers :return: None """
format_list = [] header_sepa_format_list = [] # actual widths of columns self.col_widths = {} for col in self.col_list: col_length = self.col_longest[col] col_width = col_length + self._separate() # -2 is for implicit separator -- spaces arou...
<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_all_longest_col_lengths(self): """ iterate over all columns and get their longest values :return: dict, {"column_name": 132} """
response = {} for col in self.col_list: response[col] = self._longest_val_in_column(col) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _separate(self): """ get a width of separator for current column :return: int """
if self.total_free_space is None: return 0 else: sepa = self.default_column_space # we need to distribute remainders if self.default_column_space_remainder > 0: sepa += 1 self.default_column_space_remainder -= 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 render(self): """ print provided table :return: None """
print(self.format_str.format(**self.header), file=sys.stderr) print(self.header_format_str.format(**self.header_data), file=sys.stderr) for row in self.data: print(self.format_str.format(**row))
<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_params(self, **kwargs): """ set parameters in the user parameters these parameters are accepted: :param git_uri: str, uri of the git repository for the s...
# Here we cater to the koji "scratch" build type, this will disable # all plugins that might cause importing of data to koji self.scratch = kwargs.get('scratch') # When true, it indicates build was automatically started by # OpenShift via a trigger, for instance ImageChangeTrig...
<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_data_from_reactor_config(self): """ Sets data from reactor config """
reactor_config_override = self.user_params.reactor_config_override.value reactor_config_map = self.user_params.reactor_config_map.value data = None if reactor_config_override: data = reactor_config_override elif reactor_config_map: config_map = self.osbs...
<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_required_secrets(self, required_secrets, token_secrets): """ Sets required secrets """
if self.user_params.build_type.value == BUILD_TYPE_ORCHESTRATOR: required_secrets += token_secrets if not required_secrets: return secrets = self.template['spec']['strategy']['customStrategy'].setdefault('secrets', []) existing = set(secret_mount['secretSource'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_for_isolated(self): """ Remove certain plugins in order to handle the "isolated build" scenario. """
if self.user_params.isolated.value: remove_plugins = [ ("prebuild_plugins", "check_and_set_rebuild"), ("prebuild_plugins", "stop_autorebuild_if_disabled") ] for when, which in remove_plugins: self.pt.remove_plugin(when, which,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_for_flatpak(self): """ Remove plugins that don't work when building Flatpaks """
if self.user_params.flatpak.value: remove_plugins = [ ("prebuild_plugins", "resolve_composes"), # We'll extract the filesystem anyways for a Flatpak instead of exporting # the docker image directly, so squash just slows things down. ("...
<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_customizations(self): """ Customize template for site user specified customizations """
disable_plugins = self.pt.customize_conf.get('disable_plugins', []) if not disable_plugins: logger.debug('No site-user specified plugins to disable') else: for plugin in disable_plugins: try: self.pt.remove_plugin(plugin['plugin_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 render_koji(self): """ if there is yum repo in user params, don't pick stuff from koji """
phase = 'prebuild_plugins' plugin = 'koji' if not self.pt.has_plugin_conf(phase, plugin): return if self.user_params.yum_repourls.value: self.pt.remove_plugin(phase, plugin, 'there is a yum repo user parameter') elif not self.pt.set_plugin_arg_valid(phas...
<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_check_and_set_platforms(self): """ If the check_and_set_platforms plugin is present, configure it """
phase = 'prebuild_plugins' plugin = 'check_and_set_platforms' if not self.pt.has_plugin_conf(phase, plugin): return if self.user_params.koji_target.value: self.pt.set_plugin_arg(phase, plugin, "koji_target", self.user_params.ko...
<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_all_build_configs_by_labels(self, label_selectors): """ Returns all builds matching a given set of label selectors. It is up to the calling function to f...
labels = ['%s=%s' % (field, value) for field, value in label_selectors] labels = ','.join(labels) url = self._build_url("buildconfigs/", labelSelector=labels) return self._get(url).json()['items']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_build_config_by_labels(self, label_selectors): """ Returns a build config matching the given label selectors. This method will raise OsbsException if not...
items = self.get_all_build_configs_by_labels(label_selectors) if not items: raise OsbsException( "Build config not found for labels: %r" % (label_selectors, )) if len(items) > 1: raise OsbsException( "More than one build c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_build_config_by_labels_filtered(self, label_selectors, filter_key, filter_value): """ Returns a build config matching the given label selectors, filterin...
items = self.get_all_build_configs_by_labels(label_selectors) if filter_value is not None: build_configs = [] for build_config in items: match_value = graceful_chain_get(build_config, *filter_key.split('.')) if filter_value == match_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 stream_logs(self, build_id): """ stream logs from build :param build_id: str :return: iterator """
kwargs = {'follow': 1} # If connection is closed within this many seconds, give up: min_idle_timeout = 60 # Stream logs, but be careful of the connection closing # due to idle timeout. In that case, try again until the # call returns more quickly than a reasonable time...
<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_builds(self, build_config_id=None, koji_task_id=None, field_selector=None, labels=None): """ List builds matching criteria :param build_config_id: str, ...
query = {} selector = '{key}={value}' label = {} if labels is not None: label.update(labels) if build_config_id is not None: label['buildconfig'] = build_config_id if koji_task_id is not None: label['koji-task-id'] = str(koji_task_i...
<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_resource_quota(self, name, quota_json): """ Prevent builds being scheduled and wait for running builds to finish. :return: """
url = self._build_k8s_url("resourcequotas/") response = self._post(url, data=json.dumps(quota_json), headers={"Content-Type": "application/json"}) if response.status_code == http_client.CONFLICT: url = self._build_k8s_url("resourcequotas/%s" % 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 adjust_attributes_on_object(self, collection, name, things, values, how): """ adjust labels or annotations on object labels have to match RE: (([A-Za-z0-9][-...
url = self._build_url("%s/%s" % (collection, name)) response = self._get(url) logger.debug("before modification: %s", response.content) build_json = response.json() how(build_json['metadata'], things, values) response = self._put(url, data=json.dumps(build_json), use_jso...
<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_annotations_on_build(self, build_id, annotations): """ set annotations on build object :param build_id: str, id of build :param annotations: dict, ann...
return self.adjust_attributes_on_object('builds', build_id, 'annotations', annotations, self._update_metadata_things)
<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): """ Extract tabular data as |TableData| instances from a Line-delimited JSON file. |load_source_desc_file| :return: Loaded table data iterator. |...
formatter = JsonLinesTableFormatter(self.load_dict()) formatter.accept(self) return formatter.to_table_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self): """ Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google She...
import gspread from oauth2client.service_account import ServiceAccountCredentials self._validate_table_name() self._validate_title() scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildconfig_update(orig, new, remove_nonexistent_keys=False): """Performs update of given `orig` BuildConfig with values from `new` BuildConfig. Both BuildCo...
if isinstance(orig, dict) and isinstance(new, dict): clean_triggers(orig, new) if remove_nonexistent_keys: missing = set(orig.keys()) - set(new.keys()) for k in missing: orig.pop(k) for k, v in new.items(): if k == 'strategy': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkout_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, op...
tmpdir = tempfile.mkdtemp() target_dir = target_dir or os.path.join(tmpdir, "repo") try: yield clone_git_repo(git_url, target_dir, commit, retry_times, branch, depth) finally: shutil.rmtree(tmpdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_git_repo(git_url, target_dir=None, commit=None, retry_times=GIT_MAX_RETRIES, branch=None, depth=None): """ clone provided git repo to target_dir, optio...
retry_delay = GIT_BACKOFF_FACTOR target_dir = target_dir or os.path.join(tempfile.mkdtemp(), "repo") commit = commit or "master" logger.info("cloning git repo '%s'", git_url) logger.debug("url = '%s', dir = '%s', commit = '%s'", git_url, target_dir, commit) cmd = ["git", "clon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_git_repo(target_dir, git_reference, retry_depth=None): """ hard reset git clone in target_dir to given git_reference :param target_dir: str, filesystem...
deepen = retry_depth or 0 base_commit_depth = 0 for _ in range(GIT_FETCH_RETRY): try: if not deepen: cmd = ['git', 'rev-list', '--count', git_reference] base_commit_depth = int(subprocess.check_output(cmd, cwd=target_dir)) - 1 cmd = ["git", "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_imagestreamtag_from_image(image): """ return ImageStreamTag, give a FROM value :param image: str, the FROM value from the Dockerfile :return: str, ImageS...
ret = image # Remove the registry part ret = strip_registry_from_image(image) # ImageStream names cannot contain '/' ret = ret.replace('/', '-') # If there is no ':' suffix value, add one if ret.find(':') == -1: ret += ":latest" return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_time_from_rfc3339(rfc3339): """ return time tuple from an RFC 3339-formatted time string :param rfc3339: str, time in RFC 3339 format :return: float, sec...
try: # py 3 dt = dateutil.parser.parse(rfc3339, ignoretz=False) return dt.timestamp() except NameError: # py 2 # Decode the RFC 3339 date with no fractional seconds (the # format Origin provides). Note that this will fail to parse # valid ISO8601 times...
<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_name_from_git(repo, branch, limit=53, separator='-', hash_size=5): """ return name string representing the given git repo and branch to be used as a bui...
branch = branch or 'unknown' full = urlparse(repo).path.lstrip('/') + branch repo = git_repo_humanish_part_from_uri(repo) shaval = sha256(full.encode('utf-8')).hexdigest() hash_str = shaval[:hash_size] limit = limit - len(hash_str) - 1 sanitized = sanitize_strings_for_openshift(repo, bran...
<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_name_from_git(prefix, suffix, *args, **kwargs): """ wraps the result of make_name_from_git in a suffix and postfix adding separators for each. see docst...
# 64 is maximum length allowed by OpenShift # 2 is the number of dashes that will be added prefix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(prefix))) suffix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(suffix))) kwargs['limit'] = kwargs.get('limit', 64) - len(prefix) ...
<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_name(self, label_type): """ returns the most preferred label name if there isn't any correct name in the list it will return newest label name """
if label_type in self._label_values: return self._label_values[label_type][0] else: return Labels.LABEL_NAMES[label_type][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 get_new_names_by_old(): """Return dictionary, new label name indexed by old label name."""
newdict = {} for label_type, label_names in Labels.LABEL_NAMES.items(): for oldname in label_names[1:]: newdict[oldname] = Labels.LABEL_NAMES[label_type][0] return newdict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kerberos_ccache_init(principal, keytab_file, ccache_file=None): """ Checks whether kerberos credential cache has ticket-granting ticket that is valid for at ...
tgt_valid = False env = {"LC_ALL": "C"} # klist uses locales to format date on RHEL7+ if ccache_file: env["KRB5CCNAME"] = ccache_file # check if we have tgt that is valid more than one hour rc, klist, _ = run(["klist"], extraenv=env) if rc == 0: for line in klist.splitlines():...
<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): """ Extract tabular data as |TableData| instances from a SQLite database file. |load_source_desc_file| :return: Loaded table data iterator. |load...
self._validate() formatter = SqliteTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data(self): """ Find the data stored in the config_map :return: dict, the json of the data data that was passed into the ConfigMap on creation """
data = graceful_chain_get(self.json, "data") if data is None: return {} data_dict = {} for key in data: if self.is_yaml(key): data_dict[key] = yaml.load(data[key]) else: data_dict[key] = json.loads(data[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_data_by_key(self, name): """ Find the object stored by a JSON string at key 'name' :return: str or dict, the json of the str or dict stored in the Config...
data = graceful_chain_get(self.json, "data") if data is None or name not in data: return {} if self.is_yaml(name): return yaml.load(data[name]) or {} return json.loads(data[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 list_builds(self, field_selector=None, koji_task_id=None, running=None, labels=None): """ List builds with matching fields :param field_selector: str, field ...
if running: running_fs = ",".join(["status!={status}".format(status=status.capitalize()) for status in BUILD_FINISHED_STATES]) if not field_selector: field_selector = running_fs else: field_selector = ','.joi...
<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_build_request(self, build_type=None, inner_template=None, outer_template=None, customize_conf=None, arrangement_version=DEFAULT_ARRANGEMENT_VERSION): """...
if build_type is not None: warnings.warn("build types are deprecated, do not use the build_type argument") validate_arrangement_version(arrangement_version) if not arrangement_version or arrangement_version < REACTOR_CONFIG_ARRANGEMENT_VERSION: build_request = BuildReq...
<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_build_from_buildrequest(self, build_request): """ render provided build_request and submit build from it :param build_request: instance of build.build...
build_request.set_openshift_required_version(self.os_conf.get_openshift_required_version()) build = build_request.render() response = self.os.create_build(json.dumps(build)) build_response = BuildResponse(response.json(), self) return build_response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_image_stream_info_for_build_request(self, build_request): """Return ImageStream, and ImageStreamTag name for base_image of build_request If build_reques...
image_stream = None image_stream_tag_name = None if build_request.has_ist_trigger(): image_stream_tag_id = build_request.trigger_imagestreamtag image_stream_id, image_stream_tag_name = image_stream_tag_id.split(':') try: image_stream = self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_prod_build(self, *args, **kwargs): """ Create a production build :param git_uri: str, URI of git repository :param git_ref: str, reference to commit :...
logger.warning("prod (all-in-one) builds are deprecated, " "please use create_orchestrator_build " "(support will be removed in version 0.54)") return self._do_create_prod_build(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_worker_build(self, **kwargs): """ Create a worker build Pass through method to create_prod_build with the following modifications: - platform param is...
missing = set() for required in ('platform', 'release', 'arrangement_version'): if not kwargs.get(required): missing.add(required) if missing: raise ValueError("Worker build missing required parameters: %s" % missing) ...
<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_orchestrator_build(self, **kwargs): """ Create an orchestrator build Pass through method to create_prod_build with the following modifications: - plat...
if not self.can_orchestrate(): raise OsbsOrchestratorNotEnabled("can't create orchestrate build " "when can_orchestrate isn't enabled") extra = [x for x in ('platform',) if kwargs.get(x)] if extra: raise ValueError("Orchestrat...
<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_orchestrator_build_logs(self, build_id, follow=False, wait_if_missing=False): """ provide logs from orchestrator build :param build_id: str :param follow...
logs = self.get_build_logs(build_id=build_id, follow=follow, wait_if_missing=wait_if_missing, decode=True) if logs is None: return if isinstance(logs, GeneratorType): for entries in logs: for entry in entries.splitlines...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_image_tags(self, name, tags, repository, insecure=False): """Import image tags from specified container repository. :param name: str, name of ImageStr...
stream_import_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_import.json') with open(stream_import_file) as f: stream_import = json.load(f) return self.os.import_image_tags(name, stream_import, tags, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_image_stream_tag(self, stream, tag_name, scheduled=False, source_registry=None, organization=None, base_image=None): """Ensures the tag is monitored i...
img_stream_tag_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream_tag.json') with open(img_stream_tag_file) as f: tag_template = json.load(f) repository = None registry = None insecure = False i...
<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_image_stream(self, name, docker_image_repository, insecure_registry=False): """ Create an ImageStream object Raises exception on error :param name: st...
img_stream_file = os.path.join(self.os_conf.get_build_json_store(), 'image_stream.json') with open(img_stream_file) as f: stream = json.load(f) stream['metadata']['name'] = name stream['metadata'].setdefault('annotations', {}) stream['metadata']['annotations'][ANNOTA...
<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_compression_extension(self): """ Find the filename extension for the 'docker save' output, which may or may not be compressed. Raises OsbsValidationExcep...
build_request = BuildRequest(build_json_store=self.os_conf.get_build_json_store()) inner = build_request.inner_template postbuild_plugins = inner.get('postbuild_plugins', []) for plugin in postbuild_plugins: if plugin.get('name') == 'compress': args = plugin...
<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_config_map(self, name, data): """ Create an ConfigMap object on the server Raises exception on error :param name: str, name of configMap :param data: ...
config_data_file = os.path.join(self.os_conf.get_build_json_store(), 'config_map.json') with open(config_data_file) as f: config_data = json.load(f) config_data['metadata']['name'] = name data_dict = {} for key, value in data.items(): data_dict[key] = jso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config_map(self, name): """ Get a ConfigMap object from the server Raises exception on error :param name: str, name of configMap to get from the server :...
response = self.os.get_config_map(name) config_map_response = ConfigMapResponse(response.json()) return config_map_response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wipe(self): """ Wipe the bolt database. Calling this after HoverPy has been instantiated is potentially dangerous. This function is mostly used internally fo...
try: if os.isfile(self._dbpath): os.remove(self._dbpath) except OSError: 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 metadata(self, delete=False): """ Gets the metadata. """
if delete: return self._session.delete(self.__v1() + "/metadata").json() else: return self._session.get(self.__v1() + "/metadata").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 addDelay(self, urlPattern="", delay=0, httpMethod=None): """ Adds delays. """
print("addDelay is deprecated please use delays instead") delay = {"urlPattern": urlPattern, "delay": delay} if httpMethod: delay["httpMethod"] = httpMethod return self.delays(delays={"data": [delay]})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __enableProxy(self): """ Set the required environment variables to enable the use of hoverfly as a proxy. """
os.environ[ "HTTP_PROXY"] = self.httpProxy() os.environ[ "HTTPS_PROXY"] = self.httpsProxy() os.environ["REQUESTS_CA_BUNDLE"] = os.path.join( os.path.dirname( os.path.abspath(__file__)), "cert.pem")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __writepid(self, pid): """ HoverFly fails to launch if it's already running on the same ports. So we have to keep track of them using temp files with the pro...
import tempfile d = tempfile.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) with open(name, 'w') as f: f.write(str(pid)) logging.debug("writing to %s"%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 __rmpid(self): """ Remove the PID file on shutdown, unfortunately this may not get called if not given the time to shut down. """
import tempfile d = tempfile.gettempdir() name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort)) if os.path.exists(name): os.unlink(name) logging.debug("deleting %s"%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 __start(self): """ Start the hoverfly process. This function waits until it can make contact with the hoverfly API before returning. """
logging.debug("starting %i" % id(self)) self.__kill_if_not_shut_properly() self.FNULL = open(os.devnull, 'w') flags = self.__flags() cmd = [hoverfly] + flags if self._showCmd: print(cmd) self._process = Popen( [hoverfly] + flag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __stop(self): """ Stop the hoverfly process. """
if logging: logging.debug("stopping") self._process.terminate() # communicate means we wait until the process # was actually terminated, this removes some # warnings in python3 self._process.communicate() self._process = None self.FNULL.close(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __flags(self): """ Internal method. Turns arguments into flags. """
flags = [] if self._capture: flags.append("-capture") if self._spy: flags.append("-spy") if self._dbpath: flags += ["-db-path", self._dbpath] flags += ["-db", "boltdb"] else: flags += ["-db", "memory"] if self._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self): """ Extract tabular data as |TableData| instances from a JSON file. |load_source_desc_file| This method can be loading four types of JSON formats...
formatter = JsonTableFormatter(self.load_dict()) formatter.accept(self) return formatter.to_table_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self): """ Extract tabular data as |TableData| instances from a MediaWiki file. |load_source_desc_file| :return: Loaded table data iterator. |load_table...
self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) with io.open(self.source, "r", encoding=self.encoding) as fp: formatter = MediaWikiTableFormatter(fp.read()) formatter.accept(self) return formatter....
<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): """ Extract tabular data as |TableData| instances from a MediaWiki text object. |load_source_desc_text| :return: Loaded table data iterator. |loa...
self._validate() self._logger.logging_load() formatter = MediaWikiTableFormatter(self.source) formatter.accept(self) return formatter.to_table_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dock_json(self): """ return dock json from existing build json """
env_json = self.build_json['spec']['strategy']['customStrategy']['env'] try: p = [env for env in env_json if env["name"] == "ATOMIC_REACTOR_PLUGINS"] except TypeError: raise RuntimeError("\"env\" is not iterable") if len(p) <= 0: raise RuntimeError("\...
<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_container_image_ids(self): """ Find the image IDs the containers use. :return: dict, image tag to docker ID """
statuses = graceful_chain_get(self.json, "status", "containerStatuses") if statuses is None: return {} def remove_prefix(image_id, prefix): if image_id.startswith(prefix): return image_id[len(prefix):] return image_id return {statu...
<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_failure_reason(self): """ Find the reason a pod failed :return: dict, which will always have key 'reason': reason: brief reason for state containerID (if...
reason_key = 'reason' cid_key = 'containerID' exit_key = 'exitCode' pod_status = self.json.get('status', {}) statuses = pod_status.get('containerStatuses', []) # Find the first non-zero exit code from a container # and return its 'message' or 'reason' value ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_error_message(self): """ Return an error message based on atomic-reactor's metadata """
error_reason = self.get_error_reason() if error_reason: error_message = error_reason.get('pod') or None if error_message: return "Error in pod: %s" % error_message plugin = error_reason.get('plugin')[0] or None error_message = error_reason...
<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): """ Extract tabular data as |TableData| instances from an Excel file. |spreadsheet_load_desc| :return: Loaded |TableData| iterator. |TableData| c...
import xlrd self._validate() self._logger.logging_load() try: workbook = xlrd.open_workbook(self.source) except xlrd.biffh.XLRDError as e: raise OpenError(e) for worksheet in workbook.sheets(): self._worksheet = worksheet ...
<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): """ Extract tabular data as |TableData| instances from a LTSV file. |load_source_desc_file| :return: Loaded table data. |load_table_name_desc| ==...
self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) self._ltsv_input_stream = io.open(self.source, "r", encoding=self.encoding) for data_matrix in self._to_data_matrix(): formatter = SingleJsonTableConverterA(...
<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): """ Extract tabular data as |TableData| instances from a LTSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_d...
self._validate() self._logger.logging_load() self._ltsv_input_stream = self.source.splitlines() for data_matrix in self._to_data_matrix(): formatter = SingleJsonTableConverterA(data_matrix) formatter.accept(self) return formatter.to_table_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_args(args, extra=False): """ Encode a list of arguments """
if not args: return '' methodargs = ', '.join([encode(a) for a in args]) if extra: methodargs += ', ' return methodargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill(self, field, value): """ Fill a specified form field in the current document. :param field: an instance of :class:`zombie.dom.DOMNode` :param value: any...
self.client.nowait('browser.fill', (field, value)) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value(self, value): """ Used to set the ``value`` of form elements. """
self.client.nowait( 'set_field', (Literal('browser'), self.element, 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 fire(self, event): """ Fires a specified DOM event on the current node. :param event: the name of the event to fire (e.g., 'click'). Returns the :class:`zomb...
self.browser.fire(self.element, event) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _utf8_encode(self, d): """ Ensures all values are encoded in UTF-8 and converts them to lowercase """
for k, v in d.items(): if isinstance(v, str): d[k] = v.encode('utf8').lower() if isinstance(v, list): for index,item in enumerate(v): item = item.encode('utf8').lower() v[index] = item if isinstance(v, d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bool_encode(self, d): """ Converts bool values to lowercase strings """
for k, v in d.items(): if isinstance(v, bool): d[k] = str(v).lower() return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_rosters(self): """ Parse the home and away game rosters :returns: ``self`` on success, ``None`` otherwise """
lx_doc = self.html_doc() if not self.__blocks: self.__pl_blocks(lx_doc) for t in ['home', 'away']: self.rosters[t] = self.__clean_pl_block(self.__blocks[t]) return self if self.rosters else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_scratches(self): """ Parse the home and away healthy scratches :returns: ``self`` on success, ``None`` otherwise """
lx_doc = self.html_doc() if not self.__blocks: self.__pl_blocks(lx_doc) for t in ['aw_scr', 'h_scr']: ix = 'away' if t == 'aw_scr' else 'home' self.scratches[ix] = self.__clean_pl_block(self.__blocks[t]) return self if self.scratches else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_coaches(self): """ Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise """
lx_doc = self.html_doc() tr = lx_doc.xpath('//tr[@id="HeadCoaches"]')[0] for i, td in enumerate(tr): txt = td.xpath('.//text()') txt = ex_junk(txt, ['\n','\r']) team = 'away' if i == 0 else 'home' self.coaches[team] = txt[0] return self ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_officials(self): """ Parse the officials :returns: ``self`` on success, ``None`` otherwise """
# begin proper body of method lx_doc = self.html_doc() off_parser = opm(self.game_key.season) self.officials = off_parser(lx_doc) return self if self.officials else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self, domain, diagnose=False): """Check whether a domain has a valid MX or A record. Keyword arguments: domain --- the domain to check diagnose --- ...
return_status = [ValidDiagnosis()] dns_checked = False # http://tools.ietf.org/html/rfc5321#section-2.3.5 # Names that can be resolved to MX RRs or address (i.e., A or AAAA) # RRs (as discussed in Section 5) are permitted, as are CNAME RRs # whose targets can be ...
<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_plays_stream(self): """Generate and yield a stream of parsed plays. Useful for per play processing."""
lx_doc = self.html_doc() if lx_doc is not None: parser = PlayParser(self.game_key.season, self.game_key.game_type) plays = lx_doc.xpath('//tr[@class = "evenColor"]') for p in plays: p_obj = parser.build_play(p) self.plays.appe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_files(files, hemi, source, target): """ This function takes a list of files as input and vstacks them """
import csv import os import numpy as np fname = "sdist_%s_%s_%s.csv" % (hemi, source, target) filename = os.path.join(os.getcwd(),fname) alldist = [] for dfile in files: alldist.append(np.genfromtxt(dfile, delimiter=',')) alldist = np.array(alldist) alldist.tofile(filename,",") return 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 __html_rep(self, game_key, rep_code): """Retrieves the nhl html reports for the specified game and report code"""
seas, gt, num = game_key.to_tuple() url = [ self.__domain, "scores/htmlreports/", str(seas-1), str(seas), "/", rep_code, "0", str(gt), ("%04i" % (num)), ".HTM" ] url = ''.join(url) return self.__open(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_char(token): """Transforms the ASCII control character symbols to their real char. Note: If the token is not an ASCII control character symbol, just retur...
if ord(token) in _range(9216, 9229 + 1): token = _unichr(ord(token) - 9216) return 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 load_freesurfer_label(annot_input, label_name, cortex=None): """ Get source node list for a specified freesurfer label. Inputs ------- annot_input : freesurf...
if cortex is not None: print("Warning: cortex is not used to load the freesurfer label") labels, color_table, names = nib.freesurfer.read_annot(annot_input) names = [i.decode('utf-8') for i in names] label_value = names.index(label_name) label_nodes = np.array(np.where(np.in1d(labels, lab...
<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_freesurfer_label(annot_input, verbose = True): """ Print freesurfer label names. """
labels, color_table, names = nib.freesurfer.read_annot(annot_input) if verbose: print(names) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surf_keep_cortex(surf, cortex): """ Remove medial wall from cortical surface to ensure that shortest paths are only calculated through the cortex. Inputs ---...
# split surface into vertices and triangles vertices, triangles = surf # keep only the vertices within the cortex label cortex_vertices = np.array(vertices[cortex], dtype=np.float64) # keep only the triangles within the cortex label cortex_triangles = triangles_keep_cortex(triangles, cortex)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triangles_keep_cortex(triangles, cortex): """ Remove triangles with nodes not contained in the cortex label array """
# for or each face/triangle keep only those that only contain nodes within the list of cortex nodes input_shape = triangles.shape triangle_is_in_cortex = np.all(np.reshape(np.in1d(triangles.ravel(), cortex), input_shape), axis=1) cortex_triangles_old = np.array(triangles[triangle_is_in_cortex], dtype...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dist_calc(surf, cortex, source_nodes): """ Calculate exact geodesic distance along cortical surface from set of source nodes. "dist_type" specifies whether t...
cortex_vertices, cortex_triangles = surf_keep_cortex(surf, cortex) translated_source_nodes = translate_src(source_nodes, cortex) data = gdist.compute_gdist(cortex_vertices, cortex_triangles, source_indices = translated_source_nodes) dist = recort(data, surf, cortex) del data return dist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zone_calc(surf, cortex, src): """ Calculate closest nodes to each source node using exact geodesic distance along the cortical surface. """
cortex_vertices, cortex_triangles = surf_keep_cortex(surf, cortex) dist_vals = np.zeros((len(source_nodes), len(cortex_vertices))) for x in range(len(source_nodes)): translated_source_nodes = translate_src(source_nodes[x], cortex) dist_vals[x, :] = gdist.compute_gdist(cortex_vertices, c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_module(filename): """ Loads a module by filename """
basename = os.path.basename(filename) path = os.path.dirname(filename) sys.path.append(path) # TODO(tlan) need to figure out how to handle errors thrown here return __import__(os.path.splitext(basename)[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 make_machine_mapping(machine_list): """ Convert the machine list argument from a list of names into a mapping of logical names to physical hosts. This is sim...
if machine_list is None: return {} else: mapping = {} for pair in machine_list: if (constants.MACHINE_SEPARATOR not in pair) or (pair.count(constants.MACHINE_SEPARATOR) != 1): raise ValueError("machine pairs must be passed as two strings separted by a %s", constants.MACHINE_SEPARATOR) ...
<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_config_list(config_list): """ Parse a list of configuration properties separated by '=' """
if config_list is None: return {} else: mapping = {} for pair in config_list: if (constants.CONFIG_SEPARATOR not in pair) or (pair.count(constants.CONFIG_SEPARATOR) != 1): raise ValueError("configs must be passed as two strings separted by a %s", constants.CONFIG_SEPARATOR) (config,...
<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(self, unique_id, configs=None): """Deploys the service to the host. This should at least perform the same actions as install and start but may perform...
self.install(unique_id, configs) self.start(unique_id, configs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def undeploy(self, unique_id, configs=None): """Undeploys the service. This should at least perform the same actions as stop and uninstall but may perform additi...
self.stop(unique_id, configs) self.uninstall(unique_id, configs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sleep(self, unique_id, delay, configs=None): """ Pauses the process for the specified delay and then resumes it :Parameter unique_id: the name of the process...
self.pause(unique_id, configs) time.sleep(delay) self.resume(unique_id, configs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self, unique_id, configs=None): """ Issues a sigstop for the specified process :Parameter unique_id: the name of the process """
pids = self.get_pid(unique_id, configs) if pids != constants.PROCESS_NOT_RUNNING_PID: pid_str = ' '.join(str(pid) for pid in pids) hostname = self.processes[unique_id].hostname with get_ssh_client(hostname, username=runtime.get_username(), password=runtime.get_password()) as ssh: bett...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_signal(self, unique_id, signalno, configs): """ Issues a signal for the specified process :Parameter unique_id: the name of the process """
pids = self.get_pid(unique_id, configs) if pids != constants.PROCESS_NOT_RUNNING_PID: pid_str = ' '.join(str(pid) for pid in pids) hostname = self.processes[unique_id].hostname msg= Deployer._signalnames.get(signalno,"SENDING SIGNAL %s TO"%signalno) with get_ssh_client(hostname, userna...