id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
10,300
user-cont/conu
conu/backend/k8s/backend.py
K8sBackend.list_pods
def list_pods(self, namespace=None): """ List all available pods. :param namespace: str, if not specified list pods for all namespaces :return: collection of instances of :class:`conu.backend.k8s.pod.Pod` """ 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.metadata.name, namespace=p.metadata.namespace, spec=p.spec) for p in self.core_api.list_pod_for_all_namespaces(watch=False).items]
python
def list_pods(self, namespace=None): """ List all available pods. :param namespace: str, if not specified list pods for all namespaces :return: collection of instances of :class:`conu.backend.k8s.pod.Pod` """ 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.metadata.name, namespace=p.metadata.namespace, spec=p.spec) for p in self.core_api.list_pod_for_all_namespaces(watch=False).items]
[ "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", ".", "metadata", ".", "name", ",", "namespace", "=", "p", ".", "metadata", ".", "namespace", ",", "spec", "=", "p", ".", "spec", ")", "for", "p", "in", "self", ".", "core_api", ".", "list_pod_for_all_namespaces", "(", "watch", "=", "False", ")", ".", "items", "]" ]
List all available pods. :param namespace: str, if not specified list pods for all namespaces :return: collection of instances of :class:`conu.backend.k8s.pod.Pod`
[ "List", "all", "available", "pods", "." ]
08caae7bb6bdd265b55bb106c3da6a7946a5a352
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/k8s/backend.py#L70-L83
10,301
user-cont/conu
conu/backend/k8s/backend.py
K8sBackend.list_services
def list_services(self, namespace=None): """ List all available services. :param namespace: str, if not specified list services for all namespaces :return: collection of instances of :class:`conu.backend.k8s.service.Service` """ if namespace: return [Service(name=s.metadata.name, ports=k8s_ports_to_metadata_ports(s.spec.ports), namespace=s.metadata.namespace, labels=s.metadata.labels, selector=s.spec.selector, spec=s.spec) for s in self.core_api.list_namespaced_service(namespace, watch=False).items] return [Service(name=s.metadata.name, ports=k8s_ports_to_metadata_ports(s.spec.ports), namespace=s.metadata.namespace, labels=s.metadata.labels, selector=s.spec.selector, spec=s.spec) for s in self.core_api.list_service_for_all_namespaces(watch=False).items]
python
def list_services(self, namespace=None): """ List all available services. :param namespace: str, if not specified list services for all namespaces :return: collection of instances of :class:`conu.backend.k8s.service.Service` """ if namespace: return [Service(name=s.metadata.name, ports=k8s_ports_to_metadata_ports(s.spec.ports), namespace=s.metadata.namespace, labels=s.metadata.labels, selector=s.spec.selector, spec=s.spec) for s in self.core_api.list_namespaced_service(namespace, watch=False).items] return [Service(name=s.metadata.name, ports=k8s_ports_to_metadata_ports(s.spec.ports), namespace=s.metadata.namespace, labels=s.metadata.labels, selector=s.spec.selector, spec=s.spec) for s in self.core_api.list_service_for_all_namespaces(watch=False).items]
[ "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", ",", "labels", "=", "s", ".", "metadata", ".", "labels", ",", "selector", "=", "s", ".", "spec", ".", "selector", ",", "spec", "=", "s", ".", "spec", ")", "for", "s", "in", "self", ".", "core_api", ".", "list_namespaced_service", "(", "namespace", ",", "watch", "=", "False", ")", ".", "items", "]", "return", "[", "Service", "(", "name", "=", "s", ".", "metadata", ".", "name", ",", "ports", "=", "k8s_ports_to_metadata_ports", "(", "s", ".", "spec", ".", "ports", ")", ",", "namespace", "=", "s", ".", "metadata", ".", "namespace", ",", "labels", "=", "s", ".", "metadata", ".", "labels", ",", "selector", "=", "s", ".", "spec", ".", "selector", ",", "spec", "=", "s", ".", "spec", ")", "for", "s", "in", "self", ".", "core_api", ".", "list_service_for_all_namespaces", "(", "watch", "=", "False", ")", ".", "items", "]" ]
List all available services. :param namespace: str, if not specified list services for all namespaces :return: collection of instances of :class:`conu.backend.k8s.service.Service`
[ "List", "all", "available", "services", "." ]
08caae7bb6bdd265b55bb106c3da6a7946a5a352
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/k8s/backend.py#L85-L104
10,302
user-cont/conu
conu/backend/k8s/backend.py
K8sBackend.list_deployments
def list_deployments(self, namespace=None): """ List all available deployments. :param namespace: str, if not specified list deployments for all namespaces :return: collection of instances of :class:`conu.backend.k8s.deployment.Deployment` """ if namespace: return [Deployment(name=d.metadata.name, namespace=d.metadata.namespace, labels=d.metadata.labels, selector=d.spec.selector, image_metadata=ImageMetadata( name=d.spec.template.spec.containers[0].name.split("-", 1)[0])) for d in self.apps_api.list_namespaced_deployment(namespace, watch=False).items] return [Deployment(name=d.metadata.name, namespace=d.metadata.namespace, labels=d.metadata.labels, selector=d.spec.selector, image_metadata=ImageMetadata( name=d.spec.template.spec.containers[0].name.split("-", 1)[0])) for d in self.apps_api.list_deployment_for_all_namespaces(watch=False).items]
python
def list_deployments(self, namespace=None): """ List all available deployments. :param namespace: str, if not specified list deployments for all namespaces :return: collection of instances of :class:`conu.backend.k8s.deployment.Deployment` """ if namespace: return [Deployment(name=d.metadata.name, namespace=d.metadata.namespace, labels=d.metadata.labels, selector=d.spec.selector, image_metadata=ImageMetadata( name=d.spec.template.spec.containers[0].name.split("-", 1)[0])) for d in self.apps_api.list_namespaced_deployment(namespace, watch=False).items] return [Deployment(name=d.metadata.name, namespace=d.metadata.namespace, labels=d.metadata.labels, selector=d.spec.selector, image_metadata=ImageMetadata( name=d.spec.template.spec.containers[0].name.split("-", 1)[0])) for d in self.apps_api.list_deployment_for_all_namespaces(watch=False).items]
[ "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", ",", "image_metadata", "=", "ImageMetadata", "(", "name", "=", "d", ".", "spec", ".", "template", ".", "spec", ".", "containers", "[", "0", "]", ".", "name", ".", "split", "(", "\"-\"", ",", "1", ")", "[", "0", "]", ")", ")", "for", "d", "in", "self", ".", "apps_api", ".", "list_namespaced_deployment", "(", "namespace", ",", "watch", "=", "False", ")", ".", "items", "]", "return", "[", "Deployment", "(", "name", "=", "d", ".", "metadata", ".", "name", ",", "namespace", "=", "d", ".", "metadata", ".", "namespace", ",", "labels", "=", "d", ".", "metadata", ".", "labels", ",", "selector", "=", "d", ".", "spec", ".", "selector", ",", "image_metadata", "=", "ImageMetadata", "(", "name", "=", "d", ".", "spec", ".", "template", ".", "spec", ".", "containers", "[", "0", "]", ".", "name", ".", "split", "(", "\"-\"", ",", "1", ")", "[", "0", "]", ")", ")", "for", "d", "in", "self", ".", "apps_api", ".", "list_deployment_for_all_namespaces", "(", "watch", "=", "False", ")", ".", "items", "]" ]
List all available deployments. :param namespace: str, if not specified list deployments for all namespaces :return: collection of instances of :class:`conu.backend.k8s.deployment.Deployment`
[ "List", "all", "available", "deployments", "." ]
08caae7bb6bdd265b55bb106c3da6a7946a5a352
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/k8s/backend.py#L106-L127
10,303
user-cont/conu
conu/utils/http_client.py
get_url
def get_url(path, host, port, method="http"): """ make url from path, host and port :param method: str :param path: str, path within the request, e.g. "/api/version" :param host: str :param port: str or int :return: str """ return urlunsplit( (method, "%s:%s" % (host, port), path, "", "") )
python
def get_url(path, host, port, method="http"): """ make url from path, host and port :param method: str :param path: str, path within the request, e.g. "/api/version" :param host: str :param port: str or int :return: str """ return urlunsplit( (method, "%s:%s" % (host, port), path, "", "") )
[ "def", "get_url", "(", "path", ",", "host", ",", "port", ",", "method", "=", "\"http\"", ")", ":", "return", "urlunsplit", "(", "(", "method", ",", "\"%s:%s\"", "%", "(", "host", ",", "port", ")", ",", "path", ",", "\"\"", ",", "\"\"", ")", ")" ]
make url from path, host and port :param method: str :param path: str, path within the request, e.g. "/api/version" :param host: str :param port: str or int :return: str
[ "make", "url", "from", "path", "host", "and", "port" ]
08caae7bb6bdd265b55bb106c3da6a7946a5a352
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/http_client.py#L20-L32
10,304
user-cont/conu
conu/backend/docker/backend.py
DockerBackend.list_containers
def list_containers(self): """ List all available docker containers. Container objects returned from this methods will contain a limited amount of metadata in property `short_metadata`. These are just a subset of `.inspect()`, but don't require an API call against dockerd. :return: collection of instances of :class:`conu.DockerContainer` """ 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["ImageID"]) cont = DockerContainer(i, c["Id"], name=name) # TODO: docker_client.containers produces different metadata than inspect inspect_to_container_metadata(cont.metadata, c, i) result.append(cont) return result
python
def list_containers(self): """ List all available docker containers. Container objects returned from this methods will contain a limited amount of metadata in property `short_metadata`. These are just a subset of `.inspect()`, but don't require an API call against dockerd. :return: collection of instances of :class:`conu.DockerContainer` """ 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["ImageID"]) cont = DockerContainer(i, c["Id"], name=name) # TODO: docker_client.containers produces different metadata than inspect inspect_to_container_metadata(cont.metadata, c, i) result.append(cont) return result
[ "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", "[", "\"ImageID\"", "]", ")", "cont", "=", "DockerContainer", "(", "i", ",", "c", "[", "\"Id\"", "]", ",", "name", "=", "name", ")", "# TODO: docker_client.containers produces different metadata than inspect", "inspect_to_container_metadata", "(", "cont", ".", "metadata", ",", "c", ",", "i", ")", "result", ".", "append", "(", "cont", ")", "return", "result" ]
List all available docker containers. Container objects returned from this methods will contain a limited amount of metadata in property `short_metadata`. These are just a subset of `.inspect()`, but don't require an API call against dockerd. :return: collection of instances of :class:`conu.DockerContainer`
[ "List", "all", "available", "docker", "containers", "." ]
08caae7bb6bdd265b55bb106c3da6a7946a5a352
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/docker/backend.py#L85-L106
10,305
user-cont/conu
conu/backend/docker/backend.py
DockerBackend.list_images
def list_images(self): """ List all available docker images. Image objects returned from this methods will contain a limited amount of metadata in property `short_metadata`. These are just a subset of `.inspect()`, but don't require an API call against dockerd. :return: collection of instances of :class:`conu.DockerImage` """ 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 = DockerImage(i_name, tag=tag, identifier=im["Id"], pull_policy=DockerImagePullPolicy.NEVER) inspect_to_metadata(d_im.metadata, im) response.append(d_im) return response
python
def list_images(self): """ List all available docker images. Image objects returned from this methods will contain a limited amount of metadata in property `short_metadata`. These are just a subset of `.inspect()`, but don't require an API call against dockerd. :return: collection of instances of :class:`conu.DockerImage` """ 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 = DockerImage(i_name, tag=tag, identifier=im["Id"], pull_policy=DockerImagePullPolicy.NEVER) inspect_to_metadata(d_im.metadata, im) response.append(d_im) return response
[ "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", "=", "DockerImage", "(", "i_name", ",", "tag", "=", "tag", ",", "identifier", "=", "im", "[", "\"Id\"", "]", ",", "pull_policy", "=", "DockerImagePullPolicy", ".", "NEVER", ")", "inspect_to_metadata", "(", "d_im", ".", "metadata", ",", "im", ")", "response", ".", "append", "(", "d_im", ")", "return", "response" ]
List all available docker images. Image objects returned from this methods will contain a limited amount of metadata in property `short_metadata`. These are just a subset of `.inspect()`, but don't require an API call against dockerd. :return: collection of instances of :class:`conu.DockerImage`
[ "List", "all", "available", "docker", "images", "." ]
08caae7bb6bdd265b55bb106c3da6a7946a5a352
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/docker/backend.py#L108-L129
10,306
mapbox/mapbox-cli-py
mapboxcli/scripts/mapmatching.py
match
def match(ctx, features, profile, gps_precision): """Mapbox Map Matching API lets you use snap your GPS traces to the OpenStreetMap road and path network. $ mapbox mapmatching trace.geojson An access token is required, see `mapbox --help`. """ 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 feature") service = mapbox.MapMatcher(access_token=access_token) try: res = service.match( features[0], profile=profile, gps_precision=gps_precision) except mapbox.errors.ValidationError as exc: raise click.BadParameter(str(exc)) if res.status_code == 200: stdout = click.open_file('-', 'w') click.echo(res.text, file=stdout) else: raise MapboxCLIException(res.text.strip())
python
def match(ctx, features, profile, gps_precision): """Mapbox Map Matching API lets you use snap your GPS traces to the OpenStreetMap road and path network. $ mapbox mapmatching trace.geojson An access token is required, see `mapbox --help`. """ 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 feature") service = mapbox.MapMatcher(access_token=access_token) try: res = service.match( features[0], profile=profile, gps_precision=gps_precision) except mapbox.errors.ValidationError as exc: raise click.BadParameter(str(exc)) if res.status_code == 200: stdout = click.open_file('-', 'w') click.echo(res.text, file=stdout) else: raise MapboxCLIException(res.text.strip())
[ "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 feature\"", ")", "service", "=", "mapbox", ".", "MapMatcher", "(", "access_token", "=", "access_token", ")", "try", ":", "res", "=", "service", ".", "match", "(", "features", "[", "0", "]", ",", "profile", "=", "profile", ",", "gps_precision", "=", "gps_precision", ")", "except", "mapbox", ".", "errors", ".", "ValidationError", "as", "exc", ":", "raise", "click", ".", "BadParameter", "(", "str", "(", "exc", ")", ")", "if", "res", ".", "status_code", "==", "200", ":", "stdout", "=", "click", ".", "open_file", "(", "'-'", ",", "'w'", ")", "click", ".", "echo", "(", "res", ".", "text", ",", "file", "=", "stdout", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Mapbox Map Matching API lets you use snap your GPS traces to the OpenStreetMap road and path network. $ mapbox mapmatching trace.geojson An access token is required, see `mapbox --help`.
[ "Mapbox", "Map", "Matching", "API", "lets", "you", "use", "snap", "your", "GPS", "traces", "to", "the", "OpenStreetMap", "road", "and", "path", "network", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/mapmatching.py#L15-L43
10,307
mapbox/mapbox-cli-py
mapboxcli/scripts/static.py
staticmap
def staticmap(ctx, mapid, output, features, lat, lon, zoom, size): """ Generate static map images from existing Mapbox map ids. Optionally overlay with geojson features. $ mapbox staticmap --features features.geojson mapbox.satellite out.png $ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png An access token is required, see `mapbox --help`. """ access_token = (ctx.obj and ctx.obj.get('access_token')) or None if features: features = list( cligj.normalize_feature_inputs(None, 'features', [features])) service = mapbox.Static(access_token=access_token) try: res = service.image( mapid, lon=lon, lat=lat, z=zoom, width=size[0], height=size[1], features=features, sort_keys=True) except mapbox.errors.ValidationError as exc: raise click.BadParameter(str(exc)) if res.status_code == 200: output.write(res.content) else: raise MapboxCLIException(res.text.strip())
python
def staticmap(ctx, mapid, output, features, lat, lon, zoom, size): """ Generate static map images from existing Mapbox map ids. Optionally overlay with geojson features. $ mapbox staticmap --features features.geojson mapbox.satellite out.png $ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png An access token is required, see `mapbox --help`. """ access_token = (ctx.obj and ctx.obj.get('access_token')) or None if features: features = list( cligj.normalize_feature_inputs(None, 'features', [features])) service = mapbox.Static(access_token=access_token) try: res = service.image( mapid, lon=lon, lat=lat, z=zoom, width=size[0], height=size[1], features=features, sort_keys=True) except mapbox.errors.ValidationError as exc: raise click.BadParameter(str(exc)) if res.status_code == 200: output.write(res.content) else: raise MapboxCLIException(res.text.strip())
[ "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", "=", "mapbox", ".", "Static", "(", "access_token", "=", "access_token", ")", "try", ":", "res", "=", "service", ".", "image", "(", "mapid", ",", "lon", "=", "lon", ",", "lat", "=", "lat", ",", "z", "=", "zoom", ",", "width", "=", "size", "[", "0", "]", ",", "height", "=", "size", "[", "1", "]", ",", "features", "=", "features", ",", "sort_keys", "=", "True", ")", "except", "mapbox", ".", "errors", ".", "ValidationError", "as", "exc", ":", "raise", "click", ".", "BadParameter", "(", "str", "(", "exc", ")", ")", "if", "res", ".", "status_code", "==", "200", ":", "output", ".", "write", "(", "res", ".", "content", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Generate static map images from existing Mapbox map ids. Optionally overlay with geojson features. $ mapbox staticmap --features features.geojson mapbox.satellite out.png $ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png An access token is required, see `mapbox --help`.
[ "Generate", "static", "map", "images", "from", "existing", "Mapbox", "map", "ids", ".", "Optionally", "overlay", "with", "geojson", "features", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/static.py#L18-L47
10,308
mapbox/mapbox-cli-py
mapboxcli/scripts/cli.py
main_group
def main_group(ctx, verbose, quiet, access_token, config): """This is the command line interface to Mapbox web services. Mapbox web services require an access token. Your token is shown on the https://www.mapbox.com/studio/account/tokens/ page when you are logged in. The token can be provided on the command line $ mapbox --access-token MY_TOKEN ... as an environment variable named MAPBOX_ACCESS_TOKEN (higher precedence) or MapboxAccessToken (lower precedence). \b $ export MAPBOX_ACCESS_TOKEN=MY_TOKEN $ mapbox ... or in a config file \b ; configuration file mapbox.ini [mapbox] access-token = MY_TOKEN The OS-dependent default config file path is something like \b ~/Library/Application Support/mapbox/mapbox.ini ~/.config/mapbox/mapbox.ini ~/.mapbox/mapbox.ini """ 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.default_map = cfg verbosity = (os.environ.get('MAPBOX_VERBOSE') or ctx.lookup_default('mapbox.verbosity') or 0) if verbose or quiet: verbosity = verbose - quiet verbosity = int(verbosity) configure_logging(verbosity) access_token = (access_token or os.environ.get('MAPBOX_ACCESS_TOKEN') or os.environ.get('MapboxAccessToken') or ctx.lookup_default('mapbox.access-token')) ctx.obj['verbosity'] = verbosity ctx.obj['access_token'] = access_token
python
def main_group(ctx, verbose, quiet, access_token, config): """This is the command line interface to Mapbox web services. Mapbox web services require an access token. Your token is shown on the https://www.mapbox.com/studio/account/tokens/ page when you are logged in. The token can be provided on the command line $ mapbox --access-token MY_TOKEN ... as an environment variable named MAPBOX_ACCESS_TOKEN (higher precedence) or MapboxAccessToken (lower precedence). \b $ export MAPBOX_ACCESS_TOKEN=MY_TOKEN $ mapbox ... or in a config file \b ; configuration file mapbox.ini [mapbox] access-token = MY_TOKEN The OS-dependent default config file path is something like \b ~/Library/Application Support/mapbox/mapbox.ini ~/.config/mapbox/mapbox.ini ~/.mapbox/mapbox.ini """ 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.default_map = cfg verbosity = (os.environ.get('MAPBOX_VERBOSE') or ctx.lookup_default('mapbox.verbosity') or 0) if verbose or quiet: verbosity = verbose - quiet verbosity = int(verbosity) configure_logging(verbosity) access_token = (access_token or os.environ.get('MAPBOX_ACCESS_TOKEN') or os.environ.get('MapboxAccessToken') or ctx.lookup_default('mapbox.access-token')) ctx.obj['verbosity'] = verbosity ctx.obj['access_token'] = access_token
[ "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", ".", "default_map", "=", "cfg", "verbosity", "=", "(", "os", ".", "environ", ".", "get", "(", "'MAPBOX_VERBOSE'", ")", "or", "ctx", ".", "lookup_default", "(", "'mapbox.verbosity'", ")", "or", "0", ")", "if", "verbose", "or", "quiet", ":", "verbosity", "=", "verbose", "-", "quiet", "verbosity", "=", "int", "(", "verbosity", ")", "configure_logging", "(", "verbosity", ")", "access_token", "=", "(", "access_token", "or", "os", ".", "environ", ".", "get", "(", "'MAPBOX_ACCESS_TOKEN'", ")", "or", "os", ".", "environ", ".", "get", "(", "'MapboxAccessToken'", ")", "or", "ctx", ".", "lookup_default", "(", "'mapbox.access-token'", ")", ")", "ctx", ".", "obj", "[", "'verbosity'", "]", "=", "verbosity", "ctx", ".", "obj", "[", "'access_token'", "]", "=", "access_token" ]
This is the command line interface to Mapbox web services. Mapbox web services require an access token. Your token is shown on the https://www.mapbox.com/studio/account/tokens/ page when you are logged in. The token can be provided on the command line $ mapbox --access-token MY_TOKEN ... as an environment variable named MAPBOX_ACCESS_TOKEN (higher precedence) or MapboxAccessToken (lower precedence). \b $ export MAPBOX_ACCESS_TOKEN=MY_TOKEN $ mapbox ... or in a config file \b ; configuration file mapbox.ini [mapbox] access-token = MY_TOKEN The OS-dependent default config file path is something like \b ~/Library/Application Support/mapbox/mapbox.ini ~/.config/mapbox/mapbox.ini ~/.mapbox/mapbox.ini
[ "This", "is", "the", "command", "line", "interface", "to", "Mapbox", "web", "services", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/cli.py#L43-L94
10,309
mapbox/mapbox-cli-py
mapboxcli/scripts/config.py
config
def config(ctx): """Show access token and other configuration settings. The access token and command verbosity level can be set on the command line, as environment variables, and in mapbox.ini config files. """ 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 'MAPBOX_ACCESS_TOKEN' in os.environ: click.echo("MAPBOX_ACCESS_TOKEN = {0}".format( os.environ['MAPBOX_ACCESS_TOKEN'])) if 'MapboxAccessToken' in os.environ: click.echo("MapboxAccessToken = {0}".format( os.environ['MapboxAccessToken'])) if 'MAPBOX_VERBOSE' in os.environ: click.echo("MAPBOX_VERBOSE = {0}".format( os.environ['MAPBOX_VERBOSE'])) click.echo("") if 'config_file' in ctx.obj: click.echo("Config file {0}:".format(ctx.obj['config_file'])) for key, value in ctx.default_map.items(): click.echo("{0} = {1}".format(key, value)) click.echo("")
python
def config(ctx): """Show access token and other configuration settings. The access token and command verbosity level can be set on the command line, as environment variables, and in mapbox.ini config files. """ 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 'MAPBOX_ACCESS_TOKEN' in os.environ: click.echo("MAPBOX_ACCESS_TOKEN = {0}".format( os.environ['MAPBOX_ACCESS_TOKEN'])) if 'MapboxAccessToken' in os.environ: click.echo("MapboxAccessToken = {0}".format( os.environ['MapboxAccessToken'])) if 'MAPBOX_VERBOSE' in os.environ: click.echo("MAPBOX_VERBOSE = {0}".format( os.environ['MAPBOX_VERBOSE'])) click.echo("") if 'config_file' in ctx.obj: click.echo("Config file {0}:".format(ctx.obj['config_file'])) for key, value in ctx.default_map.items(): click.echo("{0} = {1}".format(key, value)) click.echo("")
[ "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", "'MAPBOX_ACCESS_TOKEN'", "in", "os", ".", "environ", ":", "click", ".", "echo", "(", "\"MAPBOX_ACCESS_TOKEN = {0}\"", ".", "format", "(", "os", ".", "environ", "[", "'MAPBOX_ACCESS_TOKEN'", "]", ")", ")", "if", "'MapboxAccessToken'", "in", "os", ".", "environ", ":", "click", ".", "echo", "(", "\"MapboxAccessToken = {0}\"", ".", "format", "(", "os", ".", "environ", "[", "'MapboxAccessToken'", "]", ")", ")", "if", "'MAPBOX_VERBOSE'", "in", "os", ".", "environ", ":", "click", ".", "echo", "(", "\"MAPBOX_VERBOSE = {0}\"", ".", "format", "(", "os", ".", "environ", "[", "'MAPBOX_VERBOSE'", "]", ")", ")", "click", ".", "echo", "(", "\"\"", ")", "if", "'config_file'", "in", "ctx", ".", "obj", ":", "click", ".", "echo", "(", "\"Config file {0}:\"", ".", "format", "(", "ctx", ".", "obj", "[", "'config_file'", "]", ")", ")", "for", "key", ",", "value", "in", "ctx", ".", "default_map", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "\"{0} = {1}\"", ".", "format", "(", "key", ",", "value", ")", ")", "click", ".", "echo", "(", "\"\"", ")" ]
Show access token and other configuration settings. The access token and command verbosity level can be set on the command line, as environment variables, and in mapbox.ini config files.
[ "Show", "access", "token", "and", "other", "configuration", "settings", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/config.py#L8-L37
10,310
mapbox/mapbox-cli-py
mapboxcli/scripts/geocoding.py
echo_headers
def echo_headers(headers, file=None): """Echo headers, sorted.""" for k, v in sorted(headers.items()): click.echo("{0}: {1}".format(k.title(), v), file=file) click.echo(file=file)
python
def echo_headers(headers, file=None): """Echo headers, sorted.""" for k, v in sorted(headers.items()): click.echo("{0}: {1}".format(k.title(), v), file=file) click.echo(file=file)
[ "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.
[ "Echo", "headers", "sorted", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L34-L38
10,311
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
datasets
def datasets(ctx): """Read and write GeoJSON from Mapbox-hosted datasets All endpoints require authentication. An access token with appropriate dataset scopes is required, see `mapbox --help`. Note that this API is currently a limited-access beta. """ access_token = (ctx.obj and ctx.obj.get('access_token')) or None service = mapbox.Datasets(access_token=access_token) ctx.obj['service'] = service
python
def datasets(ctx): """Read and write GeoJSON from Mapbox-hosted datasets All endpoints require authentication. An access token with appropriate dataset scopes is required, see `mapbox --help`. Note that this API is currently a limited-access beta. """ access_token = (ctx.obj and ctx.obj.get('access_token')) or None service = mapbox.Datasets(access_token=access_token) ctx.obj['service'] = service
[ "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 All endpoints require authentication. An access token with appropriate dataset scopes is required, see `mapbox --help`. Note that this API is currently a limited-access beta.
[ "Read", "and", "write", "GeoJSON", "from", "Mapbox", "-", "hosted", "datasets" ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L13-L24
10,312
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
create
def create(ctx, name, description): """Create a new dataset. Prints a JSON object containing the attributes of the new dataset. $ mapbox datasets create All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`. """ 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())
python
def create(ctx, name, description): """Create a new dataset. Prints a JSON object containing the attributes of the new dataset. $ mapbox datasets create All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`. """ 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())
[ "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. Prints a JSON object containing the attributes of the new dataset. $ mapbox datasets create All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`.
[ "Create", "a", "new", "dataset", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L56-L74
10,313
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
read_dataset
def read_dataset(ctx, dataset, output): """Read the attributes of a dataset. Prints a JSON object containing the attributes of a dataset. The attributes: owner (a Mapbox account), id (dataset id), created (Unix timestamp), modified (timestamp), name (string), and description (string). $ mapbox datasets read-dataset dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`. """ 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 MapboxCLIException(res.text.strip())
python
def read_dataset(ctx, dataset, output): """Read the attributes of a dataset. Prints a JSON object containing the attributes of a dataset. The attributes: owner (a Mapbox account), id (dataset id), created (Unix timestamp), modified (timestamp), name (string), and description (string). $ mapbox datasets read-dataset dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`. """ 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 MapboxCLIException(res.text.strip())
[ "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", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Read the attributes of a dataset. Prints a JSON object containing the attributes of a dataset. The attributes: owner (a Mapbox account), id (dataset id), created (Unix timestamp), modified (timestamp), name (string), and description (string). $ mapbox datasets read-dataset dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`.
[ "Read", "the", "attributes", "of", "a", "dataset", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L82-L103
10,314
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
list_features
def list_features(ctx, dataset, reverse, start, limit, output): """Get features of a dataset. Prints the features of the dataset as a GeoJSON feature collection. $ mapbox datasets list-features dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`. """ 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, file=stdout) else: raise MapboxCLIException(res.text.strip())
python
def list_features(ctx, dataset, reverse, start, limit, output): """Get features of a dataset. Prints the features of the dataset as a GeoJSON feature collection. $ mapbox datasets list-features dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`. """ 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, file=stdout) else: raise MapboxCLIException(res.text.strip())
[ "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", ",", "file", "=", "stdout", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Get features of a dataset. Prints the features of the dataset as a GeoJSON feature collection. $ mapbox datasets list-features dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`.
[ "Get", "features", "of", "a", "dataset", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L165-L183
10,315
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
put_feature
def put_feature(ctx, dataset, fid, feature, input): """Create or update a dataset feature. The semantics of HTTP PUT apply: if the dataset has no feature with the given `fid` a new feature will be created. Returns a GeoJSON representation of the new or updated feature. $ mapbox datasets put-feature dataset-id feature-id 'geojson-feature' All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`. """ 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, feature) if res.status_code == 200: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
python
def put_feature(ctx, dataset, fid, feature, input): """Create or update a dataset feature. The semantics of HTTP PUT apply: if the dataset has no feature with the given `fid` a new feature will be created. Returns a GeoJSON representation of the new or updated feature. $ mapbox datasets put-feature dataset-id feature-id 'geojson-feature' All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`. """ 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, feature) if res.status_code == 200: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
[ "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", ",", "feature", ")", "if", "res", ".", "status_code", "==", "200", ":", "click", ".", "echo", "(", "res", ".", "text", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Create or update a dataset feature. The semantics of HTTP PUT apply: if the dataset has no feature with the given `fid` a new feature will be created. Returns a GeoJSON representation of the new or updated feature. $ mapbox datasets put-feature dataset-id feature-id 'geojson-feature' All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`.
[ "Create", "or", "update", "a", "dataset", "feature", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L221-L246
10,316
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
delete_feature
def delete_feature(ctx, dataset, fid): """Delete a feature. $ mapbox datasets delete-feature dataset-id feature-id All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`. """ service = ctx.obj.get('service') res = service.delete_feature(dataset, fid) if res.status_code != 204: raise MapboxCLIException(res.text.strip())
python
def delete_feature(ctx, dataset, fid): """Delete a feature. $ mapbox datasets delete-feature dataset-id feature-id All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`. """ service = ctx.obj.get('service') res = service.delete_feature(dataset, fid) if res.status_code != 204: raise MapboxCLIException(res.text.strip())
[ "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. $ mapbox datasets delete-feature dataset-id feature-id All endpoints require authentication. An access token with `datasets:write` scope is required, see `mapbox --help`.
[ "Delete", "a", "feature", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L254-L267
10,317
mapbox/mapbox-cli-py
mapboxcli/scripts/datasets.py
create_tileset
def create_tileset(ctx, dataset, tileset, name): """Create a vector tileset from a dataset. $ mapbox datasets create-tileset dataset-id username.data Note that the tileset must start with your username and the dataset must be one that you own. To view processing status, visit https://www.mapbox.com/data/. You may not generate another tilesets from the same dataset until the first processing job has completed. All endpoints require authentication. An access token with `uploads:write` scope is required, see `mapbox --help`. """ 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('.')[0], dataset=dataset) res = service.create(uri, tileset, name) if res.status_code == 201: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
python
def create_tileset(ctx, dataset, tileset, name): """Create a vector tileset from a dataset. $ mapbox datasets create-tileset dataset-id username.data Note that the tileset must start with your username and the dataset must be one that you own. To view processing status, visit https://www.mapbox.com/data/. You may not generate another tilesets from the same dataset until the first processing job has completed. All endpoints require authentication. An access token with `uploads:write` scope is required, see `mapbox --help`. """ 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('.')[0], dataset=dataset) res = service.create(uri, tileset, name) if res.status_code == 201: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
[ "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", "(", "'.'", ")", "[", "0", "]", ",", "dataset", "=", "dataset", ")", "res", "=", "service", ".", "create", "(", "uri", ",", "tileset", ",", "name", ")", "if", "res", ".", "status_code", "==", "201", ":", "click", ".", "echo", "(", "res", ".", "text", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Create a vector tileset from a dataset. $ mapbox datasets create-tileset dataset-id username.data Note that the tileset must start with your username and the dataset must be one that you own. To view processing status, visit https://www.mapbox.com/data/. You may not generate another tilesets from the same dataset until the first processing job has completed. All endpoints require authentication. An access token with `uploads:write` scope is required, see `mapbox --help`.
[ "Create", "a", "vector", "tileset", "from", "a", "dataset", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L276-L301
10,318
mapbox/mapbox-cli-py
mapboxcli/scripts/directions.py
directions
def directions(ctx, features, profile, alternatives, geometries, overview, steps, continue_straight, waypoint_snapping, annotations, language, output): """The Mapbox Directions API will show you how to get where you're going. mapbox directions "[0, 0]" "[1, 1]" An access token is required. See "mapbox --help". """ access_token = (ctx.obj and ctx.obj.get("access_token")) or None service = mapbox.Directions(access_token=access_token) # The Directions SDK expects False to be # a bool, not a str. if overview == "False": overview = False # When using waypoint snapping, the # Directions SDK expects features to be # a list, not a generator. if waypoint_snapping is not None: features = list(features) if annotations: annotations = annotations.split(",") stdout = click.open_file(output, "w") try: res = service.directions( features, profile=profile, alternatives=alternatives, geometries=geometries, overview=overview, steps=steps, continue_straight=continue_straight, waypoint_snapping=waypoint_snapping, annotations=annotations, language=language ) except mapbox.errors.ValidationError as exc: raise click.BadParameter(str(exc)) if res.status_code == 200: if geometries == "geojson": click.echo(json.dumps(res.geojson()), file=stdout) else: click.echo(res.text, file=stdout) else: raise MapboxCLIException(res.text.strip())
python
def directions(ctx, features, profile, alternatives, geometries, overview, steps, continue_straight, waypoint_snapping, annotations, language, output): """The Mapbox Directions API will show you how to get where you're going. mapbox directions "[0, 0]" "[1, 1]" An access token is required. See "mapbox --help". """ access_token = (ctx.obj and ctx.obj.get("access_token")) or None service = mapbox.Directions(access_token=access_token) # The Directions SDK expects False to be # a bool, not a str. if overview == "False": overview = False # When using waypoint snapping, the # Directions SDK expects features to be # a list, not a generator. if waypoint_snapping is not None: features = list(features) if annotations: annotations = annotations.split(",") stdout = click.open_file(output, "w") try: res = service.directions( features, profile=profile, alternatives=alternatives, geometries=geometries, overview=overview, steps=steps, continue_straight=continue_straight, waypoint_snapping=waypoint_snapping, annotations=annotations, language=language ) except mapbox.errors.ValidationError as exc: raise click.BadParameter(str(exc)) if res.status_code == 200: if geometries == "geojson": click.echo(json.dumps(res.geojson()), file=stdout) else: click.echo(res.text, file=stdout) else: raise MapboxCLIException(res.text.strip())
[ "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", "=", "mapbox", ".", "Directions", "(", "access_token", "=", "access_token", ")", "# The Directions SDK expects False to be", "# a bool, not a str.", "if", "overview", "==", "\"False\"", ":", "overview", "=", "False", "# When using waypoint snapping, the ", "# Directions SDK expects features to be ", "# a list, not a generator.", "if", "waypoint_snapping", "is", "not", "None", ":", "features", "=", "list", "(", "features", ")", "if", "annotations", ":", "annotations", "=", "annotations", ".", "split", "(", "\",\"", ")", "stdout", "=", "click", ".", "open_file", "(", "output", ",", "\"w\"", ")", "try", ":", "res", "=", "service", ".", "directions", "(", "features", ",", "profile", "=", "profile", ",", "alternatives", "=", "alternatives", ",", "geometries", "=", "geometries", ",", "overview", "=", "overview", ",", "steps", "=", "steps", ",", "continue_straight", "=", "continue_straight", ",", "waypoint_snapping", "=", "waypoint_snapping", ",", "annotations", "=", "annotations", ",", "language", "=", "language", ")", "except", "mapbox", ".", "errors", ".", "ValidationError", "as", "exc", ":", "raise", "click", ".", "BadParameter", "(", "str", "(", "exc", ")", ")", "if", "res", ".", "status_code", "==", "200", ":", "if", "geometries", "==", "\"geojson\"", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "res", ".", "geojson", "(", ")", ")", ",", "file", "=", "stdout", ")", "else", ":", "click", ".", "echo", "(", "res", ".", "text", ",", "file", "=", "stdout", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
The Mapbox Directions API will show you how to get where you're going. mapbox directions "[0, 0]" "[1, 1]" An access token is required. See "mapbox --help".
[ "The", "Mapbox", "Directions", "API", "will", "show", "you", "how", "to", "get", "where", "you", "re", "going", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/directions.py#L163-L218
10,319
mapbox/mapbox-cli-py
mapboxcli/scripts/uploads.py
upload
def upload(ctx, tileset, datasource, name, patch): """Upload data to Mapbox accounts. Uploaded data lands at https://www.mapbox.com/data/ and can be used in new or existing projects. All endpoints require authentication. You can specify the tileset id and input file $ mapbox upload username.data mydata.geojson Or specify just the tileset id and take an input file on stdin $ cat mydata.geojson | mapbox upload username.data The --name option defines the title as it appears in Studio and defaults to the last part of the tileset id, e.g. "data" Note that the tileset must start with your username. An access token with upload scope is required, see `mapbox --help`. Your account must be flagged in order to use the patch mode feature. """ 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('https://'): # Skip staging. Note this this only works for specific buckets. res = service.create(datasource, tileset, name=name, patch=patch) else: sourcefile = click.File('rb')(datasource) if hasattr(sourcefile, 'name'): filelen = ( 1 if sourcefile.name == '<stdin>' else os.stat(sourcefile.name).st_size) else: filelen = (len(sourcefile.getbuffer()) if hasattr(sourcefile, 'getbuffer') else 1) with click.progressbar(length=filelen, label='Uploading data source', fill_char="#", empty_char='-', file=sys.stderr) as bar: def callback(num_bytes): """Update the progress bar""" bar.update(num_bytes) res = service.upload(sourcefile, tileset, name, patch=patch, callback=callback) if res.status_code == 201: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
python
def upload(ctx, tileset, datasource, name, patch): """Upload data to Mapbox accounts. Uploaded data lands at https://www.mapbox.com/data/ and can be used in new or existing projects. All endpoints require authentication. You can specify the tileset id and input file $ mapbox upload username.data mydata.geojson Or specify just the tileset id and take an input file on stdin $ cat mydata.geojson | mapbox upload username.data The --name option defines the title as it appears in Studio and defaults to the last part of the tileset id, e.g. "data" Note that the tileset must start with your username. An access token with upload scope is required, see `mapbox --help`. Your account must be flagged in order to use the patch mode feature. """ 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('https://'): # Skip staging. Note this this only works for specific buckets. res = service.create(datasource, tileset, name=name, patch=patch) else: sourcefile = click.File('rb')(datasource) if hasattr(sourcefile, 'name'): filelen = ( 1 if sourcefile.name == '<stdin>' else os.stat(sourcefile.name).st_size) else: filelen = (len(sourcefile.getbuffer()) if hasattr(sourcefile, 'getbuffer') else 1) with click.progressbar(length=filelen, label='Uploading data source', fill_char="#", empty_char='-', file=sys.stderr) as bar: def callback(num_bytes): """Update the progress bar""" bar.update(num_bytes) res = service.upload(sourcefile, tileset, name, patch=patch, callback=callback) if res.status_code == 201: click.echo(res.text) else: raise MapboxCLIException(res.text.strip())
[ "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", "(", "'https://'", ")", ":", "# Skip staging. Note this this only works for specific buckets.", "res", "=", "service", ".", "create", "(", "datasource", ",", "tileset", ",", "name", "=", "name", ",", "patch", "=", "patch", ")", "else", ":", "sourcefile", "=", "click", ".", "File", "(", "'rb'", ")", "(", "datasource", ")", "if", "hasattr", "(", "sourcefile", ",", "'name'", ")", ":", "filelen", "=", "(", "1", "if", "sourcefile", ".", "name", "==", "'<stdin>'", "else", "os", ".", "stat", "(", "sourcefile", ".", "name", ")", ".", "st_size", ")", "else", ":", "filelen", "=", "(", "len", "(", "sourcefile", ".", "getbuffer", "(", ")", ")", "if", "hasattr", "(", "sourcefile", ",", "'getbuffer'", ")", "else", "1", ")", "with", "click", ".", "progressbar", "(", "length", "=", "filelen", ",", "label", "=", "'Uploading data source'", ",", "fill_char", "=", "\"#\"", ",", "empty_char", "=", "'-'", ",", "file", "=", "sys", ".", "stderr", ")", "as", "bar", ":", "def", "callback", "(", "num_bytes", ")", ":", "\"\"\"Update the progress bar\"\"\"", "bar", ".", "update", "(", "num_bytes", ")", "res", "=", "service", ".", "upload", "(", "sourcefile", ",", "tileset", ",", "name", ",", "patch", "=", "patch", ",", "callback", "=", "callback", ")", "if", "res", ".", "status_code", "==", "201", ":", "click", ".", "echo", "(", "res", ".", "text", ")", "else", ":", "raise", "MapboxCLIException", "(", "res", ".", "text", ".", "strip", "(", ")", ")" ]
Upload data to Mapbox accounts. Uploaded data lands at https://www.mapbox.com/data/ and can be used in new or existing projects. All endpoints require authentication. You can specify the tileset id and input file $ mapbox upload username.data mydata.geojson Or specify just the tileset id and take an input file on stdin $ cat mydata.geojson | mapbox upload username.data The --name option defines the title as it appears in Studio and defaults to the last part of the tileset id, e.g. "data" Note that the tileset must start with your username. An access token with upload scope is required, see `mapbox --help`. Your account must be flagged in order to use the patch mode feature.
[ "Upload", "data", "to", "Mapbox", "accounts", "." ]
b75544a2f83a4fda79d78b5673058e16e64a4f6d
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/uploads.py#L17-L76
10,320
aaren/notedown
notedown/contentsmanager.py
NotedownContentsManager._save_notebook
def _save_notebook(self, os_path, nb): """Save a notebook to an os_path.""" 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) == 'markdown': nbjson = nbformat.writes(nb, version=nbformat.NO_CONVERT) markdown = convert(nbjson, informat='notebook', outformat='markdown', strip_outputs=self.strip_outputs) f.write(markdown)
python
def _save_notebook(self, os_path, nb): """Save a notebook to an os_path.""" 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) == 'markdown': nbjson = nbformat.writes(nb, version=nbformat.NO_CONVERT) markdown = convert(nbjson, informat='notebook', outformat='markdown', strip_outputs=self.strip_outputs) f.write(markdown)
[ "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", ")", "==", "'markdown'", ":", "nbjson", "=", "nbformat", ".", "writes", "(", "nb", ",", "version", "=", "nbformat", ".", "NO_CONVERT", ")", "markdown", "=", "convert", "(", "nbjson", ",", "informat", "=", "'notebook'", ",", "outformat", "=", "'markdown'", ",", "strip_outputs", "=", "self", ".", "strip_outputs", ")", "f", ".", "write", "(", "markdown", ")" ]
Save a notebook to an os_path.
[ "Save", "a", "notebook", "to", "an", "os_path", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/contentsmanager.py#L52-L63
10,321
aaren/notedown
notedown/main.py
ftdetect
def ftdetect(filename): """Determine if filename is markdown or notebook, based on the file extension. """ _, 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 'notebook' else: return None
python
def ftdetect(filename): """Determine if filename is markdown or notebook, based on the file extension. """ _, 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 'notebook' else: return None
[ "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", "'notebook'", "else", ":", "return", "None" ]
Determine if filename is markdown or notebook, based on the file extension.
[ "Determine", "if", "filename", "is", "markdown", "or", "notebook", "based", "on", "the", "file", "extension", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/main.py#L107-L119
10,322
aaren/notedown
notedown/notedown.py
strip
def strip(notebook): """Remove outputs from a notebook.""" for cell in notebook.cells: if cell.cell_type == 'code': cell.outputs = [] cell.execution_count = None
python
def strip(notebook): """Remove outputs from a notebook.""" for cell in notebook.cells: if cell.cell_type == 'code': cell.outputs = [] cell.execution_count = None
[ "def", "strip", "(", "notebook", ")", ":", "for", "cell", "in", "notebook", ".", "cells", ":", "if", "cell", ".", "cell_type", "==", "'code'", ":", "cell", ".", "outputs", "=", "[", "]", "cell", ".", "execution_count", "=", "None" ]
Remove outputs from a notebook.
[ "Remove", "outputs", "from", "a", "notebook", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L38-L43
10,323
aaren/notedown
notedown/notedown.py
get_caption_comments
def get_caption_comments(content): """Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped. """ 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.startswith('##'): break else: caption.append(line.lstrip('# ').rstrip()) # add " around the caption. TODO: consider doing this upstream # in pandoc-attributes caption = '"' + ' '.join(caption) + '"' return id, caption
python
def get_caption_comments(content): """Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped. """ 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.startswith('##'): break else: caption.append(line.lstrip('# ').rstrip()) # add " around the caption. TODO: consider doing this upstream # in pandoc-attributes caption = '"' + ' '.join(caption) + '"' return id, caption
[ "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", ".", "startswith", "(", "'##'", ")", ":", "break", "else", ":", "caption", ".", "append", "(", "line", ".", "lstrip", "(", "'# '", ")", ".", "rstrip", "(", ")", ")", "# add \" around the caption. TODO: consider doing this upstream", "# in pandoc-attributes", "caption", "=", "'\"'", "+", "' '", ".", "join", "(", "caption", ")", "+", "'\"'", "return", "id", ",", "caption" ]
Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped.
[ "Retrieve", "an", "id", "and", "a", "caption", "from", "a", "code", "cell", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L648-L679
10,324
aaren/notedown
notedown/notedown.py
MarkdownReader.new_code_block
def new_code_block(self, **kwargs): """Create a new code block.""" proto = {'content': '', 'type': self.code, 'IO': '', 'attributes': ''} proto.update(**kwargs) return proto
python
def new_code_block(self, **kwargs): """Create a new code block.""" proto = {'content': '', 'type': self.code, 'IO': '', 'attributes': ''} proto.update(**kwargs) return proto
[ "def", "new_code_block", "(", "self", ",", "*", "*", "kwargs", ")", ":", "proto", "=", "{", "'content'", ":", "''", ",", "'type'", ":", "self", ".", "code", ",", "'IO'", ":", "''", ",", "'attributes'", ":", "''", "}", "proto", ".", "update", "(", "*", "*", "kwargs", ")", "return", "proto" ]
Create a new code block.
[ "Create", "a", "new", "code", "block", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L147-L154
10,325
aaren/notedown
notedown/notedown.py
MarkdownReader.new_text_block
def new_text_block(self, **kwargs): """Create a new text block.""" proto = {'content': '', 'type': self.markdown} proto.update(**kwargs) return proto
python
def new_text_block(self, **kwargs): """Create a new text block.""" proto = {'content': '', 'type': self.markdown} proto.update(**kwargs) return proto
[ "def", "new_text_block", "(", "self", ",", "*", "*", "kwargs", ")", ":", "proto", "=", "{", "'content'", ":", "''", ",", "'type'", ":", "self", ".", "markdown", "}", "proto", ".", "update", "(", "*", "*", "kwargs", ")", "return", "proto" ]
Create a new text block.
[ "Create", "a", "new", "text", "block", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L156-L160
10,326
aaren/notedown
notedown/notedown.py
MarkdownReader.pre_process_code_block
def pre_process_code_block(block): """Preprocess the content of a code block, modifying the code block in place. Just dedents indented code. """ if 'indent' in block and block['indent']: indent = r'^' + block['indent'] block['content'] = re.sub(indent, '', block['icontent'], flags=re.MULTILINE)
python
def pre_process_code_block(block): """Preprocess the content of a code block, modifying the code block in place. Just dedents indented code. """ if 'indent' in block and block['indent']: indent = r'^' + block['indent'] block['content'] = re.sub(indent, '', block['icontent'], flags=re.MULTILINE)
[ "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 block in place. Just dedents indented code.
[ "Preprocess", "the", "content", "of", "a", "code", "block", "modifying", "the", "code", "block", "in", "place", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L169-L178
10,327
aaren/notedown
notedown/notedown.py
MarkdownReader.process_code_block
def process_code_block(self, block): """Parse block attributes""" if block['type'] != self.code: return block attr = PandocAttributes(block['attributes'], 'markdown') if self.match == 'all': pass elif self.match == 'fenced' and block.get('indent'): return self.new_text_block(content=('\n' + block['icontent'] + '\n')) elif self.match == 'strict' and 'input' not in attr.classes: return self.new_text_block(content=block['raw']) elif self.match not in list(attr.classes) + ['fenced', 'strict']: return self.new_text_block(content=block['raw']) # set input / output status of cell if 'output' in attr.classes and 'json' in attr.classes: block['IO'] = 'output' elif 'input' in attr.classes: block['IO'] = 'input' attr.classes.remove('input') else: block['IO'] = 'input' if self.caption_comments: # override attributes id and caption with those set in # comments, if they exist id, caption = get_caption_comments(block['content']) if id: attr.id = id if caption: attr['caption'] = caption try: # determine the language as the first class that # is in the block attributes and also in the list # of languages language = set(attr.classes).intersection(languages).pop() attr.classes.remove(language) except KeyError: language = None block['language'] = language block['attributes'] = attr # ensure one identifier for python code if language in ('python', 'py', '', None): block['language'] = self.python # add alternate language execution magic elif language != self.python and self.magic: block['content'] = CodeMagician.magic(language) + block['content'] block['language'] = language return self.new_code_block(**block)
python
def process_code_block(self, block): """Parse block attributes""" if block['type'] != self.code: return block attr = PandocAttributes(block['attributes'], 'markdown') if self.match == 'all': pass elif self.match == 'fenced' and block.get('indent'): return self.new_text_block(content=('\n' + block['icontent'] + '\n')) elif self.match == 'strict' and 'input' not in attr.classes: return self.new_text_block(content=block['raw']) elif self.match not in list(attr.classes) + ['fenced', 'strict']: return self.new_text_block(content=block['raw']) # set input / output status of cell if 'output' in attr.classes and 'json' in attr.classes: block['IO'] = 'output' elif 'input' in attr.classes: block['IO'] = 'input' attr.classes.remove('input') else: block['IO'] = 'input' if self.caption_comments: # override attributes id and caption with those set in # comments, if they exist id, caption = get_caption_comments(block['content']) if id: attr.id = id if caption: attr['caption'] = caption try: # determine the language as the first class that # is in the block attributes and also in the list # of languages language = set(attr.classes).intersection(languages).pop() attr.classes.remove(language) except KeyError: language = None block['language'] = language block['attributes'] = attr # ensure one identifier for python code if language in ('python', 'py', '', None): block['language'] = self.python # add alternate language execution magic elif language != self.python and self.magic: block['content'] = CodeMagician.magic(language) + block['content'] block['language'] = language return self.new_code_block(**block)
[ "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", ".", "get", "(", "'indent'", ")", ":", "return", "self", ".", "new_text_block", "(", "content", "=", "(", "'\\n'", "+", "block", "[", "'icontent'", "]", "+", "'\\n'", ")", ")", "elif", "self", ".", "match", "==", "'strict'", "and", "'input'", "not", "in", "attr", ".", "classes", ":", "return", "self", ".", "new_text_block", "(", "content", "=", "block", "[", "'raw'", "]", ")", "elif", "self", ".", "match", "not", "in", "list", "(", "attr", ".", "classes", ")", "+", "[", "'fenced'", ",", "'strict'", "]", ":", "return", "self", ".", "new_text_block", "(", "content", "=", "block", "[", "'raw'", "]", ")", "# set input / output status of cell", "if", "'output'", "in", "attr", ".", "classes", "and", "'json'", "in", "attr", ".", "classes", ":", "block", "[", "'IO'", "]", "=", "'output'", "elif", "'input'", "in", "attr", ".", "classes", ":", "block", "[", "'IO'", "]", "=", "'input'", "attr", ".", "classes", ".", "remove", "(", "'input'", ")", "else", ":", "block", "[", "'IO'", "]", "=", "'input'", "if", "self", ".", "caption_comments", ":", "# override attributes id and caption with those set in", "# comments, if they exist", "id", ",", "caption", "=", "get_caption_comments", "(", "block", "[", "'content'", "]", ")", "if", "id", ":", "attr", ".", "id", "=", "id", "if", "caption", ":", "attr", "[", "'caption'", "]", "=", "caption", "try", ":", "# determine the language as the first class that", "# is in the block attributes and also in the list", "# of languages", "language", "=", "set", "(", "attr", ".", "classes", ")", ".", "intersection", "(", "languages", ")", ".", "pop", "(", ")", "attr", ".", "classes", ".", "remove", "(", "language", ")", "except", "KeyError", ":", "language", "=", "None", "block", "[", "'language'", "]", "=", "language", "block", "[", "'attributes'", "]", "=", "attr", "# ensure one identifier for python code", "if", "language", "in", "(", "'python'", ",", "'py'", ",", "''", ",", "None", ")", ":", "block", "[", "'language'", "]", "=", "self", ".", "python", "# add alternate language execution magic", "elif", "language", "!=", "self", ".", "python", "and", "self", ".", "magic", ":", "block", "[", "'content'", "]", "=", "CodeMagician", ".", "magic", "(", "language", ")", "+", "block", "[", "'content'", "]", "block", "[", "'language'", "]", "=", "language", "return", "self", ".", "new_code_block", "(", "*", "*", "block", ")" ]
Parse block attributes
[ "Parse", "block", "attributes" ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L189-L248
10,328
aaren/notedown
notedown/notedown.py
MarkdownReader.parse_blocks
def parse_blocks(self, text): """Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and the contents of the block. Additional keys may be parsed as well. We should switch to an external markdown library if this gets much more complicated! """ 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] text_stops = [m.start() for m in code_matches] + [len(text)] text_limits = list(zip(text_starts, text_stops)) # list of the groups from the code blocks code_blocks = [self.new_code_block(**m.groupdict()) for m in code_matches] text_blocks = [self.new_text_block(content=text[i:j]) for i, j in text_limits] # remove indents list(map(self.pre_process_code_block, code_blocks)) # remove blank line at start and end of markdown list(map(self.pre_process_text_block, text_blocks)) # create a list of the right length all_blocks = list(range(len(text_blocks) + len(code_blocks))) # NOTE: the behaviour here is a bit fragile in that we # assume that cells must alternate between code and # markdown. This isn't the case, as we could have # consecutive code cells, and we get around this by # stripping out empty cells. i.e. two consecutive code cells # have an empty markdown cell between them which is stripped # out because it is empty. # cells must alternate in order all_blocks[::2] = text_blocks all_blocks[1::2] = code_blocks # remove possible empty text cells all_blocks = [cell for cell in all_blocks if cell['content']] return all_blocks
python
def parse_blocks(self, text): """Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and the contents of the block. Additional keys may be parsed as well. We should switch to an external markdown library if this gets much more complicated! """ 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] text_stops = [m.start() for m in code_matches] + [len(text)] text_limits = list(zip(text_starts, text_stops)) # list of the groups from the code blocks code_blocks = [self.new_code_block(**m.groupdict()) for m in code_matches] text_blocks = [self.new_text_block(content=text[i:j]) for i, j in text_limits] # remove indents list(map(self.pre_process_code_block, code_blocks)) # remove blank line at start and end of markdown list(map(self.pre_process_text_block, text_blocks)) # create a list of the right length all_blocks = list(range(len(text_blocks) + len(code_blocks))) # NOTE: the behaviour here is a bit fragile in that we # assume that cells must alternate between code and # markdown. This isn't the case, as we could have # consecutive code cells, and we get around this by # stripping out empty cells. i.e. two consecutive code cells # have an empty markdown cell between them which is stripped # out because it is empty. # cells must alternate in order all_blocks[::2] = text_blocks all_blocks[1::2] = code_blocks # remove possible empty text cells all_blocks = [cell for cell in all_blocks if cell['content']] return all_blocks
[ "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", "]", "text_stops", "=", "[", "m", ".", "start", "(", ")", "for", "m", "in", "code_matches", "]", "+", "[", "len", "(", "text", ")", "]", "text_limits", "=", "list", "(", "zip", "(", "text_starts", ",", "text_stops", ")", ")", "# list of the groups from the code blocks", "code_blocks", "=", "[", "self", ".", "new_code_block", "(", "*", "*", "m", ".", "groupdict", "(", ")", ")", "for", "m", "in", "code_matches", "]", "text_blocks", "=", "[", "self", ".", "new_text_block", "(", "content", "=", "text", "[", "i", ":", "j", "]", ")", "for", "i", ",", "j", "in", "text_limits", "]", "# remove indents", "list", "(", "map", "(", "self", ".", "pre_process_code_block", ",", "code_blocks", ")", ")", "# remove blank line at start and end of markdown", "list", "(", "map", "(", "self", ".", "pre_process_text_block", ",", "text_blocks", ")", ")", "# create a list of the right length", "all_blocks", "=", "list", "(", "range", "(", "len", "(", "text_blocks", ")", "+", "len", "(", "code_blocks", ")", ")", ")", "# NOTE: the behaviour here is a bit fragile in that we", "# assume that cells must alternate between code and", "# markdown. This isn't the case, as we could have", "# consecutive code cells, and we get around this by", "# stripping out empty cells. i.e. two consecutive code cells", "# have an empty markdown cell between them which is stripped", "# out because it is empty.", "# cells must alternate in order", "all_blocks", "[", ":", ":", "2", "]", "=", "text_blocks", "all_blocks", "[", "1", ":", ":", "2", "]", "=", "code_blocks", "# remove possible empty text cells", "all_blocks", "=", "[", "cell", "for", "cell", "in", "all_blocks", "if", "cell", "[", "'content'", "]", "]", "return", "all_blocks" ]
Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and the contents of the block. Additional keys may be parsed as well. We should switch to an external markdown library if this gets much more complicated!
[ "Extract", "the", "code", "and", "non", "-", "code", "blocks", "from", "given", "markdown", "text", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L250-L302
10,329
aaren/notedown
notedown/notedown.py
MarkdownReader.create_code_cell
def create_code_cell(block): """Create a notebook code cell from a 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()}) execution_count = attr.kvs.get('n') if not execution_count: code_cell.execution_count = None else: code_cell.execution_count = int(execution_count) return code_cell
python
def create_code_cell(block): """Create a notebook code cell from a 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()}) execution_count = attr.kvs.get('n') if not execution_count: code_cell.execution_count = None else: code_cell.execution_count = int(execution_count) return code_cell
[ "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", "(", ")", "}", ")", "execution_count", "=", "attr", ".", "kvs", ".", "get", "(", "'n'", ")", "if", "not", "execution_count", ":", "code_cell", ".", "execution_count", "=", "None", "else", ":", "code_cell", ".", "execution_count", "=", "int", "(", "execution_count", ")", "return", "code_cell" ]
Create a notebook code cell from a block.
[ "Create", "a", "notebook", "code", "cell", "from", "a", "block", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L305-L319
10,330
aaren/notedown
notedown/notedown.py
MarkdownReader.create_markdown_cell
def create_markdown_cell(block): """Create a markdown cell from a block.""" kwargs = {'cell_type': block['type'], 'source': block['content']} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
python
def create_markdown_cell(block): """Create a markdown cell from a block.""" kwargs = {'cell_type': block['type'], 'source': block['content']} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
[ "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.
[ "Create", "a", "markdown", "cell", "from", "a", "block", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L322-L327
10,331
aaren/notedown
notedown/notedown.py
MarkdownReader.create_cells
def create_cells(self, blocks): """Turn the list of blocks into a list of notebook cells.""" 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) elif (block['type'] == self.code and block['IO'] == 'output' and cells[-1].cell_type == 'code'): cells[-1].outputs = self.create_outputs(block) elif block['type'] == self.markdown: markdown_cell = self.create_markdown_cell(block) cells.append(markdown_cell) else: raise NotImplementedError("{} is not supported as a cell" "type".format(block['type'])) return cells
python
def create_cells(self, blocks): """Turn the list of blocks into a list of notebook cells.""" 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) elif (block['type'] == self.code and block['IO'] == 'output' and cells[-1].cell_type == 'code'): cells[-1].outputs = self.create_outputs(block) elif block['type'] == self.markdown: markdown_cell = self.create_markdown_cell(block) cells.append(markdown_cell) else: raise NotImplementedError("{} is not supported as a cell" "type".format(block['type'])) return cells
[ "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", ")", "elif", "(", "block", "[", "'type'", "]", "==", "self", ".", "code", "and", "block", "[", "'IO'", "]", "==", "'output'", "and", "cells", "[", "-", "1", "]", ".", "cell_type", "==", "'code'", ")", ":", "cells", "[", "-", "1", "]", ".", "outputs", "=", "self", ".", "create_outputs", "(", "block", ")", "elif", "block", "[", "'type'", "]", "==", "self", ".", "markdown", ":", "markdown_cell", "=", "self", ".", "create_markdown_cell", "(", "block", ")", "cells", ".", "append", "(", "markdown_cell", ")", "else", ":", "raise", "NotImplementedError", "(", "\"{} is not supported as a cell\"", "\"type\"", ".", "format", "(", "block", "[", "'type'", "]", ")", ")", "return", "cells" ]
Turn the list of blocks into a list of notebook cells.
[ "Turn", "the", "list", "of", "blocks", "into", "a", "list", "of", "notebook", "cells", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L337-L358
10,332
aaren/notedown
notedown/notedown.py
MarkdownReader.to_notebook
def to_notebook(self, s, **kwargs): """Convert the markdown string s to an IPython notebook. Returns a notebook. """ 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.process_code_block(block) for block in all_blocks] cells = self.create_cells(blocks) nb = nbbase.new_notebook(cells=cells) return nb
python
def to_notebook(self, s, **kwargs): """Convert the markdown string s to an IPython notebook. Returns a notebook. """ 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.process_code_block(block) for block in all_blocks] cells = self.create_cells(blocks) nb = nbbase.new_notebook(cells=cells) return nb
[ "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", ".", "process_code_block", "(", "block", ")", "for", "block", "in", "all_blocks", "]", "cells", "=", "self", ".", "create_cells", "(", "blocks", ")", "nb", "=", "nbbase", ".", "new_notebook", "(", "cells", "=", "cells", ")", "return", "nb" ]
Convert the markdown string s to an IPython notebook. Returns a notebook.
[ "Convert", "the", "markdown", "string", "s", "to", "an", "IPython", "notebook", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L360-L376
10,333
aaren/notedown
notedown/notedown.py
MarkdownWriter.write_resources
def write_resources(self, resources): """Write the output data in resources returned by exporter to files. """ 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) if path and not os.path.isdir(path): os.makedirs(path) # Write file with open(dest, 'wb') as f: f.write(data)
python
def write_resources(self, resources): """Write the output data in resources returned by exporter to files. """ 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) if path and not os.path.isdir(path): os.makedirs(path) # Write file with open(dest, 'wb') as f: f.write(data)
[ "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", ")", "if", "path", "and", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "# Write file", "with", "open", "(", "dest", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")" ]
Write the output data in resources returned by exporter to files.
[ "Write", "the", "output", "data", "in", "resources", "returned", "by", "exporter", "to", "files", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L445-L458
10,334
aaren/notedown
notedown/notedown.py
MarkdownWriter.string2json
def string2json(self, string): """Convert json into its string representation. Used for writing outputs to markdown.""" kwargs = { 'cls': BytesEncoder, # use the IPython bytes encoder 'indent': 1, 'sort_keys': True, 'separators': (',', ': '), } return cast_unicode(json.dumps(string, **kwargs), 'utf-8')
python
def string2json(self, string): """Convert json into its string representation. Used for writing outputs to markdown.""" kwargs = { 'cls': BytesEncoder, # use the IPython bytes encoder 'indent': 1, 'sort_keys': True, 'separators': (',', ': '), } return cast_unicode(json.dumps(string, **kwargs), 'utf-8')
[ "def", "string2json", "(", "self", ",", "string", ")", ":", "kwargs", "=", "{", "'cls'", ":", "BytesEncoder", ",", "# use the IPython bytes encoder", "'indent'", ":", "1", ",", "'sort_keys'", ":", "True", ",", "'separators'", ":", "(", "','", ",", "': '", ")", ",", "}", "return", "cast_unicode", "(", "json", ".", "dumps", "(", "string", ",", "*", "*", "kwargs", ")", ",", "'utf-8'", ")" ]
Convert json into its string representation. Used for writing outputs to markdown.
[ "Convert", "json", "into", "its", "string", "representation", ".", "Used", "for", "writing", "outputs", "to", "markdown", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L461-L470
10,335
aaren/notedown
notedown/notedown.py
MarkdownWriter.create_attributes
def create_attributes(self, cell, cell_type=None): """Turn the attribute dict into an attribute string for the code block. """ if self.strip_outputs or not hasattr(cell, 'execution_count'): return 'python' attrs = cell.metadata.get('attributes') attr = PandocAttributes(attrs, 'dict') if 'python' in attr.classes: attr.classes.remove('python') if 'input' in attr.classes: attr.classes.remove('input') if cell_type == 'figure': attr.kvs.pop('caption', '') attr.classes.append('figure') attr.classes.append('output') return attr.to_html() elif cell_type == 'input': # ensure python goes first so that github highlights it attr.classes.insert(0, 'python') attr.classes.insert(1, 'input') if cell.execution_count: attr.kvs['n'] = cell.execution_count return attr.to_markdown(format='{classes} {id} {kvs}') else: return attr.to_markdown()
python
def create_attributes(self, cell, cell_type=None): """Turn the attribute dict into an attribute string for the code block. """ if self.strip_outputs or not hasattr(cell, 'execution_count'): return 'python' attrs = cell.metadata.get('attributes') attr = PandocAttributes(attrs, 'dict') if 'python' in attr.classes: attr.classes.remove('python') if 'input' in attr.classes: attr.classes.remove('input') if cell_type == 'figure': attr.kvs.pop('caption', '') attr.classes.append('figure') attr.classes.append('output') return attr.to_html() elif cell_type == 'input': # ensure python goes first so that github highlights it attr.classes.insert(0, 'python') attr.classes.insert(1, 'input') if cell.execution_count: attr.kvs['n'] = cell.execution_count return attr.to_markdown(format='{classes} {id} {kvs}') else: return attr.to_markdown()
[ "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'", "in", "attr", ".", "classes", ":", "attr", ".", "classes", ".", "remove", "(", "'python'", ")", "if", "'input'", "in", "attr", ".", "classes", ":", "attr", ".", "classes", ".", "remove", "(", "'input'", ")", "if", "cell_type", "==", "'figure'", ":", "attr", ".", "kvs", ".", "pop", "(", "'caption'", ",", "''", ")", "attr", ".", "classes", ".", "append", "(", "'figure'", ")", "attr", ".", "classes", ".", "append", "(", "'output'", ")", "return", "attr", ".", "to_html", "(", ")", "elif", "cell_type", "==", "'input'", ":", "# ensure python goes first so that github highlights it", "attr", ".", "classes", ".", "insert", "(", "0", ",", "'python'", ")", "attr", ".", "classes", ".", "insert", "(", "1", ",", "'input'", ")", "if", "cell", ".", "execution_count", ":", "attr", ".", "kvs", "[", "'n'", "]", "=", "cell", ".", "execution_count", "return", "attr", ".", "to_markdown", "(", "format", "=", "'{classes} {id} {kvs}'", ")", "else", ":", "return", "attr", ".", "to_markdown", "(", ")" ]
Turn the attribute dict into an attribute string for the code block.
[ "Turn", "the", "attribute", "dict", "into", "an", "attribute", "string", "for", "the", "code", "block", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L493-L523
10,336
aaren/notedown
notedown/notedown.py
MarkdownWriter.dequote
def dequote(s): """Remove excess quotes from a string.""" if len(s) < 2: return s elif (s[0] == s[-1]) and s.startswith(('"', "'")): return s[1: -1] else: return s
python
def dequote(s): """Remove excess quotes from a string.""" if len(s) < 2: return s elif (s[0] == s[-1]) and s.startswith(('"', "'")): return s[1: -1] else: return s
[ "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.
[ "Remove", "excess", "quotes", "from", "a", "string", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L526-L533
10,337
aaren/notedown
notedown/notedown.py
MarkdownWriter.data2uri
def data2uri(data, data_type): """Convert base64 data into a data uri with the given data_type.""" MIME_MAP = { 'image/jpeg': 'jpeg', 'image/png': 'png', 'text/plain': 'text', 'text/html': 'html', 'text/latex': 'latex', 'application/javascript': 'html', 'image/svg+xml': 'svg', } inverse_map = {v: k for k, v in list(MIME_MAP.items())} mime_type = inverse_map[data_type] uri = r"data:{mime};base64,{data}" return uri.format(mime=mime_type, data=data[mime_type].replace('\n', ''))
python
def data2uri(data, data_type): """Convert base64 data into a data uri with the given data_type.""" MIME_MAP = { 'image/jpeg': 'jpeg', 'image/png': 'png', 'text/plain': 'text', 'text/html': 'html', 'text/latex': 'latex', 'application/javascript': 'html', 'image/svg+xml': 'svg', } inverse_map = {v: k for k, v in list(MIME_MAP.items())} mime_type = inverse_map[data_type] uri = r"data:{mime};base64,{data}" return uri.format(mime=mime_type, data=data[mime_type].replace('\n', ''))
[ "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'", ",", "'image/svg+xml'", ":", "'svg'", ",", "}", "inverse_map", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "list", "(", "MIME_MAP", ".", "items", "(", ")", ")", "}", "mime_type", "=", "inverse_map", "[", "data_type", "]", "uri", "=", "r\"data:{mime};base64,{data}\"", "return", "uri", ".", "format", "(", "mime", "=", "mime_type", ",", "data", "=", "data", "[", "mime_type", "]", ".", "replace", "(", "'\\n'", ",", "''", ")", ")" ]
Convert base64 data into a data uri with the given data_type.
[ "Convert", "base64", "data", "into", "a", "data", "uri", "with", "the", "given", "data_type", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L536-L551
10,338
aaren/notedown
notedown/notedown.py
CodeMagician.magic
def magic(self, alias): """Returns the appropriate IPython code magic when called with an alias for a language. """ if alias in self.aliases: return self.aliases[alias] else: return "%%{}\n".format(alias)
python
def magic(self, alias): """Returns the appropriate IPython code magic when called with an alias for a language. """ if alias in self.aliases: return self.aliases[alias] else: return "%%{}\n".format(alias)
[ "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 called with an alias for a language.
[ "Returns", "the", "appropriate", "IPython", "code", "magic", "when", "called", "with", "an", "alias", "for", "a", "language", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L565-L572
10,339
aaren/notedown
notedown/notedown.py
Knitr.knit
def knit(self, input_file, opts_chunk='eval=FALSE'): """Use Knitr to convert the r-markdown input_file into markdown, returning a file object. """ # 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_file.read()) tmp_in.file.flush() tmp_in.file.seek(0) self._knit(tmp_in.name, tmp_out.name, opts_chunk) tmp_out.file.flush() return tmp_out
python
def knit(self, input_file, opts_chunk='eval=FALSE'): """Use Knitr to convert the r-markdown input_file into markdown, returning a file object. """ # 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_file.read()) tmp_in.file.flush() tmp_in.file.seek(0) self._knit(tmp_in.name, tmp_out.name, opts_chunk) tmp_out.file.flush() return tmp_out
[ "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_file", ".", "read", "(", ")", ")", "tmp_in", ".", "file", ".", "flush", "(", ")", "tmp_in", ".", "file", ".", "seek", "(", "0", ")", "self", ".", "_knit", "(", "tmp_in", ".", "name", ",", "tmp_out", ".", "name", ",", "opts_chunk", ")", "tmp_out", ".", "file", ".", "flush", "(", ")", "return", "tmp_out" ]
Use Knitr to convert the r-markdown input_file into markdown, returning a file object.
[ "Use", "Knitr", "to", "convert", "the", "r", "-", "markdown", "input_file", "into", "markdown", "returning", "a", "file", "object", "." ]
1e920c7e4ecbe47420c12eed3d5bcae735121222
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L602-L616
10,340
cyface/django-termsandconditions
termsandconditions/middleware.py
is_path_protected
def is_path_protected(path): """ returns True if given path is to be protected, otherwise False The path is not to be protected when it appears on: TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as ACCEPT_TERMS_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: protected = False if path in TERMS_EXCLUDE_URL_LIST: protected = False if path.startswith(ACCEPT_TERMS_PATH): protected = False return protected
python
def is_path_protected(path): """ returns True if given path is to be protected, otherwise False The path is not to be protected when it appears on: TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as ACCEPT_TERMS_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: protected = False if path in TERMS_EXCLUDE_URL_LIST: protected = False if path.startswith(ACCEPT_TERMS_PATH): protected = False return protected
[ "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", ":", "protected", "=", "False", "if", "path", "in", "TERMS_EXCLUDE_URL_LIST", ":", "protected", "=", "False", "if", "path", ".", "startswith", "(", "ACCEPT_TERMS_PATH", ")", ":", "protected", "=", "False", "return", "protected" ]
returns True if given path is to be protected, otherwise False The path is not to be protected when it appears on: TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as ACCEPT_TERMS_PATH
[ "returns", "True", "if", "given", "path", "is", "to", "be", "protected", "otherwise", "False" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/middleware.py#L49-L74
10,341
cyface/django-termsandconditions
termsandconditions/middleware.py
TermsAndConditionsRedirectMiddleware.process_request
def process_request(self, request): """Process each request to app to ensure terms have been accepted""" LOGGER.debug('termsandconditions.middleware') current_path = request.META['PATH_INFO'] if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if user_authenticated and is_path_protected(current_path): for term in TermsAndConditions.get_active_terms_not_agreed_to(request.user): # Check for querystring and include it if there is one qs = request.META['QUERY_STRING'] current_path += '?' + qs if qs else '' return redirect_to_terms_accept(current_path, term.slug) return None
python
def process_request(self, request): """Process each request to app to ensure terms have been accepted""" LOGGER.debug('termsandconditions.middleware') current_path = request.META['PATH_INFO'] if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if user_authenticated and is_path_protected(current_path): for term in TermsAndConditions.get_active_terms_not_agreed_to(request.user): # Check for querystring and include it if there is one qs = request.META['QUERY_STRING'] current_path += '?' + qs if qs else '' return redirect_to_terms_accept(current_path, term.slug) return None
[ "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", ":", "user_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "if", "user_authenticated", "and", "is_path_protected", "(", "current_path", ")", ":", "for", "term", "in", "TermsAndConditions", ".", "get_active_terms_not_agreed_to", "(", "request", ".", "user", ")", ":", "# Check for querystring and include it if there is one", "qs", "=", "request", ".", "META", "[", "'QUERY_STRING'", "]", "current_path", "+=", "'?'", "+", "qs", "if", "qs", "else", "''", "return", "redirect_to_terms_accept", "(", "current_path", ",", "term", ".", "slug", ")", "return", "None" ]
Process each request to app to ensure terms have been accepted
[ "Process", "each", "request", "to", "app", "to", "ensure", "terms", "have", "been", "accepted" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/middleware.py#L27-L46
10,342
cyface/django-termsandconditions
termsandconditions/views.py
TermsView.get_context_data
def get_context_data(self, **kwargs): """Pass additional context data""" context = super(TermsView, self).get_context_data(**kwargs) context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE) return context
python
def get_context_data(self, **kwargs): """Pass additional context data""" context = super(TermsView, self).get_context_data(**kwargs) context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE) return context
[ "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
[ "Pass", "additional", "context", "data" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L53-L57
10,343
cyface/django-termsandconditions
termsandconditions/views.py
AcceptTermsView.get_initial
def get_initial(self): """Override of CreateView method, queries for which T&C to accept and catches returnTo from URL""" 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}
python
def get_initial(self): """Override of CreateView method, queries for which T&C to accept and catches returnTo from URL""" 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}
[ "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
[ "Override", "of", "CreateView", "method", "queries", "for", "which", "T&C", "to", "accept", "and", "catches", "returnTo", "from", "URL" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L82-L89
10,344
cyface/django-termsandconditions
termsandconditions/views.py
AcceptTermsView.post
def post(self, request, *args, **kwargs): """ Handles POST request. """ return_url = request.POST.get('returnTo', '/') terms_ids = request.POST.getlist('terms') if not terms_ids: # pragma: nocover return HttpResponseRedirect(return_url) if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if user_authenticated: user = request.user else: # Get user out of saved pipeline from django-socialauth if 'partial_pipeline' in request.session: user_pk = request.session['partial_pipeline']['kwargs']['user']['pk'] user = User.objects.get(id=user_pk) else: return HttpResponseRedirect('/') store_ip_address = getattr(settings, 'TERMS_STORE_IP_ADDRESS', True) if store_ip_address: ip_address = request.META.get(getattr(settings, 'TERMS_IP_HEADER_NAME', DEFAULT_TERMS_IP_HEADER_NAME)) else: ip_address = "" for terms_id in terms_ids: try: new_user_terms = UserTermsAndConditions( user=user, terms=TermsAndConditions.objects.get(pk=int(terms_id)), ip_address=ip_address ) new_user_terms.save() except IntegrityError: # pragma: nocover pass return HttpResponseRedirect(return_url)
python
def post(self, request, *args, **kwargs): """ Handles POST request. """ return_url = request.POST.get('returnTo', '/') terms_ids = request.POST.getlist('terms') if not terms_ids: # pragma: nocover return HttpResponseRedirect(return_url) if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if user_authenticated: user = request.user else: # Get user out of saved pipeline from django-socialauth if 'partial_pipeline' in request.session: user_pk = request.session['partial_pipeline']['kwargs']['user']['pk'] user = User.objects.get(id=user_pk) else: return HttpResponseRedirect('/') store_ip_address = getattr(settings, 'TERMS_STORE_IP_ADDRESS', True) if store_ip_address: ip_address = request.META.get(getattr(settings, 'TERMS_IP_HEADER_NAME', DEFAULT_TERMS_IP_HEADER_NAME)) else: ip_address = "" for terms_id in terms_ids: try: new_user_terms = UserTermsAndConditions( user=user, terms=TermsAndConditions.objects.get(pk=int(terms_id)), ip_address=ip_address ) new_user_terms.save() except IntegrityError: # pragma: nocover pass return HttpResponseRedirect(return_url)
[ "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_VERSION", "<=", "(", "2", ",", "0", ",", "0", ")", ":", "user_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "(", ")", "else", ":", "user_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "if", "user_authenticated", ":", "user", "=", "request", ".", "user", "else", ":", "# Get user out of saved pipeline from django-socialauth", "if", "'partial_pipeline'", "in", "request", ".", "session", ":", "user_pk", "=", "request", ".", "session", "[", "'partial_pipeline'", "]", "[", "'kwargs'", "]", "[", "'user'", "]", "[", "'pk'", "]", "user", "=", "User", ".", "objects", ".", "get", "(", "id", "=", "user_pk", ")", "else", ":", "return", "HttpResponseRedirect", "(", "'/'", ")", "store_ip_address", "=", "getattr", "(", "settings", ",", "'TERMS_STORE_IP_ADDRESS'", ",", "True", ")", "if", "store_ip_address", ":", "ip_address", "=", "request", ".", "META", ".", "get", "(", "getattr", "(", "settings", ",", "'TERMS_IP_HEADER_NAME'", ",", "DEFAULT_TERMS_IP_HEADER_NAME", ")", ")", "else", ":", "ip_address", "=", "\"\"", "for", "terms_id", "in", "terms_ids", ":", "try", ":", "new_user_terms", "=", "UserTermsAndConditions", "(", "user", "=", "user", ",", "terms", "=", "TermsAndConditions", ".", "objects", ".", "get", "(", "pk", "=", "int", "(", "terms_id", ")", ")", ",", "ip_address", "=", "ip_address", ")", "new_user_terms", ".", "save", "(", ")", "except", "IntegrityError", ":", "# pragma: nocover", "pass", "return", "HttpResponseRedirect", "(", "return_url", ")" ]
Handles POST request.
[ "Handles", "POST", "request", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L91-L133
10,345
cyface/django-termsandconditions
termsandconditions/views.py
EmailTermsView.form_valid
def form_valid(self, form): """Override of CreateView method, sends the email.""" LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid') template = get_template("termsandconditions/tc_email_terms.html") template_rendered = template.render({"terms": form.cleaned_data.get('terms')}) LOGGER.debug("Email Terms Body:") LOGGER.debug(template_rendered) try: send_mail(form.cleaned_data.get('email_subject', _('Terms')), template_rendered, settings.DEFAULT_FROM_EMAIL, [form.cleaned_data.get('email_address')], fail_silently=False) messages.add_message(self.request, messages.INFO, _("Terms and Conditions Sent.")) except SMTPException: # pragma: no cover messages.add_message(self.request, messages.ERROR, _("An Error Occurred Sending Your Message.")) self.success_url = form.cleaned_data.get('returnTo', '/') or '/' return super(EmailTermsView, self).form_valid(form)
python
def form_valid(self, form): """Override of CreateView method, sends the email.""" LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid') template = get_template("termsandconditions/tc_email_terms.html") template_rendered = template.render({"terms": form.cleaned_data.get('terms')}) LOGGER.debug("Email Terms Body:") LOGGER.debug(template_rendered) try: send_mail(form.cleaned_data.get('email_subject', _('Terms')), template_rendered, settings.DEFAULT_FROM_EMAIL, [form.cleaned_data.get('email_address')], fail_silently=False) messages.add_message(self.request, messages.INFO, _("Terms and Conditions Sent.")) except SMTPException: # pragma: no cover messages.add_message(self.request, messages.ERROR, _("An Error Occurred Sending Your Message.")) self.success_url = form.cleaned_data.get('returnTo', '/') or '/' return super(EmailTermsView, self).form_valid(form)
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "LOGGER", ".", "debug", "(", "'termsandconditions.views.EmailTermsView.form_valid'", ")", "template", "=", "get_template", "(", "\"termsandconditions/tc_email_terms.html\"", ")", "template_rendered", "=", "template", ".", "render", "(", "{", "\"terms\"", ":", "form", ".", "cleaned_data", ".", "get", "(", "'terms'", ")", "}", ")", "LOGGER", ".", "debug", "(", "\"Email Terms Body:\"", ")", "LOGGER", ".", "debug", "(", "template_rendered", ")", "try", ":", "send_mail", "(", "form", ".", "cleaned_data", ".", "get", "(", "'email_subject'", ",", "_", "(", "'Terms'", ")", ")", ",", "template_rendered", ",", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "[", "form", ".", "cleaned_data", ".", "get", "(", "'email_address'", ")", "]", ",", "fail_silently", "=", "False", ")", "messages", ".", "add_message", "(", "self", ".", "request", ",", "messages", ".", "INFO", ",", "_", "(", "\"Terms and Conditions Sent.\"", ")", ")", "except", "SMTPException", ":", "# pragma: no cover", "messages", ".", "add_message", "(", "self", ".", "request", ",", "messages", ".", "ERROR", ",", "_", "(", "\"An Error Occurred Sending Your Message.\"", ")", ")", "self", ".", "success_url", "=", "form", ".", "cleaned_data", ".", "get", "(", "'returnTo'", ",", "'/'", ")", "or", "'/'", "return", "super", "(", "EmailTermsView", ",", "self", ")", ".", "form_valid", "(", "form", ")" ]
Override of CreateView method, sends the email.
[ "Override", "of", "CreateView", "method", "sends", "the", "email", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L162-L184
10,346
cyface/django-termsandconditions
termsandconditions/views.py
EmailTermsView.form_invalid
def form_invalid(self, form): """Override of CreateView method, logs invalid email form submissions.""" LOGGER.debug("Invalid Email Form Submitted") messages.add_message(self.request, messages.ERROR, _("Invalid Email Address.")) return super(EmailTermsView, self).form_invalid(form)
python
def form_invalid(self, form): """Override of CreateView method, logs invalid email form submissions.""" LOGGER.debug("Invalid Email Form Submitted") messages.add_message(self.request, messages.ERROR, _("Invalid Email Address.")) return super(EmailTermsView, self).form_invalid(form)
[ "def", "form_invalid", "(", "self", ",", "form", ")", ":", "LOGGER", ".", "debug", "(", "\"Invalid Email Form Submitted\"", ")", "messages", ".", "add_message", "(", "self", ".", "request", ",", "messages", ".", "ERROR", ",", "_", "(", "\"Invalid Email Address.\"", ")", ")", "return", "super", "(", "EmailTermsView", ",", "self", ")", ".", "form_invalid", "(", "form", ")" ]
Override of CreateView method, logs invalid email form submissions.
[ "Override", "of", "CreateView", "method", "logs", "invalid", "email", "form", "submissions", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L186-L190
10,347
cyface/django-termsandconditions
termsandconditions/decorators.py
terms_required
def terms_required(view_func): """ This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): """Method to wrap the view passed in""" # If user has not logged in, or if they have logged in and already agreed to the terms, let the view through if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if not user_authenticated or not TermsAndConditions.get_active_terms_not_agreed_to(request.user): return view_func(request, *args, **kwargs) # Otherwise, redirect to terms accept current_path = request.path login_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) querystring = QueryDict(login_url_parts[4], mutable=True) querystring['returnTo'] = current_path login_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urlunparse(login_url_parts)) return _wrapped_view
python
def terms_required(view_func): """ This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): """Method to wrap the view passed in""" # If user has not logged in, or if they have logged in and already agreed to the terms, let the view through if DJANGO_VERSION <= (2, 0, 0): user_authenticated = request.user.is_authenticated() else: user_authenticated = request.user.is_authenticated if not user_authenticated or not TermsAndConditions.get_active_terms_not_agreed_to(request.user): return view_func(request, *args, **kwargs) # Otherwise, redirect to terms accept current_path = request.path login_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) querystring = QueryDict(login_url_parts[4], mutable=True) querystring['returnTo'] = current_path login_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urlunparse(login_url_parts)) return _wrapped_view
[ "def", "terms_required", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Method to wrap the view passed in\"\"\"", "# If user has not logged in, or if they have logged in and already agreed to the terms, let the view through", "if", "DJANGO_VERSION", "<=", "(", "2", ",", "0", ",", "0", ")", ":", "user_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "(", ")", "else", ":", "user_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "if", "not", "user_authenticated", "or", "not", "TermsAndConditions", ".", "get_active_terms_not_agreed_to", "(", "request", ".", "user", ")", ":", "return", "view_func", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Otherwise, redirect to terms accept", "current_path", "=", "request", ".", "path", "login_url_parts", "=", "list", "(", "urlparse", "(", "ACCEPT_TERMS_PATH", ")", ")", "querystring", "=", "QueryDict", "(", "login_url_parts", "[", "4", "]", ",", "mutable", "=", "True", ")", "querystring", "[", "'returnTo'", "]", "=", "current_path", "login_url_parts", "[", "4", "]", "=", "querystring", ".", "urlencode", "(", "safe", "=", "'/'", ")", "return", "HttpResponseRedirect", "(", "urlunparse", "(", "login_url_parts", ")", ")", "return", "_wrapped_view" ]
This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms.
[ "This", "decorator", "checks", "to", "see", "if", "the", "user", "is", "logged", "in", "and", "if", "so", "if", "they", "have", "accepted", "the", "site", "terms", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/decorators.py#L11-L36
10,348
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active
def get_active(slug=DEFAULT_TERMS_SLUG): """Finds the latest of a particular terms and conditions""" active_terms = cache.get('tandc.active_terms_' + slug) if active_terms is None: try: active_terms = TermsAndConditions.objects.filter( date_active__isnull=False, date_active__lte=timezone.now(), slug=slug).latest('date_active') cache.set('tandc.active_terms_' + slug, active_terms, TERMS_CACHE_SECONDS) except TermsAndConditions.DoesNotExist: # pragma: nocover LOGGER.error("Requested Terms and Conditions that Have Not Been Created.") return None return active_terms
python
def get_active(slug=DEFAULT_TERMS_SLUG): """Finds the latest of a particular terms and conditions""" active_terms = cache.get('tandc.active_terms_' + slug) if active_terms is None: try: active_terms = TermsAndConditions.objects.filter( date_active__isnull=False, date_active__lte=timezone.now(), slug=slug).latest('date_active') cache.set('tandc.active_terms_' + slug, active_terms, TERMS_CACHE_SECONDS) except TermsAndConditions.DoesNotExist: # pragma: nocover LOGGER.error("Requested Terms and Conditions that Have Not Been Created.") return None return active_terms
[ "def", "get_active", "(", "slug", "=", "DEFAULT_TERMS_SLUG", ")", ":", "active_terms", "=", "cache", ".", "get", "(", "'tandc.active_terms_'", "+", "slug", ")", "if", "active_terms", "is", "None", ":", "try", ":", "active_terms", "=", "TermsAndConditions", ".", "objects", ".", "filter", "(", "date_active__isnull", "=", "False", ",", "date_active__lte", "=", "timezone", ".", "now", "(", ")", ",", "slug", "=", "slug", ")", ".", "latest", "(", "'date_active'", ")", "cache", ".", "set", "(", "'tandc.active_terms_'", "+", "slug", ",", "active_terms", ",", "TERMS_CACHE_SECONDS", ")", "except", "TermsAndConditions", ".", "DoesNotExist", ":", "# pragma: nocover", "LOGGER", ".", "error", "(", "\"Requested Terms and Conditions that Have Not Been Created.\"", ")", "return", "None", "return", "active_terms" ]
Finds the latest of a particular terms and conditions
[ "Finds", "the", "latest", "of", "a", "particular", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L75-L90
10,349
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active_terms_ids
def get_active_terms_ids(): """Returns a list of the IDs of of all terms and conditions""" active_terms_ids = cache.get('tandc.active_terms_ids') if active_terms_ids is None: active_terms_dict = {} active_terms_ids = [] active_terms_set = TermsAndConditions.objects.filter(date_active__isnull=False, date_active__lte=timezone.now()).order_by('date_active') for active_terms in active_terms_set: active_terms_dict[active_terms.slug] = active_terms.id active_terms_dict = OrderedDict(sorted(active_terms_dict.items(), key=lambda t: t[0])) for terms in active_terms_dict: active_terms_ids.append(active_terms_dict[terms]) cache.set('tandc.active_terms_ids', active_terms_ids, TERMS_CACHE_SECONDS) return active_terms_ids
python
def get_active_terms_ids(): """Returns a list of the IDs of of all terms and conditions""" active_terms_ids = cache.get('tandc.active_terms_ids') if active_terms_ids is None: active_terms_dict = {} active_terms_ids = [] active_terms_set = TermsAndConditions.objects.filter(date_active__isnull=False, date_active__lte=timezone.now()).order_by('date_active') for active_terms in active_terms_set: active_terms_dict[active_terms.slug] = active_terms.id active_terms_dict = OrderedDict(sorted(active_terms_dict.items(), key=lambda t: t[0])) for terms in active_terms_dict: active_terms_ids.append(active_terms_dict[terms]) cache.set('tandc.active_terms_ids', active_terms_ids, TERMS_CACHE_SECONDS) return active_terms_ids
[ "def", "get_active_terms_ids", "(", ")", ":", "active_terms_ids", "=", "cache", ".", "get", "(", "'tandc.active_terms_ids'", ")", "if", "active_terms_ids", "is", "None", ":", "active_terms_dict", "=", "{", "}", "active_terms_ids", "=", "[", "]", "active_terms_set", "=", "TermsAndConditions", ".", "objects", ".", "filter", "(", "date_active__isnull", "=", "False", ",", "date_active__lte", "=", "timezone", ".", "now", "(", ")", ")", ".", "order_by", "(", "'date_active'", ")", "for", "active_terms", "in", "active_terms_set", ":", "active_terms_dict", "[", "active_terms", ".", "slug", "]", "=", "active_terms", ".", "id", "active_terms_dict", "=", "OrderedDict", "(", "sorted", "(", "active_terms_dict", ".", "items", "(", ")", ",", "key", "=", "lambda", "t", ":", "t", "[", "0", "]", ")", ")", "for", "terms", "in", "active_terms_dict", ":", "active_terms_ids", ".", "append", "(", "active_terms_dict", "[", "terms", "]", ")", "cache", ".", "set", "(", "'tandc.active_terms_ids'", ",", "active_terms_ids", ",", "TERMS_CACHE_SECONDS", ")", "return", "active_terms_ids" ]
Returns a list of the IDs of of all terms and conditions
[ "Returns", "a", "list", "of", "the", "IDs", "of", "of", "all", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L93-L112
10,350
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active_terms_list
def get_active_terms_list(): """Returns all the latest active terms and conditions""" active_terms_list = cache.get('tandc.active_terms_list') if active_terms_list is None: active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_by('slug') cache.set('tandc.active_terms_list', active_terms_list, TERMS_CACHE_SECONDS) return active_terms_list
python
def get_active_terms_list(): """Returns all the latest active terms and conditions""" active_terms_list = cache.get('tandc.active_terms_list') if active_terms_list is None: active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_by('slug') cache.set('tandc.active_terms_list', active_terms_list, TERMS_CACHE_SECONDS) return active_terms_list
[ "def", "get_active_terms_list", "(", ")", ":", "active_terms_list", "=", "cache", ".", "get", "(", "'tandc.active_terms_list'", ")", "if", "active_terms_list", "is", "None", ":", "active_terms_list", "=", "TermsAndConditions", ".", "objects", ".", "filter", "(", "id__in", "=", "TermsAndConditions", ".", "get_active_terms_ids", "(", ")", ")", ".", "order_by", "(", "'slug'", ")", "cache", ".", "set", "(", "'tandc.active_terms_list'", ",", "active_terms_list", ",", "TERMS_CACHE_SECONDS", ")", "return", "active_terms_list" ]
Returns all the latest active terms and conditions
[ "Returns", "all", "the", "latest", "active", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L115-L123
10,351
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active_terms_not_agreed_to
def get_active_terms_not_agreed_to(user): """Checks to see if a specified user has agreed to all the latest terms and conditions""" if TERMS_EXCLUDE_USERS_WITH_PERM is not None: if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser: # Django's has_perm() returns True if is_superuser, we don't want that return [] not_agreed_terms = cache.get('tandc.not_agreed_terms_' + user.get_username()) if not_agreed_terms is None: try: LOGGER.debug("Not Agreed Terms") not_agreed_terms = TermsAndConditions.get_active_terms_list().exclude( userterms__in=UserTermsAndConditions.objects.filter(user=user) ).order_by('slug') cache.set('tandc.not_agreed_terms_' + user.get_username(), not_agreed_terms, TERMS_CACHE_SECONDS) except (TypeError, UserTermsAndConditions.DoesNotExist): return [] return not_agreed_terms
python
def get_active_terms_not_agreed_to(user): """Checks to see if a specified user has agreed to all the latest terms and conditions""" if TERMS_EXCLUDE_USERS_WITH_PERM is not None: if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser: # Django's has_perm() returns True if is_superuser, we don't want that return [] not_agreed_terms = cache.get('tandc.not_agreed_terms_' + user.get_username()) if not_agreed_terms is None: try: LOGGER.debug("Not Agreed Terms") not_agreed_terms = TermsAndConditions.get_active_terms_list().exclude( userterms__in=UserTermsAndConditions.objects.filter(user=user) ).order_by('slug') cache.set('tandc.not_agreed_terms_' + user.get_username(), not_agreed_terms, TERMS_CACHE_SECONDS) except (TypeError, UserTermsAndConditions.DoesNotExist): return [] return not_agreed_terms
[ "def", "get_active_terms_not_agreed_to", "(", "user", ")", ":", "if", "TERMS_EXCLUDE_USERS_WITH_PERM", "is", "not", "None", ":", "if", "user", ".", "has_perm", "(", "TERMS_EXCLUDE_USERS_WITH_PERM", ")", "and", "not", "user", ".", "is_superuser", ":", "# Django's has_perm() returns True if is_superuser, we don't want that", "return", "[", "]", "not_agreed_terms", "=", "cache", ".", "get", "(", "'tandc.not_agreed_terms_'", "+", "user", ".", "get_username", "(", ")", ")", "if", "not_agreed_terms", "is", "None", ":", "try", ":", "LOGGER", ".", "debug", "(", "\"Not Agreed Terms\"", ")", "not_agreed_terms", "=", "TermsAndConditions", ".", "get_active_terms_list", "(", ")", ".", "exclude", "(", "userterms__in", "=", "UserTermsAndConditions", ".", "objects", ".", "filter", "(", "user", "=", "user", ")", ")", ".", "order_by", "(", "'slug'", ")", "cache", ".", "set", "(", "'tandc.not_agreed_terms_'", "+", "user", ".", "get_username", "(", ")", ",", "not_agreed_terms", ",", "TERMS_CACHE_SECONDS", ")", "except", "(", "TypeError", ",", "UserTermsAndConditions", ".", "DoesNotExist", ")", ":", "return", "[", "]", "return", "not_agreed_terms" ]
Checks to see if a specified user has agreed to all the latest terms and conditions
[ "Checks", "to", "see", "if", "a", "specified", "user", "has", "agreed", "to", "all", "the", "latest", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L126-L146
10,352
cyface/django-termsandconditions
termsandconditions/templatetags/terms_tags.py
show_terms_if_not_agreed
def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD): """Displays a modal on a current page if a user has not yet agreed to the given terms. If terms are not specified, the default slug is used. A small snippet is included into your template if a user who requested the view has not yet agreed the terms. The snippet takes care of displaying a respective modal. """ request = context['request'] url = urlparse(request.META[field]) not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(request.user) if not_agreed_terms and is_path_protected(url.path): return {'not_agreed_terms': not_agreed_terms, 'returnTo': url.path} else: return {}
python
def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD): """Displays a modal on a current page if a user has not yet agreed to the given terms. If terms are not specified, the default slug is used. A small snippet is included into your template if a user who requested the view has not yet agreed the terms. The snippet takes care of displaying a respective modal. """ request = context['request'] url = urlparse(request.META[field]) not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(request.user) if not_agreed_terms and is_path_protected(url.path): return {'not_agreed_terms': not_agreed_terms, 'returnTo': url.path} else: return {}
[ "def", "show_terms_if_not_agreed", "(", "context", ",", "field", "=", "TERMS_HTTP_PATH_FIELD", ")", ":", "request", "=", "context", "[", "'request'", "]", "url", "=", "urlparse", "(", "request", ".", "META", "[", "field", "]", ")", "not_agreed_terms", "=", "TermsAndConditions", ".", "get_active_terms_not_agreed_to", "(", "request", ".", "user", ")", "if", "not_agreed_terms", "and", "is_path_protected", "(", "url", ".", "path", ")", ":", "return", "{", "'not_agreed_terms'", ":", "not_agreed_terms", ",", "'returnTo'", ":", "url", ".", "path", "}", "else", ":", "return", "{", "}" ]
Displays a modal on a current page if a user has not yet agreed to the given terms. If terms are not specified, the default slug is used. A small snippet is included into your template if a user who requested the view has not yet agreed the terms. The snippet takes care of displaying a respective modal.
[ "Displays", "a", "modal", "on", "a", "current", "page", "if", "a", "user", "has", "not", "yet", "agreed", "to", "the", "given", "terms", ".", "If", "terms", "are", "not", "specified", "the", "default", "slug", "is", "used", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/templatetags/terms_tags.py#L15-L30
10,353
cyface/django-termsandconditions
termsandconditions/pipeline.py
user_accept_terms
def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs): """Check if the user has accepted the terms and conditions after creation.""" LOGGER.debug('user_accept_terms') if TermsAndConditions.get_active_terms_not_agreed_to(user): return redirect_to_terms_accept('/') else: return {'social_user': social_user, 'user': user}
python
def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs): """Check if the user has accepted the terms and conditions after creation.""" LOGGER.debug('user_accept_terms') if TermsAndConditions.get_active_terms_not_agreed_to(user): return redirect_to_terms_accept('/') else: return {'social_user': social_user, 'user': user}
[ "def", "user_accept_terms", "(", "backend", ",", "user", ",", "uid", ",", "social_user", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "'user_accept_terms'", ")", "if", "TermsAndConditions", ".", "get_active_terms_not_agreed_to", "(", "user", ")", ":", "return", "redirect_to_terms_accept", "(", "'/'", ")", "else", ":", "return", "{", "'social_user'", ":", "social_user", ",", "'user'", ":", "user", "}" ]
Check if the user has accepted the terms and conditions after creation.
[ "Check", "if", "the", "user", "has", "accepted", "the", "terms", "and", "conditions", "after", "creation", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L17-L25
10,354
cyface/django-termsandconditions
termsandconditions/pipeline.py
redirect_to_terms_accept
def redirect_to_terms_accept(current_path='/', slug='default'): """Redirect the user to the terms and conditions accept page.""" redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) if slug != 'default': redirect_url_parts[2] += slug querystring = QueryDict(redirect_url_parts[4], mutable=True) querystring[TERMS_RETURNTO_PARAM] = current_path redirect_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urlunparse(redirect_url_parts))
python
def redirect_to_terms_accept(current_path='/', slug='default'): """Redirect the user to the terms and conditions accept page.""" redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) if slug != 'default': redirect_url_parts[2] += slug querystring = QueryDict(redirect_url_parts[4], mutable=True) querystring[TERMS_RETURNTO_PARAM] = current_path redirect_url_parts[4] = querystring.urlencode(safe='/') return HttpResponseRedirect(urlunparse(redirect_url_parts))
[ "def", "redirect_to_terms_accept", "(", "current_path", "=", "'/'", ",", "slug", "=", "'default'", ")", ":", "redirect_url_parts", "=", "list", "(", "urlparse", "(", "ACCEPT_TERMS_PATH", ")", ")", "if", "slug", "!=", "'default'", ":", "redirect_url_parts", "[", "2", "]", "+=", "slug", "querystring", "=", "QueryDict", "(", "redirect_url_parts", "[", "4", "]", ",", "mutable", "=", "True", ")", "querystring", "[", "TERMS_RETURNTO_PARAM", "]", "=", "current_path", "redirect_url_parts", "[", "4", "]", "=", "querystring", ".", "urlencode", "(", "safe", "=", "'/'", ")", "return", "HttpResponseRedirect", "(", "urlunparse", "(", "redirect_url_parts", ")", ")" ]
Redirect the user to the terms and conditions accept page.
[ "Redirect", "the", "user", "to", "the", "terms", "and", "conditions", "accept", "page", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L28-L36
10,355
cyface/django-termsandconditions
termsandconditions/signals.py
user_terms_updated
def user_terms_updated(sender, **kwargs): """Called when user terms and conditions is changed - to force cache clearing""" LOGGER.debug("User T&C Updated Signal Handler") if kwargs.get('instance').user: cache.delete('tandc.not_agreed_terms_' + kwargs.get('instance').user.get_username())
python
def user_terms_updated(sender, **kwargs): """Called when user terms and conditions is changed - to force cache clearing""" LOGGER.debug("User T&C Updated Signal Handler") if kwargs.get('instance').user: cache.delete('tandc.not_agreed_terms_' + kwargs.get('instance').user.get_username())
[ "def", "user_terms_updated", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "\"User T&C Updated Signal Handler\"", ")", "if", "kwargs", ".", "get", "(", "'instance'", ")", ".", "user", ":", "cache", ".", "delete", "(", "'tandc.not_agreed_terms_'", "+", "kwargs", ".", "get", "(", "'instance'", ")", ".", "user", ".", "get_username", "(", ")", ")" ]
Called when user terms and conditions is changed - to force cache clearing
[ "Called", "when", "user", "terms", "and", "conditions", "is", "changed", "-", "to", "force", "cache", "clearing" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L15-L19
10,356
cyface/django-termsandconditions
termsandconditions/signals.py
terms_updated
def terms_updated(sender, **kwargs): """Called when terms and conditions is changed - to force cache clearing""" LOGGER.debug("T&C Updated Signal Handler") cache.delete('tandc.active_terms_ids') cache.delete('tandc.active_terms_list') if kwargs.get('instance').slug: cache.delete('tandc.active_terms_' + kwargs.get('instance').slug) for utandc in UserTermsAndConditions.objects.all(): cache.delete('tandc.not_agreed_terms_' + utandc.user.get_username())
python
def terms_updated(sender, **kwargs): """Called when terms and conditions is changed - to force cache clearing""" LOGGER.debug("T&C Updated Signal Handler") cache.delete('tandc.active_terms_ids') cache.delete('tandc.active_terms_list') if kwargs.get('instance').slug: cache.delete('tandc.active_terms_' + kwargs.get('instance').slug) for utandc in UserTermsAndConditions.objects.all(): cache.delete('tandc.not_agreed_terms_' + utandc.user.get_username())
[ "def", "terms_updated", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "\"T&C Updated Signal Handler\"", ")", "cache", ".", "delete", "(", "'tandc.active_terms_ids'", ")", "cache", ".", "delete", "(", "'tandc.active_terms_list'", ")", "if", "kwargs", ".", "get", "(", "'instance'", ")", ".", "slug", ":", "cache", ".", "delete", "(", "'tandc.active_terms_'", "+", "kwargs", ".", "get", "(", "'instance'", ")", ".", "slug", ")", "for", "utandc", "in", "UserTermsAndConditions", ".", "objects", ".", "all", "(", ")", ":", "cache", ".", "delete", "(", "'tandc.not_agreed_terms_'", "+", "utandc", ".", "user", ".", "get_username", "(", ")", ")" ]
Called when terms and conditions is changed - to force cache clearing
[ "Called", "when", "terms", "and", "conditions", "is", "changed", "-", "to", "force", "cache", "clearing" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L23-L31
10,357
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
paginate
def paginate(parser, token, paginator_class=None): """Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* original variable (usually a queryset) and add to the context another name that refers to entries of the current page, e.g.: .. code-block:: html+django {% paginate entries as page_entries %} The *as* argument is also useful when a nested context variable is provided as queryset. In this case, and only in this case, the resulting variable name is mandatory, e.g.: .. code-block:: html+django {% paginate entries.all as entries %} The number of paginated entries is taken from settings, but you can override the default locally, e.g.: .. code-block:: html+django {% paginate 20 entries %} Of course you can mix it all: .. code-block:: html+django {% paginate 20 entries as paginated_entries %} By default, the first page is displayed the first time you load the page, but you can change this, e.g.: .. code-block:: html+django {% paginate entries starting from page 3 %} When changing the default page, it is also possible to reference the last page (or the second last page, and so on) by using negative indexes, e.g: .. code-block:: html+django {% paginate entries starting from page -1 %} This can be also achieved using a template variable that was passed to the context, e.g.: .. code-block:: html+django {% paginate entries starting from page page_number %} If the passed page number does not exist, the first page is displayed. If you have multiple paginations in the same page, you can change the querydict key for the single pagination, e.g.: .. code-block:: html+django {% paginate entries using article_page %} In this case *article_page* is intended to be a context variable, but you can hardcode the key using quotes, e.g.: .. code-block:: html+django {% paginate entries using 'articles_at_page' %} Again, you can mix it all (the order of arguments is important): .. code-block:: html+django {% paginate 20 entries starting from page 3 using page_key as paginated_entries %} Additionally you can pass a path to be used for the pagination: .. code-block:: html+django {% paginate 20 entries using page_key with pagination_url as paginated_entries %} This way you can easily create views acting as API endpoints, and point your Ajax calls to that API. In this case *pagination_url* is considered a context variable, but it is also possible to hardcode the URL, e.g.: .. code-block:: html+django {% paginate 20 entries with "/mypage/" %} If you want the first page to contain a different number of items than subsequent pages, you can separate the two values with a comma, e.g. if you want 3 items on the first page and 10 on other pages: .. code-block:: html+django {% paginate 3,10 entries %} You must use this tag before calling the {% show_more %} one. """ # Validate arguments. try: tag_name, tag_args = token.contents.split(None, 1) except ValueError: msg = '%r tag requires arguments' % token.contents.split()[0] raise template.TemplateSyntaxError(msg) # Use a regexp to catch args. match = PAGINATE_EXPRESSION.match(tag_args) if match is None: msg = 'Invalid arguments for %r tag' % tag_name raise template.TemplateSyntaxError(msg) # Retrieve objects. kwargs = match.groupdict() objects = kwargs.pop('objects') # The variable name must be present if a nested context variable is passed. if '.' in objects and kwargs['var_name'] is None: msg = ( '%(tag)r tag requires a variable name `as` argumnent if the ' 'queryset is provided as a nested context variable (%(objects)s). ' 'You must either pass a direct queryset (e.g. taking advantage ' 'of the `with` template tag) or provide a new variable name to ' 'store the resulting queryset (e.g. `%(tag)s %(objects)s as ' 'objects`).' ) % {'tag': tag_name, 'objects': objects} raise template.TemplateSyntaxError(msg) # Call the node. return PaginateNode(paginator_class, objects, **kwargs)
python
def paginate(parser, token, paginator_class=None): """Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* original variable (usually a queryset) and add to the context another name that refers to entries of the current page, e.g.: .. code-block:: html+django {% paginate entries as page_entries %} The *as* argument is also useful when a nested context variable is provided as queryset. In this case, and only in this case, the resulting variable name is mandatory, e.g.: .. code-block:: html+django {% paginate entries.all as entries %} The number of paginated entries is taken from settings, but you can override the default locally, e.g.: .. code-block:: html+django {% paginate 20 entries %} Of course you can mix it all: .. code-block:: html+django {% paginate 20 entries as paginated_entries %} By default, the first page is displayed the first time you load the page, but you can change this, e.g.: .. code-block:: html+django {% paginate entries starting from page 3 %} When changing the default page, it is also possible to reference the last page (or the second last page, and so on) by using negative indexes, e.g: .. code-block:: html+django {% paginate entries starting from page -1 %} This can be also achieved using a template variable that was passed to the context, e.g.: .. code-block:: html+django {% paginate entries starting from page page_number %} If the passed page number does not exist, the first page is displayed. If you have multiple paginations in the same page, you can change the querydict key for the single pagination, e.g.: .. code-block:: html+django {% paginate entries using article_page %} In this case *article_page* is intended to be a context variable, but you can hardcode the key using quotes, e.g.: .. code-block:: html+django {% paginate entries using 'articles_at_page' %} Again, you can mix it all (the order of arguments is important): .. code-block:: html+django {% paginate 20 entries starting from page 3 using page_key as paginated_entries %} Additionally you can pass a path to be used for the pagination: .. code-block:: html+django {% paginate 20 entries using page_key with pagination_url as paginated_entries %} This way you can easily create views acting as API endpoints, and point your Ajax calls to that API. In this case *pagination_url* is considered a context variable, but it is also possible to hardcode the URL, e.g.: .. code-block:: html+django {% paginate 20 entries with "/mypage/" %} If you want the first page to contain a different number of items than subsequent pages, you can separate the two values with a comma, e.g. if you want 3 items on the first page and 10 on other pages: .. code-block:: html+django {% paginate 3,10 entries %} You must use this tag before calling the {% show_more %} one. """ # Validate arguments. try: tag_name, tag_args = token.contents.split(None, 1) except ValueError: msg = '%r tag requires arguments' % token.contents.split()[0] raise template.TemplateSyntaxError(msg) # Use a regexp to catch args. match = PAGINATE_EXPRESSION.match(tag_args) if match is None: msg = 'Invalid arguments for %r tag' % tag_name raise template.TemplateSyntaxError(msg) # Retrieve objects. kwargs = match.groupdict() objects = kwargs.pop('objects') # The variable name must be present if a nested context variable is passed. if '.' in objects and kwargs['var_name'] is None: msg = ( '%(tag)r tag requires a variable name `as` argumnent if the ' 'queryset is provided as a nested context variable (%(objects)s). ' 'You must either pass a direct queryset (e.g. taking advantage ' 'of the `with` template tag) or provide a new variable name to ' 'store the resulting queryset (e.g. `%(tag)s %(objects)s as ' 'objects`).' ) % {'tag': tag_name, 'objects': objects} raise template.TemplateSyntaxError(msg) # Call the node. return PaginateNode(paginator_class, objects, **kwargs)
[ "def", "paginate", "(", "parser", ",", "token", ",", "paginator_class", "=", "None", ")", ":", "# Validate arguments.", "try", ":", "tag_name", ",", "tag_args", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "msg", "=", "'%r tag requires arguments'", "%", "token", ".", "contents", ".", "split", "(", ")", "[", "0", "]", "raise", "template", ".", "TemplateSyntaxError", "(", "msg", ")", "# Use a regexp to catch args.", "match", "=", "PAGINATE_EXPRESSION", ".", "match", "(", "tag_args", ")", "if", "match", "is", "None", ":", "msg", "=", "'Invalid arguments for %r tag'", "%", "tag_name", "raise", "template", ".", "TemplateSyntaxError", "(", "msg", ")", "# Retrieve objects.", "kwargs", "=", "match", ".", "groupdict", "(", ")", "objects", "=", "kwargs", ".", "pop", "(", "'objects'", ")", "# The variable name must be present if a nested context variable is passed.", "if", "'.'", "in", "objects", "and", "kwargs", "[", "'var_name'", "]", "is", "None", ":", "msg", "=", "(", "'%(tag)r tag requires a variable name `as` argumnent if the '", "'queryset is provided as a nested context variable (%(objects)s). '", "'You must either pass a direct queryset (e.g. taking advantage '", "'of the `with` template tag) or provide a new variable name to '", "'store the resulting queryset (e.g. `%(tag)s %(objects)s as '", "'objects`).'", ")", "%", "{", "'tag'", ":", "tag_name", ",", "'objects'", ":", "objects", "}", "raise", "template", ".", "TemplateSyntaxError", "(", "msg", ")", "# Call the node.", "return", "PaginateNode", "(", "paginator_class", ",", "objects", ",", "*", "*", "kwargs", ")" ]
Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* original variable (usually a queryset) and add to the context another name that refers to entries of the current page, e.g.: .. code-block:: html+django {% paginate entries as page_entries %} The *as* argument is also useful when a nested context variable is provided as queryset. In this case, and only in this case, the resulting variable name is mandatory, e.g.: .. code-block:: html+django {% paginate entries.all as entries %} The number of paginated entries is taken from settings, but you can override the default locally, e.g.: .. code-block:: html+django {% paginate 20 entries %} Of course you can mix it all: .. code-block:: html+django {% paginate 20 entries as paginated_entries %} By default, the first page is displayed the first time you load the page, but you can change this, e.g.: .. code-block:: html+django {% paginate entries starting from page 3 %} When changing the default page, it is also possible to reference the last page (or the second last page, and so on) by using negative indexes, e.g: .. code-block:: html+django {% paginate entries starting from page -1 %} This can be also achieved using a template variable that was passed to the context, e.g.: .. code-block:: html+django {% paginate entries starting from page page_number %} If the passed page number does not exist, the first page is displayed. If you have multiple paginations in the same page, you can change the querydict key for the single pagination, e.g.: .. code-block:: html+django {% paginate entries using article_page %} In this case *article_page* is intended to be a context variable, but you can hardcode the key using quotes, e.g.: .. code-block:: html+django {% paginate entries using 'articles_at_page' %} Again, you can mix it all (the order of arguments is important): .. code-block:: html+django {% paginate 20 entries starting from page 3 using page_key as paginated_entries %} Additionally you can pass a path to be used for the pagination: .. code-block:: html+django {% paginate 20 entries using page_key with pagination_url as paginated_entries %} This way you can easily create views acting as API endpoints, and point your Ajax calls to that API. In this case *pagination_url* is considered a context variable, but it is also possible to hardcode the URL, e.g.: .. code-block:: html+django {% paginate 20 entries with "/mypage/" %} If you want the first page to contain a different number of items than subsequent pages, you can separate the two values with a comma, e.g. if you want 3 items on the first page and 10 on other pages: .. code-block:: html+django {% paginate 3,10 entries %} You must use this tag before calling the {% show_more %} one.
[ "Paginate", "objects", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L45-L185
10,358
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
get_pages
def get_pages(parser, token): """Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in different ways: - just print *pages.get_rendered* and you will get Digg-style pagination displayed: .. code-block:: html+django {{ pages.get_rendered }} - display pages count: .. code-block:: html+django {{ pages|length }} - check if the page list contains more than one page: .. code-block:: html+django {{ pages.paginated }} {# the following is equivalent #} {{ pages|length > 1 }} - get a specific page: .. code-block:: html+django {# the current selected page #} {{ pages.current }} {# the first page #} {{ pages.first }} {# the last page #} {{ pages.last }} {# the previous page (or nothing if you are on first page) #} {{ pages.previous }} {# the next page (or nothing if you are in last page) #} {{ pages.next }} {# the third page #} {{ pages.3 }} {# this means page.1 is the same as page.first #} {# the 1-based index of the first item on the current page #} {{ pages.current_start_index }} {# the 1-based index of the last item on the current page #} {{ pages.current_end_index }} {# the total number of objects, across all pages #} {{ pages.total_count }} {# the first page represented as an arrow #} {{ pages.first_as_arrow }} {# the last page represented as an arrow #} {{ pages.last_as_arrow }} - iterate over *pages* to get all pages: .. code-block:: html+django {% for page in pages %} {# display page link #} {{ page.render_link}} {# the page url (beginning with "?") #} {{ page.url }} {# the page path #} {{ page.path }} {# the page number #} {{ page.number }} {# a string representing the page (commonly the page number) #} {{ page.label }} {# check if the page is the current one #} {{ page.is_current }} {# check if the page is the first one #} {{ page.is_first }} {# check if the page is the last one #} {{ page.is_last }} {% endfor %} You can change the variable name, e.g.: .. code-block:: html+django {% get_pages as page_links %} Must be called after ``{% paginate objects %}``. """ # Validate args. try: tag_name, args = token.contents.split(None, 1) except ValueError: var_name = 'pages' else: args = args.split() if len(args) == 2 and args[0] == 'as': var_name = args[1] else: msg = 'Invalid arguments for %r tag' % tag_name raise template.TemplateSyntaxError(msg) # Call the node. return GetPagesNode(var_name)
python
def get_pages(parser, token): """Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in different ways: - just print *pages.get_rendered* and you will get Digg-style pagination displayed: .. code-block:: html+django {{ pages.get_rendered }} - display pages count: .. code-block:: html+django {{ pages|length }} - check if the page list contains more than one page: .. code-block:: html+django {{ pages.paginated }} {# the following is equivalent #} {{ pages|length > 1 }} - get a specific page: .. code-block:: html+django {# the current selected page #} {{ pages.current }} {# the first page #} {{ pages.first }} {# the last page #} {{ pages.last }} {# the previous page (or nothing if you are on first page) #} {{ pages.previous }} {# the next page (or nothing if you are in last page) #} {{ pages.next }} {# the third page #} {{ pages.3 }} {# this means page.1 is the same as page.first #} {# the 1-based index of the first item on the current page #} {{ pages.current_start_index }} {# the 1-based index of the last item on the current page #} {{ pages.current_end_index }} {# the total number of objects, across all pages #} {{ pages.total_count }} {# the first page represented as an arrow #} {{ pages.first_as_arrow }} {# the last page represented as an arrow #} {{ pages.last_as_arrow }} - iterate over *pages* to get all pages: .. code-block:: html+django {% for page in pages %} {# display page link #} {{ page.render_link}} {# the page url (beginning with "?") #} {{ page.url }} {# the page path #} {{ page.path }} {# the page number #} {{ page.number }} {# a string representing the page (commonly the page number) #} {{ page.label }} {# check if the page is the current one #} {{ page.is_current }} {# check if the page is the first one #} {{ page.is_first }} {# check if the page is the last one #} {{ page.is_last }} {% endfor %} You can change the variable name, e.g.: .. code-block:: html+django {% get_pages as page_links %} Must be called after ``{% paginate objects %}``. """ # Validate args. try: tag_name, args = token.contents.split(None, 1) except ValueError: var_name = 'pages' else: args = args.split() if len(args) == 2 and args[0] == 'as': var_name = args[1] else: msg = 'Invalid arguments for %r tag' % tag_name raise template.TemplateSyntaxError(msg) # Call the node. return GetPagesNode(var_name)
[ "def", "get_pages", "(", "parser", ",", "token", ")", ":", "# Validate args.", "try", ":", "tag_name", ",", "args", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "var_name", "=", "'pages'", "else", ":", "args", "=", "args", ".", "split", "(", ")", "if", "len", "(", "args", ")", "==", "2", "and", "args", "[", "0", "]", "==", "'as'", ":", "var_name", "=", "args", "[", "1", "]", "else", ":", "msg", "=", "'Invalid arguments for %r tag'", "%", "tag_name", "raise", "template", ".", "TemplateSyntaxError", "(", "msg", ")", "# Call the node.", "return", "GetPagesNode", "(", "var_name", ")" ]
Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in different ways: - just print *pages.get_rendered* and you will get Digg-style pagination displayed: .. code-block:: html+django {{ pages.get_rendered }} - display pages count: .. code-block:: html+django {{ pages|length }} - check if the page list contains more than one page: .. code-block:: html+django {{ pages.paginated }} {# the following is equivalent #} {{ pages|length > 1 }} - get a specific page: .. code-block:: html+django {# the current selected page #} {{ pages.current }} {# the first page #} {{ pages.first }} {# the last page #} {{ pages.last }} {# the previous page (or nothing if you are on first page) #} {{ pages.previous }} {# the next page (or nothing if you are in last page) #} {{ pages.next }} {# the third page #} {{ pages.3 }} {# this means page.1 is the same as page.first #} {# the 1-based index of the first item on the current page #} {{ pages.current_start_index }} {# the 1-based index of the last item on the current page #} {{ pages.current_end_index }} {# the total number of objects, across all pages #} {{ pages.total_count }} {# the first page represented as an arrow #} {{ pages.first_as_arrow }} {# the last page represented as an arrow #} {{ pages.last_as_arrow }} - iterate over *pages* to get all pages: .. code-block:: html+django {% for page in pages %} {# display page link #} {{ page.render_link}} {# the page url (beginning with "?") #} {{ page.url }} {# the page path #} {{ page.path }} {# the page number #} {{ page.number }} {# a string representing the page (commonly the page number) #} {{ page.label }} {# check if the page is the current one #} {{ page.is_current }} {# check if the page is the first one #} {{ page.is_first }} {# check if the page is the last one #} {{ page.is_last }} {% endfor %} You can change the variable name, e.g.: .. code-block:: html+django {% get_pages as page_links %} Must be called after ``{% paginate objects %}``.
[ "Add", "to", "context", "the", "list", "of", "page", "links", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L378-L500
10,359
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
show_pages
def show_pages(parser, token): """Show page links. Usage: .. code-block:: html+django {% show_pages %} It is just a shortcut for: .. code-block:: html+django {% get_pages %} {{ pages.get_rendered }} You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py* to a callable, or to a dotted path representing a callable, used to customize the pages that are displayed. See the *__unicode__* method of ``endless_pagination.models.PageList`` for a detailed explanation of how the callable can be used. Must be called after ``{% paginate objects %}``. """ # Validate args. if len(token.contents.split()) != 1: msg = '%r tag takes no arguments' % token.contents.split()[0] raise template.TemplateSyntaxError(msg) # Call the node. return ShowPagesNode()
python
def show_pages(parser, token): """Show page links. Usage: .. code-block:: html+django {% show_pages %} It is just a shortcut for: .. code-block:: html+django {% get_pages %} {{ pages.get_rendered }} You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py* to a callable, or to a dotted path representing a callable, used to customize the pages that are displayed. See the *__unicode__* method of ``endless_pagination.models.PageList`` for a detailed explanation of how the callable can be used. Must be called after ``{% paginate objects %}``. """ # Validate args. if len(token.contents.split()) != 1: msg = '%r tag takes no arguments' % token.contents.split()[0] raise template.TemplateSyntaxError(msg) # Call the node. return ShowPagesNode()
[ "def", "show_pages", "(", "parser", ",", "token", ")", ":", "# Validate args.", "if", "len", "(", "token", ".", "contents", ".", "split", "(", ")", ")", "!=", "1", ":", "msg", "=", "'%r tag takes no arguments'", "%", "token", ".", "contents", ".", "split", "(", ")", "[", "0", "]", "raise", "template", ".", "TemplateSyntaxError", "(", "msg", ")", "# Call the node.", "return", "ShowPagesNode", "(", ")" ]
Show page links. Usage: .. code-block:: html+django {% show_pages %} It is just a shortcut for: .. code-block:: html+django {% get_pages %} {{ pages.get_rendered }} You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py* to a callable, or to a dotted path representing a callable, used to customize the pages that are displayed. See the *__unicode__* method of ``endless_pagination.models.PageList`` for a detailed explanation of how the callable can be used. Must be called after ``{% paginate objects %}``.
[ "Show", "page", "links", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L526-L556
10,360
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
show_current_number
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} If you use multiple paginations in the same page, you can get the page number for a specific pagination using the querystring key, e.g.: .. code-block:: html+django {% show_current_number using mykey %} The default page when no querystring is specified is 1. If you changed it in the `paginate`_ template tag, you have to call ``show_current_number`` according to your choice, e.g.: .. code-block:: html+django {% show_current_number starting from page 3 %} This can be also achieved using a template variable you passed to the context, e.g.: .. code-block:: html+django {% show_current_number starting from page page_number %} You can of course mix it all (the order of arguments is important): .. code-block:: html+django {% show_current_number starting from page 3 using mykey %} If you want to insert the current page number in the context, without actually displaying it in the template, use the *as* argument, i.e.: .. code-block:: html+django {% show_current_number as page_number %} {% show_current_number starting from page 3 using mykey as page_number %} """ # Validate args. try: tag_name, args = token.contents.split(None, 1) except ValueError: key = None number = None tag_name = token.contents[0] var_name = None else: # Use a regexp to catch args. match = SHOW_CURRENT_NUMBER_EXPRESSION.match(args) if match is None: msg = 'Invalid arguments for %r tag' % tag_name raise template.TemplateSyntaxError(msg) # Retrieve objects. groupdict = match.groupdict() key = groupdict['key'] number = groupdict['number'] var_name = groupdict['var_name'] # Call the node. return ShowCurrentNumberNode(number, key, var_name)
python
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} If you use multiple paginations in the same page, you can get the page number for a specific pagination using the querystring key, e.g.: .. code-block:: html+django {% show_current_number using mykey %} The default page when no querystring is specified is 1. If you changed it in the `paginate`_ template tag, you have to call ``show_current_number`` according to your choice, e.g.: .. code-block:: html+django {% show_current_number starting from page 3 %} This can be also achieved using a template variable you passed to the context, e.g.: .. code-block:: html+django {% show_current_number starting from page page_number %} You can of course mix it all (the order of arguments is important): .. code-block:: html+django {% show_current_number starting from page 3 using mykey %} If you want to insert the current page number in the context, without actually displaying it in the template, use the *as* argument, i.e.: .. code-block:: html+django {% show_current_number as page_number %} {% show_current_number starting from page 3 using mykey as page_number %} """ # Validate args. try: tag_name, args = token.contents.split(None, 1) except ValueError: key = None number = None tag_name = token.contents[0] var_name = None else: # Use a regexp to catch args. match = SHOW_CURRENT_NUMBER_EXPRESSION.match(args) if match is None: msg = 'Invalid arguments for %r tag' % tag_name raise template.TemplateSyntaxError(msg) # Retrieve objects. groupdict = match.groupdict() key = groupdict['key'] number = groupdict['number'] var_name = groupdict['var_name'] # Call the node. return ShowCurrentNumberNode(number, key, var_name)
[ "def", "show_current_number", "(", "parser", ",", "token", ")", ":", "# Validate args.", "try", ":", "tag_name", ",", "args", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "key", "=", "None", "number", "=", "None", "tag_name", "=", "token", ".", "contents", "[", "0", "]", "var_name", "=", "None", "else", ":", "# Use a regexp to catch args.", "match", "=", "SHOW_CURRENT_NUMBER_EXPRESSION", ".", "match", "(", "args", ")", "if", "match", "is", "None", ":", "msg", "=", "'Invalid arguments for %r tag'", "%", "tag_name", "raise", "template", ".", "TemplateSyntaxError", "(", "msg", ")", "# Retrieve objects.", "groupdict", "=", "match", ".", "groupdict", "(", ")", "key", "=", "groupdict", "[", "'key'", "]", "number", "=", "groupdict", "[", "'number'", "]", "var_name", "=", "groupdict", "[", "'var_name'", "]", "# Call the node.", "return", "ShowCurrentNumberNode", "(", "number", ",", "key", ",", "var_name", ")" ]
Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} If you use multiple paginations in the same page, you can get the page number for a specific pagination using the querystring key, e.g.: .. code-block:: html+django {% show_current_number using mykey %} The default page when no querystring is specified is 1. If you changed it in the `paginate`_ template tag, you have to call ``show_current_number`` according to your choice, e.g.: .. code-block:: html+django {% show_current_number starting from page 3 %} This can be also achieved using a template variable you passed to the context, e.g.: .. code-block:: html+django {% show_current_number starting from page page_number %} You can of course mix it all (the order of arguments is important): .. code-block:: html+django {% show_current_number starting from page 3 using mykey %} If you want to insert the current page number in the context, without actually displaying it in the template, use the *as* argument, i.e.: .. code-block:: html+django {% show_current_number as page_number %} {% show_current_number starting from page 3 using mykey as page_number %}
[ "Show", "the", "current", "page", "number", "or", "insert", "it", "in", "the", "context", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L579-L649
10,361
shtalinberg/django-el-pagination
el_pagination/decorators.py
page_template
def page_template(template, key=PAGE_LABEL): """Return a view dynamically switching template if the request is Ajax. Decorate a view that takes a *template* and *extra_context* keyword arguments (like generic views). The template is switched to *page_template* if request is ajax and if *querystring_key* variable passed by the request equals to *key*. This allows multiple Ajax paginations in the same page. The name of the page template is given as *page_template* in the extra context. """ def decorator(view): @wraps(view) def decorated(request, *args, **kwargs): # Trust the developer: he wrote ``context.update(extra_context)`` # in his view. extra_context = kwargs.setdefault('extra_context', {}) extra_context['page_template'] = template # Switch the template when the request is Ajax. querystring_key = request.GET.get(QS_KEY, request.POST.get(QS_KEY, PAGE_LABEL)) if request.is_ajax() and querystring_key == key: kwargs[TEMPLATE_VARNAME] = template return view(request, *args, **kwargs) return decorated return decorator
python
def page_template(template, key=PAGE_LABEL): """Return a view dynamically switching template if the request is Ajax. Decorate a view that takes a *template* and *extra_context* keyword arguments (like generic views). The template is switched to *page_template* if request is ajax and if *querystring_key* variable passed by the request equals to *key*. This allows multiple Ajax paginations in the same page. The name of the page template is given as *page_template* in the extra context. """ def decorator(view): @wraps(view) def decorated(request, *args, **kwargs): # Trust the developer: he wrote ``context.update(extra_context)`` # in his view. extra_context = kwargs.setdefault('extra_context', {}) extra_context['page_template'] = template # Switch the template when the request is Ajax. querystring_key = request.GET.get(QS_KEY, request.POST.get(QS_KEY, PAGE_LABEL)) if request.is_ajax() and querystring_key == key: kwargs[TEMPLATE_VARNAME] = template return view(request, *args, **kwargs) return decorated return decorator
[ "def", "page_template", "(", "template", ",", "key", "=", "PAGE_LABEL", ")", ":", "def", "decorator", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "decorated", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Trust the developer: he wrote ``context.update(extra_context)``", "# in his view.", "extra_context", "=", "kwargs", ".", "setdefault", "(", "'extra_context'", ",", "{", "}", ")", "extra_context", "[", "'page_template'", "]", "=", "template", "# Switch the template when the request is Ajax.", "querystring_key", "=", "request", ".", "GET", ".", "get", "(", "QS_KEY", ",", "request", ".", "POST", ".", "get", "(", "QS_KEY", ",", "PAGE_LABEL", ")", ")", "if", "request", ".", "is_ajax", "(", ")", "and", "querystring_key", "==", "key", ":", "kwargs", "[", "TEMPLATE_VARNAME", "]", "=", "template", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorated", "return", "decorator" ]
Return a view dynamically switching template if the request is Ajax. Decorate a view that takes a *template* and *extra_context* keyword arguments (like generic views). The template is switched to *page_template* if request is ajax and if *querystring_key* variable passed by the request equals to *key*. This allows multiple Ajax paginations in the same page. The name of the page template is given as *page_template* in the extra context.
[ "Return", "a", "view", "dynamically", "switching", "template", "if", "the", "request", "is", "Ajax", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L13-L39
10,362
shtalinberg/django-el-pagination
el_pagination/decorators.py
_get_template
def _get_template(querystring_key, mapping): """Return the template corresponding to the given ``querystring_key``.""" default = None try: template_and_keys = mapping.items() except AttributeError: template_and_keys = mapping for template, key in template_and_keys: if key is None: key = PAGE_LABEL default = template if key == querystring_key: return template return default
python
def _get_template(querystring_key, mapping): """Return the template corresponding to the given ``querystring_key``.""" default = None try: template_and_keys = mapping.items() except AttributeError: template_and_keys = mapping for template, key in template_and_keys: if key is None: key = PAGE_LABEL default = template if key == querystring_key: return template return default
[ "def", "_get_template", "(", "querystring_key", ",", "mapping", ")", ":", "default", "=", "None", "try", ":", "template_and_keys", "=", "mapping", ".", "items", "(", ")", "except", "AttributeError", ":", "template_and_keys", "=", "mapping", "for", "template", ",", "key", "in", "template_and_keys", ":", "if", "key", "is", "None", ":", "key", "=", "PAGE_LABEL", "default", "=", "template", "if", "key", "==", "querystring_key", ":", "return", "template", "return", "default" ]
Return the template corresponding to the given ``querystring_key``.
[ "Return", "the", "template", "corresponding", "to", "the", "given", "querystring_key", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L42-L55
10,363
shtalinberg/django-el-pagination
el_pagination/views.py
MultipleObjectMixin.get_queryset
def get_queryset(self): """Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.queryset is not None: queryset = self.queryset if hasattr(queryset, '_clone'): queryset = queryset._clone() elif self.model is not None: queryset = self.model._default_manager.all() else: msg = '{0} must define ``queryset`` or ``model``' raise ImproperlyConfigured(msg.format(self.__class__.__name__)) return queryset
python
def get_queryset(self): """Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.queryset is not None: queryset = self.queryset if hasattr(queryset, '_clone'): queryset = queryset._clone() elif self.model is not None: queryset = self.model._default_manager.all() else: msg = '{0} must define ``queryset`` or ``model``' raise ImproperlyConfigured(msg.format(self.__class__.__name__)) return queryset
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "not", "None", ":", "queryset", "=", "self", ".", "queryset", "if", "hasattr", "(", "queryset", ",", "'_clone'", ")", ":", "queryset", "=", "queryset", ".", "_clone", "(", ")", "elif", "self", ".", "model", "is", "not", "None", ":", "queryset", "=", "self", ".", "model", ".", "_default_manager", ".", "all", "(", ")", "else", ":", "msg", "=", "'{0} must define ``queryset`` or ``model``'", "raise", "ImproperlyConfigured", "(", "msg", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "return", "queryset" ]
Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). See original in ``django.views.generic.list.MultipleObjectMixin``.
[ "Get", "the", "list", "of", "items", "for", "this", "view", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L22-L39
10,364
shtalinberg/django-el-pagination
el_pagination/views.py
MultipleObjectMixin.get_context_object_name
def get_context_object_name(self, object_list): """Get the name of the item to be used in the context. See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.context_object_name: return self.context_object_name elif hasattr(object_list, 'model'): object_name = object_list.model._meta.object_name.lower() return smart_str('{0}_list'.format(object_name)) else: return None
python
def get_context_object_name(self, object_list): """Get the name of the item to be used in the context. See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.context_object_name: return self.context_object_name elif hasattr(object_list, 'model'): object_name = object_list.model._meta.object_name.lower() return smart_str('{0}_list'.format(object_name)) else: return None
[ "def", "get_context_object_name", "(", "self", ",", "object_list", ")", ":", "if", "self", ".", "context_object_name", ":", "return", "self", ".", "context_object_name", "elif", "hasattr", "(", "object_list", ",", "'model'", ")", ":", "object_name", "=", "object_list", ".", "model", ".", "_meta", ".", "object_name", ".", "lower", "(", ")", "return", "smart_str", "(", "'{0}_list'", ".", "format", "(", "object_name", ")", ")", "else", ":", "return", "None" ]
Get the name of the item to be used in the context. See original in ``django.views.generic.list.MultipleObjectMixin``.
[ "Get", "the", "name", "of", "the", "item", "to", "be", "used", "in", "the", "context", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L50-L61
10,365
shtalinberg/django-el-pagination
el_pagination/views.py
AjaxMultipleObjectTemplateResponseMixin.get_page_template
def get_page_template(self, **kwargs): """Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*. """ opts = self.object_list.model._meta return '{0}/{1}{2}{3}.html'.format( opts.app_label, opts.object_name.lower(), self.template_name_suffix, self.page_template_suffix, )
python
def get_page_template(self, **kwargs): """Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*. """ opts = self.object_list.model._meta return '{0}/{1}{2}{3}.html'.format( opts.app_label, opts.object_name.lower(), self.template_name_suffix, self.page_template_suffix, )
[ "def", "get_page_template", "(", "self", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "self", ".", "object_list", ".", "model", ".", "_meta", "return", "'{0}/{1}{2}{3}.html'", ".", "format", "(", "opts", ".", "app_label", ",", "opts", ".", "object_name", ".", "lower", "(", ")", ",", "self", ".", "template_name_suffix", ",", "self", ".", "page_template_suffix", ",", ")" ]
Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*.
[ "Return", "the", "template", "name", "used", "for", "this", "request", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L135-L147
10,366
shtalinberg/django-el-pagination
el_pagination/models.py
ELPage.render_link
def render_link(self): """Render the page as a link.""" extra_context = { 'add_nofollow': settings.ADD_NOFOLLOW, 'page': self, 'querystring_key': self.querystring_key, } if self.is_current: template_name = 'el_pagination/current_link.html' else: template_name = 'el_pagination/page_link.html' if settings.USE_NEXT_PREVIOUS_LINKS: if self.is_previous: template_name = 'el_pagination/previous_link.html' if self.is_next: template_name = 'el_pagination/next_link.html' if template_name not in _template_cache: _template_cache[template_name] = loader.get_template(template_name) template = _template_cache[template_name] with self.context.push(**extra_context): return template.render(self.context.flatten())
python
def render_link(self): """Render the page as a link.""" extra_context = { 'add_nofollow': settings.ADD_NOFOLLOW, 'page': self, 'querystring_key': self.querystring_key, } if self.is_current: template_name = 'el_pagination/current_link.html' else: template_name = 'el_pagination/page_link.html' if settings.USE_NEXT_PREVIOUS_LINKS: if self.is_previous: template_name = 'el_pagination/previous_link.html' if self.is_next: template_name = 'el_pagination/next_link.html' if template_name not in _template_cache: _template_cache[template_name] = loader.get_template(template_name) template = _template_cache[template_name] with self.context.push(**extra_context): return template.render(self.context.flatten())
[ "def", "render_link", "(", "self", ")", ":", "extra_context", "=", "{", "'add_nofollow'", ":", "settings", ".", "ADD_NOFOLLOW", ",", "'page'", ":", "self", ",", "'querystring_key'", ":", "self", ".", "querystring_key", ",", "}", "if", "self", ".", "is_current", ":", "template_name", "=", "'el_pagination/current_link.html'", "else", ":", "template_name", "=", "'el_pagination/page_link.html'", "if", "settings", ".", "USE_NEXT_PREVIOUS_LINKS", ":", "if", "self", ".", "is_previous", ":", "template_name", "=", "'el_pagination/previous_link.html'", "if", "self", ".", "is_next", ":", "template_name", "=", "'el_pagination/next_link.html'", "if", "template_name", "not", "in", "_template_cache", ":", "_template_cache", "[", "template_name", "]", "=", "loader", ".", "get_template", "(", "template_name", ")", "template", "=", "_template_cache", "[", "template_name", "]", "with", "self", ".", "context", ".", "push", "(", "*", "*", "extra_context", ")", ":", "return", "template", ".", "render", "(", "self", ".", "context", ".", "flatten", "(", ")", ")" ]
Render the page as a link.
[ "Render", "the", "page", "as", "a", "link", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L63-L83
10,367
shtalinberg/django-el-pagination
el_pagination/models.py
PageList.previous
def previous(self): """Return the previous page. The page label is defined in ``settings.PREVIOUS_LABEL``. Return an empty string if current page is the first. """ if self._page.has_previous(): return self._endless_page( self._page.previous_page_number(), label=settings.PREVIOUS_LABEL) return ''
python
def previous(self): """Return the previous page. The page label is defined in ``settings.PREVIOUS_LABEL``. Return an empty string if current page is the first. """ if self._page.has_previous(): return self._endless_page( self._page.previous_page_number(), label=settings.PREVIOUS_LABEL) return ''
[ "def", "previous", "(", "self", ")", ":", "if", "self", ".", "_page", ".", "has_previous", "(", ")", ":", "return", "self", ".", "_endless_page", "(", "self", ".", "_page", ".", "previous_page_number", "(", ")", ",", "label", "=", "settings", ".", "PREVIOUS_LABEL", ")", "return", "''" ]
Return the previous page. The page label is defined in ``settings.PREVIOUS_LABEL``. Return an empty string if current page is the first.
[ "Return", "the", "previous", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L243-L253
10,368
shtalinberg/django-el-pagination
el_pagination/models.py
PageList.next
def next(self): """Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last. """ if self._page.has_next(): return self._endless_page( self._page.next_page_number(), label=settings.NEXT_LABEL) return ''
python
def next(self): """Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last. """ if self._page.has_next(): return self._endless_page( self._page.next_page_number(), label=settings.NEXT_LABEL) return ''
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_page", ".", "has_next", "(", ")", ":", "return", "self", ".", "_endless_page", "(", "self", ".", "_page", ".", "next_page_number", "(", ")", ",", "label", "=", "settings", ".", "NEXT_LABEL", ")", "return", "''" ]
Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last.
[ "Return", "the", "next", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L255-L265
10,369
shtalinberg/django-el-pagination
el_pagination/paginators.py
CustomPage.start_index
def start_index(self): """Return the 1-based index of the first item on this page.""" paginator = self.paginator # Special case, return zero if no items. if paginator.count == 0: return 0 elif self.number == 1: return 1 return ( (self.number - 2) * paginator.per_page + paginator.first_page + 1)
python
def start_index(self): """Return the 1-based index of the first item on this page.""" paginator = self.paginator # Special case, return zero if no items. if paginator.count == 0: return 0 elif self.number == 1: return 1 return ( (self.number - 2) * paginator.per_page + paginator.first_page + 1)
[ "def", "start_index", "(", "self", ")", ":", "paginator", "=", "self", ".", "paginator", "# Special case, return zero if no items.", "if", "paginator", ".", "count", "==", "0", ":", "return", "0", "elif", "self", ".", "number", "==", "1", ":", "return", "1", "return", "(", "(", "self", ".", "number", "-", "2", ")", "*", "paginator", ".", "per_page", "+", "paginator", ".", "first_page", "+", "1", ")" ]
Return the 1-based index of the first item on this page.
[ "Return", "the", "1", "-", "based", "index", "of", "the", "first", "item", "on", "this", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/paginators.py#L17-L26
10,370
shtalinberg/django-el-pagination
el_pagination/paginators.py
CustomPage.end_index
def end_index(self): """Return the 1-based index of the last item on this page.""" paginator = self.paginator # Special case for the last page because there can be orphans. if self.number == paginator.num_pages: return paginator.count return (self.number - 1) * paginator.per_page + paginator.first_page
python
def end_index(self): """Return the 1-based index of the last item on this page.""" paginator = self.paginator # Special case for the last page because there can be orphans. if self.number == paginator.num_pages: return paginator.count return (self.number - 1) * paginator.per_page + paginator.first_page
[ "def", "end_index", "(", "self", ")", ":", "paginator", "=", "self", ".", "paginator", "# Special case for the last page because there can be orphans.", "if", "self", ".", "number", "==", "paginator", ".", "num_pages", ":", "return", "paginator", ".", "count", "return", "(", "self", ".", "number", "-", "1", ")", "*", "paginator", ".", "per_page", "+", "paginator", ".", "first_page" ]
Return the 1-based index of the last item on this page.
[ "Return", "the", "1", "-", "based", "index", "of", "the", "last", "item", "on", "this", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/paginators.py#L28-L34
10,371
shtalinberg/django-el-pagination
el_pagination/utils.py
get_page_numbers
def get_page_numbers( current_page, num_pages, extremes=DEFAULT_CALLABLE_EXTREMES, arounds=DEFAULT_CALLABLE_AROUNDS, arrows=DEFAULT_CALLABLE_ARROWS): """Default callable for page listing. Produce a Digg-style pagination. """ page_range = range(1, num_pages + 1) pages = [] if current_page != 1: if arrows: pages.append('first') pages.append('previous') # Get first and last pages (extremes). first = page_range[:extremes] pages.extend(first) last = page_range[-extremes:] # Get the current pages (arounds). current_start = current_page - 1 - arounds if current_start < 0: current_start = 0 current_end = current_page + arounds if current_end > num_pages: current_end = num_pages current = page_range[current_start:current_end] # Mix first with current pages. to_add = current if extremes: diff = current[0] - first[-1] if diff > 1: pages.append(None) elif diff < 1: to_add = current[abs(diff) + 1:] pages.extend(to_add) # Mix current with last pages. if extremes: diff = last[0] - current[-1] to_add = last if diff > 1: pages.append(None) elif diff < 1: to_add = last[abs(diff) + 1:] pages.extend(to_add) if current_page != num_pages: pages.append('next') if arrows: pages.append('last') return pages
python
def get_page_numbers( current_page, num_pages, extremes=DEFAULT_CALLABLE_EXTREMES, arounds=DEFAULT_CALLABLE_AROUNDS, arrows=DEFAULT_CALLABLE_ARROWS): """Default callable for page listing. Produce a Digg-style pagination. """ page_range = range(1, num_pages + 1) pages = [] if current_page != 1: if arrows: pages.append('first') pages.append('previous') # Get first and last pages (extremes). first = page_range[:extremes] pages.extend(first) last = page_range[-extremes:] # Get the current pages (arounds). current_start = current_page - 1 - arounds if current_start < 0: current_start = 0 current_end = current_page + arounds if current_end > num_pages: current_end = num_pages current = page_range[current_start:current_end] # Mix first with current pages. to_add = current if extremes: diff = current[0] - first[-1] if diff > 1: pages.append(None) elif diff < 1: to_add = current[abs(diff) + 1:] pages.extend(to_add) # Mix current with last pages. if extremes: diff = last[0] - current[-1] to_add = last if diff > 1: pages.append(None) elif diff < 1: to_add = last[abs(diff) + 1:] pages.extend(to_add) if current_page != num_pages: pages.append('next') if arrows: pages.append('last') return pages
[ "def", "get_page_numbers", "(", "current_page", ",", "num_pages", ",", "extremes", "=", "DEFAULT_CALLABLE_EXTREMES", ",", "arounds", "=", "DEFAULT_CALLABLE_AROUNDS", ",", "arrows", "=", "DEFAULT_CALLABLE_ARROWS", ")", ":", "page_range", "=", "range", "(", "1", ",", "num_pages", "+", "1", ")", "pages", "=", "[", "]", "if", "current_page", "!=", "1", ":", "if", "arrows", ":", "pages", ".", "append", "(", "'first'", ")", "pages", ".", "append", "(", "'previous'", ")", "# Get first and last pages (extremes).", "first", "=", "page_range", "[", ":", "extremes", "]", "pages", ".", "extend", "(", "first", ")", "last", "=", "page_range", "[", "-", "extremes", ":", "]", "# Get the current pages (arounds).", "current_start", "=", "current_page", "-", "1", "-", "arounds", "if", "current_start", "<", "0", ":", "current_start", "=", "0", "current_end", "=", "current_page", "+", "arounds", "if", "current_end", ">", "num_pages", ":", "current_end", "=", "num_pages", "current", "=", "page_range", "[", "current_start", ":", "current_end", "]", "# Mix first with current pages.", "to_add", "=", "current", "if", "extremes", ":", "diff", "=", "current", "[", "0", "]", "-", "first", "[", "-", "1", "]", "if", "diff", ">", "1", ":", "pages", ".", "append", "(", "None", ")", "elif", "diff", "<", "1", ":", "to_add", "=", "current", "[", "abs", "(", "diff", ")", "+", "1", ":", "]", "pages", ".", "extend", "(", "to_add", ")", "# Mix current with last pages.", "if", "extremes", ":", "diff", "=", "last", "[", "0", "]", "-", "current", "[", "-", "1", "]", "to_add", "=", "last", "if", "diff", ">", "1", ":", "pages", ".", "append", "(", "None", ")", "elif", "diff", "<", "1", ":", "to_add", "=", "last", "[", "abs", "(", "diff", ")", "+", "1", ":", "]", "pages", ".", "extend", "(", "to_add", ")", "if", "current_page", "!=", "num_pages", ":", "pages", ".", "append", "(", "'next'", ")", "if", "arrows", ":", "pages", ".", "append", "(", "'last'", ")", "return", "pages" ]
Default callable for page listing. Produce a Digg-style pagination.
[ "Default", "callable", "for", "page", "listing", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L50-L104
10,372
shtalinberg/django-el-pagination
el_pagination/utils.py
_make_elastic_range
def _make_elastic_range(begin, end): """Generate an S-curved range of pages. Start from both left and right, adding exponentially growing indexes, until the two trends collide. """ # Limit growth for huge numbers of pages. starting_factor = max(1, (end - begin) // 100) factor = _iter_factors(starting_factor) left_half, right_half = [], [] left_val, right_val = begin, end right_val = end while left_val < right_val: left_half.append(left_val) right_half.append(right_val) next_factor = next(factor) left_val = begin + next_factor right_val = end - next_factor # If the trends happen to meet exactly at one point, retain it. if left_val == right_val: left_half.append(left_val) right_half.reverse() return left_half + right_half
python
def _make_elastic_range(begin, end): """Generate an S-curved range of pages. Start from both left and right, adding exponentially growing indexes, until the two trends collide. """ # Limit growth for huge numbers of pages. starting_factor = max(1, (end - begin) // 100) factor = _iter_factors(starting_factor) left_half, right_half = [], [] left_val, right_val = begin, end right_val = end while left_val < right_val: left_half.append(left_val) right_half.append(right_val) next_factor = next(factor) left_val = begin + next_factor right_val = end - next_factor # If the trends happen to meet exactly at one point, retain it. if left_val == right_val: left_half.append(left_val) right_half.reverse() return left_half + right_half
[ "def", "_make_elastic_range", "(", "begin", ",", "end", ")", ":", "# Limit growth for huge numbers of pages.", "starting_factor", "=", "max", "(", "1", ",", "(", "end", "-", "begin", ")", "//", "100", ")", "factor", "=", "_iter_factors", "(", "starting_factor", ")", "left_half", ",", "right_half", "=", "[", "]", ",", "[", "]", "left_val", ",", "right_val", "=", "begin", ",", "end", "right_val", "=", "end", "while", "left_val", "<", "right_val", ":", "left_half", ".", "append", "(", "left_val", ")", "right_half", ".", "append", "(", "right_val", ")", "next_factor", "=", "next", "(", "factor", ")", "left_val", "=", "begin", "+", "next_factor", "right_val", "=", "end", "-", "next_factor", "# If the trends happen to meet exactly at one point, retain it.", "if", "left_val", "==", "right_val", ":", "left_half", ".", "append", "(", "left_val", ")", "right_half", ".", "reverse", "(", ")", "return", "left_half", "+", "right_half" ]
Generate an S-curved range of pages. Start from both left and right, adding exponentially growing indexes, until the two trends collide.
[ "Generate", "an", "S", "-", "curved", "range", "of", "pages", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L118-L140
10,373
shtalinberg/django-el-pagination
el_pagination/utils.py
get_elastic_page_numbers
def get_elastic_page_numbers(current_page, num_pages): """Alternative callable for page listing. Produce an adaptive pagination, useful for big numbers of pages, by splitting the num_pages ranges in two parts at current_page. Each part will have its own S-curve. """ if num_pages <= 10: return list(range(1, num_pages + 1)) if current_page == 1: pages = [1] else: pages = ['first', 'previous'] pages.extend(_make_elastic_range(1, current_page)) if current_page != num_pages: pages.extend(_make_elastic_range(current_page, num_pages)[1:]) pages.extend(['next', 'last']) return pages
python
def get_elastic_page_numbers(current_page, num_pages): """Alternative callable for page listing. Produce an adaptive pagination, useful for big numbers of pages, by splitting the num_pages ranges in two parts at current_page. Each part will have its own S-curve. """ if num_pages <= 10: return list(range(1, num_pages + 1)) if current_page == 1: pages = [1] else: pages = ['first', 'previous'] pages.extend(_make_elastic_range(1, current_page)) if current_page != num_pages: pages.extend(_make_elastic_range(current_page, num_pages)[1:]) pages.extend(['next', 'last']) return pages
[ "def", "get_elastic_page_numbers", "(", "current_page", ",", "num_pages", ")", ":", "if", "num_pages", "<=", "10", ":", "return", "list", "(", "range", "(", "1", ",", "num_pages", "+", "1", ")", ")", "if", "current_page", "==", "1", ":", "pages", "=", "[", "1", "]", "else", ":", "pages", "=", "[", "'first'", ",", "'previous'", "]", "pages", ".", "extend", "(", "_make_elastic_range", "(", "1", ",", "current_page", ")", ")", "if", "current_page", "!=", "num_pages", ":", "pages", ".", "extend", "(", "_make_elastic_range", "(", "current_page", ",", "num_pages", ")", "[", "1", ":", "]", ")", "pages", ".", "extend", "(", "[", "'next'", ",", "'last'", "]", ")", "return", "pages" ]
Alternative callable for page listing. Produce an adaptive pagination, useful for big numbers of pages, by splitting the num_pages ranges in two parts at current_page. Each part will have its own S-curve.
[ "Alternative", "callable", "for", "page", "listing", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L143-L160
10,374
justinmayer/django-autoslug
autoslug/utils.py
get_prepopulated_value
def get_prepopulated_value(field, instance): """ Returns preliminary value based on `populate_from`. """ if hasattr(field.populate_from, '__call__'): # AutoSlugField(populate_from=lambda instance: ...) return field.populate_from(instance) else: # AutoSlugField(populate_from='foo') attr = getattr(instance, field.populate_from) return callable(attr) and attr() or attr
python
def get_prepopulated_value(field, instance): """ Returns preliminary value based on `populate_from`. """ if hasattr(field.populate_from, '__call__'): # AutoSlugField(populate_from=lambda instance: ...) return field.populate_from(instance) else: # AutoSlugField(populate_from='foo') attr = getattr(instance, field.populate_from) return callable(attr) and attr() or attr
[ "def", "get_prepopulated_value", "(", "field", ",", "instance", ")", ":", "if", "hasattr", "(", "field", ".", "populate_from", ",", "'__call__'", ")", ":", "# AutoSlugField(populate_from=lambda instance: ...)", "return", "field", ".", "populate_from", "(", "instance", ")", "else", ":", "# AutoSlugField(populate_from='foo')", "attr", "=", "getattr", "(", "instance", ",", "field", ".", "populate_from", ")", "return", "callable", "(", "attr", ")", "and", "attr", "(", ")", "or", "attr" ]
Returns preliminary value based on `populate_from`.
[ "Returns", "preliminary", "value", "based", "on", "populate_from", "." ]
b3991daddf5a476a829b48c28afad4ae08a18179
https://github.com/justinmayer/django-autoslug/blob/b3991daddf5a476a829b48c28afad4ae08a18179/autoslug/utils.py#L35-L45
10,375
justinmayer/django-autoslug
autoslug/utils.py
get_uniqueness_lookups
def get_uniqueness_lookups(field, instance, unique_with): """ Returns a dict'able tuple of lookups to ensure uniqueness of a slug. """ for original_lookup_name in unique_with: if '__' in original_lookup_name: field_name, inner_lookup = original_lookup_name.split('__', 1) else: field_name, inner_lookup = original_lookup_name, None try: other_field = instance._meta.get_field(field_name) except FieldDoesNotExist: raise ValueError('Could not find attribute %s.%s referenced' ' by %s.%s (see constraint `unique_with`)' % (instance._meta.object_name, field_name, instance._meta.object_name, field.name)) if field == other_field: raise ValueError('Attribute %s.%s references itself in `unique_with`.' ' Please use "unique=True" for this case.' % (instance._meta.object_name, field_name)) value = getattr(instance, field_name) if not value: if other_field.blank: field_object = instance._meta.get_field(field_name) if isinstance(field_object, ForeignKey): lookup = '%s__isnull' % field_name yield lookup, True break raise ValueError('Could not check uniqueness of %s.%s with' ' respect to %s.%s because the latter is empty.' ' Please ensure that "%s" is declared *after*' ' all fields listed in unique_with.' % (instance._meta.object_name, field.name, instance._meta.object_name, field_name, field.name)) if isinstance(other_field, DateField): # DateTimeField is a DateField subclass inner_lookup = inner_lookup or 'day' if '__' in inner_lookup: raise ValueError('The `unique_with` constraint in %s.%s' ' is set to "%s", but AutoSlugField only' ' accepts one level of nesting for dates' ' (e.g. "date__month").' % (instance._meta.object_name, field.name, original_lookup_name)) parts = ['year', 'month', 'day'] try: granularity = parts.index(inner_lookup) + 1 except ValueError: raise ValueError('expected one of %s, got "%s" in "%s"' % (parts, inner_lookup, original_lookup_name)) else: for part in parts[:granularity]: lookup = '%s__%s' % (field_name, part) yield lookup, getattr(value, part) else: # TODO: this part should be documented as it involves recursion if inner_lookup: if not hasattr(value, '_meta'): raise ValueError('Could not resolve lookup "%s" in `unique_with` of %s.%s' % (original_lookup_name, instance._meta.object_name, field.name)) for inner_name, inner_value in get_uniqueness_lookups(field, value, [inner_lookup]): yield original_lookup_name, inner_value else: yield field_name, value
python
def get_uniqueness_lookups(field, instance, unique_with): """ Returns a dict'able tuple of lookups to ensure uniqueness of a slug. """ for original_lookup_name in unique_with: if '__' in original_lookup_name: field_name, inner_lookup = original_lookup_name.split('__', 1) else: field_name, inner_lookup = original_lookup_name, None try: other_field = instance._meta.get_field(field_name) except FieldDoesNotExist: raise ValueError('Could not find attribute %s.%s referenced' ' by %s.%s (see constraint `unique_with`)' % (instance._meta.object_name, field_name, instance._meta.object_name, field.name)) if field == other_field: raise ValueError('Attribute %s.%s references itself in `unique_with`.' ' Please use "unique=True" for this case.' % (instance._meta.object_name, field_name)) value = getattr(instance, field_name) if not value: if other_field.blank: field_object = instance._meta.get_field(field_name) if isinstance(field_object, ForeignKey): lookup = '%s__isnull' % field_name yield lookup, True break raise ValueError('Could not check uniqueness of %s.%s with' ' respect to %s.%s because the latter is empty.' ' Please ensure that "%s" is declared *after*' ' all fields listed in unique_with.' % (instance._meta.object_name, field.name, instance._meta.object_name, field_name, field.name)) if isinstance(other_field, DateField): # DateTimeField is a DateField subclass inner_lookup = inner_lookup or 'day' if '__' in inner_lookup: raise ValueError('The `unique_with` constraint in %s.%s' ' is set to "%s", but AutoSlugField only' ' accepts one level of nesting for dates' ' (e.g. "date__month").' % (instance._meta.object_name, field.name, original_lookup_name)) parts = ['year', 'month', 'day'] try: granularity = parts.index(inner_lookup) + 1 except ValueError: raise ValueError('expected one of %s, got "%s" in "%s"' % (parts, inner_lookup, original_lookup_name)) else: for part in parts[:granularity]: lookup = '%s__%s' % (field_name, part) yield lookup, getattr(value, part) else: # TODO: this part should be documented as it involves recursion if inner_lookup: if not hasattr(value, '_meta'): raise ValueError('Could not resolve lookup "%s" in `unique_with` of %s.%s' % (original_lookup_name, instance._meta.object_name, field.name)) for inner_name, inner_value in get_uniqueness_lookups(field, value, [inner_lookup]): yield original_lookup_name, inner_value else: yield field_name, value
[ "def", "get_uniqueness_lookups", "(", "field", ",", "instance", ",", "unique_with", ")", ":", "for", "original_lookup_name", "in", "unique_with", ":", "if", "'__'", "in", "original_lookup_name", ":", "field_name", ",", "inner_lookup", "=", "original_lookup_name", ".", "split", "(", "'__'", ",", "1", ")", "else", ":", "field_name", ",", "inner_lookup", "=", "original_lookup_name", ",", "None", "try", ":", "other_field", "=", "instance", ".", "_meta", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", ":", "raise", "ValueError", "(", "'Could not find attribute %s.%s referenced'", "' by %s.%s (see constraint `unique_with`)'", "%", "(", "instance", ".", "_meta", ".", "object_name", ",", "field_name", ",", "instance", ".", "_meta", ".", "object_name", ",", "field", ".", "name", ")", ")", "if", "field", "==", "other_field", ":", "raise", "ValueError", "(", "'Attribute %s.%s references itself in `unique_with`.'", "' Please use \"unique=True\" for this case.'", "%", "(", "instance", ".", "_meta", ".", "object_name", ",", "field_name", ")", ")", "value", "=", "getattr", "(", "instance", ",", "field_name", ")", "if", "not", "value", ":", "if", "other_field", ".", "blank", ":", "field_object", "=", "instance", ".", "_meta", ".", "get_field", "(", "field_name", ")", "if", "isinstance", "(", "field_object", ",", "ForeignKey", ")", ":", "lookup", "=", "'%s__isnull'", "%", "field_name", "yield", "lookup", ",", "True", "break", "raise", "ValueError", "(", "'Could not check uniqueness of %s.%s with'", "' respect to %s.%s because the latter is empty.'", "' Please ensure that \"%s\" is declared *after*'", "' all fields listed in unique_with.'", "%", "(", "instance", ".", "_meta", ".", "object_name", ",", "field", ".", "name", ",", "instance", ".", "_meta", ".", "object_name", ",", "field_name", ",", "field", ".", "name", ")", ")", "if", "isinstance", "(", "other_field", ",", "DateField", ")", ":", "# DateTimeField is a DateField subclass", "inner_lookup", "=", "inner_lookup", "or", "'day'", "if", "'__'", "in", "inner_lookup", ":", "raise", "ValueError", "(", "'The `unique_with` constraint in %s.%s'", "' is set to \"%s\", but AutoSlugField only'", "' accepts one level of nesting for dates'", "' (e.g. \"date__month\").'", "%", "(", "instance", ".", "_meta", ".", "object_name", ",", "field", ".", "name", ",", "original_lookup_name", ")", ")", "parts", "=", "[", "'year'", ",", "'month'", ",", "'day'", "]", "try", ":", "granularity", "=", "parts", ".", "index", "(", "inner_lookup", ")", "+", "1", "except", "ValueError", ":", "raise", "ValueError", "(", "'expected one of %s, got \"%s\" in \"%s\"'", "%", "(", "parts", ",", "inner_lookup", ",", "original_lookup_name", ")", ")", "else", ":", "for", "part", "in", "parts", "[", ":", "granularity", "]", ":", "lookup", "=", "'%s__%s'", "%", "(", "field_name", ",", "part", ")", "yield", "lookup", ",", "getattr", "(", "value", ",", "part", ")", "else", ":", "# TODO: this part should be documented as it involves recursion", "if", "inner_lookup", ":", "if", "not", "hasattr", "(", "value", ",", "'_meta'", ")", ":", "raise", "ValueError", "(", "'Could not resolve lookup \"%s\" in `unique_with` of %s.%s'", "%", "(", "original_lookup_name", ",", "instance", ".", "_meta", ".", "object_name", ",", "field", ".", "name", ")", ")", "for", "inner_name", ",", "inner_value", "in", "get_uniqueness_lookups", "(", "field", ",", "value", ",", "[", "inner_lookup", "]", ")", ":", "yield", "original_lookup_name", ",", "inner_value", "else", ":", "yield", "field_name", ",", "value" ]
Returns a dict'able tuple of lookups to ensure uniqueness of a slug.
[ "Returns", "a", "dict", "able", "tuple", "of", "lookups", "to", "ensure", "uniqueness", "of", "a", "slug", "." ]
b3991daddf5a476a829b48c28afad4ae08a18179
https://github.com/justinmayer/django-autoslug/blob/b3991daddf5a476a829b48c28afad4ae08a18179/autoslug/utils.py#L94-L162
10,376
erikrose/blessings
blessings/__init__.py
derivative_colors
def derivative_colors(colors): """Return the names of valid color variants, given the base colors.""" return set([('on_' + c) for c in colors] + [('bright_' + c) for c in colors] + [('on_bright_' + c) for c in colors])
python
def derivative_colors(colors): """Return the names of valid color variants, given the base colors.""" return set([('on_' + c) for c in colors] + [('bright_' + c) for c in colors] + [('on_bright_' + c) for c in colors])
[ "def", "derivative_colors", "(", "colors", ")", ":", "return", "set", "(", "[", "(", "'on_'", "+", "c", ")", "for", "c", "in", "colors", "]", "+", "[", "(", "'bright_'", "+", "c", ")", "for", "c", "in", "colors", "]", "+", "[", "(", "'on_bright_'", "+", "c", ")", "for", "c", "in", "colors", "]", ")" ]
Return the names of valid color variants, given the base colors.
[ "Return", "the", "names", "of", "valid", "color", "variants", "given", "the", "base", "colors", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L414-L418
10,377
erikrose/blessings
blessings/__init__.py
split_into_formatters
def split_into_formatters(compound): """Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan') ['red', 'no_italic', 'shadow', 'on_bright_cyan'] """ merged_segs = [] # These occur only as prefixes, so they can always be merged: mergeable_prefixes = ['no', 'on', 'bright', 'on_bright'] for s in compound.split('_'): if merged_segs and merged_segs[-1] in mergeable_prefixes: merged_segs[-1] += '_' + s else: merged_segs.append(s) return merged_segs
python
def split_into_formatters(compound): """Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan') ['red', 'no_italic', 'shadow', 'on_bright_cyan'] """ merged_segs = [] # These occur only as prefixes, so they can always be merged: mergeable_prefixes = ['no', 'on', 'bright', 'on_bright'] for s in compound.split('_'): if merged_segs and merged_segs[-1] in mergeable_prefixes: merged_segs[-1] += '_' + s else: merged_segs.append(s) return merged_segs
[ "def", "split_into_formatters", "(", "compound", ")", ":", "merged_segs", "=", "[", "]", "# These occur only as prefixes, so they can always be merged:", "mergeable_prefixes", "=", "[", "'no'", ",", "'on'", ",", "'bright'", ",", "'on_bright'", "]", "for", "s", "in", "compound", ".", "split", "(", "'_'", ")", ":", "if", "merged_segs", "and", "merged_segs", "[", "-", "1", "]", "in", "mergeable_prefixes", ":", "merged_segs", "[", "-", "1", "]", "+=", "'_'", "+", "s", "else", ":", "merged_segs", ".", "append", "(", "s", ")", "return", "merged_segs" ]
Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan') ['red', 'no_italic', 'shadow', 'on_bright_cyan']
[ "Split", "a", "possibly", "compound", "format", "string", "into", "segments", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L548-L564
10,378
erikrose/blessings
blessings/__init__.py
Terminal.location
def location(self, x=None, y=None): """Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): print('Hello, world!') for x in xrange(10): print('I can do it %i times!' % x) Specify ``x`` to move to a certain column, ``y`` to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement. """ # Save position and move to the requested column, row, or both: self.stream.write(self.save) if x is not None and y is not None: self.stream.write(self.move(y, x)) elif x is not None: self.stream.write(self.move_x(x)) elif y is not None: self.stream.write(self.move_y(y)) try: yield finally: # Restore original cursor position: self.stream.write(self.restore)
python
def location(self, x=None, y=None): """Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): print('Hello, world!') for x in xrange(10): print('I can do it %i times!' % x) Specify ``x`` to move to a certain column, ``y`` to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement. """ # Save position and move to the requested column, row, or both: self.stream.write(self.save) if x is not None and y is not None: self.stream.write(self.move(y, x)) elif x is not None: self.stream.write(self.move_x(x)) elif y is not None: self.stream.write(self.move_y(y)) try: yield finally: # Restore original cursor position: self.stream.write(self.restore)
[ "def", "location", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "# Save position and move to the requested column, row, or both:", "self", ".", "stream", ".", "write", "(", "self", ".", "save", ")", "if", "x", "is", "not", "None", "and", "y", "is", "not", "None", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move", "(", "y", ",", "x", ")", ")", "elif", "x", "is", "not", "None", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move_x", "(", "x", ")", ")", "elif", "y", "is", "not", "None", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move_y", "(", "y", ")", ")", "try", ":", "yield", "finally", ":", "# Restore original cursor position:", "self", ".", "stream", ".", "write", "(", "self", ".", "restore", ")" ]
Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): print('Hello, world!') for x in xrange(10): print('I can do it %i times!' % x) Specify ``x`` to move to a certain column, ``y`` to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement.
[ "Return", "a", "context", "manager", "for", "temporarily", "moving", "the", "cursor", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L242-L273
10,379
erikrose/blessings
blessings/__init__.py
Terminal.fullscreen
def fullscreen(self): """Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.""" self.stream.write(self.enter_fullscreen) try: yield finally: self.stream.write(self.exit_fullscreen)
python
def fullscreen(self): """Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.""" self.stream.write(self.enter_fullscreen) try: yield finally: self.stream.write(self.exit_fullscreen)
[ "def", "fullscreen", "(", "self", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "enter_fullscreen", ")", "try", ":", "yield", "finally", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "exit_fullscreen", ")" ]
Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.
[ "Return", "a", "context", "manager", "that", "enters", "fullscreen", "mode", "while", "inside", "it", "and", "restores", "normal", "mode", "on", "leaving", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L276-L283
10,380
erikrose/blessings
blessings/__init__.py
Terminal.hidden_cursor
def hidden_cursor(self): """Return a context manager that hides the cursor while inside it and makes it visible on leaving.""" self.stream.write(self.hide_cursor) try: yield finally: self.stream.write(self.normal_cursor)
python
def hidden_cursor(self): """Return a context manager that hides the cursor while inside it and makes it visible on leaving.""" self.stream.write(self.hide_cursor) try: yield finally: self.stream.write(self.normal_cursor)
[ "def", "hidden_cursor", "(", "self", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "hide_cursor", ")", "try", ":", "yield", "finally", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "normal_cursor", ")" ]
Return a context manager that hides the cursor while inside it and makes it visible on leaving.
[ "Return", "a", "context", "manager", "that", "hides", "the", "cursor", "while", "inside", "it", "and", "makes", "it", "visible", "on", "leaving", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L286-L293
10,381
erikrose/blessings
blessings/__init__.py
Terminal._resolve_formatter
def _resolve_formatter(self, attr): """Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``. """ if attr in COLORS: return self._resolve_color(attr) elif attr in COMPOUNDABLES: # Bold, underline, or something that takes no parameters return self._formatting_string(self._resolve_capability(attr)) else: formatters = split_into_formatters(attr) if all(f in COMPOUNDABLES for f in formatters): # It's a compound formatter, like "bold_green_on_red". Future # optimization: combine all formatting into a single escape # sequence. return self._formatting_string( u''.join(self._resolve_formatter(s) for s in formatters)) else: return ParametrizingString(self._resolve_capability(attr))
python
def _resolve_formatter(self, attr): """Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``. """ if attr in COLORS: return self._resolve_color(attr) elif attr in COMPOUNDABLES: # Bold, underline, or something that takes no parameters return self._formatting_string(self._resolve_capability(attr)) else: formatters = split_into_formatters(attr) if all(f in COMPOUNDABLES for f in formatters): # It's a compound formatter, like "bold_green_on_red". Future # optimization: combine all formatting into a single escape # sequence. return self._formatting_string( u''.join(self._resolve_formatter(s) for s in formatters)) else: return ParametrizingString(self._resolve_capability(attr))
[ "def", "_resolve_formatter", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "COLORS", ":", "return", "self", ".", "_resolve_color", "(", "attr", ")", "elif", "attr", "in", "COMPOUNDABLES", ":", "# Bold, underline, or something that takes no parameters", "return", "self", ".", "_formatting_string", "(", "self", ".", "_resolve_capability", "(", "attr", ")", ")", "else", ":", "formatters", "=", "split_into_formatters", "(", "attr", ")", "if", "all", "(", "f", "in", "COMPOUNDABLES", "for", "f", "in", "formatters", ")", ":", "# It's a compound formatter, like \"bold_green_on_red\". Future", "# optimization: combine all formatting into a single escape", "# sequence.", "return", "self", ".", "_formatting_string", "(", "u''", ".", "join", "(", "self", ".", "_resolve_formatter", "(", "s", ")", "for", "s", "in", "formatters", ")", ")", "else", ":", "return", "ParametrizingString", "(", "self", ".", "_resolve_capability", "(", "attr", ")", ")" ]
Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``.
[ "Resolve", "a", "sugary", "or", "plain", "capability", "name", "color", "or", "compound", "formatting", "function", "name", "into", "a", "callable", "capability", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L347-L368
10,382
erikrose/blessings
blessings/__init__.py
Terminal._resolve_capability
def _resolve_capability(self, atom): """Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings. """ code = tigetstr(self._sugar.get(atom, atom)) if code: # See the comment in ParametrizingString for why this is latin1. return code.decode('latin1') return u''
python
def _resolve_capability(self, atom): """Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings. """ code = tigetstr(self._sugar.get(atom, atom)) if code: # See the comment in ParametrizingString for why this is latin1. return code.decode('latin1') return u''
[ "def", "_resolve_capability", "(", "self", ",", "atom", ")", ":", "code", "=", "tigetstr", "(", "self", ".", "_sugar", ".", "get", "(", "atom", ",", "atom", ")", ")", "if", "code", ":", "# See the comment in ParametrizingString for why this is latin1.", "return", "code", ".", "decode", "(", "'latin1'", ")", "return", "u''" ]
Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings.
[ "Return", "a", "terminal", "code", "for", "a", "capname", "or", "a", "sugary", "name", "or", "an", "empty", "Unicode", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L370-L382
10,383
erikrose/blessings
blessings/__init__.py
Terminal._resolve_color
def _resolve_color(self, color): """Resolve a color like red or on_bright_green into a callable capability.""" # TODO: Does curses automatically exchange red and blue and cyan and # yellow when a terminal supports setf/setb rather than setaf/setab? # I'll be blasted if I can find any documentation. The following # assumes it does. color_cap = (self._background_color if 'on_' in color else self._foreground_color) # curses constants go up to only 7, so add an offset to get at the # bright colors at 8-15: offset = 8 if 'bright_' in color else 0 base_color = color.rsplit('_', 1)[-1] return self._formatting_string( color_cap(getattr(curses, 'COLOR_' + base_color.upper()) + offset))
python
def _resolve_color(self, color): """Resolve a color like red or on_bright_green into a callable capability.""" # TODO: Does curses automatically exchange red and blue and cyan and # yellow when a terminal supports setf/setb rather than setaf/setab? # I'll be blasted if I can find any documentation. The following # assumes it does. color_cap = (self._background_color if 'on_' in color else self._foreground_color) # curses constants go up to only 7, so add an offset to get at the # bright colors at 8-15: offset = 8 if 'bright_' in color else 0 base_color = color.rsplit('_', 1)[-1] return self._formatting_string( color_cap(getattr(curses, 'COLOR_' + base_color.upper()) + offset))
[ "def", "_resolve_color", "(", "self", ",", "color", ")", ":", "# TODO: Does curses automatically exchange red and blue and cyan and", "# yellow when a terminal supports setf/setb rather than setaf/setab?", "# I'll be blasted if I can find any documentation. The following", "# assumes it does.", "color_cap", "=", "(", "self", ".", "_background_color", "if", "'on_'", "in", "color", "else", "self", ".", "_foreground_color", ")", "# curses constants go up to only 7, so add an offset to get at the", "# bright colors at 8-15:", "offset", "=", "8", "if", "'bright_'", "in", "color", "else", "0", "base_color", "=", "color", ".", "rsplit", "(", "'_'", ",", "1", ")", "[", "-", "1", "]", "return", "self", ".", "_formatting_string", "(", "color_cap", "(", "getattr", "(", "curses", ",", "'COLOR_'", "+", "base_color", ".", "upper", "(", ")", ")", "+", "offset", ")", ")" ]
Resolve a color like red or on_bright_green into a callable capability.
[ "Resolve", "a", "color", "like", "red", "or", "on_bright_green", "into", "a", "callable", "capability", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L384-L398
10,384
relekang/django-nopassword
nopassword/backends/sms.py
TwilioBackend.send_login_code
def send_login_code(self, code, context, **kwargs): """ Send a login code via SMS """ from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER') sms_content = render_to_string(self.template_name, context) self.twilio_client.messages.create( to=code.user.phone_number, from_=from_number, body=sms_content )
python
def send_login_code(self, code, context, **kwargs): """ Send a login code via SMS """ from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER') sms_content = render_to_string(self.template_name, context) self.twilio_client.messages.create( to=code.user.phone_number, from_=from_number, body=sms_content )
[ "def", "send_login_code", "(", "self", ",", "code", ",", "context", ",", "*", "*", "kwargs", ")", ":", "from_number", "=", "self", ".", "from_number", "or", "getattr", "(", "settings", ",", "'DEFAULT_FROM_NUMBER'", ")", "sms_content", "=", "render_to_string", "(", "self", ".", "template_name", ",", "context", ")", "self", ".", "twilio_client", ".", "messages", ".", "create", "(", "to", "=", "code", ".", "user", ".", "phone_number", ",", "from_", "=", "from_number", ",", "body", "=", "sms_content", ")" ]
Send a login code via SMS
[ "Send", "a", "login", "code", "via", "SMS" ]
d1d0f99617b1394c860864852326be673f9b935f
https://github.com/relekang/django-nopassword/blob/d1d0f99617b1394c860864852326be673f9b935f/nopassword/backends/sms.py#L20-L31
10,385
bshillingford/python-torchfile
torchfile.py
load
def load(filename, **kwargs): """ Loads the given t7 file using default settings; kwargs are forwarded to `T7Reader`. """ with open(filename, 'rb') as f: reader = T7Reader(f, **kwargs) return reader.read_obj()
python
def load(filename, **kwargs): """ Loads the given t7 file using default settings; kwargs are forwarded to `T7Reader`. """ with open(filename, 'rb') as f: reader = T7Reader(f, **kwargs) return reader.read_obj()
[ "def", "load", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "reader", "=", "T7Reader", "(", "f", ",", "*", "*", "kwargs", ")", "return", "reader", ".", "read_obj", "(", ")" ]
Loads the given t7 file using default settings; kwargs are forwarded to `T7Reader`.
[ "Loads", "the", "given", "t7", "file", "using", "default", "settings", ";", "kwargs", "are", "forwarded", "to", "T7Reader", "." ]
20b3e13b6267c254e9df67446844010629f48d61
https://github.com/bshillingford/python-torchfile/blob/20b3e13b6267c254e9df67446844010629f48d61/torchfile.py#L417-L424
10,386
slackapi/python-rtmbot
rtmbot/core.py
Job.check
def check(self): ''' Returns True if `interval` seconds have passed since it last ran ''' if self.lastrun + self.interval < time.time(): return True else: return False
python
def check(self): ''' Returns True if `interval` seconds have passed since it last ran ''' if self.lastrun + self.interval < time.time(): return True else: return False
[ "def", "check", "(", "self", ")", ":", "if", "self", ".", "lastrun", "+", "self", ".", "interval", "<", "time", ".", "time", "(", ")", ":", "return", "True", "else", ":", "return", "False" ]
Returns True if `interval` seconds have passed since it last ran
[ "Returns", "True", "if", "interval", "seconds", "have", "passed", "since", "it", "last", "ran" ]
1adc5df6791a9f6e7070ab1ff0d1c95db7dbb0ab
https://github.com/slackapi/python-rtmbot/blob/1adc5df6791a9f6e7070ab1ff0d1c95db7dbb0ab/rtmbot/core.py#L293-L298
10,387
anttttti/Wordbatch
wordbatch/feature_union.py
make_union
def make_union(*transformers, **kwargs): """Construct a FeatureUnion from the given transformers. This is a shorthand for the FeatureUnion constructor; it does not require, and does not permit, naming the transformers. Instead, they will be given names automatically based on their types. It also does not allow weighting. Parameters ---------- *transformers : list of estimators n_jobs : int, optional Number of jobs to run in parallel (default 1). Returns ------- f : FeatureUnion Examples -------- >>> from sklearn.decomposition import PCA, TruncatedSVD >>> from sklearn.pipeline import make_union >>> make_union(PCA(), TruncatedSVD()) # doctest: +NORMALIZE_WHITESPACE FeatureUnion(n_jobs=1, transformer_list=[('pca', PCA(copy=True, iterated_power='auto', n_components=None, random_state=None, svd_solver='auto', tol=0.0, whiten=False)), ('truncatedsvd', TruncatedSVD(algorithm='randomized', n_components=2, n_iter=5, random_state=None, tol=0.0))], transformer_weights=None) """ n_jobs = kwargs.pop('n_jobs', 1) concatenate = kwargs.pop('concatenate', True) if kwargs: # We do not currently support `transformer_weights` as we may want to # change its type spec in make_union raise TypeError('Unknown keyword arguments: "{}"' .format(list(kwargs.keys())[0])) return FeatureUnion(_name_estimators(transformers), n_jobs= n_jobs, concatenate= concatenate)
python
def make_union(*transformers, **kwargs): """Construct a FeatureUnion from the given transformers. This is a shorthand for the FeatureUnion constructor; it does not require, and does not permit, naming the transformers. Instead, they will be given names automatically based on their types. It also does not allow weighting. Parameters ---------- *transformers : list of estimators n_jobs : int, optional Number of jobs to run in parallel (default 1). Returns ------- f : FeatureUnion Examples -------- >>> from sklearn.decomposition import PCA, TruncatedSVD >>> from sklearn.pipeline import make_union >>> make_union(PCA(), TruncatedSVD()) # doctest: +NORMALIZE_WHITESPACE FeatureUnion(n_jobs=1, transformer_list=[('pca', PCA(copy=True, iterated_power='auto', n_components=None, random_state=None, svd_solver='auto', tol=0.0, whiten=False)), ('truncatedsvd', TruncatedSVD(algorithm='randomized', n_components=2, n_iter=5, random_state=None, tol=0.0))], transformer_weights=None) """ n_jobs = kwargs.pop('n_jobs', 1) concatenate = kwargs.pop('concatenate', True) if kwargs: # We do not currently support `transformer_weights` as we may want to # change its type spec in make_union raise TypeError('Unknown keyword arguments: "{}"' .format(list(kwargs.keys())[0])) return FeatureUnion(_name_estimators(transformers), n_jobs= n_jobs, concatenate= concatenate)
[ "def", "make_union", "(", "*", "transformers", ",", "*", "*", "kwargs", ")", ":", "n_jobs", "=", "kwargs", ".", "pop", "(", "'n_jobs'", ",", "1", ")", "concatenate", "=", "kwargs", ".", "pop", "(", "'concatenate'", ",", "True", ")", "if", "kwargs", ":", "# We do not currently support `transformer_weights` as we may want to", "# change its type spec in make_union", "raise", "TypeError", "(", "'Unknown keyword arguments: \"{}\"'", ".", "format", "(", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "[", "0", "]", ")", ")", "return", "FeatureUnion", "(", "_name_estimators", "(", "transformers", ")", ",", "n_jobs", "=", "n_jobs", ",", "concatenate", "=", "concatenate", ")" ]
Construct a FeatureUnion from the given transformers. This is a shorthand for the FeatureUnion constructor; it does not require, and does not permit, naming the transformers. Instead, they will be given names automatically based on their types. It also does not allow weighting. Parameters ---------- *transformers : list of estimators n_jobs : int, optional Number of jobs to run in parallel (default 1). Returns ------- f : FeatureUnion Examples -------- >>> from sklearn.decomposition import PCA, TruncatedSVD >>> from sklearn.pipeline import make_union >>> make_union(PCA(), TruncatedSVD()) # doctest: +NORMALIZE_WHITESPACE FeatureUnion(n_jobs=1, transformer_list=[('pca', PCA(copy=True, iterated_power='auto', n_components=None, random_state=None, svd_solver='auto', tol=0.0, whiten=False)), ('truncatedsvd', TruncatedSVD(algorithm='randomized', n_components=2, n_iter=5, random_state=None, tol=0.0))], transformer_weights=None)
[ "Construct", "a", "FeatureUnion", "from", "the", "given", "transformers", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L208-L249
10,388
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.get_feature_names
def get_feature_names(self): """Get feature names from all transformers. Returns ------- feature_names : list of strings Names of the features produced by transform. """ feature_names = [] for name, trans, weight in self._iter(): if not hasattr(trans, 'get_feature_names'): raise AttributeError("Transformer %s (type %s) does not " "provide get_feature_names." % (str(name), type(trans).__name__)) feature_names.extend([name + "__" + f for f in trans.get_feature_names()]) return feature_names
python
def get_feature_names(self): """Get feature names from all transformers. Returns ------- feature_names : list of strings Names of the features produced by transform. """ feature_names = [] for name, trans, weight in self._iter(): if not hasattr(trans, 'get_feature_names'): raise AttributeError("Transformer %s (type %s) does not " "provide get_feature_names." % (str(name), type(trans).__name__)) feature_names.extend([name + "__" + f for f in trans.get_feature_names()]) return feature_names
[ "def", "get_feature_names", "(", "self", ")", ":", "feature_names", "=", "[", "]", "for", "name", ",", "trans", ",", "weight", "in", "self", ".", "_iter", "(", ")", ":", "if", "not", "hasattr", "(", "trans", ",", "'get_feature_names'", ")", ":", "raise", "AttributeError", "(", "\"Transformer %s (type %s) does not \"", "\"provide get_feature_names.\"", "%", "(", "str", "(", "name", ")", ",", "type", "(", "trans", ")", ".", "__name__", ")", ")", "feature_names", ".", "extend", "(", "[", "name", "+", "\"__\"", "+", "f", "for", "f", "in", "trans", ".", "get_feature_names", "(", ")", "]", ")", "return", "feature_names" ]
Get feature names from all transformers. Returns ------- feature_names : list of strings Names of the features produced by transform.
[ "Get", "feature", "names", "from", "all", "transformers", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L97-L113
10,389
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.fit
def fit(self, X, y=None): """Fit all transformers using X. Parameters ---------- X : iterable or array-like, depending on transformers Input data, used to fit transformers. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- self : FeatureUnion This estimator """ self.transformer_list = list(self.transformer_list) self._validate_transformers() with Pool(self.n_jobs) as pool: transformers = pool.starmap(_fit_one_transformer, ((trans, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y) for _, trans, _ in self._iter())) self._update_transformer_list(transformers) return self
python
def fit(self, X, y=None): """Fit all transformers using X. Parameters ---------- X : iterable or array-like, depending on transformers Input data, used to fit transformers. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- self : FeatureUnion This estimator """ self.transformer_list = list(self.transformer_list) self._validate_transformers() with Pool(self.n_jobs) as pool: transformers = pool.starmap(_fit_one_transformer, ((trans, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y) for _, trans, _ in self._iter())) self._update_transformer_list(transformers) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "transformer_list", "=", "list", "(", "self", ".", "transformer_list", ")", "self", ".", "_validate_transformers", "(", ")", "with", "Pool", "(", "self", ".", "n_jobs", ")", "as", "pool", ":", "transformers", "=", "pool", ".", "starmap", "(", "_fit_one_transformer", ",", "(", "(", "trans", ",", "X", "[", "trans", "[", "'col_pick'", "]", "]", "if", "hasattr", "(", "trans", ",", "'col_pick'", ")", "else", "X", ",", "y", ")", "for", "_", ",", "trans", ",", "_", "in", "self", ".", "_iter", "(", ")", ")", ")", "self", ".", "_update_transformer_list", "(", "transformers", ")", "return", "self" ]
Fit all transformers using X. Parameters ---------- X : iterable or array-like, depending on transformers Input data, used to fit transformers. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- self : FeatureUnion This estimator
[ "Fit", "all", "transformers", "using", "X", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L115-L137
10,390
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.fit_transform
def fit_transform(self, X, y=None, **fit_params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. """ self._validate_transformers() with Pool(self.n_jobs) as pool: result = pool.starmap(_fit_transform_one, ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y) for name, trans, weight in self._iter())) if not result: # All transformers are None return np.zeros((X.shape[0], 0)) Xs, transformers = zip(*result) self._update_transformer_list(transformers) if self.concatenate: if any(sparse.issparse(f) for f in Xs): Xs = sparse.hstack(Xs).tocsr() else: Xs = np.hstack(Xs) return Xs
python
def fit_transform(self, X, y=None, **fit_params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. """ self._validate_transformers() with Pool(self.n_jobs) as pool: result = pool.starmap(_fit_transform_one, ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X, y) for name, trans, weight in self._iter())) if not result: # All transformers are None return np.zeros((X.shape[0], 0)) Xs, transformers = zip(*result) self._update_transformer_list(transformers) if self.concatenate: if any(sparse.issparse(f) for f in Xs): Xs = sparse.hstack(Xs).tocsr() else: Xs = np.hstack(Xs) return Xs
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "fit_params", ")", ":", "self", ".", "_validate_transformers", "(", ")", "with", "Pool", "(", "self", ".", "n_jobs", ")", "as", "pool", ":", "result", "=", "pool", ".", "starmap", "(", "_fit_transform_one", ",", "(", "(", "trans", ",", "weight", ",", "X", "[", "trans", "[", "'col_pick'", "]", "]", "if", "hasattr", "(", "trans", ",", "'col_pick'", ")", "else", "X", ",", "y", ")", "for", "name", ",", "trans", ",", "weight", "in", "self", ".", "_iter", "(", ")", ")", ")", "if", "not", "result", ":", "# All transformers are None", "return", "np", ".", "zeros", "(", "(", "X", ".", "shape", "[", "0", "]", ",", "0", ")", ")", "Xs", ",", "transformers", "=", "zip", "(", "*", "result", ")", "self", ".", "_update_transformer_list", "(", "transformers", ")", "if", "self", ".", "concatenate", ":", "if", "any", "(", "sparse", ".", "issparse", "(", "f", ")", "for", "f", "in", "Xs", ")", ":", "Xs", "=", "sparse", ".", "hstack", "(", "Xs", ")", ".", "tocsr", "(", ")", "else", ":", "Xs", "=", "np", ".", "hstack", "(", "Xs", ")", "return", "Xs" ]
Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers.
[ "Fit", "all", "transformers", "transform", "the", "data", "and", "concatenate", "results", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L139-L171
10,391
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.transform
def transform(self, X): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. """ with Pool(self.n_jobs) as pool: Xs = pool.starmap(_transform_one, ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X) for name, trans, weight in self._iter())) if not Xs: # All transformers are None return np.zeros((X.shape[0], 0)) if self.concatenate: if any(sparse.issparse(f) for f in Xs): Xs = sparse.hstack(Xs).tocsr() else: Xs = np.hstack(Xs) return Xs
python
def transform(self, X): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. """ with Pool(self.n_jobs) as pool: Xs = pool.starmap(_transform_one, ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X) for name, trans, weight in self._iter())) if not Xs: # All transformers are None return np.zeros((X.shape[0], 0)) if self.concatenate: if any(sparse.issparse(f) for f in Xs): Xs = sparse.hstack(Xs).tocsr() else: Xs = np.hstack(Xs) return Xs
[ "def", "transform", "(", "self", ",", "X", ")", ":", "with", "Pool", "(", "self", ".", "n_jobs", ")", "as", "pool", ":", "Xs", "=", "pool", ".", "starmap", "(", "_transform_one", ",", "(", "(", "trans", ",", "weight", ",", "X", "[", "trans", "[", "'col_pick'", "]", "]", "if", "hasattr", "(", "trans", ",", "'col_pick'", ")", "else", "X", ")", "for", "name", ",", "trans", ",", "weight", "in", "self", ".", "_iter", "(", ")", ")", ")", "if", "not", "Xs", ":", "# All transformers are None", "return", "np", ".", "zeros", "(", "(", "X", ".", "shape", "[", "0", "]", ",", "0", ")", ")", "if", "self", ".", "concatenate", ":", "if", "any", "(", "sparse", ".", "issparse", "(", "f", ")", "for", "f", "in", "Xs", ")", ":", "Xs", "=", "sparse", ".", "hstack", "(", "Xs", ")", ".", "tocsr", "(", ")", "else", ":", "Xs", "=", "np", ".", "hstack", "(", "Xs", ")", "return", "Xs" ]
Transform X separately by each transformer, concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) hstack of results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers.
[ "Transform", "X", "separately", "by", "each", "transformer", "concatenate", "results", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L173-L198
10,392
anttttti/Wordbatch
wordbatch/batcher.py
Batcher.split_batches
def split_batches(self, data, minibatch_size= None): """Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatches split from the data. Returns ------- data_split: list List of minibatches, each entry is a list-like object representing the data subset in a batch. """ if minibatch_size==None: minibatch_size= self.minibatch_size if isinstance(data, list) or isinstance(data, tuple): len_data= len(data) else: len_data= data.shape[0] if isinstance(data,pd.DataFrame): data_split = [data.iloc[x * minibatch_size:(x + 1) * minibatch_size] for x in range(int(ceil(len_data / minibatch_size)))] else: data_split= [data[x* minibatch_size:min(len_data, (x+1)*minibatch_size)] for x in range(int(ceil(len_data/minibatch_size)))] return data_split
python
def split_batches(self, data, minibatch_size= None): """Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatches split from the data. Returns ------- data_split: list List of minibatches, each entry is a list-like object representing the data subset in a batch. """ if minibatch_size==None: minibatch_size= self.minibatch_size if isinstance(data, list) or isinstance(data, tuple): len_data= len(data) else: len_data= data.shape[0] if isinstance(data,pd.DataFrame): data_split = [data.iloc[x * minibatch_size:(x + 1) * minibatch_size] for x in range(int(ceil(len_data / minibatch_size)))] else: data_split= [data[x* minibatch_size:min(len_data, (x+1)*minibatch_size)] for x in range(int(ceil(len_data/minibatch_size)))] return data_split
[ "def", "split_batches", "(", "self", ",", "data", ",", "minibatch_size", "=", "None", ")", ":", "if", "minibatch_size", "==", "None", ":", "minibatch_size", "=", "self", ".", "minibatch_size", "if", "isinstance", "(", "data", ",", "list", ")", "or", "isinstance", "(", "data", ",", "tuple", ")", ":", "len_data", "=", "len", "(", "data", ")", "else", ":", "len_data", "=", "data", ".", "shape", "[", "0", "]", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "data_split", "=", "[", "data", ".", "iloc", "[", "x", "*", "minibatch_size", ":", "(", "x", "+", "1", ")", "*", "minibatch_size", "]", "for", "x", "in", "range", "(", "int", "(", "ceil", "(", "len_data", "/", "minibatch_size", ")", ")", ")", "]", "else", ":", "data_split", "=", "[", "data", "[", "x", "*", "minibatch_size", ":", "min", "(", "len_data", ",", "(", "x", "+", "1", ")", "*", "minibatch_size", ")", "]", "for", "x", "in", "range", "(", "int", "(", "ceil", "(", "len_data", "/", "minibatch_size", ")", ")", ")", "]", "return", "data_split" ]
Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatches split from the data. Returns ------- data_split: list List of minibatches, each entry is a list-like object representing the data subset in a batch.
[ "Split", "data", "into", "minibatches", "with", "a", "specified", "size" ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L77-L102
10,393
anttttti/Wordbatch
wordbatch/batcher.py
Batcher.merge_batches
def merge_batches(self, data): """Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches """ if isinstance(data[0], ssp.csr_matrix): return ssp.vstack(data) if isinstance(data[0], pd.DataFrame) or isinstance(data[0], pd.Series): return pd.concat(data) return [item for sublist in data for item in sublist]
python
def merge_batches(self, data): """Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches """ if isinstance(data[0], ssp.csr_matrix): return ssp.vstack(data) if isinstance(data[0], pd.DataFrame) or isinstance(data[0], pd.Series): return pd.concat(data) return [item for sublist in data for item in sublist]
[ "def", "merge_batches", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", "[", "0", "]", ",", "ssp", ".", "csr_matrix", ")", ":", "return", "ssp", ".", "vstack", "(", "data", ")", "if", "isinstance", "(", "data", "[", "0", "]", ",", "pd", ".", "DataFrame", ")", "or", "isinstance", "(", "data", "[", "0", "]", ",", "pd", ".", "Series", ")", ":", "return", "pd", ".", "concat", "(", "data", ")", "return", "[", "item", "for", "sublist", "in", "data", "for", "item", "in", "sublist", "]" ]
Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches
[ "Merge", "a", "list", "of", "data", "minibatches", "into", "one", "single", "instance", "representing", "the", "data" ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L104-L119
10,394
anttttti/Wordbatch
wordbatch/batcher.py
Batcher.shuffle_batch
def shuffle_batch(self, texts, labels= None, seed= None): """Shuffle a list of samples, as well as the labels if specified Parameters ---------- texts: list-like List of samples to shuffle labels: list-like (optional) List of labels to shuffle, should be correspondent to the samples given seed: int The seed of the pseudo random number generator to use for shuffling Returns ------- texts: list List of shuffled samples (texts parameters) labels: list (optional) List of shuffled labels. This will only be returned when non-None labels is passed """ if seed!=None: random.seed(seed) index_shuf= list(range(len(texts))) random.shuffle(index_shuf) texts= [texts[x] for x in index_shuf] if labels==None: return texts labels= [labels[x] for x in index_shuf] return texts, labels
python
def shuffle_batch(self, texts, labels= None, seed= None): """Shuffle a list of samples, as well as the labels if specified Parameters ---------- texts: list-like List of samples to shuffle labels: list-like (optional) List of labels to shuffle, should be correspondent to the samples given seed: int The seed of the pseudo random number generator to use for shuffling Returns ------- texts: list List of shuffled samples (texts parameters) labels: list (optional) List of shuffled labels. This will only be returned when non-None labels is passed """ if seed!=None: random.seed(seed) index_shuf= list(range(len(texts))) random.shuffle(index_shuf) texts= [texts[x] for x in index_shuf] if labels==None: return texts labels= [labels[x] for x in index_shuf] return texts, labels
[ "def", "shuffle_batch", "(", "self", ",", "texts", ",", "labels", "=", "None", ",", "seed", "=", "None", ")", ":", "if", "seed", "!=", "None", ":", "random", ".", "seed", "(", "seed", ")", "index_shuf", "=", "list", "(", "range", "(", "len", "(", "texts", ")", ")", ")", "random", ".", "shuffle", "(", "index_shuf", ")", "texts", "=", "[", "texts", "[", "x", "]", "for", "x", "in", "index_shuf", "]", "if", "labels", "==", "None", ":", "return", "texts", "labels", "=", "[", "labels", "[", "x", "]", "for", "x", "in", "index_shuf", "]", "return", "texts", ",", "labels" ]
Shuffle a list of samples, as well as the labels if specified Parameters ---------- texts: list-like List of samples to shuffle labels: list-like (optional) List of labels to shuffle, should be correspondent to the samples given seed: int The seed of the pseudo random number generator to use for shuffling Returns ------- texts: list List of shuffled samples (texts parameters) labels: list (optional) List of shuffled labels. This will only be returned when non-None labels is passed
[ "Shuffle", "a", "list", "of", "samples", "as", "well", "as", "the", "labels", "if", "specified" ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L230-L259
10,395
t-makaro/animatplot
animatplot/util.py
demeshgrid
def demeshgrid(arr): """Turns an ndarray created by a meshgrid back into a 1D array Parameters ---------- arr : array of dimension > 1 This array should have been created by a meshgrid. """ dim = len(arr.shape) for i in range(dim): Slice1 = [0]*dim Slice2 = [1]*dim Slice1[i] = slice(None) Slice2[i] = slice(None) if (arr[tuple(Slice1)] == arr[tuple(Slice2)]).all(): return arr[tuple(Slice1)]
python
def demeshgrid(arr): """Turns an ndarray created by a meshgrid back into a 1D array Parameters ---------- arr : array of dimension > 1 This array should have been created by a meshgrid. """ dim = len(arr.shape) for i in range(dim): Slice1 = [0]*dim Slice2 = [1]*dim Slice1[i] = slice(None) Slice2[i] = slice(None) if (arr[tuple(Slice1)] == arr[tuple(Slice2)]).all(): return arr[tuple(Slice1)]
[ "def", "demeshgrid", "(", "arr", ")", ":", "dim", "=", "len", "(", "arr", ".", "shape", ")", "for", "i", "in", "range", "(", "dim", ")", ":", "Slice1", "=", "[", "0", "]", "*", "dim", "Slice2", "=", "[", "1", "]", "*", "dim", "Slice1", "[", "i", "]", "=", "slice", "(", "None", ")", "Slice2", "[", "i", "]", "=", "slice", "(", "None", ")", "if", "(", "arr", "[", "tuple", "(", "Slice1", ")", "]", "==", "arr", "[", "tuple", "(", "Slice2", ")", "]", ")", ".", "all", "(", ")", ":", "return", "arr", "[", "tuple", "(", "Slice1", ")", "]" ]
Turns an ndarray created by a meshgrid back into a 1D array Parameters ---------- arr : array of dimension > 1 This array should have been created by a meshgrid.
[ "Turns", "an", "ndarray", "created", "by", "a", "meshgrid", "back", "into", "a", "1D", "array" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/util.py#L23-L38
10,396
t-makaro/animatplot
animatplot/animation.py
Animation.timeline_slider
def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None): """Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' ax : matplotlib.axes.Axes, optional The matplotlib axes to attach the slider to. valfmt : str, optional a format specifier used to print the time Defaults to '%s' for datetime64, timedelta64 and '%1.2f' otherwise. color : The color of the slider. """ if ax is None: adjust_plot = {'bottom': .2} rect = [.18, .05, .5, .03] plt.subplots_adjust(**adjust_plot) self.slider_ax = plt.axes(rect) else: self.slider_ax = ax if valfmt is None: if (np.issubdtype(self.timeline.t.dtype, np.datetime64) or np.issubdtype(self.timeline.t.dtype, np.timedelta64)): valfmt = '%s' else: valfmt = '%1.2f' if self.timeline.log: valfmt = '$10^{%s}$' % valfmt self.slider = Slider( self.slider_ax, text, 0, self.timeline._len-1, valinit=0, valfmt=(valfmt+self.timeline.units), valstep=1, color=color ) self._has_slider = True def set_time(t): self.timeline.index = int(self.slider.val) self.slider.valtext.set_text( self.slider.valfmt % (self.timeline[self.timeline.index])) if self._pause: for block in self.blocks: block._update(self.timeline.index) self.fig.canvas.draw() self.slider.on_changed(set_time)
python
def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None): """Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' ax : matplotlib.axes.Axes, optional The matplotlib axes to attach the slider to. valfmt : str, optional a format specifier used to print the time Defaults to '%s' for datetime64, timedelta64 and '%1.2f' otherwise. color : The color of the slider. """ if ax is None: adjust_plot = {'bottom': .2} rect = [.18, .05, .5, .03] plt.subplots_adjust(**adjust_plot) self.slider_ax = plt.axes(rect) else: self.slider_ax = ax if valfmt is None: if (np.issubdtype(self.timeline.t.dtype, np.datetime64) or np.issubdtype(self.timeline.t.dtype, np.timedelta64)): valfmt = '%s' else: valfmt = '%1.2f' if self.timeline.log: valfmt = '$10^{%s}$' % valfmt self.slider = Slider( self.slider_ax, text, 0, self.timeline._len-1, valinit=0, valfmt=(valfmt+self.timeline.units), valstep=1, color=color ) self._has_slider = True def set_time(t): self.timeline.index = int(self.slider.val) self.slider.valtext.set_text( self.slider.valfmt % (self.timeline[self.timeline.index])) if self._pause: for block in self.blocks: block._update(self.timeline.index) self.fig.canvas.draw() self.slider.on_changed(set_time)
[ "def", "timeline_slider", "(", "self", ",", "text", "=", "'Time'", ",", "ax", "=", "None", ",", "valfmt", "=", "None", ",", "color", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "adjust_plot", "=", "{", "'bottom'", ":", ".2", "}", "rect", "=", "[", ".18", ",", ".05", ",", ".5", ",", ".03", "]", "plt", ".", "subplots_adjust", "(", "*", "*", "adjust_plot", ")", "self", ".", "slider_ax", "=", "plt", ".", "axes", "(", "rect", ")", "else", ":", "self", ".", "slider_ax", "=", "ax", "if", "valfmt", "is", "None", ":", "if", "(", "np", ".", "issubdtype", "(", "self", ".", "timeline", ".", "t", ".", "dtype", ",", "np", ".", "datetime64", ")", "or", "np", ".", "issubdtype", "(", "self", ".", "timeline", ".", "t", ".", "dtype", ",", "np", ".", "timedelta64", ")", ")", ":", "valfmt", "=", "'%s'", "else", ":", "valfmt", "=", "'%1.2f'", "if", "self", ".", "timeline", ".", "log", ":", "valfmt", "=", "'$10^{%s}$'", "%", "valfmt", "self", ".", "slider", "=", "Slider", "(", "self", ".", "slider_ax", ",", "text", ",", "0", ",", "self", ".", "timeline", ".", "_len", "-", "1", ",", "valinit", "=", "0", ",", "valfmt", "=", "(", "valfmt", "+", "self", ".", "timeline", ".", "units", ")", ",", "valstep", "=", "1", ",", "color", "=", "color", ")", "self", ".", "_has_slider", "=", "True", "def", "set_time", "(", "t", ")", ":", "self", ".", "timeline", ".", "index", "=", "int", "(", "self", ".", "slider", ".", "val", ")", "self", ".", "slider", ".", "valtext", ".", "set_text", "(", "self", ".", "slider", ".", "valfmt", "%", "(", "self", ".", "timeline", "[", "self", ".", "timeline", ".", "index", "]", ")", ")", "if", "self", ".", "_pause", ":", "for", "block", "in", "self", ".", "blocks", ":", "block", ".", "_update", "(", "self", ".", "timeline", ".", "index", ")", "self", ".", "fig", ".", "canvas", ".", "draw", "(", ")", "self", ".", "slider", ".", "on_changed", "(", "set_time", ")" ]
Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' ax : matplotlib.axes.Axes, optional The matplotlib axes to attach the slider to. valfmt : str, optional a format specifier used to print the time Defaults to '%s' for datetime64, timedelta64 and '%1.2f' otherwise. color : The color of the slider.
[ "Creates", "a", "timeline", "slider", "." ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L100-L150
10,397
t-makaro/animatplot
animatplot/animation.py
Animation.controls
def controls(self, timeline_slider_args={}, toggle_args={}): """Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be passed to timeline_slider() toggle_args : Dict, optional A dictionary of argyments to be passed to toggle() """ self.timeline_slider(**timeline_slider_args) self.toggle(**toggle_args)
python
def controls(self, timeline_slider_args={}, toggle_args={}): """Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be passed to timeline_slider() toggle_args : Dict, optional A dictionary of argyments to be passed to toggle() """ self.timeline_slider(**timeline_slider_args) self.toggle(**toggle_args)
[ "def", "controls", "(", "self", ",", "timeline_slider_args", "=", "{", "}", ",", "toggle_args", "=", "{", "}", ")", ":", "self", ".", "timeline_slider", "(", "*", "*", "timeline_slider_args", ")", "self", ".", "toggle", "(", "*", "*", "toggle_args", ")" ]
Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be passed to timeline_slider() toggle_args : Dict, optional A dictionary of argyments to be passed to toggle()
[ "Creates", "interactive", "controls", "for", "the", "animation" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L152-L165
10,398
t-makaro/animatplot
animatplot/animation.py
Animation.save_gif
def save_gif(self, filename): """Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(filename+'.gif', writer=PillowWriter(fps=self.timeline.fps))
python
def save_gif(self, filename): """Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(filename+'.gif', writer=PillowWriter(fps=self.timeline.fps))
[ "def", "save_gif", "(", "self", ",", "filename", ")", ":", "self", ".", "timeline", ".", "index", "-=", "1", "# required for proper starting point for save", "self", ".", "animation", ".", "save", "(", "filename", "+", "'.gif'", ",", "writer", "=", "PillowWriter", "(", "fps", "=", "self", ".", "timeline", ".", "fps", ")", ")" ]
Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension
[ "Saves", "the", "animation", "to", "a", "gif" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L167-L179
10,399
t-makaro/animatplot
animatplot/animation.py
Animation.save
def save(self, *args, **kwargs): """Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save` """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(*args, **kwargs)
python
def save(self, *args, **kwargs): """Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save` """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "timeline", ".", "index", "-=", "1", "# required for proper starting point for save", "self", ".", "animation", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save`
[ "Saves", "an", "animation" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L181-L187