Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def process_rpm_ql_line(line_str, allowed_keys): try: name, key_str = line_str.split(' ', 1) except ValueError: logger.error("Failed to split line '{0}".format(repr(line_str))) return False if name in no_key_pkgs: return True ...
[ "\n Checks single line of rpm-ql for correct keys\n\n :param line_str: line to process\n :param allowed_keys: list of allowed keys\n :return: bool\n " ]
Please provide a description of the function:def check_signatures(pkg_list, allowed_keys): all_passed = True for line_str in pkg_list: all_passed &= process_rpm_ql_line(line_str.strip(), allowed_keys) if not all_passed: raise PackageSignatureException( 'Error while checking...
[ "\n Go through list of packages with signatures and check if all are properly signed\n\n :param pkg_list: list of packages in format '%{name} %{SIGPGP:pgpsig}'\n :param allowed_keys: list of allowed keys\n :return: bool\n " ]
Please provide a description of the function:def get_parameters(self): import argparse parser = argparse.ArgumentParser(add_help=False) # without parameter parser.add_argument("-i", "--interactive", action="store_true", dest="stdin_open") parser.add_argument("-d", "--de...
[ "\n Parse DockerRunBuilder options and create object with properties for docker-py run command\n :return: DockerContainerParameters\n " ]
Please provide a description of the function:def get_id(self): if self._id is None: # FIXME: provide a better error message when key is not defined self._id = self.inspect(refresh=False)["Id"] return self._id
[ "\n get unique identifier of this container\n\n :return: str\n " ]
Please provide a description of the function:def inspect(self, refresh=True): if refresh or not self._inspect_data: ident = self._id or self.name if not ident: raise ConuException("This container does not have a valid identifier.") self._inspect_data ...
[ "\n return cached metadata by default\n\n :param refresh: bool, returns up to date metadata if set to True\n :return: dict\n " ]
Please provide a description of the function:def get_ports(self): ports = [] container_ports = self.inspect(refresh=True)["NetworkSettings"]["Ports"] if not container_ports: return ports for p in container_ports: # TODO: gracefullness, error handling ...
[ "\n get ports specified in container metadata\n\n :return: list of str\n " ]
Please provide a description of the function:def get_port_mappings(self, port=None): port_mappings = self.inspect(refresh=True)["NetworkSettings"]["Ports"] if not port: return port_mappings if str(port) not in self.get_ports(): return [] for p in port_...
[ "\n Get list of port mappings between container and host. The format of dicts is:\n\n {\"HostIp\": XX, \"HostPort\": YY};\n\n When port is None - return all port mappings. The container needs\n to be running, otherwise this returns an empty list.\n\n :param port: int or None, ...
Please provide a description of the function:def execute(self, command, blocking=True, exec_create_kwargs=None, exec_start_kwargs=None): logger.info("running command %s", command) exec_create_kwargs = exec_create_kwargs or {} exec_start_kwargs = exec_start_kwargs or {} exec_sta...
[ "\n Execute a command in this container -- the container needs to be running.\n\n If the command fails, a ConuException is thrown.\n\n This is a blocking call by default and writes output of the command to logger\n using the INFO level -- this behavior can be changed if you set\n ...
Please provide a description of the function:def logs(self, follow=False): return self.d.logs(self.get_id(), stream=True, follow=follow)
[ "\n Get logs from this container. Every item of the iterator contains one log line\n terminated with a newline. The logs are encoded (they are bytes, not str).\n\n Let's look at an example::\n\n image = conu.DockerImage(\"fedora\", tag=\"27\")\n command = [\"bash\", \"-c\"...
Please provide a description of the function:def kill(self, signal=None): self.d.kill(self.get_id(), signal=signal)
[ "\n send a signal to this container (bear in mind that the process won't have time\n to shutdown properly and your service may end up in an inconsistent state)\n\n :param signal: str or int, signal to use for killing the container (SIGKILL by default)\n :return: None\n " ]
Please provide a description of the function:def delete(self, force=False, volumes=False, **kwargs): self.d.remove_container(self.get_id(), v=volumes, force=force)
[ "\n remove this container; kwargs indicate that some container runtimes\n might accept more parameters\n\n :param force: bool, if container engine supports this, force the functionality\n :param volumes: bool, remove also associated volumes\n :return: None\n " ]
Please provide a description of the function:def write_to_stdin(self, message): if not self.is_running(): raise ConuException( "Container must be running") if not self.popen_instance: raise ConuException( "This container doesn't seem to be...
[ "\n Write provided text to container's standard input. In order to make this function work, there needs to be several conditions met:\n * the container needs to be running\n * the container needs to have stdin open\n * the container has to be created using method `run_via_binary_in_fo...
Please provide a description of the function:def get_metadata(self): inspect_data = self.inspect(refresh=True) inspect_to_container_metadata(self.metadata, inspect_data, self.image) return self.metadata
[ "\n Convert dictionary returned after docker inspect command into instance of ContainerMetadata class\n :return: ContainerMetadata, container metadata instance\n " ]
Please provide a description of the function:def _clean_tmp_dirs(self): def onerror(fnc, path, excinfo): # we might not have rights to do this, the files could be owned by root self.logger.info("we were not able to remove temporary file %s: %s", path, excinfo[1]) shuti...
[ "\n Remove temporary dir associated with this backend instance.\n\n :return: None\n " ]
Please provide a description of the function:def _clean(self): if CleanupPolicy.EVERYTHING in self.cleanup: self.cleanup_containers() self.cleanup_volumes() self.cleanup_images() self._clean_tmp_dirs() else: if CleanupP...
[ "\n Method for cleaning according to object cleanup policy value\n\n :return: None\n " ]
Please provide a description of the function:def list_containers(self): data = run_cmd(["machinectl", "list", "--no-legend", "--no-pager"], return_output=True) output = [] reg = re.compile(r"\s+") for line in data.split("\n"): stripped = line.s...
[ "\n list all available nspawn containers\n\n :return: collection of instances of :class:`conu.backend.nspawn.container.NspawnContainer`\n " ]
Please provide a description of the function:def list_images(self): # Fedora-Cloud-Base-27-1.6.x86_64 raw no 601.7M Sun 2017-11-05 08:30:10 CET \ # Sun 2017-11-05 08:30:10 CET data = os.listdir(CONU_IMAGES_STORE) output = [] for name in data: output.appen...
[ "\n list all available nspawn images\n\n :return: collection of instances of :class:`conu.backend.nspawn.image.NspawnImage`\n " ]
Please provide a description of the function:def cleanup_containers(self): for cont in self.list_containers(): if CONU_ARTIFACT_TAG in cont.name: try: logger.debug("removing container %s created by conu", cont) # TODO: move this functi...
[ "\n stop all container created by conu\n\n :return: None\n " ]
Please provide a description of the function:def cleanup_images(self): for image in self.list_images(): if CONU_ARTIFACT_TAG in image.name: image.rmi() # remove all hidden images -> causes trouble when pulling the image again run_cmd(["machinectl", "--no-page...
[ "\n Remove all images created by CONU and remove all hidden images (cached dowloads)\n\n :return: None\n " ]
Please provide a description of the function:def all_pods_ready(self): if self.get_status().replicas and self.get_status().ready_replicas: if self.get_status().replicas == self.get_status().ready_replicas: logger.info("All pods are ready for deployment %s in namespace: %s",...
[ "\n Check if number of replicas with same selector is equals to number of ready replicas\n :return: bool\n " ]
Please provide a description of the function:def create_in_cluster(self): try: self.api.create_namespaced_deployment(self.namespace, self.body) except ApiException as e: raise ConuException( "Exception when calling Kubernetes API - create_namespaced_deplo...
[ "\n call Kubernetes API and create this Deployment in cluster,\n raise ConuException if the API call fails\n :return: None\n " ]
Please provide a description of the function:def get_core_api(): global core_api if core_api is None: config.load_kube_config() if API_KEY is not None: # Configure API key authorization: BearerToken configuration = client.Configuration() configuration.ap...
[ "\n Create instance of Core V1 API of kubernetes:\n https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md\n :return: instance of client\n " ]
Please provide a description of the function:def get_apps_api(): global apps_api if apps_api is None: config.load_kube_config() if API_KEY is not None: # Configure API key authorization: BearerToken configuration = client.Configuration() configuration.ap...
[ "\n Create instance of Apps V1 API of kubernetes:\n https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md\n :return: instance of client\n " ]
Please provide a description of the function:def check_port(port, host, timeout=10): logger.info("trying to open connection to %s:%s", host, port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.settimeout(timeout) result = sock.connect_ex((host, port)) logger...
[ "\n connect to port on host and return True on success\n\n :param port: int, port to check\n :param host: string, host address\n :param timeout: int, number of seconds spent trying\n :return: bool\n " ]
Please provide a description of the function:def get_selinux_status(): getenforce_command_exists() # alternatively, we could read directly from /sys/fs/selinux/{enforce,status}, but status is # empty (why?) and enforce doesn't tell whether SELinux is disabled or not o = run_cmd(["getenforce"], retu...
[ "\n get SELinux status of host\n\n :return: string, one of Enforced, Permissive, Disabled\n " ]
Please provide a description of the function:def random_str(size=10): return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))
[ "\n create random string of selected size\n\n :param size: int, length of the string\n :return: the string\n " ]
Please provide a description of the function:def run_cmd(cmd, return_output=False, ignore_status=False, log_output=True, **kwargs): logger.debug('command: "%s"' % ' '.join(cmd)) process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlin...
[ "\n run provided command on host system using the same user as you invoked this code, raises\n subprocess.CalledProcessError if it fails\n\n :param cmd: list of str\n :param return_output: bool, return output of the command\n :param ignore_status: bool, do not fail in case nonzero return code\n :p...
Please provide a description of the function:def command_exists(command, noop_invocation, exc_msg): try: found = bool(shutil.which(command)) # py3 only except AttributeError: # py2 branch try: p = subprocess.Popen(noop_invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE...
[ "\n Verify that the provided command exists. Raise CommandDoesNotExistException in case of an\n error or if the command does not exist.\n\n :param command: str, command to check (python 3 only)\n :param noop_invocation: list of str, command to check (python 2 only)\n :param exc_msg: str, message of e...
Please provide a description of the function:def check_docker_command_works(): try: out = subprocess.check_output(["docker", "version"], stderr=subprocess.STDOUT, universal_newlines=True) except OSError: logger.info...
[ "\n Verify that dockerd and docker binary works fine. This is performed by calling `docker\n version`, which also checks server API version.\n\n :return: bool, True if all is good, otherwise ConuException or CommandDoesNotExistException\n is thrown\n " ]
Please provide a description of the function:def graceful_get(d, *args): if not d: return d value = d for arg in args: try: value = value[arg] except (IndexError, KeyError, AttributeError, TypeError) as ex: logger.debug("exception while getting a value %r...
[ "\n Obtain values from dicts and lists gracefully. Example:\n\n ::\n\n print(graceful_get({\"a\": [{1: 2}, {\"b\": \"c\"}]}, \"a\", \"b\"))\n c\n\n :param d: collection (usually a dict or list)\n :param args: list of keys which are used as a lookup\n :return: the value from your collect...
Please provide a description of the function:def export_docker_container_to_directory(client, container, path): # we don't do this because of a bug in docker: # https://bugzilla.redhat.com/show_bug.cgi?id=1570828 # stream, _ = client.get_archive(container.get_id(), "/") check_docker_command_works()...
[ "\n take selected docker container, create an archive out of it and\n unpack it to a selected location\n\n :param client: instance of docker.APIClient\n :param container: instance of DockerContainer\n :param path: str, path to a directory, doesn't need to exist\n :return: None\n " ]
Please provide a description of the function:def get_oc_api_token(): oc_command_exists() try: return run_cmd(["oc", "whoami", "-t"], return_output=True).rstrip() # remove '\n' except subprocess.CalledProcessError as ex: raise ConuException("oc whoami -t failed: %s" % ex)
[ "\n Get token of user logged in OpenShift cluster\n :return: str, API token\n " ]
Please provide a description of the function:def parse_reference(reference): if ":" in reference: im, tag = reference.rsplit(":", 1) if "/" in tag: # this is case when there is port in the registry URI return (reference, "latest") else: return (im, ta...
[ "\n parse provided image reference into <image_repository>:<tag>\n\n :param reference: str, e.g. (registry.fedoraproject.org/fedora:27)\n :return: collection (tuple or list), (\"registry.fedoraproject.org/fedora\", \"27\")\n " ]
Please provide a description of the function:def get_version(self): raw_version = run_cmd(["podman", "version"], return_output=True) regex = re.compile(r"Version:\s*(\d+)\.(\d+)\.(\d+)") match = regex.findall(raw_version) try: return match[0] except IndexErro...
[ "\n return 3-tuple of version info or None\n\n :return: (str, str, str)\n " ]
Please provide a description of the function:def list_containers(self): containers = [] for container in self._list_podman_containers(): identifier = container["ID"] name = container["Names"] image_name = container["Image"] try: i...
[ "\n List all available podman containers.\n\n :return: collection of instances of :class:`conu.PodmanContainer`\n " ]
Please provide a description of the function:def list_images(self): images = [] for image in self._list_all_podman_images(): try: i_name, tag = parse_reference(image["names"][0]) except (IndexError, TypeError): i_name, tag = None, None ...
[ "\n List all available podman images.\n\n :return: collection of instances of :class:`conu.PodmanImage`\n " ]
Please provide a description of the function:def _list_all_podman_images(): cmdline = ["podman", "images", "--format", "json"] output = run_cmd(cmdline, return_output=True) images = json.loads(output) return images
[ "\n Finds all podman containers\n :return: list of dicts with image info\n " ]
Please provide a description of the function:def _list_podman_containers(filter=None): option = ["--filter", filter] if filter else ["-a"] cmdline = ["podman", "ps"] + option + ["--format", "json"] output = run_cmd(cmdline, return_output=True) containers = json.loads(output) ...
[ "\n Finds podman containers by filter or all containers\n :return: list of dicts with containers info\n " ]
Please provide a description of the function:def inspect_to_metadata(metadata_object, inspect_data): identifier = graceful_get(inspect_data, 'Id') if identifier: if ":" in identifier: # format of image name from docker inspect: # sha256:8f0e66c924c0c169352de487a3c2463d82da24...
[ "\n process data from `docker inspect` and update provided metadata object\n\n :param metadata_object: instance of Metadata\n :param inspect_data: dict, metadata from `docker inspect` or `dockert_client.images()`\n :return: instance of Metadata\n " ]
Please provide a description of the function:def inspect_to_container_metadata(c_metadata_object, inspect_data, image_instance): inspect_to_metadata(c_metadata_object, inspect_data) status = ContainerStatus.get_from_docker( graceful_get(inspect_data, "State", "Status"), graceful_get(inspec...
[ "\n process data from `docker container inspect` and update provided container metadata object\n\n :param c_metadata_object: instance of ContainerMetadata\n :param inspect_data: dict, metadata from `docker inspect` or `dockert_client.images()`\n :param image_instance: instance of DockerImage\n :retur...
Please provide a description of the function:def list_pods(self, namespace=None): if namespace: return [Pod(name=p.metadata.name, namespace=namespace, spec=p.spec) for p in self.core_api.list_namespaced_pod(namespace, watch=False).items] return [Pod(name=p.meta...
[ "\n List all available pods.\n\n :param namespace: str, if not specified list pods for all namespaces\n :return: collection of instances of :class:`conu.backend.k8s.pod.Pod`\n " ]
Please provide a description of the function:def list_services(self, namespace=None): if namespace: return [Service(name=s.metadata.name, ports=k8s_ports_to_metadata_ports(s.spec.ports), namespace=s.metadata.namespace, ...
[ "\n List all available services.\n\n :param namespace: str, if not specified list services for all namespaces\n :return: collection of instances of :class:`conu.backend.k8s.service.Service`\n " ]
Please provide a description of the function:def list_deployments(self, namespace=None): if namespace: return [Deployment(name=d.metadata.name, namespace=d.metadata.namespace, labels=d.metadata.labels, selector=d.spec.selector, ...
[ "\n List all available deployments.\n\n :param namespace: str, if not specified list deployments for all namespaces\n :return: collection of instances of :class:`conu.backend.k8s.deployment.Deployment`\n " ]
Please provide a description of the function:def create_namespace(self): name = 'namespace-{random_string}'.format(random_string=random_str(5)) namespace = client.V1Namespace(metadata=client.V1ObjectMeta(name=name)) self.core_api.create_namespace(namespace) logger.info("Creat...
[ "\n Create namespace with random name\n :return: name of new created namespace\n " ]
Please provide a description of the function:def _namespace_ready(self, namespace): try: secrets = self.core_api.list_namespaced_secret(namespace=namespace) if len(secrets.items) > 0: # API tokens for service accounts are generated logger.info("Na...
[ "\n Check if API tokens for service accounts are generated\n :param namespace: str, namespace\n :return: bool\n " ]
Please provide a description of the function:def delete_namespace(self, name): self.core_api.delete_namespace(name, client.V1DeleteOptions()) logger.info("Deleting namespace: %s", name)
[ "\n Delete namespace with specific name\n :param name: str, namespace to delete\n :return: None\n " ]
Please provide a description of the function:def _clean(self): if K8sCleanupPolicy.NAMESPACES in self.cleanup: self.cleanup_namespaces() elif K8sCleanupPolicy.EVERYTHING in self.cleanup: self.cleanup_pods() self.cleanup_services() self.cleanup_dep...
[ "\n Method for cleaning according to object cleanup policy value\n :return: None\n " ]
Please provide a description of the function:def cleanup_pods(self): pods = self.list_pods() for pod in pods: if pod.namespace in self.managed_namespaces: pod.delete()
[ "\n Delete all pods created in namespaces associated with this backend\n :return: None\n " ]
Please provide a description of the function:def cleanup_services(self): services = self.list_services() for service in services: if service.namespace in self.managed_namespaces: service.delete()
[ "\n Delete all services created in namespaces associated with this backend\n :return: None\n " ]
Please provide a description of the function:def cleanup_deployments(self): deployments = self.list_deployments() for deployment in deployments: if deployment.namespace in self.managed_namespaces: deployment.delete()
[ "\n Delete all deployments created in namespaces associated with this backend\n :return: None\n " ]
Please provide a description of the function:def get_url(path, host, port, method="http"): return urlunsplit( (method, "%s:%s" % (host, port), path, "", "") )
[ "\n make url from path, host and port\n\n :param method: str\n :param path: str, path within the request, e.g. \"/api/version\"\n :param host: str\n :param port: str or int\n :return: str\n " ]
Please provide a description of the function:def list_containers(self): result = [] for c in self.d.containers(all=True): name = None names = c.get("Names", None) if names: name = names[0] i = DockerImage(None, identifier=c["ImageI...
[ "\n List all available docker containers.\n\n Container objects returned from this methods will contain a limited\n amount of metadata in property `short_metadata`. These are just a subset\n of `.inspect()`, but don't require an API call against dockerd.\n\n :return: collection of...
Please provide a description of the function:def list_images(self): response = [] for im in self.d.images(): try: i_name, tag = parse_reference(im["RepoTags"][0]) except (IndexError, TypeError): i_name, tag = None, None d_im = ...
[ "\n List all available docker images.\n\n Image objects returned from this methods will contain a limited\n amount of metadata in property `short_metadata`. These are just a subset\n of `.inspect()`, but don't require an API call against dockerd.\n\n :return: collection of instanc...
Please provide a description of the function:def login(self, username, password=None, email=None, registry=None, reauth=False, dockercfg_path=None): self.d.login(username, password, email, registry, reauth, dockercfg_path) logger.info("Login to %s succeed", registry)
[ "\n :param username: The registry username\n :param password: The plaintext password\n :param email: The email for the registry account\n :param registry: URL to the registry, example:\n - https://index.docker.io/v1/\n :param reauth: Whether or not to refresh existin...
Please provide a description of the function:def match(ctx, features, profile, gps_precision): access_token = (ctx.obj and ctx.obj.get('access_token')) or None features = list(features) if len(features) != 1: raise click.BadParameter( "Mapmatching requires a single LineString featu...
[ "Mapbox Map Matching API lets you use snap your GPS traces\nto the OpenStreetMap road and path network.\n\n $ mapbox mapmatching trace.geojson\n\nAn access token is required, see `mapbox --help`.\n " ]
Please provide a description of the function:def staticmap(ctx, mapid, output, features, lat, lon, zoom, size): access_token = (ctx.obj and ctx.obj.get('access_token')) or None if features: features = list( cligj.normalize_feature_inputs(None, 'features', [features])) service = map...
[ "\n Generate static map images from existing Mapbox map ids.\n Optionally overlay with geojson features.\n\n $ mapbox staticmap --features features.geojson mapbox.satellite out.png\n $ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png\n\n An access token is required, see...
Please provide a description of the function:def main_group(ctx, verbose, quiet, access_token, config): ctx.obj = {} config = config or os.path.join(click.get_app_dir('mapbox'), 'mapbox.ini') cfg = read_config(config) if cfg: ctx.obj['config_file'] = config ctx.obj['cfg'] = cfg ctx....
[ "This is the command line interface to Mapbox web services.\n\n Mapbox web services require an access token. Your token is shown\n on the https://www.mapbox.com/studio/account/tokens/ page when you are\n logged in. The token can be provided on the command line\n\n $ mapbox --access-token MY_TOKEN ...\...
Please provide a description of the function:def config(ctx): ctx.default_map = ctx.obj['cfg'] click.echo("CLI:") click.echo("access-token = {0}".format(ctx.obj['access_token'])) click.echo("verbosity = {0}".format(ctx.obj['verbosity'])) click.echo("") click.echo("Environment:") if 'MA...
[ "Show access token and other configuration settings.\n\n The access token and command verbosity level can be set on the\n command line, as environment variables, and in mapbox.ini config\n files.\n " ]
Please provide a description of the function:def coords_from_query(query): try: coords = json.loads(query) except ValueError: vals = re.split(r'[,\s]+', query.strip()) coords = [float(v) for v in vals] return tuple(coords[:2])
[ "Transform a query line into a (lng, lat) pair of coordinates." ]
Please provide a description of the function:def echo_headers(headers, file=None): for k, v in sorted(headers.items()): click.echo("{0}: {1}".format(k.title(), v), file=file) click.echo(file=file)
[ "Echo headers, sorted." ]
Please provide a description of the function:def geocoding(ctx, query, forward, include_headers, lat, lon, place_type, output, dataset, country, bbox, features, limit): access_token = (ctx.obj and ctx.obj.get('access_token')) or None stdout = click.open_file(output, 'w') geocoder = Geoco...
[ "This command returns places matching an address (forward mode) or\n places matching coordinates (reverse mode).\n\n In forward (the default) mode the query argument shall be an address\n such as '1600 pennsylvania ave nw'.\n\n $ mapbox geocoding '1600 pennsylvania ave nw'\n\n In reverse mode the q...
Please provide a description of the function:def datasets(ctx): access_token = (ctx.obj and ctx.obj.get('access_token')) or None service = mapbox.Datasets(access_token=access_token) ctx.obj['service'] = service
[ "Read and write GeoJSON from Mapbox-hosted datasets\n\n All endpoints require authentication. An access token with\n appropriate dataset scopes is required, see `mapbox --help`.\n\n Note that this API is currently a limited-access beta.\n " ]
Please provide a description of the function:def create(ctx, name, description): service = ctx.obj.get('service') res = service.create(name, description) if res.status_code == 200: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
[ "Create a new dataset.\n\n Prints a JSON object containing the attributes\n of the new dataset.\n\n $ mapbox datasets create\n\n All endpoints require authentication. An access token with\n `datasets:write` scope is required, see `mapbox --help`.\n " ]
Please provide a description of the function:def read_dataset(ctx, dataset, output): stdout = click.open_file(output, 'w') service = ctx.obj.get('service') res = service.read_dataset(dataset) if res.status_code == 200: click.echo(res.text, file=stdout) else: raise MapboxCLIExc...
[ "Read the attributes of a dataset.\n\n Prints a JSON object containing the attributes\n of a dataset. The attributes: owner (a Mapbox account),\n id (dataset id), created (Unix timestamp), modified\n (timestamp), name (string), and description (string).\n\n $ mapbox datasets read-dataset dataset-...
Please provide a description of the function:def delete_dataset(ctx, dataset): service = ctx.obj.get('service') res = service.delete_dataset(dataset) if res.status_code != 204: raise MapboxCLIException(res.text.strip())
[ "Delete a dataset.\n\n $ mapbox datasets delete-dataset dataset-id\n\n All endpoints require authentication. An access token with\n `datasets:write` scope is required, see `mapbox --help`.\n " ]
Please provide a description of the function:def list_features(ctx, dataset, reverse, start, limit, output): stdout = click.open_file(output, 'w') service = ctx.obj.get('service') res = service.list_features(dataset, reverse, start, limit) if res.status_code == 200: click.echo(res.text, f...
[ "Get features of a dataset.\n\n Prints the features of the dataset as a GeoJSON feature collection.\n\n $ mapbox datasets list-features dataset-id\n\n All endpoints require authentication. An access token with\n `datasets:read` scope is required, see `mapbox --help`.\n " ]
Please provide a description of the function:def put_feature(ctx, dataset, fid, feature, input): if feature is None: stdin = click.open_file(input, 'r') feature = stdin.read() feature = json.loads(feature) service = ctx.obj.get('service') res = service.update_feature(dataset, fid...
[ "Create or update a dataset feature.\n\n The semantics of HTTP PUT apply: if the dataset has no feature\n with the given `fid` a new feature will be created. Returns a\n GeoJSON representation of the new or updated feature.\n\n $ mapbox datasets put-feature dataset-id feature-id 'geojson-feature'\n\...
Please provide a description of the function:def delete_feature(ctx, dataset, fid): service = ctx.obj.get('service') res = service.delete_feature(dataset, fid) if res.status_code != 204: raise MapboxCLIException(res.text.strip())
[ "Delete a feature.\n\n $ mapbox datasets delete-feature dataset-id feature-id\n\n All endpoints require authentication. An access token with\n `datasets:write` scope is required, see `mapbox --help`.\n " ]
Please provide a description of the function:def create_tileset(ctx, dataset, tileset, name): access_token = (ctx.obj and ctx.obj.get('access_token')) or None service = mapbox.Uploader(access_token=access_token) uri = "mapbox://datasets/{username}/{dataset}".format( username=tileset.split('.'...
[ "Create a vector tileset from a dataset.\n\n $ mapbox datasets create-tileset dataset-id username.data\n\n Note that the tileset must start with your username and the dataset\n must be one that you own. To view processing status, visit\n https://www.mapbox.com/data/. You may not generate another til...
Please provide a description of the function:def directions(ctx, features, profile, alternatives, geometries, overview, steps, continue_straight, waypoint_snapping, annotations, language, output): access_token = (ctx.obj and ctx.obj.get("access_token")) or None service = m...
[ "The Mapbox Directions API will show you how to get\n where you're going.\n\n mapbox directions \"[0, 0]\" \"[1, 1]\"\n\n An access token is required. See \"mapbox --help\".\n " ]
Please provide a description of the function:def upload(ctx, tileset, datasource, name, patch): access_token = (ctx.obj and ctx.obj.get('access_token')) or None service = mapbox.Uploader(access_token=access_token) if name is None: name = tileset.split(".")[-1] if datasource.startswith('h...
[ "Upload data to Mapbox accounts.\n\n Uploaded data lands at https://www.mapbox.com/data/ and can be used\n in new or existing projects. All endpoints require authentication.\n\n You can specify the tileset id and input file\n\n $ mapbox upload username.data mydata.geojson\n\n Or specify just the ti...
Please provide a description of the function:def _read_notebook(self, os_path, as_version=4): with self.open(os_path, 'r', encoding='utf-8') as f: try: if ftdetect(os_path) == 'notebook': return nbformat.read(f, as_version=as_version) elif...
[ "Read a notebook from an os path." ]
Please provide a description of the function:def _save_notebook(self, os_path, nb): with self.atomic_writing(os_path, encoding='utf-8') as f: if ftdetect(os_path) == 'notebook': nbformat.write(nb, f, version=nbformat.NO_CONVERT) elif ftdetect(os_path) == 'markdow...
[ "Save a notebook to an os_path." ]
Please provide a description of the function:def ftdetect(filename): _, extension = os.path.splitext(filename) md_exts = ['.md', '.markdown', '.mkd', '.mdown', '.mkdn', '.Rmd'] nb_exts = ['.ipynb'] if extension in md_exts: return 'markdown' elif extension in nb_exts: return 'not...
[ "Determine if filename is markdown or notebook,\n based on the file extension.\n " ]
Please provide a description of the function:def command_line_parser(): description = "Create an IPython notebook from markdown." example_use = "Example: notedown some_markdown.md > new_notebook.ipynb" parser = argparse.ArgumentParser(description=description, epilo...
[ "Create parser for command line usage." ]
Please provide a description of the function:def strip(notebook): for cell in notebook.cells: if cell.cell_type == 'code': cell.outputs = [] cell.execution_count = None
[ "Remove outputs from a notebook." ]
Please provide a description of the function:def get_caption_comments(content): if not content.startswith('## fig:'): return None, None content = content.splitlines() id = content[0].strip('## ') caption = [] for line in content[1:]: if not line.startswith('# ') or line.star...
[ "Retrieve an id and a caption from a code cell.\n\n If the code cell content begins with a commented\n block that looks like\n\n ## fig:id\n # multi-line or single-line\n # caption\n\n then the 'fig:id' and the caption will be returned.\n The '#' are stripped.\n " ]
Please provide a description of the function:def new_code_block(self, **kwargs): proto = {'content': '', 'type': self.code, 'IO': '', 'attributes': ''} proto.update(**kwargs) return proto
[ "Create a new code block." ]
Please provide a description of the function:def new_text_block(self, **kwargs): proto = {'content': '', 'type': self.markdown} proto.update(**kwargs) return proto
[ "Create a new text block." ]
Please provide a description of the function:def pre_process_code_block(block): if 'indent' in block and block['indent']: indent = r'^' + block['indent'] block['content'] = re.sub(indent, '', block['icontent'], flags=re.MULTILINE)
[ "Preprocess the content of a code block, modifying the code\n block in place.\n\n Just dedents indented code.\n " ]
Please provide a description of the function:def process_code_block(self, block): if block['type'] != self.code: return block attr = PandocAttributes(block['attributes'], 'markdown') if self.match == 'all': pass elif self.match == 'fenced' and block.ge...
[ "Parse block attributes" ]
Please provide a description of the function:def parse_blocks(self, text): code_matches = [m for m in self.code_pattern.finditer(text)] # determine where the limits of the non code bits are # based on the code block edges text_starts = [0] + [m.end() for m in code_matches] ...
[ "Extract the code and non-code blocks from given markdown text.\n\n Returns a list of block dictionaries.\n\n Each dictionary has at least the keys 'type' and 'content',\n containing the type of the block ('markdown', 'code') and\n the contents of the block.\n\n Additional keys ma...
Please provide a description of the function:def create_code_cell(block): code_cell = nbbase.new_code_cell(source=block['content']) attr = block['attributes'] if not attr.is_empty: code_cell.metadata \ = nbbase.NotebookNode({'attributes': attr.to_dict()}) ...
[ "Create a notebook code cell from a block." ]
Please provide a description of the function:def create_markdown_cell(block): kwargs = {'cell_type': block['type'], 'source': block['content']} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
[ "Create a markdown cell from a block." ]
Please provide a description of the function:def create_cells(self, blocks): cells = [] for block in blocks: if (block['type'] == self.code) and (block['IO'] == 'input'): code_cell = self.create_code_cell(block) cells.append(code_cell) el...
[ "Turn the list of blocks into a list of notebook cells." ]
Please provide a description of the function:def to_notebook(self, s, **kwargs): all_blocks = self.parse_blocks(s) if self.pre_code_block['content']: # TODO: if first block is markdown, place after? all_blocks.insert(0, self.pre_code_block) blocks = [self.proces...
[ "Convert the markdown string s to an IPython notebook.\n\n Returns a notebook.\n " ]
Please provide a description of the function:def write_resources(self, resources): for filename, data in list(resources.get('outputs', {}).items()): # Determine where to write the file to dest = os.path.join(self.output_dir, filename) path = os.path.dirname(dest) ...
[ "Write the output data in resources returned by exporter\n to files.\n " ]
Please provide a description of the function:def string2json(self, string): kwargs = { 'cls': BytesEncoder, # use the IPython bytes encoder 'indent': 1, 'sort_keys': True, 'separators': (',', ': '), } return cast_unicode(json.dumps(string...
[ "Convert json into its string representation.\n Used for writing outputs to markdown." ]
Please provide a description of the function:def create_attributes(self, cell, cell_type=None): if self.strip_outputs or not hasattr(cell, 'execution_count'): return 'python' attrs = cell.metadata.get('attributes') attr = PandocAttributes(attrs, 'dict') if 'python'...
[ "Turn the attribute dict into an attribute string\n for the code block.\n " ]
Please provide a description of the function:def dequote(s): if len(s) < 2: return s elif (s[0] == s[-1]) and s.startswith(('"', "'")): return s[1: -1] else: return s
[ "Remove excess quotes from a string." ]
Please provide a description of the function:def data2uri(data, data_type): MIME_MAP = { 'image/jpeg': 'jpeg', 'image/png': 'png', 'text/plain': 'text', 'text/html': 'html', 'text/latex': 'latex', 'application/javascript': 'html', ...
[ "Convert base64 data into a data uri with the given data_type." ]
Please provide a description of the function:def magic(self, alias): if alias in self.aliases: return self.aliases[alias] else: return "%%{}\n".format(alias)
[ "Returns the appropriate IPython code magic when\n called with an alias for a language.\n " ]
Please provide a description of the function:def knit(self, input_file, opts_chunk='eval=FALSE'): # use temporary files at both ends to allow stdin / stdout tmp_in = tempfile.NamedTemporaryFile(mode='w+') tmp_out = tempfile.NamedTemporaryFile(mode='w+') tmp_in.file.write(input_...
[ "Use Knitr to convert the r-markdown input_file\n into markdown, returning a file object.\n " ]
Please provide a description of the function:def _knit(fin, fout, opts_knit='progress=FALSE, verbose=FALSE', opts_chunk='eval=FALSE'): script = ('sink("/dev/null");' 'library(knitr);' 'opts_knit$set({opts_knit});' 'opts_c...
[ "Use knitr to convert r markdown (or anything knitr supports)\n to markdown.\n\n fin / fout - strings, input / output filenames.\n opts_knit - string, options to pass to knit\n opts_shunk - string, chunk options\n\n options are passed verbatim to knitr:knit running in Rscript.\n ...
Please provide a description of the function:def is_path_protected(path): protected = True for exclude_path in TERMS_EXCLUDE_URL_PREFIX_LIST: if path.startswith(exclude_path): protected = False for contains_path in TERMS_EXCLUDE_URL_CONTAINS_LIST: if contains_path in path:...
[ "\n returns True if given path is to be protected, otherwise False\n\n The path is not to be protected when it appears on:\n TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as\n ACCEPT_TERMS_PATH\n " ]
Please provide a description of the function:def process_request(self, request): LOGGER.debug('termsandconditions.middleware') current_path = request.META['PATH_INFO'] if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: ...
[ "Process each request to app to ensure terms have been accepted" ]
Please provide a description of the function:def get_terms(self, kwargs): slug = kwargs.get("slug") version = kwargs.get("version") if slug and version: terms = [TermsAndConditions.objects.filter(slug=slug, version_number=version).latest('date_active')] elif slug: ...
[ "Checks URL parameters for slug and/or version to pull the right TermsAndConditions object" ]
Please provide a description of the function:def get_context_data(self, **kwargs): context = super(TermsView, self).get_context_data(**kwargs) context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE) return context
[ "Pass additional context data" ]
Please provide a description of the function:def get_initial(self): LOGGER.debug('termsandconditions.views.AcceptTermsView.get_initial') terms = self.get_terms(self.kwargs) return_to = self.request.GET.get('returnTo', '/') return {'terms': terms, 'returnTo': return_to}
[ "Override of CreateView method, queries for which T&C to accept and catches returnTo from URL" ]
Please provide a description of the function:def post(self, request, *args, **kwargs): return_url = request.POST.get('returnTo', '/') terms_ids = request.POST.getlist('terms') if not terms_ids: # pragma: nocover return HttpResponseRedirect(return_url) if DJANGO_VE...
[ "\n Handles POST request.\n " ]