repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
mapbox/mapbox-cli-py | mapboxcli/scripts/mapmatching.py | match | python | 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... | 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`. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/mapmatching.py#L15-L43 | null | import click
import cligj
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.command('mapmatching', short_help="Snap GPS traces to OpenStreetMap")
@cligj.features_in_arg
@click.option("--gps-precision", default=4, type=int,
help="Assumed precision of tracking device (default 4 meters)"... |
mapbox/mapbox-cli-py | mapboxcli/scripts/static.py | staticmap | python | 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:
... | 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`. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/static.py#L18-L47 | null | import click
import cligj
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.command(short_help="Static map images.")
@click.argument('mapid', required=True)
@click.argument('output', type=click.File('wb'), required=True)
@click.option('--features', help="GeoJSON Features to render as overlay")
@cl... |
mapbox/mapbox-cli-py | mapboxcli/scripts/cli.py | main_group | python | 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... | 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 ... | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/cli.py#L43-L94 | [
"def configure_logging(verbosity):\n log_level = max(10, 30 - 10 * verbosity)\n logging.basicConfig(stream=sys.stderr, level=log_level)\n",
"def read_config(cfg):\n parser = configparser.ConfigParser()\n parser.read(cfg)\n rv = {}\n for section in parser.sections():\n for key, value in pa... | """
Main click group for CLI
"""
import logging
import os
import sys
import click
import cligj
import mapboxcli
from mapboxcli.compat import configparser
from mapboxcli.scripts import (
config, geocoding, directions, mapmatching, uploads, static, datasets)
def configure_logging(verbosity):
log_level = max(... |
mapbox/mapbox-cli-py | mapboxcli/scripts/config.py | config | python | 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.ec... | 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. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/config.py#L8-L37 | null | import os
import click
@click.command(short_help="Show all config settings.")
@click.pass_context
|
mapbox/mapbox-cli-py | mapboxcli/scripts/geocoding.py | coords_from_query | python | def coords_from_query(query):
try:
coords = json.loads(query)
except ValueError:
vals = re.split(r'[,\s]+', query.strip())
coords = [float(v) for v in vals]
return tuple(coords[:2]) | Transform a query line into a (lng, lat) pair of coordinates. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L24-L31 | null | import logging
from itertools import chain
import json
import re
import click
import mapbox
from mapbox import Geocoder
from mapboxcli.compat import map
from mapboxcli.errors import MapboxCLIException
def iter_query(query):
"""Accept a filename, stream, or string.
Returns an iterator over lines of the query... |
mapbox/mapbox-cli-py | mapboxcli/scripts/geocoding.py | echo_headers | python | 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. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L34-L38 | null | import logging
from itertools import chain
import json
import re
import click
import mapbox
from mapbox import Geocoder
from mapboxcli.compat import map
from mapboxcli.errors import MapboxCLIException
def iter_query(query):
"""Accept a filename, stream, or string.
Returns an iterator over lines of the query... |
mapbox/mapbox-cli-py | mapboxcli/scripts/geocoding.py | geocoding | python | def geocoding(ctx, query, forward, include_headers, lat, lon,
place_type, output, dataset, country, bbox, features, limit):
access_token = (ctx.obj and ctx.obj.get('access_token')) or None
stdout = click.open_file(output, 'w')
geocoder = Geocoder(name=dataset, access_token=access_token)
... | This command returns places matching an address (forward mode) or
places matching coordinates (reverse mode).
In forward (the default) mode the query argument shall be an address
such as '1600 pennsylvania ave nw'.
$ mapbox geocoding '1600 pennsylvania ave nw'
In reverse mode the query argument... | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L78-L147 | [
"def iter_query(query):\n \"\"\"Accept a filename, stream, or string.\n Returns an iterator over lines of the query.\"\"\"\n try:\n itr = click.open_file(query).readlines()\n except IOError:\n itr = [query]\n return itr\n",
"def echo_headers(headers, file=None):\n \"\"\"Echo header... | import logging
from itertools import chain
import json
import re
import click
import mapbox
from mapbox import Geocoder
from mapboxcli.compat import map
from mapboxcli.errors import MapboxCLIException
def iter_query(query):
"""Accept a filename, stream, or string.
Returns an iterator over lines of the query... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | datasets | python | 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. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L13-L24 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
@datasets.command(short_help="List datasets")
@click.option('--output', '-o', default='-', help="Save output to a fil... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | create | python | 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`. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L56-L74 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | read_dataset | python | 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 ... | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L82-L103 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | delete_dataset | python | def delete_dataset(ctx, dataset):
service = ctx.obj.get('service')
res = service.delete_dataset(dataset)
if res.status_code != 204:
raise MapboxCLIException(res.text.strip()) | Delete a dataset.
$ mapbox datasets delete-dataset dataset-id
All endpoints require authentication. An access token with
`datasets:write` scope is required, see `mapbox --help`. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L137-L150 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | list_features | python | 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 MapboxCLIExcep... | 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`. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L165-L183 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | put_feature | python | 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:
... | 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 endp... | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L221-L246 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | delete_feature | python | 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`. | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L254-L267 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/datasets.py | create_tileset | python | 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(u... | 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
f... | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/datasets.py#L276-L301 | null | # Datasets.
import json
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.group(short_help="Read and write Mapbox datasets (has subcommands)")
@click.pass_context
def datasets(ctx):
"""Read and write GeoJSON from Mapbox-hosted datasets
All endpoints require authentication. ... |
mapbox/mapbox-cli-py | mapboxcli/scripts/directions.py | directions | python | 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 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". | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/directions.py#L163-L218 | null | import json
import re
import click
import cligj
import mapbox
from mapboxcli.errors import MapboxCLIException
def waypoint_snapping_callback(ctx, param, value):
results = []
tuple_pattern = re.compile("[,]")
int_pattern = re.compile("[0-9]")
# value is an n-tuple, each element of
# which conta... |
mapbox/mapbox-cli-py | mapboxcli/scripts/uploads.py | upload | python | 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 ... | 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 t... | train | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/uploads.py#L17-L76 | null | from io import BytesIO
import os
import sys
import click
import mapbox
from mapboxcli.errors import MapboxCLIException
@click.command(short_help="Upload datasets to Mapbox accounts")
@click.argument('tileset', required=True, type=str, metavar='TILESET')
@click.argument('datasource', type=str, default='-', metavar='... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | shared_options | python | def shared_options(rq):
"Default class options to pass to the CLI commands."
return {
'url': rq.redis_url,
'config': None,
'worker_class': rq.worker_class,
'job_class': rq.job_class,
'queue_class': rq.queue_class,
'connection_class': rq.connection_class,
} | Default class options to pass to the CLI commands. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L35-L44 | null | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | empty | python | def empty(rq, ctx, all, queues):
"Empty given queues."
return ctx.invoke(
rq_cli.empty,
all=all,
queues=queues or rq.queues,
**shared_options(rq)
) | Empty given queues. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L66-L73 | [
"def shared_options(rq):\n \"Default class options to pass to the CLI commands.\"\n return {\n 'url': rq.redis_url,\n 'config': None,\n 'worker_class': rq.worker_class,\n 'job_class': rq.job_class,\n 'queue_class': rq.queue_class,\n 'connection_class': rq.connection_c... | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | requeue | python | def requeue(rq, ctx, all, job_ids):
"Requeue failed jobs."
return ctx.invoke(
rq_cli.requeue,
all=all,
job_ids=job_ids,
**shared_options(rq)
) | Requeue failed jobs. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L79-L86 | [
"def shared_options(rq):\n \"Default class options to pass to the CLI commands.\"\n return {\n 'url': rq.redis_url,\n 'config': None,\n 'worker_class': rq.worker_class,\n 'job_class': rq.job_class,\n 'queue_class': rq.queue_class,\n 'connection_class': rq.connection_c... | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | info | python | def info(rq, ctx, path, interval, raw, only_queues, only_workers, by_queue,
queues):
"RQ command-line monitor."
return ctx.invoke(
rq_cli.info,
path=path,
interval=interval,
raw=raw,
only_queues=only_queues,
only_workers=only_workers,
by_queue=by_... | RQ command-line monitor. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L100-L113 | [
"def shared_options(rq):\n \"Default class options to pass to the CLI commands.\"\n return {\n 'url': rq.redis_url,\n 'config': None,\n 'worker_class': rq.worker_class,\n 'job_class': rq.job_class,\n 'queue_class': rq.queue_class,\n 'connection_class': rq.connection_c... | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | worker | python | def worker(rq, ctx, burst, logging_level, name, path, results_ttl,
worker_ttl, verbose, quiet, sentry_dsn, exception_handler, pid,
queues):
"Starts an RQ worker."
ctx.invoke(
rq_cli.worker,
burst=burst,
logging_level=logging_level,
name=name,
path=pa... | Starts an RQ worker. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L136-L155 | [
"def shared_options(rq):\n \"Default class options to pass to the CLI commands.\"\n return {\n 'url': rq.redis_url,\n 'config': None,\n 'worker_class': rq.worker_class,\n 'job_class': rq.job_class,\n 'queue_class': rq.queue_class,\n 'connection_class': rq.connection_c... | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | suspend | python | def suspend(rq, ctx, duration):
"Suspends all workers."
ctx.invoke(
rq_cli.suspend,
duration=duration,
**shared_options(rq)
) | Suspends all workers. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L162-L168 | [
"def shared_options(rq):\n \"Default class options to pass to the CLI commands.\"\n return {\n 'url': rq.redis_url,\n 'config': None,\n 'worker_class': rq.worker_class,\n 'job_class': rq.job_class,\n 'queue_class': rq.queue_class,\n 'connection_class': rq.connection_c... | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/cli.py | scheduler | python | def scheduler(rq, ctx, verbose, burst, queue, interval, pid):
"Periodically checks for scheduled jobs."
scheduler = rq.get_scheduler(interval=interval, queue=queue)
if pid:
with open(os.path.expanduser(pid), 'w') as fp:
fp.write(str(os.getpid()))
if verbose:
level = 'DEBUG'
... | Periodically checks for scheduled jobs. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/cli.py#L193-L204 | null | # -*- coding: utf-8 -*-
"""
flask_rq2.cli
~~~~~~~~~~~~~
Support for the Click based Flask CLI via Flask-CLI.
"""
import operator
import os
from functools import update_wrapper
import click
from rq.cli import cli as rq_cli
from rq.defaults import DEFAULT_RESULT_TTL, DEFAULT_WORKER_TTL
try:
from flas... |
rq/Flask-RQ2 | src/flask_rq2/functions.py | JobFunctions.queue | python | def queue(self, *args, **kwargs):
queue_name = kwargs.pop('queue', self.queue_name)
timeout = kwargs.pop('timeout', self.timeout)
result_ttl = kwargs.pop('result_ttl', self.result_ttl)
ttl = kwargs.pop('ttl', self.ttl)
depends_on = kwargs.pop('depends_on', self._depends_on)
... | A function to queue a RQ job, e.g.::
@rq.job(timeout=60)
def add(x, y):
return x + y
add.queue(1, 2, timeout=30)
:param \\*args: The positional arguments to pass to the queued job.
:param \\*\\*kwargs: The keyword arguments to pass to the queued jo... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/functions.py#L65-L139 | null | class JobFunctions(object):
"""
Some helper functions that are added to a function decorated
with a :meth:`~flask_rq2.app.RQ.job` decorator.
"""
#: the methods to add to jobs automatically
functions = ['queue', 'schedule', 'cron']
def __init__(self, rq, wrapped, queue_name, timeout, result_... |
rq/Flask-RQ2 | src/flask_rq2/functions.py | JobFunctions.schedule | python | def schedule(self, time_or_delta, *args, **kwargs):
queue_name = kwargs.pop('queue', self.queue_name)
timeout = kwargs.pop('timeout', self.timeout)
description = kwargs.pop('description', None)
result_ttl = kwargs.pop('result_ttl', self.result_ttl)
ttl = kwargs.pop('ttl', self.tt... | A function to schedule running a RQ job at a given time
or after a given timespan::
@rq.job
def add(x, y):
return x + y
add.schedule(timedelta(hours=2), 1, 2, timeout=10)
add.schedule(datetime(2016, 12, 31, 23, 59, 59), 1, 2)
add.sche... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/functions.py#L141-L221 | null | class JobFunctions(object):
"""
Some helper functions that are added to a function decorated
with a :meth:`~flask_rq2.app.RQ.job` decorator.
"""
#: the methods to add to jobs automatically
functions = ['queue', 'schedule', 'cron']
def __init__(self, rq, wrapped, queue_name, timeout, result_... |
rq/Flask-RQ2 | src/flask_rq2/functions.py | JobFunctions.cron | python | def cron(self, pattern, name, *args, **kwargs):
queue_name = kwargs.pop('queue', self.queue_name)
timeout = kwargs.pop('timeout', self.timeout)
description = kwargs.pop('description', None)
repeat = kwargs.pop('repeat', None)
return self.rq.get_scheduler().cron(
patte... | A function to setup a RQ job as a cronjob::
@rq.job('low', timeout=60)
def add(x, y):
return x + y
add.cron('* * * * *', 'add-some-numbers', 1, 2, timeout=10)
:param \\*args: The positional arguments to pass to the queued job.
:param \\*\\*kwargs: ... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/functions.py#L223-L279 | null | class JobFunctions(object):
"""
Some helper functions that are added to a function decorated
with a :meth:`~flask_rq2.app.RQ.job` decorator.
"""
#: the methods to add to jobs automatically
functions = ['queue', 'schedule', 'cron']
def __init__(self, rq, wrapped, queue_name, timeout, result_... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.init_app | python | def init_app(self, app):
# The connection related config values
self.redis_url = app.config.setdefault(
'RQ_REDIS_URL',
self.redis_url,
)
self.connection_class = app.config.setdefault(
'RQ_CONNECTION_CLASS',
self.connection_class,
)... | Initialize the app, e.g. can be used if factory pattern is used. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L137-L193 | [
"def init_cli(self, app):\n \"\"\"\n Initialize the Flask CLI support in case it was enabled for the\n app.\n\n Works with both Flask>=1.0's CLI support as well as the backport\n in the Flask-CLI package for Flask<1.0.\n \"\"\"\n # in case click isn't installed after all\n if click is None:\... | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.init_cli | python | def init_cli(self, app):
# in case click isn't installed after all
if click is None:
raise RuntimeError('Cannot import click. Is it installed?')
# only add commands if we have a click context available
from .cli import add_commands
add_commands(app.cli, self) | Initialize the Flask CLI support in case it was enabled for the
app.
Works with both Flask>=1.0's CLI support as well as the backport
in the Flask-CLI package for Flask<1.0. | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L195-L208 | [
"def add_commands(cli, rq):\n @click.group(cls=AppGroup, help='Runs RQ commands with app context.')\n @click.pass_context\n def rq_group(ctx):\n ctx.ensure_object(ScriptInfo).data['rq'] = rq\n\n sorted_commands = sorted(_commands.items(), key=operator.itemgetter(0))\n for name, func in sorted_... | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.exception_handler | python | def exception_handler(self, callback):
path = '.'.join([callback.__module__, callback.__name__])
self._exception_handlers.append(path)
return callback | Decorator to add an exception handler to the worker, e.g.::
rq = RQ()
@rq.exception_handler
def my_custom_handler(job, *exc_info):
# do custom things here
... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L210-L224 | null | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.job | python | def job(self, func_or_queue=None, timeout=None, result_ttl=None, ttl=None,
depends_on=None, at_front=None, meta=None, description=None):
if callable(func_or_queue):
func = func_or_queue
queue_name = None
else:
func = None
queue_name = func_or_q... | Decorator to mark functions for queuing via RQ, e.g.::
rq = RQ()
@rq.job
def add(x, y):
return x + y
or::
@rq.job(timeout=60, result_ttl=60 * 60)
def add(x, y):
return x + y
Adds various functions to the job... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L226-L308 | [
"def wrapper(wrapped):\n self._jobs.append(wrapped)\n helper = self._functions_cls(\n rq=self,\n wrapped=wrapped,\n queue_name=queue_name,\n timeout=timeout,\n result_ttl=result_ttl,\n ttl=ttl,\n depends_on=depends_on,\n at_front=at_front,\n meta=... | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.get_scheduler | python | def get_scheduler(self, interval=None, queue=None):
if interval is None:
interval = self.scheduler_interval
if not queue:
queue = self.scheduler_queue
scheduler_cls = import_attribute(self.scheduler_class)
scheduler = scheduler_cls(
queue_name=queue... | When installed returns a ``rq_scheduler.Scheduler`` instance to
schedule job execution, e.g.::
scheduler = rq.get_scheduler(interval=10)
:param interval: Time in seconds of the periodic check for scheduled
jobs.
:type interval: int
:param queue: Nam... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L310-L337 | null | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.get_queue | python | def get_queue(self, name=None):
if not name:
name = self.default_queue
queue = self._queue_instances.get(name)
if queue is None:
queue_cls = import_attribute(self.queue_class)
queue = queue_cls(
name=name,
default_timeout=self.d... | Returns an RQ queue instance with the given name, e.g.::
default_queue = rq.get_queue()
low_queue = rq.get_queue('low')
:param name: Name of the queue to return, defaults to
:attr:`~flask_rq2.RQ.default_queue`.
:type name: str
:return: An RQ queue i... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L339-L365 | null | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
rq/Flask-RQ2 | src/flask_rq2/app.py | RQ.get_worker | python | def get_worker(self, *queues):
if not queues:
queues = self.queues
queues = [self.get_queue(name) for name in queues]
worker_cls = import_attribute(self.worker_class)
worker = worker_cls(
queues,
connection=self.connection,
job_class=self.j... | Returns an RQ worker instance for the given queue names, e.g.::
configured_worker = rq.get_worker()
default_worker = rq.get_worker('default')
default_low_worker = rq.get_worker('default', 'low')
:param \\*queues: Names of queues the worker should act on, falls back
... | train | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L367-L390 | null | class RQ(object):
"""
The main RQ object to be used in user apps.
"""
#: Name of the default queue.
default_queue = 'default'
#: The fallback default timeout value.
default_timeout = Queue.DEFAULT_TIMEOUT
#: The fallback default result TTL.
#:
#: .. versionadded:: 17.1
defa... |
aio-libs/aiohttp_admin | aiohttp_admin/admin.py | setup_admin_on_rest_handlers | python | def setup_admin_on_rest_handlers(admin, admin_handler):
add_route = admin.router.add_route
add_static = admin.router.add_static
static_folder = str(PROJ_ROOT / 'static')
a = admin_handler
add_route('GET', '', a.index_page, name='admin.index')
add_route('POST', '/token', a.token, name='admin.tok... | Initialize routes. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L148-L160 | null | from aiohttp_jinja2 import render_template
from aiohttp_security import remember, forget
from yarl import URL
from .consts import TEMPLATE_APP_KEY, PROJ_ROOT
from .exceptions import JsonValidaitonError
from .security import authorize
from .utils import json_response, validate_payload, LoginForm
__all__ = [
'Admi... |
aio-libs/aiohttp_admin | aiohttp_admin/admin.py | AdminOnRestHandler.index_page | python | async def index_page(self, request):
context = {"initial_state": self.schema.to_json()}
return render_template(
self.template,
request,
context,
app_key=TEMPLATE_APP_KEY,
) | Return index page with initial state for admin | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L105-L116 | null | class AdminOnRestHandler:
template = 'admin_on_rest.jinja2'
def __init__(self, admin, *, resources, loop, schema):
self._admin = admin
self._loop = loop
self.schema = schema
for r in resources:
r.setup(self._admin, URL('/'))
self._resources = tuple(resource... |
aio-libs/aiohttp_admin | aiohttp_admin/admin.py | AdminOnRestHandler.logout | python | async def logout(self, request):
if "Authorization" not in request.headers:
msg = "Auth header is not present, can not destroy token"
raise JsonValidaitonError(msg)
response = json_response()
await forget(request, response)
return response | Simple handler for logout | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L134-L145 | null | class AdminOnRestHandler:
template = 'admin_on_rest.jinja2'
def __init__(self, admin, *, resources, loop, schema):
self._admin = admin
self._loop = loop
self.schema = schema
for r in resources:
r.setup(self._admin, URL('/'))
self._resources = tuple(resource... |
aio-libs/aiohttp_admin | aiohttp_admin/utils.py | json_datetime_serial | python | def json_datetime_serial(obj):
if isinstance(obj, (datetime, date)):
serial = obj.isoformat()
return serial
if ObjectId is not None and isinstance(obj, ObjectId):
# TODO: try to use bson.json_util instead
return str(obj)
raise TypeError("Type not serializable") | JSON serializer for objects not serializable by default json code | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/utils.py#L29-L39 | null | import json
from collections import namedtuple
from datetime import datetime, date
from functools import partial
from types import MappingProxyType
import trafaret as t
from aiohttp import web
from .exceptions import JsonValidaitonError
from .consts import TEMPLATES_ROOT
try:
from bson import ObjectId
except Im... |
aio-libs/aiohttp_admin | aiohttp_admin/utils.py | validate_query_structure | python | def validate_query_structure(query):
query_dict = dict(query)
filters = query_dict.pop('_filters', None)
if filters:
try:
f = json.loads(filters)
except ValueError:
msg = '_filters field can not be serialized'
raise JsonValidaitonError(msg)
else:
... | Validate query arguments in list request.
:param query: mapping with pagination and filtering information | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/utils.py#L82-L103 | [
"def as_dict(exc, value=None):\n result = exc.as_dict(value)\n if isinstance(result, str):\n return {\"error\": result}\n return result\n"
] | import json
from collections import namedtuple
from datetime import datetime, date
from functools import partial
from types import MappingProxyType
import trafaret as t
from aiohttp import web
from .exceptions import JsonValidaitonError
from .consts import TEMPLATES_ROOT
try:
from bson import ObjectId
except Im... |
aio-libs/aiohttp_admin | aiohttp_admin/contrib/admin.py | Schema.to_json | python | def to_json(self):
endpoints = []
for endpoint in self.endpoints:
list_fields = endpoint.fields
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
data = endpoint.to_dict()
data['fields'] = resource_type.get_type_of_fields... | Prepare data for the initial state of the admin-on-rest | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/admin.py#L30-L52 | null | class Schema:
"""
The main abstraction for registering tables and presenting data in
admin-on-rest format.
"""
def __init__(self, title='Admin'):
self.title = title
self.endpoints = []
def register(self, Endpoint):
"""
Register a wrapped `ModelAdmin` class as th... |
aio-libs/aiohttp_admin | aiohttp_admin/contrib/admin.py | Schema.resources | python | def resources(self):
resources = []
for endpoint in self.endpoints:
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
url = endpoint.name
resources.append((resource_type, {'table': table, 'url': url}))
return resources | Return list of all registered resources. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/admin.py#L55-L68 | null | class Schema:
"""
The main abstraction for registering tables and presenting data in
admin-on-rest format.
"""
def __init__(self, title='Admin'):
self.title = title
self.endpoints = []
def register(self, Endpoint):
"""
Register a wrapped `ModelAdmin` class as th... |
aio-libs/aiohttp_admin | aiohttp_admin/backends/sa.py | PGResource.get_type_of_fields | python | def get_type_of_fields(fields, table):
if not fields:
fields = table.primary_key
actual_fields = [
field for field in table.c.items() if field[0] in fields
]
data_type_fields = {
name: FIELD_TYPES.get(type(field_type.type), rc.TEXT_FIELD.value)
... | Return data types of `fields` that are in `table`. If a given
parameter is empty return primary key.
:param fields: list - list of fields that need to be returned
:param table: sa.Table - the current table
:return: list - list of the tuples `(field_name, fields_type)` | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L58-L80 | null | class PGResource(AbstractResource):
def __init__(self, db, table, primary_key='id', url=None):
super().__init__(primary_key=primary_key, resource_name=url)
self._db = db
self._table = table
self._primary_key = primary_key
self._pk = table.c[primary_key]
# TODO: do we... |
aio-libs/aiohttp_admin | aiohttp_admin/backends/sa.py | PGResource.get_type_for_inputs | python | def get_type_for_inputs(table):
return [
dict(
type=INPUT_TYPES.get(
type(field_type.type), rc.TEXT_INPUT.value
),
name=name,
isPrimaryKey=(name in table.primary_key),
props=None,
) for na... | Return information about table's fields in dictionary type.
:param table: sa.Table - the current table
:return: list - list of the dictionaries | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L83-L99 | null | class PGResource(AbstractResource):
def __init__(self, db, table, primary_key='id', url=None):
super().__init__(primary_key=primary_key, resource_name=url)
self._db = db
self._table = table
self._primary_key = primary_key
self._pk = table.c[primary_key]
# TODO: do we... |
aio-libs/aiohttp_admin | aiohttp_admin/__init__.py | _setup | python | def _setup(app, *, schema, title=None, app_key=APP_KEY, db=None):
admin = web.Application(loop=app.loop)
app[app_key] = admin
loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ])
aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY)
if title:
schema.title = title
resou... | Initialize the admin-on-rest admin | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/__init__.py#L44-L70 | [
"def setup_admin_on_rest_handlers(admin, admin_handler):\n \"\"\"\n Initialize routes.\n \"\"\"\n add_route = admin.router.add_route\n add_static = admin.router.add_static\n static_folder = str(PROJ_ROOT / 'static')\n a = admin_handler\n\n add_route('GET', '', a.index_page, name='admin.index... | import aiohttp_jinja2
import jinja2
from aiohttp import web
from .admin import (
AdminHandler,
setup_admin_handlers,
setup_admin_on_rest_handlers,
AdminOnRestHandler,
)
from .consts import PROJ_ROOT, TEMPLATE_APP_KEY, APP_KEY, TEMPLATES_ROOT
from .security import Permissions, require, authorize
from .u... |
aio-libs/aiohttp_admin | aiohttp_admin/contrib/models.py | ModelAdmin.to_dict | python | def to_dict(self):
data = {
"name": self.name,
"canEdit": self.can_edit,
"canCreate": self.can_create,
"canDelete": self.can_delete,
"perPage": self.per_page,
"showPage": self.generate_data_for_show_page(),
"editPage": self.gene... | Return dict with the all base information about the instance. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L30-L45 | [
"def generate_data_for_edit_page(self):\n \"\"\"\n Generate a custom representation of table's fields in dictionary type\n if exist edit form else use default representation.\n\n :return: dict\n \"\"\"\n\n if not self.can_edit:\n return {}\n\n if self.edit_form:\n return self.edit... | class ModelAdmin:
"""
The class provides the possibility of declarative describe of information
about the table and describe all things related to viewing this table on
the administrator's page.
class Users(models.ModelAdmin):
class Meta:
resource_type = PGResource
... |
aio-libs/aiohttp_admin | aiohttp_admin/contrib/models.py | ModelAdmin.generate_data_for_edit_page | python | def generate_data_for_edit_page(self):
if not self.can_edit:
return {}
if self.edit_form:
return self.edit_form.to_dict()
return self.generate_simple_data_page() | Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L55-L69 | [
"def generate_simple_data_page(self):\n \"\"\"\n Generate a simple representation of table's fields in dictionary type.\n\n :return: dict\n \"\"\"\n return self._resource_type.get_type_for_inputs(self._table)\n"
] | class ModelAdmin:
"""
The class provides the possibility of declarative describe of information
about the table and describe all things related to viewing this table on
the administrator's page.
class Users(models.ModelAdmin):
class Meta:
resource_type = PGResource
... |
aio-libs/aiohttp_admin | aiohttp_admin/contrib/models.py | ModelAdmin.generate_data_for_create_page | python | def generate_data_for_create_page(self):
if not self.can_create:
return {}
if self.create_form:
return self.create_form.to_dict()
return self.generate_simple_data_page() | Generate a custom representation of table's fields in dictionary type
if exist create form else use default representation.
:return: dict | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L83-L96 | [
"def generate_simple_data_page(self):\n \"\"\"\n Generate a simple representation of table's fields in dictionary type.\n\n :return: dict\n \"\"\"\n return self._resource_type.get_type_for_inputs(self._table)\n"
] | class ModelAdmin:
"""
The class provides the possibility of declarative describe of information
about the table and describe all things related to viewing this table on
the administrator's page.
class Users(models.ModelAdmin):
class Meta:
resource_type = PGResource
... |
aio-libs/aiohttp_admin | demos/motortwit/motortwit/views.py | SiteHandler.register | python | async def register(self, request):
session = await get_session(request)
user_id = session.get('user_id')
if user_id:
return redirect(request, 'timeline')
error = None
form = None
if request.method == 'POST':
form = await request.post()
... | Registers the user. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L116-L145 | null | class SiteHandler:
def __init__(self, mongo):
self._mongo = mongo
@property
def mongo(self):
return self._mongo
@aiohttp_jinja2.template('timeline.html')
async def timeline(self, request):
session = await get_session(request)
user_id = session.get('user_id')
... |
aio-libs/aiohttp_admin | demos/motortwit/motortwit/views.py | SiteHandler.follow_user | python | async def follow_user(self, request):
username = request.match_info['username']
session = await get_session(request)
user_id = session.get('user_id')
if not user_id:
raise web.HTTPNotAuthorized()
whom_id = await db.get_user_id(self.mongo.user, username)
if ... | Adds the current user as follower of the given user. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L147-L165 | null | class SiteHandler:
def __init__(self, mongo):
self._mongo = mongo
@property
def mongo(self):
return self._mongo
@aiohttp_jinja2.template('timeline.html')
async def timeline(self, request):
session = await get_session(request)
user_id = session.get('user_id')
... |
aio-libs/aiohttp_admin | demos/motortwit/motortwit/views.py | SiteHandler.add_message | python | async def add_message(self, request):
session = await get_session(request)
user_id = session.get('user_id')
if not user_id:
raise web.HTTPNotAuthorized()
form = await request.post()
if form.get('text'):
user = await self.mongo.user.find_one(
... | Registers a new message for the user. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L184-L203 | null | class SiteHandler:
def __init__(self, mongo):
self._mongo = mongo
@property
def mongo(self):
return self._mongo
@aiohttp_jinja2.template('timeline.html')
async def timeline(self, request):
session = await get_session(request)
user_id = session.get('user_id')
... |
aio-libs/aiohttp_admin | demos/motortwit/motortwit/utils.py | robo_avatar_url | python | def robo_avatar_url(user_data, size=80):
hash = md5(str(user_data).strip().lower().encode('utf-8')).hexdigest()
url = "https://robohash.org/{hash}.png?size={size}x{size}".format(
hash=hash, size=size)
return url | Return the gravatar image for the given email address. | train | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/utils.py#L27-L32 | null | import pytz
import yaml
from hashlib import md5
from dateutil.parser import parse
from aiohttp import web
import motor.motor_asyncio as aiomotor
def load_config(fname):
with open(fname, 'rt') as f:
data = yaml.load(f)
# TODO: add config validation
return data
async def init_mongo(conf, loop):
... |
dakrauth/django-swingtime | swingtime/forms.py | timeslot_options | python | def timeslot_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of time slot options for use in swingtime forms.
... | Create a list of time slot options for use in swingtime forms.
The list is comprised of 2-tuples containing a 24-hour time value and a
12-hour temporal representation of that offset. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/forms.py#L101-L123 | null | '''
Convenience forms for adding and updating ``Event`` and ``Occurrence``s.
'''
from datetime import datetime, date, time, timedelta
from django import forms
from django.forms.utils import to_current_timezone
from django.utils.translation import ugettext_lazy as _
from django.forms.widgets import SelectDateWidget
fro... |
dakrauth/django-swingtime | swingtime/forms.py | timeslot_offset_options | python | def timeslot_offset_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of time slot options for use in swingtime forms... | Create a list of time slot options for use in swingtime forms.
The list is comprised of 2-tuples containing the number of seconds since the
start of the day and a 12-hour temporal representation of that offset. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/forms.py#L126-L151 | [
"def time_delta_total_seconds(time_delta):\n '''\n Calculate the total number of seconds represented by a\n ``datetime.timedelta`` object\n\n '''\n return time_delta.days * 3600 + time_delta.seconds\n"
] | '''
Convenience forms for adding and updating ``Event`` and ``Occurrence``s.
'''
from datetime import datetime, date, time, timedelta
from django import forms
from django.forms.utils import to_current_timezone
from django.utils.translation import ugettext_lazy as _
from django.forms.widgets import SelectDateWidget
fro... |
dakrauth/django-swingtime | swingtime/utils.py | month_boundaries | python | def month_boundaries(dt=None):
'''
Return a 2-tuple containing the datetime instances for the first and last
dates of the current month or using ``dt`` as a reference.
'''
dt = dt or date.today()
wkday, ndays = calendar.monthrange(dt.year, dt.month)
start = datetime(dt.year, dt.month, 1)
... | Return a 2-tuple containing the datetime instances for the first and last
dates of the current month or using ``dt`` as a reference. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/utils.py#L27-L36 | null | '''
Common features and functions for swingtime
'''
import calendar
from collections import defaultdict
from datetime import datetime, date, time, timedelta
import itertools
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.encoding import python_2_unicode_comp... |
dakrauth/django-swingtime | swingtime/utils.py | css_class_cycler | python | def css_class_cycler():
'''
Return a dictionary keyed by ``EventType`` abbreviations, whose values are an
iterable or cycle of CSS class names.
'''
FMT = 'evt-{0}-{1}'.format
return defaultdict(default_css_class_cycler, (
(e.abbr, itertools.cycle((FMT(e.abbr, 'even'), FMT(e.abbr, 'odd')... | Return a dictionary keyed by ``EventType`` abbreviations, whose values are an
iterable or cycle of CSS class names. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/utils.py#L43-L53 | null | '''
Common features and functions for swingtime
'''
import calendar
from collections import defaultdict
from datetime import datetime, date, time, timedelta
import itertools
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.encoding import python_2_unicode_comp... |
dakrauth/django-swingtime | swingtime/utils.py | create_timeslot_table | python | def create_timeslot_table(
dt=None,
items=None,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_time_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
time_delta=swingtime_settings.TIMESLOT_INTERVAL,
min_columns=swingtime_settings.TIMESLOT_MIN_COLUMNS,
css_class_cycles=css_class_cy... | Create a grid-like object representing a sequence of times (rows) and
columns where cells are either empty or reference a wrapper object for
event occasions that overlap a specific time slot.
Currently, there is an assumption that if an occurrence has a ``start_time``
that falls with the temporal scope... | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/utils.py#L95-L211 | null | '''
Common features and functions for swingtime
'''
import calendar
from collections import defaultdict
from datetime import datetime, date, time, timedelta
import itertools
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.encoding import python_2_unicode_comp... |
dakrauth/django-swingtime | swingtime/models.py | create_event | python | def create_event(
title,
event_type,
description='',
start_time=None,
end_time=None,
note=None,
**rrule_params
):
'''
Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for... | Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for ``Event.add_occurrences``.
Returns the newly created ``Event`` instance.
Parameters
``event_type``
can be either an ``EventType`` ... | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L208-L265 | null | from datetime import datetime, date, timedelta
from dateutil import rrule
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
from django.conf import settings
from django.contrib.contenttypes.fie... |
dakrauth/django-swingtime | swingtime/models.py | Event.add_occurrences | python | def add_occurrences(self, start_time, end_time, **rrule_params):
'''
Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rrule.DAILY``.
Because ``rrule.rrule`` ... | Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rrule.DAILY``.
Because ``rrule.rrule`` returns an iterator that can essentially be
unbounded, we need to slightly al... | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L84-L110 | null | class Event(models.Model):
'''
Container model for general metadata and associated ``Occurrence`` entries.
'''
title = models.CharField(_('title'), max_length=32)
description = models.CharField(_('description'), max_length=100)
event_type = models.ForeignKey(
EventType,
verbose_n... |
dakrauth/django-swingtime | swingtime/models.py | Event.daily_occurrences | python | def daily_occurrences(self, dt=None):
'''
Convenience method wrapping ``Occurrence.objects.daily_occurrences``.
'''
return Occurrence.objects.daily_occurrences(dt=dt, event=self) | Convenience method wrapping ``Occurrence.objects.daily_occurrences``. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L127-L131 | null | class Event(models.Model):
'''
Container model for general metadata and associated ``Occurrence`` entries.
'''
title = models.CharField(_('title'), max_length=32)
description = models.CharField(_('description'), max_length=100)
event_type = models.ForeignKey(
EventType,
verbose_n... |
dakrauth/django-swingtime | swingtime/models.py | OccurrenceManager.daily_occurrences | python | def daily_occurrences(self, dt=None, event=None):
'''
Returns a queryset of for instances that have any overlap with a
particular day.
* ``dt`` may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, default to the current day.
* ``event`` c... | Returns a queryset of for instances that have any overlap with a
particular day.
* ``dt`` may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, default to the current day.
* ``event`` can be an ``Event`` instance for further filtering. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/models.py#L136-L164 | null | class OccurrenceManager(models.Manager):
|
dakrauth/django-swingtime | swingtime/views.py | event_listing | python | def event_listing(
request,
template='swingtime/event_list.html',
events=None,
**extra_context
):
'''
View all ``events``.
If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
Context parameters:
``events``
an iterable of ``Event`` objects
...... | View all ``events``.
If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
Context parameters:
``events``
an iterable of ``Event`` objects
... plus all values passed in via **extra_context | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L20-L40 | null | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | event_view | python | def event_view(
request,
pk,
template='swingtime/event_detail.html',
event_form_class=forms.EventForm,
recurrence_form_class=forms.MultipleOccurrenceForm
):
'''
View an ``Event`` instance and optionally update either the event or its
occurrences.
Context parameters:
``event``
... | View an ``Event`` instance and optionally update either the event or its
occurrences.
Context parameters:
``event``
the event keyed by ``pk``
``event_form``
a form object for updating the event
``recurrence_form``
a form object for adding occurrences | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L43-L88 | null | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | occurrence_view | python | def occurrence_view(
request,
event_pk,
pk,
template='swingtime/occurrence_detail.html',
form_class=forms.SingleOccurrenceForm
):
'''
View a specific occurrence and optionally handle any updates.
Context parameters:
``occurrence``
the occurrence object keyed by ``pk``
... | View a specific occurrence and optionally handle any updates.
Context parameters:
``occurrence``
the occurrence object keyed by ``pk``
``form``
a form object for updating the occurrence | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L91-L118 | null | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | add_event | python | def add_event(
request,
template='swingtime/add_event.html',
event_form_class=forms.EventForm,
recurrence_form_class=forms.MultipleOccurrenceForm
):
'''
Add a new ``Event`` instance and 1 or more associated ``Occurrence``s.
Context parameters:
``dtstart``
a datetime.datetime ob... | Add a new ``Event`` instance and 1 or more associated ``Occurrence``s.
Context parameters:
``dtstart``
a datetime.datetime object representing the GET request value if present,
otherwise None
``event_form``
a form object for updating the event
``recurrence_form``
a fo... | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L121-L168 | null | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | _datetime_view | python | def _datetime_view(
request,
template,
dt,
timeslot_factory=None,
items=None,
params=None
):
'''
Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params.
Context parameters:
``day``
the ... | Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params.
Context parameters:
``day``
the specified datetime value (dt)
``next_day``
day + 1 day
``prev_day``
day - 1 day
``timeslots``
... | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L171-L206 | null | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | day_view | python | def day_view(request, year, month, day, template='swingtime/daily_view.html', **params):
'''
See documentation for function``_datetime_view``.
'''
dt = datetime(int(year), int(month), int(day))
return _datetime_view(request, template, dt, **params) | See documentation for function``_datetime_view``. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L209-L215 | [
"def _datetime_view(\n request,\n template,\n dt,\n timeslot_factory=None,\n items=None,\n params=None\n):\n '''\n Build a time slot grid representation for the given datetime ``dt``. See\n utils.create_timeslot_table documentation for items and params.\n\n Context parameters:\n\n `... | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | today_view | python | def today_view(request, template='swingtime/daily_view.html', **params):
'''
See documentation for function``_datetime_view``.
'''
return _datetime_view(request, template, datetime.now(), **params) | See documentation for function``_datetime_view``. | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L218-L223 | [
"def _datetime_view(\n request,\n template,\n dt,\n timeslot_factory=None,\n items=None,\n params=None\n):\n '''\n Build a time slot grid representation for the given datetime ``dt``. See\n utils.create_timeslot_table documentation for items and params.\n\n Context parameters:\n\n `... | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
dakrauth/django-swingtime | swingtime/views.py | month_view | python | def month_view(
request,
year,
month,
template='swingtime/monthly_view.html',
queryset=None
):
'''
Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
``today``
the current datetime.datetime value
``calendar``
a list of... | Render a tradional calendar grid view with temporal navigation variables.
Context parameters:
``today``
the current datetime.datetime value
``calendar``
a list of rows containing (day, items) cells, where day is the day of
the month integer and items is a (potentially empty) list ... | train | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/views.py#L270-L323 | null | import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render
from .models import Event, Occurrence... |
systemd/python-systemd | systemd/journal.py | get_catalog | python | def get_catalog(mid):
if isinstance(mid, _uuid.UUID):
mid = mid.hex
return _get_catalog(mid) | Return catalog entry for the specified ID.
`mid` should be either a UUID or a 32 digit hex number. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L393-L400 | null | # -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
#
#
# Copyright 2012 David Strauss <david@davidstrauss.net>
# Copyright 2012 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
# Copyright 2012 Marti Raudsepp <marti@juffo.org>
#
# python-systemd is free software; you can redistribute it and/or modify it... |
systemd/python-systemd | systemd/journal.py | stream | python | def stream(identifier=None, priority=LOG_INFO, level_prefix=False):
r"""Return a file object wrapping a stream to journal.
Log messages written to this file as simple newline sepearted text strings
are written to the journal.
The file will be line buffered, so messages are actually sent after a
ne... | r"""Return a file object wrapping a stream to journal.
Log messages written to this file as simple newline sepearted text strings
are written to the journal.
The file will be line buffered, so messages are actually sent after a
newline character is written.
>>> from systemd import journal
>>>... | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L460-L501 | null | # -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
#
#
# Copyright 2012 David Strauss <david@davidstrauss.net>
# Copyright 2012 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
# Copyright 2012 Marti Raudsepp <marti@juffo.org>
#
# python-systemd is free software; you can redistribute it and/or modify it... |
systemd/python-systemd | systemd/journal.py | Reader._convert_field | python | def _convert_field(self, key, value):
convert = self.converters.get(key, bytes.decode)
try:
return convert(value)
except ValueError:
# Leave in default bytes
return value | Convert value using self.converters[key].
If `key` is not present in self.converters, a standard unicode decoding
will be attempted. If the conversion (either key-specific or the
default one) fails with a ValueError, the original bytes object will be
returned. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L185-L198 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader._convert_entry | python | def _convert_entry(self, entry):
result = {}
for key, value in entry.items():
if isinstance(value, list):
result[key] = [self._convert_field(key, val) for val in value]
else:
result[key] = self._convert_field(key, value)
return result | Convert entire journal entry utilising _convert_field. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L200-L208 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.add_match | python | def add_match(self, *args, **kwargs):
args = list(args)
args.extend(_make_line(key, val) for key, val in kwargs.items())
for arg in args:
super(Reader, self).add_match(arg) | Add one or more matches to the filter journal log entries.
All matches of different field are combined with logical AND, and
matches of the same field are automatically combined with logical OR.
Matches can be passed as strings of form "FIELD=value", or keyword
arguments FIELD="value". | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L233-L244 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.get_next | python | def get_next(self, skip=1):
r"""Return the next log entry as a dictionary.
Entries will be processed with converters specified during Reader
creation.
Optional `skip` value will return the `skip`-th log entry.
Currently a standard dictionary of fields is returned, but in the
... | r"""Return the next log entry as a dictionary.
Entries will be processed with converters specified during Reader
creation.
Optional `skip` value will return the `skip`-th log entry.
Currently a standard dictionary of fields is returned, but in the
future this might be changed ... | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L246-L265 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.query_unique | python | def query_unique(self, field):
return set(self._convert_field(field, value)
for value in super(Reader, self).query_unique(field)) | Return a list of unique values appearing in the journal for the given
`field`.
Note this does not respect any journal matches.
Entries will be processed with converters specified during
Reader creation. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L283-L293 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.wait | python | def wait(self, timeout=None):
us = -1 if timeout is None else int(timeout * 1000000)
return super(Reader, self).wait(us) | Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files have been added or
removed). | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L295-L306 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.seek_realtime | python | def seek_realtime(self, realtime):
if isinstance(realtime, _datetime.datetime):
realtime = int(float(realtime.strftime("%s.%f")) * 1000000)
elif not isinstance(realtime, int):
realtime = int(realtime * 1000000)
return super(Reader, self).seek_realtime(realtime) | Seek to a matching journal entry nearest to `timestamp` time.
Argument `realtime` must be either an integer UNIX timestamp (in
microseconds since the beginning of the UNIX epoch), or an float UNIX
timestamp (in seconds since the beginning of the UNIX epoch), or a
datetime.datetime insta... | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L308-L327 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.seek_monotonic | python | def seek_monotonic(self, monotonic, bootid=None):
if isinstance(monotonic, _datetime.timedelta):
monotonic = monotonic.total_seconds()
monotonic = int(monotonic * 1000000)
if isinstance(bootid, _uuid.UUID):
bootid = bootid.hex
return super(Reader, self).seek_monot... | Seek to a matching journal entry nearest to `monotonic` time.
Argument `monotonic` is a timestamp from boot in either seconds or a
datetime.timedelta instance. Argument `bootid` is a string or UUID
representing which boot the monotonic time is reference to. Defaults to
current bootid. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L329-L342 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.log_level | python | def log_level(self, level):
if 0 <= level <= 7:
for i in range(level+1):
self.add_match(PRIORITY="%d" % i)
else:
raise ValueError("Log level must be 0 <= level <= 7") | Set maximum log `level` by setting matches for PRIORITY. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L344-L351 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.messageid_match | python | def messageid_match(self, messageid):
if isinstance(messageid, _uuid.UUID):
messageid = messageid.hex
self.add_match(MESSAGE_ID=messageid) | Add match for log entries with specified `messageid`.
`messageid` can be string of hexadicimal digits or a UUID
instance. Standard message IDs can be found in systemd.id128.
Equivalent to add_match(MESSAGE_ID=`messageid`). | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L353-L363 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.this_boot | python | def this_boot(self, bootid=None):
if bootid is None:
bootid = _id128.get_boot().hex
else:
bootid = getattr(bootid, 'hex', bootid)
self.add_match(_BOOT_ID=bootid) | Add match for _BOOT_ID for current boot or the specified boot ID.
If specified, bootid should be either a UUID or a 32 digit hex number.
Equivalent to add_match(_BOOT_ID='bootid'). | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L365-L376 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | Reader.this_machine | python | def this_machine(self, machineid=None):
if machineid is None:
machineid = _id128.get_machine().hex
else:
machineid = getattr(machineid, 'hex', machineid)
self.add_match(_MACHINE_ID=machineid) | Add match for _MACHINE_ID equal to the ID of this machine.
If specified, machineid should be either a UUID or a 32 digit hex
number.
Equivalent to add_match(_MACHINE_ID='machineid'). | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L378-L390 | null | class Reader(_Reader):
"""Access systemd journal entries.
Entries are subject to filtering and limits, see `add_match`, `this_boot`,
`this_machine` functions and the `data_treshold` attribute.
Note that in order to access the system journal, a non-root user must have
the necessary privileges, see ... |
systemd/python-systemd | systemd/journal.py | JournalHandler.emit | python | def emit(self, record):
try:
msg = self.format(record)
pri = self.map_priority(record.levelno)
# defaults
extras = self._extra.copy()
# higher priority
if record.exc_text:
extras['EXCEPTION_TEXT'] = record.exc_text
... | Write `record` as a journal event.
MESSAGE is taken from the message provided by the user, and PRIORITY,
LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields are appended
automatically. In addition, record.MESSAGE_ID will be used if present. | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/journal.py#L568-L604 | [
"def map_priority(levelno):\n \"\"\"Map logging levels to journald priorities.\n\n Since Python log level numbers are \"sparse\", we have to map numbers in\n between the standard levels too.\n \"\"\"\n if levelno <= _logging.DEBUG:\n return LOG_DEBUG\n elif levelno <= _logging.INFO:\n ... | class JournalHandler(_logging.Handler):
"""Journal handler class for the Python logging framework.
Please see the Python logging module documentation for an overview:
http://docs.python.org/library/logging.html.
To create a custom logger whose messages go only to journal:
>>> import logging
>... |
systemd/python-systemd | systemd/daemon.py | is_socket_sockaddr | python | def is_socket_sockaddr(fileobj, address, type=0, flowinfo=0, listening=-1):
fd = _convert_fileobj(fileobj)
return _is_socket_sockaddr(fd, address, type, flowinfo, listening) | Check socket type, address and/or port, flowinfo, listening state.
Wraps sd_is_socket_inet_sockaddr(3).
`address` is a systemd-style numerical IPv4 or IPv6 address as used in
ListenStream=. A port may be included after a colon (":").
See systemd.socket(5) for details.
Constants for `family` are d... | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/daemon.py#L33-L45 | [
"def _convert_fileobj(fileobj):\n try:\n return fileobj.fileno()\n except AttributeError:\n return fileobj\n"
] | from socket import AF_UNSPEC as _AF_UNSPEC
from ._daemon import (__version__,
booted,
notify,
_listen_fds,
_is_fifo,
_is_socket,
_is_socket_inet,
_is_socket_sockaddr... |
systemd/python-systemd | systemd/daemon.py | listen_fds | python | def listen_fds(unset_environment=True):
num = _listen_fds(unset_environment)
return list(range(LISTEN_FDS_START, LISTEN_FDS_START + num)) | Return a list of socket activated descriptors
Example::
(in primary window)
$ systemd-activate -l 2000 python3 -c \\
'from systemd.daemon import listen_fds; print(listen_fds())'
(in another window)
$ telnet localhost 2000
(in primary window)
...
Execing python3 ... | train | https://github.com/systemd/python-systemd/blob/c06c5d401d60ae9175367be0797a6c2b562ac5ba/systemd/daemon.py#L55-L71 | null | from socket import AF_UNSPEC as _AF_UNSPEC
from ._daemon import (__version__,
booted,
notify,
_listen_fds,
_is_fifo,
_is_socket,
_is_socket_inet,
_is_socket_sockaddr... |
JonathanRaiman/pytreebank | pytreebank/labeled_trees.py | LabeledTree.uproot | python | def uproot(tree):
uprooted = tree.copy()
uprooted.parent = None
for child in tree.all_children():
uprooted.add_general_child(child)
return uprooted | Take a subranch of a tree and deep-copy the children
of this subbranch into a new LabeledTree | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L35-L44 | [
"def copy(self):\n \"\"\"\n Deep Copy of a LabeledTree\n \"\"\"\n return LabeledTree(\n udepth = self.udepth,\n depth = self.depth,\n text = self.text,\n label = self.label,\n children = self.children.copy() if self.children != None else [],\n parent = self.pare... | class LabeledTree(object):
SCORE_MAPPING = [-12.5,-6.25,0.0,6.25,12.5]
def __init__(self,
depth=0,
text=None,
label=None,
children=None,
parent=None,
udepth=1):
self.label = label
self.child... |
JonathanRaiman/pytreebank | pytreebank/labeled_trees.py | LabeledTree.copy | python | def copy(self):
return LabeledTree(
udepth = self.udepth,
depth = self.depth,
text = self.text,
label = self.label,
children = self.children.copy() if self.children != None else [],
parent = self.parent) | Deep Copy of a LabeledTree | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L60-L70 | null | class LabeledTree(object):
SCORE_MAPPING = [-12.5,-6.25,0.0,6.25,12.5]
def __init__(self,
depth=0,
text=None,
label=None,
children=None,
parent=None,
udepth=1):
self.label = label
self.child... |
JonathanRaiman/pytreebank | pytreebank/labeled_trees.py | LabeledTree.add_child | python | def add_child(self, child):
self.children.append(child)
child.parent = self
self.udepth = max([child.udepth for child in self.children]) + 1 | Adds a branch to the current tree. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L72-L78 | null | class LabeledTree(object):
SCORE_MAPPING = [-12.5,-6.25,0.0,6.25,12.5]
def __init__(self,
depth=0,
text=None,
label=None,
children=None,
parent=None,
udepth=1):
self.label = label
self.child... |
JonathanRaiman/pytreebank | pytreebank/labeled_trees.py | LabeledTree.lowercase | python | def lowercase(self):
if len(self.children) > 0:
for child in self.children:
child.lowercase()
else:
self.text = self.text.lower() | Lowercase all strings in this tree.
Works recursively and in-place. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L92-L101 | null | class LabeledTree(object):
SCORE_MAPPING = [-12.5,-6.25,0.0,6.25,12.5]
def __init__(self,
depth=0,
text=None,
label=None,
children=None,
parent=None,
udepth=1):
self.label = label
self.child... |
JonathanRaiman/pytreebank | pytreebank/labeled_trees.py | LabeledTree.to_dict | python | def to_dict(self, index=0):
index += 1
rep = {}
rep["index"] = index
rep["leaf"] = len(self.children) == 0
rep["depth"] = self.udepth
rep["scoreDistr"] = [0.0] * len(LabeledTree.SCORE_MAPPING)
# dirac distribution at correct label
if self.label is not None... | Dict format for use in Javascript / Jason Chuang's display technology. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L103-L137 | [
"def text_size(text):\n return max(4, font.getsize(text)[0][0])\n",
"def text_size(text):\n # TODO(contributors): make changes here to incorporate cap and uncap unknown words.\n return max(4, int(len(text) * 1.1))\n"
] | class LabeledTree(object):
SCORE_MAPPING = [-12.5,-6.25,0.0,6.25,12.5]
def __init__(self,
depth=0,
text=None,
label=None,
children=None,
parent=None,
udepth=1):
self.label = label
self.child... |
JonathanRaiman/pytreebank | pytreebank/labeled_trees.py | LabeledTree.inject_visualization_javascript | python | def inject_visualization_javascript(tree_width=1200, tree_height=400, tree_node_radius=10):
from .javascript import insert_sentiment_markup
insert_sentiment_markup(tree_width=tree_width, tree_height=tree_height, tree_node_radius=tree_node_radius) | In an Ipython notebook, show SST trees using the same Javascript
code as used by Jason Chuang's visualisations. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/labeled_trees.py#L195-L201 | [
"def insert_sentiment_markup(tree_width=1200, tree_height=400, tree_node_radius=10):\n\tinsert_stanford_javascript(\n\t\ttree_width=tree_width,\n\t\ttree_height=tree_height,\n\t\ttree_node_radius=tree_node_radius\n\t)\n\tinsert_stanford_styles()\n\timport_tag(\"div\", className='trees')\n"
] | class LabeledTree(object):
SCORE_MAPPING = [-12.5,-6.25,0.0,6.25,12.5]
def __init__(self,
depth=0,
text=None,
label=None,
children=None,
parent=None,
udepth=1):
self.label = label
self.child... |
JonathanRaiman/pytreebank | pytreebank/download.py | delete_paths | python | def delete_paths(paths):
for path in paths:
if exists(path):
if isfile(path):
remove(path)
else:
rmtree(path) | Delete a list of paths that are files or directories.
If a file/directory does not exist, skip it.
Arguments:
----------
paths : list<str>, names of files/directories to remove. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/download.py#L9-L25 | null | from os import stat, makedirs, remove
from os.path import join, exists, isfile
from zipfile import ZipFile
from shutil import move, rmtree
from . import utils
def download_sst(path, url):
""""
Download from `url` the zip file corresponding to the
Stanford Sentiment Treebank and expand the resulting
... |
JonathanRaiman/pytreebank | pytreebank/download.py | download_sst | python | def download_sst(path, url):
"
local_files = {
"train": join(path, "train.txt"),
"test": join(path, "test.txt"),
"dev": join(path, "dev.txt")
}
makedirs(path, exist_ok=True)
if all(exists(fname) and stat(fname).st_size > 100 for fname in local_files.values()):
return ... | Download from `url` the zip file corresponding to the
Stanford Sentiment Treebank and expand the resulting
files into the directory `path` (Note: if the files are
already present, the download is not actually run).
Arguments
---------
path : str, directory to save the train, test, and dev f... | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/download.py#L28-L62 | [
"def delete_paths(paths):\n \"\"\"\n Delete a list of paths that are files or directories.\n If a file/directory does not exist, skip it.\n\n Arguments:\n ----------\n\n paths : list<str>, names of files/directories to remove.\n\n \"\"\"\n for path in paths:\n if exists(path):\n ... | from os import stat, makedirs, remove
from os.path import join, exists, isfile
from zipfile import ZipFile
from shutil import move, rmtree
from . import utils
def delete_paths(paths):
"""
Delete a list of paths that are files or directories.
If a file/directory does not exist, skip it.
Arguments:
... |
JonathanRaiman/pytreebank | pytreebank/parse.py | attribute_text_label | python | def attribute_text_label(node, current_word):
node.text = normalize_string(current_word)
node.text = node.text.strip(" ")
node.udepth = 1
if len(node.text) > 0 and node.text[0].isdigit():
split_sent = node.text.split(" ", 1)
label = split_sent[0]
if len(split_sent) > 1:
... | Tries to recover the label inside a string
of the form '(3 hello)' where 3 is the label,
and hello is the string. Label is not assigned
if the string does not follow the expected
format.
Arguments:
----------
node : LabeledTree, current node that should
possibly receive a la... | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L15-L46 | [
"def normalize_string(string):\n \"\"\"\n Standardize input strings by making\n non-ascii spaces be ascii, and by converting\n treebank-style brackets/parenthesis be characters\n once more.\n\n Arguments:\n ----------\n string : str, characters to be standardized.\n\n Returns:\n --... | import codecs
import os
from collections import OrderedDict
from .labeled_trees import LabeledTree
from .download import download_sst
from .utils import makedirs, normalize_string
class ParseError(ValueError):
pass
def create_tree_from_string(line):
"""
Parse and convert a string representation
o... |
JonathanRaiman/pytreebank | pytreebank/parse.py | create_tree_from_string | python | def create_tree_from_string(line):
depth = 0
current_word = ""
root = None
current_node = root
for char in line:
if char == '(':
if current_node is not None and len(current_word) > 0:
attribute_text_label(current_node, current_word)
... | Parse and convert a string representation
of an example into a LabeledTree datastructure.
Arguments:
----------
line : str, string version of the tree.
Returns:
--------
LabeledTree : parsed tree. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L49-L101 | [
"def attribute_text_label(node, current_word):\n \"\"\"\n Tries to recover the label inside a string\n of the form '(3 hello)' where 3 is the label,\n and hello is the string. Label is not assigned\n if the string does not follow the expected\n format.\n\n Arguments:\n ----------\n no... | import codecs
import os
from collections import OrderedDict
from .labeled_trees import LabeledTree
from .download import download_sst
from .utils import makedirs, normalize_string
class ParseError(ValueError):
pass
def attribute_text_label(node, current_word):
"""
Tries to recover the label inside a s... |
JonathanRaiman/pytreebank | pytreebank/parse.py | import_tree_corpus | python | def import_tree_corpus(path):
tree_list = LabeledTreeCorpus()
with codecs.open(path, "r", "UTF-8") as f:
for line in f:
tree_list.append(create_tree_from_string(line))
return tree_list | Import a text file of treebank trees.
Arguments:
----------
path : str, filename for tree corpus.
Returns:
--------
list<LabeledTree> : loaded examples. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L144-L160 | [
"def create_tree_from_string(line):\n \"\"\"\n Parse and convert a string representation\n of an example into a LabeledTree datastructure.\n\n Arguments:\n ----------\n line : str, string version of the tree.\n\n Returns:\n --------\n LabeledTree : parsed tree.\n \"\"\"\n de... | import codecs
import os
from collections import OrderedDict
from .labeled_trees import LabeledTree
from .download import download_sst
from .utils import makedirs, normalize_string
class ParseError(ValueError):
pass
def attribute_text_label(node, current_word):
"""
Tries to recover the label inside a s... |
JonathanRaiman/pytreebank | pytreebank/parse.py | load_sst | python | def load_sst(path=None,
url='http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip'):
if path is None:
# find a good temporary path
path = os.path.expanduser("~/stanford_sentiment_treebank/")
makedirs(path, exist_ok=True)
fnames = download_sst(path, url)
return {ke... | Download and read in the Stanford Sentiment Treebank dataset
into a dictionary with a 'train', 'dev', and 'test' keys. The
dictionary keys point to lists of LabeledTrees.
Arguments:
----------
path : str, (optional defaults to ~/stanford_sentiment_treebank),
directory where the corp... | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L163-L187 | [
"def download_sst(path, url):\n \"\"\"\"\n Download from `url` the zip file corresponding to the\n Stanford Sentiment Treebank and expand the resulting\n files into the directory `path` (Note: if the files are\n already present, the download is not actually run).\n\n Arguments\n ---------\n ... | import codecs
import os
from collections import OrderedDict
from .labeled_trees import LabeledTree
from .download import download_sst
from .utils import makedirs, normalize_string
class ParseError(ValueError):
pass
def attribute_text_label(node, current_word):
"""
Tries to recover the label inside a s... |
JonathanRaiman/pytreebank | pytreebank/parse.py | LabeledTreeCorpus.labels | python | def labels(self):
labelings = OrderedDict()
for tree in self:
for label, line in tree.to_labeled_lines():
labelings[line] = label
return labelings | Construct a dictionary of string -> labels
Returns:
--------
OrderedDict<str, int> : string label pairs. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L112-L124 | null | class LabeledTreeCorpus(list):
"""
Read in the Stanford Sentiment Treebank using the original serialization format:
> (3 (2 this) (3 (2 is) (3 good ) )
"""
def to_file(self, path, mode="w"):
"""
Save the corpus to a text file in the
original format.
Arguments:
... |
JonathanRaiman/pytreebank | pytreebank/parse.py | LabeledTreeCorpus.to_file | python | def to_file(self, path, mode="w"):
with open(path, mode=mode) as f:
for tree in self:
for label, line in tree.to_labeled_lines():
f.write(line + "\n") | Save the corpus to a text file in the
original format.
Arguments:
----------
path : str, where to save the corpus.
mode : str, how to open the file. | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L127-L140 | null | class LabeledTreeCorpus(list):
"""
Read in the Stanford Sentiment Treebank using the original serialization format:
> (3 (2 this) (3 (2 is) (3 good ) )
"""
def labels(self):
"""
Construct a dictionary of string -> labels
Returns:
--------
OrderedDict<st... |
JonathanRaiman/pytreebank | pytreebank/treelstm.py | import_tree_corpus | python | def import_tree_corpus(labels_path, parents_path, texts_path):
with codecs.open(labels_path, "r", "UTF-8") as f:
label_lines = f.readlines()
with codecs.open(parents_path, "r", "UTF-8") as f:
parent_lines = f.readlines()
with codecs.open(texts_path, "r", "UTF-8") as f:
word_lines = f... | Import dataset from the TreeLSTM data generation scrips.
Arguments:
----------
labels_path : str, where are labels are stored (should be in
data/sst/labels.txt).
parents_path : str, where the parent relationships are stored
(should be in data/sst/parents.txt).
te... | train | https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L8-L42 | [
"def read_tree(parents, labels, words):\n \"\"\"\n Take as input a list of integers for parents\n and labels, along with a list of words, and\n reconstruct a LabeledTree.\n \"\"\"\n trees = {}\n root = None\n for i in range(1, len(parents) + 1):\n if not i in trees and parents[i - 1] ... | """
Special loading methods for importing dataset as processed
by the TreeLSTM code from https://github.com/stanfordnlp/treelstm
"""
from .labeled_trees import LabeledTree
import codecs
def assign_texts(node, words, next_idx=0):
"""
Recursively assign the words to nodes by finding and
assigning strings to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.