repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/list_.py
_get_package_status
def _get_package_status(package): """Get the status for a package.""" status = package["status_str"] or "Unknown" stage = package["stage_str"] or "Unknown" if stage == "Fully Synchronised": return status return "%(status)s / %(stage)s" % {"status": status, "stage": stage}
python
def _get_package_status(package): """Get the status for a package.""" status = package["status_str"] or "Unknown" stage = package["stage_str"] or "Unknown" if stage == "Fully Synchronised": return status return "%(status)s / %(stage)s" % {"status": status, "stage": stage}
[ "def", "_get_package_status", "(", "package", ")", ":", "status", "=", "package", "[", "\"status_str\"", "]", "or", "\"Unknown\"", "stage", "=", "package", "[", "\"stage_str\"", "]", "or", "\"Unknown\"", "if", "stage", "==", "\"Fully Synchronised\"", ":", "retur...
Get the status for a package.
[ "Get", "the", "status", "for", "a", "package", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/list_.py#L292-L298
kalefranz/auxlib
auxlib/type_coercion.py
boolify
def boolify(value, nullable=False, return_string=False): """Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')] [True, False, True, False, False, True, True] >>> [boolify(x) for x in ("true", "yes", "on", "y")] [True, True, True, True] >>> [boolify(x) for x in ("no", "non", "none", "off", "")] [False, False, False, False, False] >>> [boolify(x) for x in ([], set(), dict(), tuple())] [False, False, False, False] >>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))] [True, True, True, True] """ # cast number types naturally if isinstance(value, BOOL_COERCEABLE_TYPES): return bool(value) # try to coerce string into number val = text_type(value).strip().lower().replace('.', '', 1) if val.isnumeric(): return bool(float(val)) elif val in BOOLISH_TRUE: return True elif nullable and val in NULL_STRINGS: return None elif val in BOOLISH_FALSE: return False else: # must be False try: return bool(complex(val)) except ValueError: if isinstance(value, string_types) and return_string: return value raise TypeCoercionError(value, "The value %r cannot be boolified." % value)
python
def boolify(value, nullable=False, return_string=False): """Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')] [True, False, True, False, False, True, True] >>> [boolify(x) for x in ("true", "yes", "on", "y")] [True, True, True, True] >>> [boolify(x) for x in ("no", "non", "none", "off", "")] [False, False, False, False, False] >>> [boolify(x) for x in ([], set(), dict(), tuple())] [False, False, False, False] >>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))] [True, True, True, True] """ # cast number types naturally if isinstance(value, BOOL_COERCEABLE_TYPES): return bool(value) # try to coerce string into number val = text_type(value).strip().lower().replace('.', '', 1) if val.isnumeric(): return bool(float(val)) elif val in BOOLISH_TRUE: return True elif nullable and val in NULL_STRINGS: return None elif val in BOOLISH_FALSE: return False else: # must be False try: return bool(complex(val)) except ValueError: if isinstance(value, string_types) and return_string: return value raise TypeCoercionError(value, "The value %r cannot be boolified." % value)
[ "def", "boolify", "(", "value", ",", "nullable", "=", "False", ",", "return_string", "=", "False", ")", ":", "# cast number types naturally", "if", "isinstance", "(", "value", ",", "BOOL_COERCEABLE_TYPES", ")", ":", "return", "bool", "(", "value", ")", "# try ...
Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')] [True, False, True, False, False, True, True] >>> [boolify(x) for x in ("true", "yes", "on", "y")] [True, True, True, True] >>> [boolify(x) for x in ("no", "non", "none", "off", "")] [False, False, False, False, False] >>> [boolify(x) for x in ([], set(), dict(), tuple())] [False, False, False, False] >>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))] [True, True, True, True]
[ "Convert", "a", "number", "string", "or", "sequence", "type", "into", "a", "pure", "boolean", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/type_coercion.py#L126-L169
kalefranz/auxlib
auxlib/type_coercion.py
typify
def typify(value, type_hint=None): """Take a primitive value, usually a string, and try to make a more relevant type out of it. An optional type_hint will try to coerce the value to that type. Args: value (Any): Usually a string, not a sequence type_hint (type or Tuple[type]): Examples: >>> typify('32') 32 >>> typify('32', float) 32.0 >>> typify('32.0') 32.0 >>> typify('32.0.0') '32.0.0' >>> [typify(x) for x in ('true', 'yes', 'on')] [True, True, True] >>> [typify(x) for x in ('no', 'FALSe', 'off')] [False, False, False] >>> [typify(x) for x in ('none', 'None', None)] [None, None, None] """ # value must be a string, or there at least needs to be a type hint if isinstance(value, string_types): value = value.strip() elif type_hint is None: # can't do anything because value isn't a string and there's no type hint return value # now we either have a stripped string, a type hint, or both # use the hint if it exists if isiterable(type_hint): if isinstance(type_hint, type) and issubclass(type_hint, Enum): try: return type_hint(value) except ValueError: return type_hint[value] type_hint = set(type_hint) if not (type_hint - NUMBER_TYPES_SET): return numberify(value) elif not (type_hint - STRING_TYPES_SET): return text_type(value) elif not (type_hint - {bool, NoneType}): return boolify(value, nullable=True) elif not (type_hint - (STRING_TYPES_SET | {bool})): return boolify(value, return_string=True) elif not (type_hint - (STRING_TYPES_SET | {NoneType})): value = text_type(value) return None if value.lower() == 'none' else value elif not (type_hint - {bool, int}): return typify_str_no_hint(text_type(value)) else: raise NotImplementedError() elif type_hint is not None: # coerce using the type hint, or use boolify for bool try: return boolify(value) if type_hint == bool else type_hint(value) except ValueError as e: # ValueError: invalid literal for int() with base 10: 'nope' raise TypeCoercionError(value, text_type(e)) else: # no type hint, but we know value is a string, so try to match with the regex patterns # if there's still no match, `typify_str_no_hint` will return `value` return typify_str_no_hint(value)
python
def typify(value, type_hint=None): """Take a primitive value, usually a string, and try to make a more relevant type out of it. An optional type_hint will try to coerce the value to that type. Args: value (Any): Usually a string, not a sequence type_hint (type or Tuple[type]): Examples: >>> typify('32') 32 >>> typify('32', float) 32.0 >>> typify('32.0') 32.0 >>> typify('32.0.0') '32.0.0' >>> [typify(x) for x in ('true', 'yes', 'on')] [True, True, True] >>> [typify(x) for x in ('no', 'FALSe', 'off')] [False, False, False] >>> [typify(x) for x in ('none', 'None', None)] [None, None, None] """ # value must be a string, or there at least needs to be a type hint if isinstance(value, string_types): value = value.strip() elif type_hint is None: # can't do anything because value isn't a string and there's no type hint return value # now we either have a stripped string, a type hint, or both # use the hint if it exists if isiterable(type_hint): if isinstance(type_hint, type) and issubclass(type_hint, Enum): try: return type_hint(value) except ValueError: return type_hint[value] type_hint = set(type_hint) if not (type_hint - NUMBER_TYPES_SET): return numberify(value) elif not (type_hint - STRING_TYPES_SET): return text_type(value) elif not (type_hint - {bool, NoneType}): return boolify(value, nullable=True) elif not (type_hint - (STRING_TYPES_SET | {bool})): return boolify(value, return_string=True) elif not (type_hint - (STRING_TYPES_SET | {NoneType})): value = text_type(value) return None if value.lower() == 'none' else value elif not (type_hint - {bool, int}): return typify_str_no_hint(text_type(value)) else: raise NotImplementedError() elif type_hint is not None: # coerce using the type hint, or use boolify for bool try: return boolify(value) if type_hint == bool else type_hint(value) except ValueError as e: # ValueError: invalid literal for int() with base 10: 'nope' raise TypeCoercionError(value, text_type(e)) else: # no type hint, but we know value is a string, so try to match with the regex patterns # if there's still no match, `typify_str_no_hint` will return `value` return typify_str_no_hint(value)
[ "def", "typify", "(", "value", ",", "type_hint", "=", "None", ")", ":", "# value must be a string, or there at least needs to be a type hint", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "elif", ...
Take a primitive value, usually a string, and try to make a more relevant type out of it. An optional type_hint will try to coerce the value to that type. Args: value (Any): Usually a string, not a sequence type_hint (type or Tuple[type]): Examples: >>> typify('32') 32 >>> typify('32', float) 32.0 >>> typify('32.0') 32.0 >>> typify('32.0.0') '32.0.0' >>> [typify(x) for x in ('true', 'yes', 'on')] [True, True, True] >>> [typify(x) for x in ('no', 'FALSe', 'off')] [False, False, False] >>> [typify(x) for x in ('none', 'None', None)] [None, None, None]
[ "Take", "a", "primitive", "value", "usually", "a", "string", "and", "try", "to", "make", "a", "more", "relevant", "type", "out", "of", "it", ".", "An", "optional", "type_hint", "will", "try", "to", "coerce", "the", "value", "to", "that", "type", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/type_coercion.py#L185-L251
kalefranz/auxlib
auxlib/type_coercion.py
listify
def listify(val, return_type=tuple): """ Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c'] """ # TODO: flatlistify((1, 2, 3), 4, (5, 6, 7)) if val is None: return return_type() elif isiterable(val): return return_type(val) else: return return_type((val, ))
python
def listify(val, return_type=tuple): """ Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c'] """ # TODO: flatlistify((1, 2, 3), 4, (5, 6, 7)) if val is None: return return_type() elif isiterable(val): return return_type(val) else: return return_type((val, ))
[ "def", "listify", "(", "val", ",", "return_type", "=", "tuple", ")", ":", "# TODO: flatlistify((1, 2, 3), 4, (5, 6, 7))", "if", "val", "is", "None", ":", "return", "return_type", "(", ")", "elif", "isiterable", "(", "val", ")", ":", "return", "return_type", "(...
Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c']
[ "Examples", ":", ">>>", "listify", "(", "abc", "return_type", "=", "list", ")", "[", "abc", "]", ">>>", "listify", "(", "None", ")", "()", ">>>", "listify", "(", "False", ")", "(", "False", ")", ">>>", "listify", "((", "a", "b", "c", ")", "return_t...
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/type_coercion.py#L273-L291
visualfabriq/bquery
bquery/toplevel.py
open
def open(rootdir, mode='a'): # ---------------------------------------------------------------------- # https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132 # ---------------------------------------------------------------------- """ open(rootdir, mode='a') Open a disk-based carray/ctable. This function could be used to open bcolz objects as bquery objects to perform queries on them. Parameters ---------- rootdir : pathname (string) The directory hosting the carray/ctable object. mode : the open mode (string) Specifies the mode in which the object is opened. The supported values are: * 'r' for read-only * 'w' for emptying the previous underlying data * 'a' for allowing read/write on top of existing data Returns ------- out : a carray/ctable object or IOError (if not objects are found) """ # First try with a carray rootsfile = os.path.join(rootdir, ROOTDIRS) if os.path.exists(rootsfile): return bquery.ctable(rootdir=rootdir, mode=mode) else: return bquery.carray(rootdir=rootdir, mode=mode)
python
def open(rootdir, mode='a'): # ---------------------------------------------------------------------- # https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132 # ---------------------------------------------------------------------- """ open(rootdir, mode='a') Open a disk-based carray/ctable. This function could be used to open bcolz objects as bquery objects to perform queries on them. Parameters ---------- rootdir : pathname (string) The directory hosting the carray/ctable object. mode : the open mode (string) Specifies the mode in which the object is opened. The supported values are: * 'r' for read-only * 'w' for emptying the previous underlying data * 'a' for allowing read/write on top of existing data Returns ------- out : a carray/ctable object or IOError (if not objects are found) """ # First try with a carray rootsfile = os.path.join(rootdir, ROOTDIRS) if os.path.exists(rootsfile): return bquery.ctable(rootdir=rootdir, mode=mode) else: return bquery.carray(rootdir=rootdir, mode=mode)
[ "def", "open", "(", "rootdir", ",", "mode", "=", "'a'", ")", ":", "# ----------------------------------------------------------------------", "# https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132", "# ----------------------------------------------------------------------"...
open(rootdir, mode='a') Open a disk-based carray/ctable. This function could be used to open bcolz objects as bquery objects to perform queries on them. Parameters ---------- rootdir : pathname (string) The directory hosting the carray/ctable object. mode : the open mode (string) Specifies the mode in which the object is opened. The supported values are: * 'r' for read-only * 'w' for emptying the previous underlying data * 'a' for allowing read/write on top of existing data Returns ------- out : a carray/ctable object or IOError (if not objects are found)
[ "open", "(", "rootdir", "mode", "=", "a", ")" ]
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/toplevel.py#L8-L41
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/delete.py
delete
def delete(ctx, opts, owner_repo_package, yes): """ Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. """ owner, repo, slug = owner_repo_package delete_args = { "owner": click.style(owner, bold=True), "repo": click.style(repo, bold=True), "package": click.style(slug, bold=True), } prompt = "delete the %(package)s from %(owner)s/%(repo)s" % delete_args if not utils.confirm_operation(prompt, assume_yes=yes): return click.echo( "Deleting %(package)s from %(owner)s/%(repo)s ... " % delete_args, nl=False ) context_msg = "Failed to delete the package!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): delete_package(owner=owner, repo=repo, identifier=slug) click.secho("OK", fg="green")
python
def delete(ctx, opts, owner_repo_package, yes): """ Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. """ owner, repo, slug = owner_repo_package delete_args = { "owner": click.style(owner, bold=True), "repo": click.style(repo, bold=True), "package": click.style(slug, bold=True), } prompt = "delete the %(package)s from %(owner)s/%(repo)s" % delete_args if not utils.confirm_operation(prompt, assume_yes=yes): return click.echo( "Deleting %(package)s from %(owner)s/%(repo)s ... " % delete_args, nl=False ) context_msg = "Failed to delete the package!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): delete_package(owner=owner, repo=repo, identifier=slug) click.secho("OK", fg="green")
[ "def", "delete", "(", "ctx", ",", "opts", ",", "owner_repo_package", ",", "yes", ")", ":", "owner", ",", "repo", ",", "slug", "=", "owner_repo_package", "delete_args", "=", "{", "\"owner\"", ":", "click", ".", "style", "(", "owner", ",", "bold", "=", "...
Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'.
[ "Delete", "a", "package", "from", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/delete.py#L32-L63
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
validate_owner_repo_identifier
def validate_owner_repo_identifier(ctx, param, value): """Ensure that owner/repo/identifier is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/IDENTIFIER" return validators.validate_slashes(param, value, minimum=3, maximum=3, form=form)
python
def validate_owner_repo_identifier(ctx, param, value): """Ensure that owner/repo/identifier is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/IDENTIFIER" return validators.validate_slashes(param, value, minimum=3, maximum=3, form=form)
[ "def", "validate_owner_repo_identifier", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "form", "=", "\"OWNER/REPO/IDENTIFIER\"", "return", "validators", ".", "validate_slashes", "(", "param", ",", "value", ",", "minimum", "=", ...
Ensure that owner/repo/identifier is formatted correctly.
[ "Ensure", "that", "owner", "/", "repo", "/", "identifier", "is", "formatted", "correctly", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L17-L21
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
common_entitlements_options
def common_entitlements_options(f): """Add common options for entitlement commands.""" @click.option( "--show-tokens", default=False, is_flag=True, help="Show entitlement token string contents in output.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.invoke(f, *args, **kwargs) return wrapper
python
def common_entitlements_options(f): """Add common options for entitlement commands.""" @click.option( "--show-tokens", default=False, is_flag=True, help="Show entitlement token string contents in output.", ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "common_entitlements_options", "(", "f", ")", ":", "@", "click", ".", "option", "(", "\"--show-tokens\"", ",", "default", "=", "False", ",", "is_flag", "=", "True", ",", "help", "=", "\"Show entitlement token string contents in output.\"", ",", ")", "@", ...
Add common options for entitlement commands.
[ "Add", "common", "options", "for", "entitlement", "commands", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L24-L39
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
list_entitlements_options
def list_entitlements_options(f): """Options for list entitlements subcommand.""" @common_entitlements_options @decorators.common_cli_config_options @decorators.common_cli_list_options @decorators.common_cli_output_options @decorators.common_api_auth_options @decorators.initialise_api @click.argument( "owner_repo", metavar="OWNER/REPO", callback=validators.validate_owner_repo ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.invoke(f, *args, **kwargs) return wrapper
python
def list_entitlements_options(f): """Options for list entitlements subcommand.""" @common_entitlements_options @decorators.common_cli_config_options @decorators.common_cli_list_options @decorators.common_cli_output_options @decorators.common_api_auth_options @decorators.initialise_api @click.argument( "owner_repo", metavar="OWNER/REPO", callback=validators.validate_owner_repo ) @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): # pylint: disable=missing-docstring return ctx.invoke(f, *args, **kwargs) return wrapper
[ "def", "list_entitlements_options", "(", "f", ")", ":", "@", "common_entitlements_options", "@", "decorators", ".", "common_cli_config_options", "@", "decorators", ".", "common_cli_list_options", "@", "decorators", ".", "common_cli_output_options", "@", "decorators", ".",...
Options for list entitlements subcommand.
[ "Options", "for", "list", "entitlements", "subcommand", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L56-L74
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
list_entitlements
def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens): """ List entitlements for a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to list entitlements for. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents list your-org/your-repo """ owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo( "Getting list of entitlements for the %(repository)s " "repository ... " % {"repository": click.style(repo, bold=True)}, nl=False, err=use_stderr, ) context_msg = "Failed to get list of entitlements!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlements_, page_info = api.list_entitlements( owner=owner, repo=repo, page=page, page_size=page_size, show_tokens=show_tokens, ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=entitlements_, page_info=page_info)
python
def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens): """ List entitlements for a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to list entitlements for. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents list your-org/your-repo """ owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo( "Getting list of entitlements for the %(repository)s " "repository ... " % {"repository": click.style(repo, bold=True)}, nl=False, err=use_stderr, ) context_msg = "Failed to get list of entitlements!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlements_, page_info = api.list_entitlements( owner=owner, repo=repo, page=page, page_size=page_size, show_tokens=show_tokens, ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=entitlements_, page_info=page_info)
[ "def", "list_entitlements", "(", "ctx", ",", "opts", ",", "owner_repo", ",", "page", ",", "page_size", ",", "show_tokens", ")", ":", "owner", ",", "repo", "=", "owner_repo", "# Use stderr for messages if the output is something else (e.g. # JSON)", "use_stderr", "=", ...
List entitlements for a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to list entitlements for. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents list your-org/your-repo
[ "List", "entitlements", "for", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L77-L115
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
print_entitlements
def print_entitlements(opts, data, page_info=None, show_list_info=True): """Print entitlements as a table or output in another format.""" if utils.maybe_print_as_json(opts, data, page_info): return headers = ["Name", "Token", "Created / Updated", "Identifier"] rows = [] for entitlement in sorted(data, key=itemgetter("name")): rows.append( [ click.style( "%(name)s (%(type)s)" % { "name": click.style(entitlement["name"], fg="cyan"), "type": "user" if entitlement["user"] else "token", } ), click.style(entitlement["token"], fg="yellow"), click.style(entitlement["updated_at"], fg="blue"), click.style(entitlement["slug_perm"], fg="green"), ] ) if data: click.echo() utils.pretty_print_table(headers, rows) if not show_list_info: return click.echo() num_results = len(data) list_suffix = "entitlement%s" % ("s" if num_results != 1 else "") utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)
python
def print_entitlements(opts, data, page_info=None, show_list_info=True): """Print entitlements as a table or output in another format.""" if utils.maybe_print_as_json(opts, data, page_info): return headers = ["Name", "Token", "Created / Updated", "Identifier"] rows = [] for entitlement in sorted(data, key=itemgetter("name")): rows.append( [ click.style( "%(name)s (%(type)s)" % { "name": click.style(entitlement["name"], fg="cyan"), "type": "user" if entitlement["user"] else "token", } ), click.style(entitlement["token"], fg="yellow"), click.style(entitlement["updated_at"], fg="blue"), click.style(entitlement["slug_perm"], fg="green"), ] ) if data: click.echo() utils.pretty_print_table(headers, rows) if not show_list_info: return click.echo() num_results = len(data) list_suffix = "entitlement%s" % ("s" if num_results != 1 else "") utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)
[ "def", "print_entitlements", "(", "opts", ",", "data", ",", "page_info", "=", "None", ",", "show_list_info", "=", "True", ")", ":", "if", "utils", ".", "maybe_print_as_json", "(", "opts", ",", "data", ",", "page_info", ")", ":", "return", "headers", "=", ...
Print entitlements as a table or output in another format.
[ "Print", "entitlements", "as", "a", "table", "or", "output", "in", "another", "format", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L126-L161
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
create
def create(ctx, opts, owner_repo, show_tokens, name, token): """ Create a new entitlement in a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to create an entitlement. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents create your-org/your-repo --name 'Foobar' """ owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Creating %(name)s entitlement for the %(repository)s " "repository ... " % { "name": click.style(name, bold=True), "repository": click.style(repo, bold=True), }, nl=False, err=use_stderr, ) context_msg = "Failed to create the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.create_entitlement( owner=owner, repo=repo, name=name, token=token, show_tokens=show_tokens ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
python
def create(ctx, opts, owner_repo, show_tokens, name, token): """ Create a new entitlement in a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to create an entitlement. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents create your-org/your-repo --name 'Foobar' """ owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Creating %(name)s entitlement for the %(repository)s " "repository ... " % { "name": click.style(name, bold=True), "repository": click.style(repo, bold=True), }, nl=False, err=use_stderr, ) context_msg = "Failed to create the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.create_entitlement( owner=owner, repo=repo, name=name, token=token, show_tokens=show_tokens ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
[ "def", "create", "(", "ctx", ",", "opts", ",", "owner_repo", ",", "show_tokens", ",", "name", ",", "token", ")", ":", "owner", ",", "repo", "=", "owner_repo", "# Use stderr for messages if the output is something else (e.g. # JSON)", "use_stderr", "=", "opts", ".",...
Create a new entitlement in a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to create an entitlement. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents create your-org/your-repo --name 'Foobar'
[ "Create", "a", "new", "entitlement", "in", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L189-L227
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
delete
def delete(ctx, opts, owner_repo_identifier, yes): """ Delete an entitlement from a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents delete your-org/your-repo/abcdef123456 """ owner, repo, identifier = owner_repo_identifier delete_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } prompt = ( "delete the %(identifier)s entitlement from the %(repository)s " "repository" % delete_args ) if not utils.confirm_operation(prompt, assume_yes=yes): return click.secho( "Deleting %(identifier)s entitlement from the %(repository)s " "repository ... " % delete_args, nl=False, ) context_msg = "Failed to delete the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): api.delete_entitlement(owner=owner, repo=repo, identifier=identifier) click.secho("OK", fg="green")
python
def delete(ctx, opts, owner_repo_identifier, yes): """ Delete an entitlement from a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents delete your-org/your-repo/abcdef123456 """ owner, repo, identifier = owner_repo_identifier delete_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } prompt = ( "delete the %(identifier)s entitlement from the %(repository)s " "repository" % delete_args ) if not utils.confirm_operation(prompt, assume_yes=yes): return click.secho( "Deleting %(identifier)s entitlement from the %(repository)s " "repository ... " % delete_args, nl=False, ) context_msg = "Failed to delete the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): api.delete_entitlement(owner=owner, repo=repo, identifier=identifier) click.secho("OK", fg="green")
[ "def", "delete", "(", "ctx", ",", "opts", ",", "owner_repo_identifier", ",", "yes", ")", ":", "owner", ",", "repo", ",", "identifier", "=", "owner_repo_identifier", "delete_args", "=", "{", "\"identifier\"", ":", "click", ".", "style", "(", "identifier", ","...
Delete an entitlement from a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents delete your-org/your-repo/abcdef123456
[ "Delete", "an", "entitlement", "from", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L248-L287
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
update
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token): """ Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents update your-org/your-repo/abcdef123456 --name 'Newly' """ owner, repo, identifier = owner_repo_identifier # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Updating %(identifier)s entitlement for the %(repository)s " "repository ... " % { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), }, nl=False, err=use_stderr, ) context_msg = "Failed to update the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.update_entitlement( owner=owner, repo=repo, identifier=identifier, name=name, token=token, show_tokens=show_tokens, ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
python
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token): """ Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents update your-org/your-repo/abcdef123456 --name 'Newly' """ owner, repo, identifier = owner_repo_identifier # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Updating %(identifier)s entitlement for the %(repository)s " "repository ... " % { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), }, nl=False, err=use_stderr, ) context_msg = "Failed to update the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.update_entitlement( owner=owner, repo=repo, identifier=identifier, name=name, token=token, show_tokens=show_tokens, ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
[ "def", "update", "(", "ctx", ",", "opts", ",", "owner_repo_identifier", ",", "show_tokens", ",", "name", ",", "token", ")", ":", "owner", ",", "repo", ",", "identifier", "=", "owner_repo_identifier", "# Use stderr for messages if the output is something else (e.g. # JS...
Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents update your-org/your-repo/abcdef123456 --name 'Newly'
[ "Update", "(", "set", ")", "a", "entitlement", "in", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L316-L360
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
refresh
def refresh(ctx, opts, owner_repo_identifier, show_tokens, yes): """ Refresh an entitlement in a repository. Note that this changes the token associated with the entitlement. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents refresh your-org/your-repo/abcdef123456 """ owner, repo, identifier = owner_repo_identifier refresh_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" prompt = ( "refresh the %(identifier)s entitlement for the %(repository)s " "repository" % refresh_args ) if not utils.confirm_operation(prompt, assume_yes=yes, err=use_stderr): return click.secho( "Refreshing %(identifier)s entitlement for the %(repository)s " "repository ... " % refresh_args, nl=False, err=use_stderr, ) context_msg = "Failed to refresh the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.refresh_entitlement( owner=owner, repo=repo, identifier=identifier, show_tokens=show_tokens ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
python
def refresh(ctx, opts, owner_repo_identifier, show_tokens, yes): """ Refresh an entitlement in a repository. Note that this changes the token associated with the entitlement. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents refresh your-org/your-repo/abcdef123456 """ owner, repo, identifier = owner_repo_identifier refresh_args = { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), } # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" prompt = ( "refresh the %(identifier)s entitlement for the %(repository)s " "repository" % refresh_args ) if not utils.confirm_operation(prompt, assume_yes=yes, err=use_stderr): return click.secho( "Refreshing %(identifier)s entitlement for the %(repository)s " "repository ... " % refresh_args, nl=False, err=use_stderr, ) context_msg = "Failed to refresh the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.refresh_entitlement( owner=owner, repo=repo, identifier=identifier, show_tokens=show_tokens ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
[ "def", "refresh", "(", "ctx", ",", "opts", ",", "owner_repo_identifier", ",", "show_tokens", ",", "yes", ")", ":", "owner", ",", "repo", ",", "identifier", "=", "owner_repo_identifier", "refresh_args", "=", "{", "\"identifier\"", ":", "click", ".", "style", ...
Refresh an entitlement in a repository. Note that this changes the token associated with the entitlement. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents refresh your-org/your-repo/abcdef123456
[ "Refresh", "an", "entitlement", "in", "a", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L382-L431
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
sync
def sync(ctx, opts, owner_repo, show_tokens, source, yes): """ Sync entitlements from another repository. ***WARNING*** This will DELETE ALL of the existing entitlements in the repository and replace them with entitlements from the source repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to sync entitlements to. All separated by a slash. Example: 'your-org/your-repo' - SOURCE: Specify the SOURCE repository to copy the entitlements from. This *must* be in the same namespace as the destination repository. Example: 'source-repo' Full CLI example: $ cloudsmith ents sync your-org/your-repo source-repo """ owner, repo = owner_repo sync_args = { "source": click.style(source, bold=True), "dest": click.style(repo, bold=True), "warning": click.style("*** WARNING ***", fg="yellow"), } # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" if not yes: click.secho( "%(warning)s This will DELETE ALL of the existing entitlements " "in the %(dest)s repository and replace them with entitlements " "from the %(source)s repository." % sync_args, fg="yellow", err=use_stderr, ) click.echo() prompt = ( "sync entitlements from the %(source)s repository to the " "%(dest)s repository" % sync_args ) if not utils.confirm_operation(prompt, assume_yes=yes, err=use_stderr): return click.secho( "Syncing entitlements from the %(source)s repository to the " "%(dest)s repository" % sync_args, nl=False, err=use_stderr, ) context_msg = "Failed to sync the entitlements!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlements_, page_info = api.sync_entitlements( owner=owner, repo=repo, source=source, show_tokens=show_tokens ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=entitlements_, page_info=page_info)
python
def sync(ctx, opts, owner_repo, show_tokens, source, yes): """ Sync entitlements from another repository. ***WARNING*** This will DELETE ALL of the existing entitlements in the repository and replace them with entitlements from the source repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to sync entitlements to. All separated by a slash. Example: 'your-org/your-repo' - SOURCE: Specify the SOURCE repository to copy the entitlements from. This *must* be in the same namespace as the destination repository. Example: 'source-repo' Full CLI example: $ cloudsmith ents sync your-org/your-repo source-repo """ owner, repo = owner_repo sync_args = { "source": click.style(source, bold=True), "dest": click.style(repo, bold=True), "warning": click.style("*** WARNING ***", fg="yellow"), } # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" if not yes: click.secho( "%(warning)s This will DELETE ALL of the existing entitlements " "in the %(dest)s repository and replace them with entitlements " "from the %(source)s repository." % sync_args, fg="yellow", err=use_stderr, ) click.echo() prompt = ( "sync entitlements from the %(source)s repository to the " "%(dest)s repository" % sync_args ) if not utils.confirm_operation(prompt, assume_yes=yes, err=use_stderr): return click.secho( "Syncing entitlements from the %(source)s repository to the " "%(dest)s repository" % sync_args, nl=False, err=use_stderr, ) context_msg = "Failed to sync the entitlements!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlements_, page_info = api.sync_entitlements( owner=owner, repo=repo, source=source, show_tokens=show_tokens ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=entitlements_, page_info=page_info)
[ "def", "sync", "(", "ctx", ",", "opts", ",", "owner_repo", ",", "show_tokens", ",", "source", ",", "yes", ")", ":", "owner", ",", "repo", "=", "owner_repo", "sync_args", "=", "{", "\"source\"", ":", "click", ".", "style", "(", "source", ",", "bold", ...
Sync entitlements from another repository. ***WARNING*** This will DELETE ALL of the existing entitlements in the repository and replace them with entitlements from the source repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to sync entitlements to. All separated by a slash. Example: 'your-org/your-repo' - SOURCE: Specify the SOURCE repository to copy the entitlements from. This *must* be in the same namespace as the destination repository. Example: 'source-repo' Full CLI example: $ cloudsmith ents sync your-org/your-repo source-repo
[ "Sync", "entitlements", "from", "another", "repository", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L452-L517
visualfabriq/bquery
bquery/benchmarks/bench_pos.py
ctime
def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
python
def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
[ "def", "ctime", "(", "message", "=", "None", ")", ":", "t", "=", "time", ".", "time", "(", ")", "yield", "if", "message", ":", "print", "message", "+", "\":\\t\"", ",", "print", "round", "(", "time", ".", "time", "(", ")", "-", "t", ",", "4", "...
Counts the time spent in some context
[ "Counts", "the", "time", "spent", "in", "some", "context" ]
train
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/benchmarks/bench_pos.py#L14-L20
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/ratelimits.py
maybe_rate_limit
def maybe_rate_limit(client, headers, atexit=False): """Optionally pause the process based on suggested rate interval.""" # pylint: disable=fixme # pylint: disable=global-statement # FIXME: Yes, I know this is not great. We'll fix it later. :-) global LAST_CLIENT, LAST_HEADERS if LAST_CLIENT and LAST_HEADERS: # Wait based on previous client/headers rate_limit(LAST_CLIENT, LAST_HEADERS, atexit=atexit) LAST_CLIENT = copy.copy(client) LAST_HEADERS = copy.copy(headers)
python
def maybe_rate_limit(client, headers, atexit=False): """Optionally pause the process based on suggested rate interval.""" # pylint: disable=fixme # pylint: disable=global-statement # FIXME: Yes, I know this is not great. We'll fix it later. :-) global LAST_CLIENT, LAST_HEADERS if LAST_CLIENT and LAST_HEADERS: # Wait based on previous client/headers rate_limit(LAST_CLIENT, LAST_HEADERS, atexit=atexit) LAST_CLIENT = copy.copy(client) LAST_HEADERS = copy.copy(headers)
[ "def", "maybe_rate_limit", "(", "client", ",", "headers", ",", "atexit", "=", "False", ")", ":", "# pylint: disable=fixme", "# pylint: disable=global-statement", "# FIXME: Yes, I know this is not great. We'll fix it later. :-)", "global", "LAST_CLIENT", ",", "LAST_HEADERS", "if...
Optionally pause the process based on suggested rate interval.
[ "Optionally", "pause", "the", "process", "based", "on", "suggested", "rate", "interval", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/ratelimits.py#L85-L97
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/ratelimits.py
rate_limit
def rate_limit(client, headers, atexit=False): """Pause the process based on suggested rate interval.""" if not client or not headers: return False if not getattr(client.config, "rate_limit", False): return False rate_info = RateLimitsInfo.from_headers(headers) if not rate_info or not rate_info.interval: return False if rate_info.interval: cb = getattr(client.config, "rate_limit_callback", None) if cb and callable(cb): cb(rate_info, atexit=atexit) time.sleep(rate_info.interval) return True
python
def rate_limit(client, headers, atexit=False): """Pause the process based on suggested rate interval.""" if not client or not headers: return False if not getattr(client.config, "rate_limit", False): return False rate_info = RateLimitsInfo.from_headers(headers) if not rate_info or not rate_info.interval: return False if rate_info.interval: cb = getattr(client.config, "rate_limit_callback", None) if cb and callable(cb): cb(rate_info, atexit=atexit) time.sleep(rate_info.interval) return True
[ "def", "rate_limit", "(", "client", ",", "headers", ",", "atexit", "=", "False", ")", ":", "if", "not", "client", "or", "not", "headers", ":", "return", "False", "if", "not", "getattr", "(", "client", ".", "config", ",", "\"rate_limit\"", ",", "False", ...
Pause the process based on suggested rate interval.
[ "Pause", "the", "process", "based", "on", "suggested", "rate", "interval", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/ratelimits.py#L100-L117
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/status.py
get_status
def get_status(with_version=False): """Retrieve status (and optionally) version from the API.""" client = get_status_api() with catch_raise_api_exception(): data, _, headers = client.status_check_basic_with_http_info() ratelimits.maybe_rate_limit(client, headers) if with_version: return data.detail, data.version return data.detail
python
def get_status(with_version=False): """Retrieve status (and optionally) version from the API.""" client = get_status_api() with catch_raise_api_exception(): data, _, headers = client.status_check_basic_with_http_info() ratelimits.maybe_rate_limit(client, headers) if with_version: return data.detail, data.version return data.detail
[ "def", "get_status", "(", "with_version", "=", "False", ")", ":", "client", "=", "get_status_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "data", ",", "_", ",", "headers", "=", "client", ".", "status_check_basic_with_http_info", "(", ")"...
Retrieve status (and optionally) version from the API.
[ "Retrieve", "status", "(", "and", "optionally", ")", "version", "from", "the", "API", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/status.py#L17-L29
kalefranz/auxlib
auxlib/collection.py
first
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x): """Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq that passes key, mutated with optional apply Examples: >>> first([0, False, None, [], (), 42]) 42 >>> first([0, False, None, [], ()]) is None True >>> first([0, False, None, [], ()], default='ohai') 'ohai' >>> import re >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) >>> m.group(1) 'bc' The optional `key` argument specifies a one-argument predicate function like that used for `filter()`. The `key` argument, if supplied, must be in keyword form. For example: >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) 4 """ return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
python
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x): """Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq that passes key, mutated with optional apply Examples: >>> first([0, False, None, [], (), 42]) 42 >>> first([0, False, None, [], ()]) is None True >>> first([0, False, None, [], ()], default='ohai') 'ohai' >>> import re >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) >>> m.group(1) 'bc' The optional `key` argument specifies a one-argument predicate function like that used for `filter()`. The `key` argument, if supplied, must be in keyword form. For example: >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) 4 """ return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
[ "def", "first", "(", "seq", ",", "key", "=", "lambda", "x", ":", "bool", "(", "x", ")", ",", "default", "=", "None", ",", "apply", "=", "lambda", "x", ":", "x", ")", ":", "return", "next", "(", "(", "apply", "(", "x", ")", "for", "x", "in", ...
Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq that passes key, mutated with optional apply Examples: >>> first([0, False, None, [], (), 42]) 42 >>> first([0, False, None, [], ()]) is None True >>> first([0, False, None, [], ()], default='ohai') 'ohai' >>> import re >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) >>> m.group(1) 'bc' The optional `key` argument specifies a one-argument predicate function like that used for `filter()`. The `key` argument, if supplied, must be in keyword form. For example: >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) 4
[ "Give", "the", "first", "value", "that", "satisfies", "the", "key", "test", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/collection.py#L87-L117
kalefranz/auxlib
auxlib/collection.py
call_each
def call_each(seq): """Calls each element of sequence to invoke the side effect. Args: seq: Returns: None """ try: reduce(lambda _, y: y(), seq) except TypeError as e: if text_type(e) != "reduce() of empty sequence with no initial value": raise
python
def call_each(seq): """Calls each element of sequence to invoke the side effect. Args: seq: Returns: None """ try: reduce(lambda _, y: y(), seq) except TypeError as e: if text_type(e) != "reduce() of empty sequence with no initial value": raise
[ "def", "call_each", "(", "seq", ")", ":", "try", ":", "reduce", "(", "lambda", "_", ",", "y", ":", "y", "(", ")", ",", "seq", ")", "except", "TypeError", "as", "e", ":", "if", "text_type", "(", "e", ")", "!=", "\"reduce() of empty sequence with no init...
Calls each element of sequence to invoke the side effect. Args: seq: Returns: None
[ "Calls", "each", "element", "of", "sequence", "to", "invoke", "the", "side", "effect", "." ]
train
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/collection.py#L128-L141
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
transform_api_header_authorization
def transform_api_header_authorization(param, value): """Transform a username:password value into a base64 string.""" try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorization header needs to be Authorization=username:password", param=param, ) value = "%s:%s" % (username.strip(), password) value = base64.b64encode(bytes(value.encode())) return "Basic %s" % value.decode("utf-8")
python
def transform_api_header_authorization(param, value): """Transform a username:password value into a base64 string.""" try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorization header needs to be Authorization=username:password", param=param, ) value = "%s:%s" % (username.strip(), password) value = base64.b64encode(bytes(value.encode())) return "Basic %s" % value.decode("utf-8")
[ "def", "transform_api_header_authorization", "(", "param", ",", "value", ")", ":", "try", ":", "username", ",", "password", "=", "value", ".", "split", "(", "\":\"", ",", "1", ")", "except", "ValueError", ":", "raise", "click", ".", "BadParameter", "(", "\...
Transform a username:password value into a base64 string.
[ "Transform", "a", "username", ":", "password", "value", "into", "a", "base64", "string", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L14-L26
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_api_headers
def validate_api_headers(param, value): """Validate that API headers is a CSV of k=v pairs.""" # pylint: disable=unused-argument if not value: return None headers = {} for kv in value.split(","): try: k, v = kv.split("=", 1) k = k.strip() for bad_header in BAD_API_HEADERS: if bad_header == k: raise click.BadParameter( "%(key)s is not an allowed header" % {"key": bad_header}, param=param, ) if k in API_HEADER_TRANSFORMS: transform_func = API_HEADER_TRANSFORMS[k] v = transform_func(param, v) except ValueError: raise click.BadParameter( "Values need to be a CSV of key=value pairs", param=param ) headers[k] = v return headers
python
def validate_api_headers(param, value): """Validate that API headers is a CSV of k=v pairs.""" # pylint: disable=unused-argument if not value: return None headers = {} for kv in value.split(","): try: k, v = kv.split("=", 1) k = k.strip() for bad_header in BAD_API_HEADERS: if bad_header == k: raise click.BadParameter( "%(key)s is not an allowed header" % {"key": bad_header}, param=param, ) if k in API_HEADER_TRANSFORMS: transform_func = API_HEADER_TRANSFORMS[k] v = transform_func(param, v) except ValueError: raise click.BadParameter( "Values need to be a CSV of key=value pairs", param=param ) headers[k] = v return headers
[ "def", "validate_api_headers", "(", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "if", "not", "value", ":", "return", "None", "headers", "=", "{", "}", "for", "kv", "in", "value", ".", "split", "(", "\",\"", ")", ":", "try", ":", ...
Validate that API headers is a CSV of k=v pairs.
[ "Validate", "that", "API", "headers", "is", "a", "CSV", "of", "k", "=", "v", "pairs", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L32-L61
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_slashes
def validate_slashes(param, value, minimum=2, maximum=None, form=None): """Ensure that parameter has slashes and minimum parts.""" try: value = value.split("/") except ValueError: value = None if value: if len(value) < minimum: value = None elif maximum and len(value) > maximum: value = None if not value: form = form or "/".join("VALUE" for _ in range(minimum)) raise click.BadParameter( "Must be in the form of %(form)s" % {"form": form}, param=param ) value = [v.strip() for v in value] if not all(value): raise click.BadParameter("Individual values cannot be blank", param=param) return value
python
def validate_slashes(param, value, minimum=2, maximum=None, form=None): """Ensure that parameter has slashes and minimum parts.""" try: value = value.split("/") except ValueError: value = None if value: if len(value) < minimum: value = None elif maximum and len(value) > maximum: value = None if not value: form = form or "/".join("VALUE" for _ in range(minimum)) raise click.BadParameter( "Must be in the form of %(form)s" % {"form": form}, param=param ) value = [v.strip() for v in value] if not all(value): raise click.BadParameter("Individual values cannot be blank", param=param) return value
[ "def", "validate_slashes", "(", "param", ",", "value", ",", "minimum", "=", "2", ",", "maximum", "=", "None", ",", "form", "=", "None", ")", ":", "try", ":", "value", "=", "value", ".", "split", "(", "\"/\"", ")", "except", "ValueError", ":", "value"...
Ensure that parameter has slashes and minimum parts.
[ "Ensure", "that", "parameter", "has", "slashes", "and", "minimum", "parts", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L64-L87
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_owner_repo
def validate_owner_repo(ctx, param, value): """Ensure that owner/repo is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
python
def validate_owner_repo(ctx, param, value): """Ensure that owner/repo is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
[ "def", "validate_owner_repo", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "form", "=", "\"OWNER/REPO\"", "return", "validate_slashes", "(", "param", ",", "value", ",", "minimum", "=", "2", ",", "maximum", "=", "2", ",...
Ensure that owner/repo is formatted correctly.
[ "Ensure", "that", "owner", "/", "repo", "is", "formatted", "correctly", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L90-L94
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_owner_repo_package
def validate_owner_repo_package(ctx, param, value): """Ensure that owner/repo/package is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/PACKAGE" return validate_slashes(param, value, minimum=3, maximum=3, form=form)
python
def validate_owner_repo_package(ctx, param, value): """Ensure that owner/repo/package is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/PACKAGE" return validate_slashes(param, value, minimum=3, maximum=3, form=form)
[ "def", "validate_owner_repo_package", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "form", "=", "\"OWNER/REPO/PACKAGE\"", "return", "validate_slashes", "(", "param", ",", "value", ",", "minimum", "=", "3", ",", "maximum", ...
Ensure that owner/repo/package is formatted correctly.
[ "Ensure", "that", "owner", "/", "repo", "/", "package", "is", "formatted", "correctly", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L97-L101
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_owner_repo_distro
def validate_owner_repo_distro(ctx, param, value): """Ensure that owner/repo/distro/version is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/DISTRO[/RELEASE]" return validate_slashes(param, value, minimum=3, maximum=4, form=form)
python
def validate_owner_repo_distro(ctx, param, value): """Ensure that owner/repo/distro/version is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/DISTRO[/RELEASE]" return validate_slashes(param, value, minimum=3, maximum=4, form=form)
[ "def", "validate_owner_repo_distro", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "form", "=", "\"OWNER/REPO/DISTRO[/RELEASE]\"", "return", "validate_slashes", "(", "param", ",", "value", ",", "minimum", "=", "3", ",", "maxi...
Ensure that owner/repo/distro/version is formatted correctly.
[ "Ensure", "that", "owner", "/", "repo", "/", "distro", "/", "version", "is", "formatted", "correctly", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L104-L108
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_page
def validate_page(ctx, param, value): """Ensure that a valid value for page is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter( "Page is not zero-based, please set a value to 1 or higher.", param=param ) return value
python
def validate_page(ctx, param, value): """Ensure that a valid value for page is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter( "Page is not zero-based, please set a value to 1 or higher.", param=param ) return value
[ "def", "validate_page", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "if", "value", "==", "0", ":", "raise", "click", ".", "BadParameter", "(", "\"Page is not zero-based, please set a value to 1 or higher.\"", ",", "param", "=...
Ensure that a valid value for page is chosen.
[ "Ensure", "that", "a", "valid", "value", "for", "page", "is", "chosen", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L111-L118
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/validators.py
validate_page_size
def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
python
def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
[ "def", "validate_page_size", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=unused-argument", "if", "value", "==", "0", ":", "raise", "click", ".", "BadParameter", "(", "\"Page size must be non-zero or unset.\"", ",", "param", "=", "param", "...
Ensure that a valid value for page size is chosen.
[ "Ensure", "that", "a", "valid", "value", "for", "page", "size", "is", "chosen", "." ]
train
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L121-L126
yagays/pybitflyer
pybitflyer/pybitflyer.py
API.getbalance
def getbalance(self, **params): """Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance """ if not all([self.api_key, self.api_secret]): raise AuthException() endpoint = "/v1/me/getbalance" return self.request(endpoint, params=params)
python
def getbalance(self, **params): """Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance """ if not all([self.api_key, self.api_secret]): raise AuthException() endpoint = "/v1/me/getbalance" return self.request(endpoint, params=params)
[ "def", "getbalance", "(", "self", ",", "*", "*", "params", ")", ":", "if", "not", "all", "(", "[", "self", ".", "api_key", ",", "self", ".", "api_secret", "]", ")", ":", "raise", "AuthException", "(", ")", "endpoint", "=", "\"/v1/me/getbalance\"", "ret...
Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance
[ "Get", "Account", "Asset", "Balance" ]
train
https://github.com/yagays/pybitflyer/blob/05858240e5f9e0367b0a397d96b4ced5e55150d9/pybitflyer/pybitflyer.py#L188-L203
willthames/ansible-inventory-grapher
lib/ansibleinventorygrapher/__init__.py
tidy_all_the_variables
def tidy_all_the_variables(host, inventory_mgr): ''' removes all overridden and inherited variables from hosts and groups ''' global _vars _vars = dict() _vars[host] = inventory_mgr.inventory.get_host_vars(host) for group in host.get_groups(): remove_inherited_and_overridden_vars(_vars[host], group, inventory_mgr) remove_inherited_and_overridden_group_vars(group, inventory_mgr) return _vars
python
def tidy_all_the_variables(host, inventory_mgr): ''' removes all overridden and inherited variables from hosts and groups ''' global _vars _vars = dict() _vars[host] = inventory_mgr.inventory.get_host_vars(host) for group in host.get_groups(): remove_inherited_and_overridden_vars(_vars[host], group, inventory_mgr) remove_inherited_and_overridden_group_vars(group, inventory_mgr) return _vars
[ "def", "tidy_all_the_variables", "(", "host", ",", "inventory_mgr", ")", ":", "global", "_vars", "_vars", "=", "dict", "(", ")", "_vars", "[", "host", "]", "=", "inventory_mgr", ".", "inventory", ".", "get_host_vars", "(", "host", ")", "for", "group", "in"...
removes all overridden and inherited variables from hosts and groups
[ "removes", "all", "overridden", "and", "inherited", "variables", "from", "hosts", "and", "groups" ]
train
https://github.com/willthames/ansible-inventory-grapher/blob/018908594776486a317ef9ed9293a9ef391fe3e9/lib/ansibleinventorygrapher/__init__.py#L90-L99
willthames/ansible-inventory-grapher
lib/ansibleinventorygrapher/inventory.py
Inventory24._plugins_inventory
def _plugins_inventory(self, entities): import os from ansible.plugins.loader import vars_loader from ansible.utils.vars import combine_vars ''' merges all entities by inventory source ''' data = {} for inventory_dir in self.variable_manager._inventory._sources: if ',' in inventory_dir: # skip host lists continue elif not os.path.isdir(inventory_dir): # always pass 'inventory directory' inventory_dir = os.path.dirname(inventory_dir) for plugin in vars_loader.all(): data = combine_vars(data, self._get_plugin_vars(plugin, inventory_dir, entities)) return data
python
def _plugins_inventory(self, entities): import os from ansible.plugins.loader import vars_loader from ansible.utils.vars import combine_vars ''' merges all entities by inventory source ''' data = {} for inventory_dir in self.variable_manager._inventory._sources: if ',' in inventory_dir: # skip host lists continue elif not os.path.isdir(inventory_dir): # always pass 'inventory directory' inventory_dir = os.path.dirname(inventory_dir) for plugin in vars_loader.all(): data = combine_vars(data, self._get_plugin_vars(plugin, inventory_dir, entities)) return data
[ "def", "_plugins_inventory", "(", "self", ",", "entities", ")", ":", "import", "os", "from", "ansible", ".", "plugins", ".", "loader", "import", "vars_loader", "from", "ansible", ".", "utils", ".", "vars", "import", "combine_vars", "data", "=", "{", "}", "...
merges all entities by inventory source
[ "merges", "all", "entities", "by", "inventory", "source" ]
train
https://github.com/willthames/ansible-inventory-grapher/blob/018908594776486a317ef9ed9293a9ef391fe3e9/lib/ansibleinventorygrapher/inventory.py#L121-L135
thelabnyc/wagtail_blog
blog/management/commands/wordpress_to_wagtail.py
Command.handle
def handle(self, *args, **options): """gets data from WordPress site""" # TODO: refactor these with .get if 'username' in options: self.username = options['username'] else: self.username = None if 'password' in options: self.password = options['password'] else: self.password = None self.xml_path = options.get('xml') self.url = options.get('url') try: blog_index = BlogIndexPage.objects.get( title__icontains=options['blog_index']) except BlogIndexPage.DoesNotExist: raise CommandError("Incorrect blog index title - have you created it?") if self.url == "just_testing": with open('test-data.json') as test_json: posts = json.load(test_json) elif self.xml_path: try: import lxml from blog.wp_xml_parser import XML_parser except ImportError as e: print("You must have lxml installed to run xml imports." " Run `pip install lxml`.") raise e self.xml_parser = XML_parser(self.xml_path) posts = self.xml_parser.get_posts_data() else: posts = self.get_posts_data(self.url) self.should_import_comments = options.get('import_comments') self.create_blog_pages(posts, blog_index)
python
def handle(self, *args, **options): """gets data from WordPress site""" # TODO: refactor these with .get if 'username' in options: self.username = options['username'] else: self.username = None if 'password' in options: self.password = options['password'] else: self.password = None self.xml_path = options.get('xml') self.url = options.get('url') try: blog_index = BlogIndexPage.objects.get( title__icontains=options['blog_index']) except BlogIndexPage.DoesNotExist: raise CommandError("Incorrect blog index title - have you created it?") if self.url == "just_testing": with open('test-data.json') as test_json: posts = json.load(test_json) elif self.xml_path: try: import lxml from blog.wp_xml_parser import XML_parser except ImportError as e: print("You must have lxml installed to run xml imports." " Run `pip install lxml`.") raise e self.xml_parser = XML_parser(self.xml_path) posts = self.xml_parser.get_posts_data() else: posts = self.get_posts_data(self.url) self.should_import_comments = options.get('import_comments') self.create_blog_pages(posts, blog_index)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# TODO: refactor these with .get", "if", "'username'", "in", "options", ":", "self", ".", "username", "=", "options", "[", "'username'", "]", "else", ":", "self", ".", "...
gets data from WordPress site
[ "gets", "data", "from", "WordPress", "site" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L64-L99
thelabnyc/wagtail_blog
blog/management/commands/wordpress_to_wagtail.py
Command.create_images_from_urls_in_content
def create_images_from_urls_in_content(self, body): """create Image objects and transfer image files to media root""" soup = BeautifulSoup(body, "html5lib") for img in soup.findAll('img'): old_url = img['src'] if 'width' in img: width = img['width'] if 'height' in img: height = img['height'] else: width = 100 height = 100 path, file_ = os.path.split(img['src']) if not img['src']: continue # Blank image if img['src'].startswith('data:'): continue # Embedded image try: remote_image = urllib.request.urlretrieve( self.prepare_url(img['src'])) except (urllib.error.HTTPError, urllib.error.URLError, UnicodeEncodeError, ValueError): print("Unable to import " + img['src']) continue image = Image(title=file_, width=width, height=height) try: image.file.save(file_, File(open(remote_image[0], 'rb'))) image.save() new_url = image.file.url body = body.replace(old_url, new_url) body = self.convert_html_entities(body) except TypeError: print("Unable to import image {}".format(remote_image[0])) return body
python
def create_images_from_urls_in_content(self, body): """create Image objects and transfer image files to media root""" soup = BeautifulSoup(body, "html5lib") for img in soup.findAll('img'): old_url = img['src'] if 'width' in img: width = img['width'] if 'height' in img: height = img['height'] else: width = 100 height = 100 path, file_ = os.path.split(img['src']) if not img['src']: continue # Blank image if img['src'].startswith('data:'): continue # Embedded image try: remote_image = urllib.request.urlretrieve( self.prepare_url(img['src'])) except (urllib.error.HTTPError, urllib.error.URLError, UnicodeEncodeError, ValueError): print("Unable to import " + img['src']) continue image = Image(title=file_, width=width, height=height) try: image.file.save(file_, File(open(remote_image[0], 'rb'))) image.save() new_url = image.file.url body = body.replace(old_url, new_url) body = self.convert_html_entities(body) except TypeError: print("Unable to import image {}".format(remote_image[0])) return body
[ "def", "create_images_from_urls_in_content", "(", "self", ",", "body", ")", ":", "soup", "=", "BeautifulSoup", "(", "body", ",", "\"html5lib\"", ")", "for", "img", "in", "soup", ".", "findAll", "(", "'img'", ")", ":", "old_url", "=", "img", "[", "'src'", ...
create Image objects and transfer image files to media root
[ "create", "Image", "objects", "and", "transfer", "image", "files", "to", "media", "root" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L159-L194
thelabnyc/wagtail_blog
blog/management/commands/wordpress_to_wagtail.py
Command.lookup_comment_by_wordpress_id
def lookup_comment_by_wordpress_id(self, comment_id, comments): """ Returns Django comment object with this wordpress id """ for comment in comments: if comment.wordpress_id == comment_id: return comment
python
def lookup_comment_by_wordpress_id(self, comment_id, comments): """ Returns Django comment object with this wordpress id """ for comment in comments: if comment.wordpress_id == comment_id: return comment
[ "def", "lookup_comment_by_wordpress_id", "(", "self", ",", "comment_id", ",", "comments", ")", ":", "for", "comment", "in", "comments", ":", "if", "comment", ".", "wordpress_id", "==", "comment_id", ":", "return", "comment" ]
Returns Django comment object with this wordpress id
[ "Returns", "Django", "comment", "object", "with", "this", "wordpress", "id" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L223-L227
thelabnyc/wagtail_blog
blog/management/commands/wordpress_to_wagtail.py
Command.create_blog_pages
def create_blog_pages(self, posts, blog_index, *args, **options): """create Blog post entries from wordpress data""" for post in posts: post_id = post.get('ID') title = post.get('title') if title: new_title = self.convert_html_entities(title) title = new_title slug = post.get('slug') description = post.get('description') if description: description = self.convert_html_entities(description) body = post.get('content') if not "<p>" in body: body = linebreaks(body) # get image info from content and create image objects body = self.create_images_from_urls_in_content(body) # author/user data author = post.get('author') user = self.create_user(author) categories = post.get('terms') # format the date date = post.get('date')[:10] try: new_entry = BlogPage.objects.get(slug=slug) new_entry.title = title new_entry.body = body new_entry.owner = user new_entry.save() except BlogPage.DoesNotExist: new_entry = blog_index.add_child(instance=BlogPage( title=title, slug=slug, search_description="description", date=date, body=body, owner=user)) featured_image = post.get('featured_image') if featured_image is not None: title = post['featured_image']['title'] source = post['featured_image']['source'] path, file_ = os.path.split(source) source = source.replace('stage.swoon', 'swoon') try: remote_image = urllib.request.urlretrieve( self.prepare_url(source)) width = 640 height = 290 header_image = Image(title=title, width=width, height=height) header_image.file.save( file_, File(open(remote_image[0], 'rb'))) header_image.save() except UnicodeEncodeError: header_image = None print('unable to set header image {}'.format(source)) else: header_image = None new_entry.header_image = header_image new_entry.save() if categories: self.create_categories_and_tags(new_entry, categories) if self.should_import_comments: self.import_comments(post_id, slug)
python
def create_blog_pages(self, posts, blog_index, *args, **options): """create Blog post entries from wordpress data""" for post in posts: post_id = post.get('ID') title = post.get('title') if title: new_title = self.convert_html_entities(title) title = new_title slug = post.get('slug') description = post.get('description') if description: description = self.convert_html_entities(description) body = post.get('content') if not "<p>" in body: body = linebreaks(body) # get image info from content and create image objects body = self.create_images_from_urls_in_content(body) # author/user data author = post.get('author') user = self.create_user(author) categories = post.get('terms') # format the date date = post.get('date')[:10] try: new_entry = BlogPage.objects.get(slug=slug) new_entry.title = title new_entry.body = body new_entry.owner = user new_entry.save() except BlogPage.DoesNotExist: new_entry = blog_index.add_child(instance=BlogPage( title=title, slug=slug, search_description="description", date=date, body=body, owner=user)) featured_image = post.get('featured_image') if featured_image is not None: title = post['featured_image']['title'] source = post['featured_image']['source'] path, file_ = os.path.split(source) source = source.replace('stage.swoon', 'swoon') try: remote_image = urllib.request.urlretrieve( self.prepare_url(source)) width = 640 height = 290 header_image = Image(title=title, width=width, height=height) header_image.file.save( file_, File(open(remote_image[0], 'rb'))) header_image.save() except UnicodeEncodeError: header_image = None print('unable to set header image {}'.format(source)) else: header_image = None new_entry.header_image = header_image new_entry.save() if categories: self.create_categories_and_tags(new_entry, categories) if self.should_import_comments: self.import_comments(post_id, slug)
[ "def", "create_blog_pages", "(", "self", ",", "posts", ",", "blog_index", ",", "*", "args", ",", "*", "*", "options", ")", ":", "for", "post", "in", "posts", ":", "post_id", "=", "post", ".", "get", "(", "'ID'", ")", "title", "=", "post", ".", "get...
create Blog post entries from wordpress data
[ "create", "Blog", "post", "entries", "from", "wordpress", "data" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L327-L388
thelabnyc/wagtail_blog
blog/utils.py
unique_slugify
def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): """ Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check against for uniqueness). ``queryset`` usually doesn't need to be explicitly provided - it'll default to using the ``.all()`` queryset from the model's default manager. """ slug_field = instance._meta.get_field(slug_field_name) slug = getattr(instance, slug_field.attname) slug_len = slug_field.max_length # Sort out the initial slug, limiting its length if necessary. slug = slugify(value) if slug_len: slug = slug[:slug_len] slug = _slug_strip(slug, slug_separator) original_slug = slug # Create the queryset if one wasn't explicitly provided and exclude the # current instance from the queryset. if queryset is None: queryset = instance.__class__._default_manager.all() if instance.pk: queryset = queryset.exclude(pk=instance.pk) # Find a unique slug. If one matches, at '-2' to the end and try again # (then '-3', etc). next = 2 while not slug or queryset.filter(**{slug_field_name: slug}): slug = original_slug end = '%s%s' % (slug_separator, next) if slug_len and len(slug) + len(end) > slug_len: slug = slug[:slug_len-len(end)] slug = _slug_strip(slug, slug_separator) slug = '%s%s' % (slug, end) next += 1 setattr(instance, slug_field.attname, slug)
python
def unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): """ Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check against for uniqueness). ``queryset`` usually doesn't need to be explicitly provided - it'll default to using the ``.all()`` queryset from the model's default manager. """ slug_field = instance._meta.get_field(slug_field_name) slug = getattr(instance, slug_field.attname) slug_len = slug_field.max_length # Sort out the initial slug, limiting its length if necessary. slug = slugify(value) if slug_len: slug = slug[:slug_len] slug = _slug_strip(slug, slug_separator) original_slug = slug # Create the queryset if one wasn't explicitly provided and exclude the # current instance from the queryset. if queryset is None: queryset = instance.__class__._default_manager.all() if instance.pk: queryset = queryset.exclude(pk=instance.pk) # Find a unique slug. If one matches, at '-2' to the end and try again # (then '-3', etc). next = 2 while not slug or queryset.filter(**{slug_field_name: slug}): slug = original_slug end = '%s%s' % (slug_separator, next) if slug_len and len(slug) + len(end) > slug_len: slug = slug[:slug_len-len(end)] slug = _slug_strip(slug, slug_separator) slug = '%s%s' % (slug, end) next += 1 setattr(instance, slug_field.attname, slug)
[ "def", "unique_slugify", "(", "instance", ",", "value", ",", "slug_field_name", "=", "'slug'", ",", "queryset", "=", "None", ",", "slug_separator", "=", "'-'", ")", ":", "slug_field", "=", "instance", ".", "_meta", ".", "get_field", "(", "slug_field_name", "...
Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check against for uniqueness). ``queryset`` usually doesn't need to be explicitly provided - it'll default to using the ``.all()`` queryset from the model's default manager.
[ "Calculates", "and", "stores", "a", "unique", "slug", "of", "value", "for", "an", "instance", "." ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/utils.py#L6-L48
thelabnyc/wagtail_blog
blog/utils.py
_slug_strip
def _slug_strip(value, separator='-'): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ separator = separator or '' if separator == '-' or not separator: re_sep = '-' else: re_sep = '(?:-|%s)' % re.escape(separator) # Remove multiple instances and if an alternate separator is provided, # replace the default '-' separator. if separator != re_sep: value = re.sub('%s+' % re_sep, separator, value) # Remove separator from the beginning and end of the slug. if separator: if separator != '-': re_sep = re.escape(separator) value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value) return value
python
def _slug_strip(value, separator='-'): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ separator = separator or '' if separator == '-' or not separator: re_sep = '-' else: re_sep = '(?:-|%s)' % re.escape(separator) # Remove multiple instances and if an alternate separator is provided, # replace the default '-' separator. if separator != re_sep: value = re.sub('%s+' % re_sep, separator, value) # Remove separator from the beginning and end of the slug. if separator: if separator != '-': re_sep = re.escape(separator) value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value) return value
[ "def", "_slug_strip", "(", "value", ",", "separator", "=", "'-'", ")", ":", "separator", "=", "separator", "or", "''", "if", "separator", "==", "'-'", "or", "not", "separator", ":", "re_sep", "=", "'-'", "else", ":", "re_sep", "=", "'(?:-|%s)'", "%", "...
Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator.
[ "Cleans", "up", "a", "slug", "by", "removing", "slug", "separator", "characters", "that", "occur", "at", "the", "beginning", "or", "end", "of", "a", "slug", "." ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/utils.py#L51-L73
thelabnyc/wagtail_blog
blog/abstract.py
limit_author_choices
def limit_author_choices(): """ Limit choices in blog author field based on config settings """ LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None) if LIMIT_AUTHOR_CHOICES: if isinstance(LIMIT_AUTHOR_CHOICES, str): limit = Q(groups__name=LIMIT_AUTHOR_CHOICES) else: limit = Q() for s in LIMIT_AUTHOR_CHOICES: limit = limit | Q(groups__name=s) if getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_ADMIN', False): limit = limit | Q(is_staff=True) else: limit = {'is_staff': True} return limit
python
def limit_author_choices(): """ Limit choices in blog author field based on config settings """ LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None) if LIMIT_AUTHOR_CHOICES: if isinstance(LIMIT_AUTHOR_CHOICES, str): limit = Q(groups__name=LIMIT_AUTHOR_CHOICES) else: limit = Q() for s in LIMIT_AUTHOR_CHOICES: limit = limit | Q(groups__name=s) if getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_ADMIN', False): limit = limit | Q(is_staff=True) else: limit = {'is_staff': True} return limit
[ "def", "limit_author_choices", "(", ")", ":", "LIMIT_AUTHOR_CHOICES", "=", "getattr", "(", "settings", ",", "'BLOG_LIMIT_AUTHOR_CHOICES_GROUP'", ",", "None", ")", "if", "LIMIT_AUTHOR_CHOICES", ":", "if", "isinstance", "(", "LIMIT_AUTHOR_CHOICES", ",", "str", ")", ":...
Limit choices in blog author field based on config settings
[ "Limit", "choices", "in", "blog", "author", "field", "based", "on", "config", "settings" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/abstract.py#L95-L109
thelabnyc/wagtail_blog
blog/models.py
get_blog_context
def get_blog_context(context): """ Get context data useful on all blog related pages """ context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages')).order_by('-owned_pages__count') context['all_categories'] = BlogCategory.objects.all() context['root_categories'] = BlogCategory.objects.filter( parent=None, ).prefetch_related( 'children', ).annotate( blog_count=Count('blogpage'), ) return context
python
def get_blog_context(context): """ Get context data useful on all blog related pages """ context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages')).order_by('-owned_pages__count') context['all_categories'] = BlogCategory.objects.all() context['root_categories'] = BlogCategory.objects.filter( parent=None, ).prefetch_related( 'children', ).annotate( blog_count=Count('blogpage'), ) return context
[ "def", "get_blog_context", "(", "context", ")", ":", "context", "[", "'authors'", "]", "=", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "owned_pages__live", "=", "True", ",", "owned_pages__content_type__model", "=", "'blogpage'", ")", ".", ...
Get context data useful on all blog related pages
[ "Get", "context", "data", "useful", "on", "all", "blog", "related", "pages" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/models.py#L118-L132
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.remove_xmlns
def remove_xmlns(xml_string): """ changes the xmlns (XML namespace) so that values are replaced with the string representation of their key this makes the import process for portable >>> xp = XML_parser >>> test_xmlns = r'<rss version="2.0" xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/">' >>> xp.remove_xmlns(test_xmlns) '<rss version="2.0" xmlns:excerpt="excerpt">' """ # splitting xml into sections, pre_chan is preamble before <channel> pre_chan, chan, post_chan= xml_string.partition('<channel>') # replace xmlns statements on preamble pre_chan = re.sub(r'xmlns:(?P<label>\w*)\=\"(?P<val>[^\"]*)\"', r'xmlns:\g<label>="\g<label>"', pre_chan) # piece back together return pre_chan + chan + post_chan
python
def remove_xmlns(xml_string): """ changes the xmlns (XML namespace) so that values are replaced with the string representation of their key this makes the import process for portable >>> xp = XML_parser >>> test_xmlns = r'<rss version="2.0" xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/">' >>> xp.remove_xmlns(test_xmlns) '<rss version="2.0" xmlns:excerpt="excerpt">' """ # splitting xml into sections, pre_chan is preamble before <channel> pre_chan, chan, post_chan= xml_string.partition('<channel>') # replace xmlns statements on preamble pre_chan = re.sub(r'xmlns:(?P<label>\w*)\=\"(?P<val>[^\"]*)\"', r'xmlns:\g<label>="\g<label>"', pre_chan) # piece back together return pre_chan + chan + post_chan
[ "def", "remove_xmlns", "(", "xml_string", ")", ":", "# splitting xml into sections, pre_chan is preamble before <channel>", "pre_chan", ",", "chan", ",", "post_chan", "=", "xml_string", ".", "partition", "(", "'<channel>'", ")", "# replace xmlns statements on preamble", "pre_...
changes the xmlns (XML namespace) so that values are replaced with the string representation of their key this makes the import process for portable >>> xp = XML_parser >>> test_xmlns = r'<rss version="2.0" xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/">' >>> xp.remove_xmlns(test_xmlns) '<rss version="2.0" xmlns:excerpt="excerpt">'
[ "changes", "the", "xmlns", "(", "XML", "namespace", ")", "so", "that", "values", "are", "replaced", "with", "the", "string", "representation", "of", "their", "key", "this", "makes", "the", "import", "process", "for", "portable" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L69-L87
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.item_dict
def item_dict(self, item): """ create a default dict of values, including category and tag lookup """ # mocking wierd JSON structure ret_dict = {"terms":{"category":[],"post_tag":[]}} for e in item: # is it a category or tag?? if "category" in e.tag: # get details slug = e.attrib["nicename"] name = htmlparser.unescape(e.text) # lookup the category or create one cat_dict = self.category_dict.get(slug) or {"slug":slug, "name":name, "taxonomy":"category"} ret_dict['terms']['category'].append(cat_dict) elif e.tag[-3:] == 'tag': # get details slug = e.attrib.get("tag_slug") name = htmlparser.unescape(e.text) # lookup the tag or create one tag_dict = self.tags_dict.get(slug) or {"slug":slug, "name":name, "taxonomy":"post_tag"} ret_dict['terms']['post_tag'].append(tag_dict) # else use tagname:tag inner test else: ret_dict[e.tag] = e.text # remove empty accumulators empty_keys = [k for k,v in ret_dict["terms"].items() if not v] for k in empty_keys: ret_dict["terms"].pop(k) return ret_dict
python
def item_dict(self, item): """ create a default dict of values, including category and tag lookup """ # mocking wierd JSON structure ret_dict = {"terms":{"category":[],"post_tag":[]}} for e in item: # is it a category or tag?? if "category" in e.tag: # get details slug = e.attrib["nicename"] name = htmlparser.unescape(e.text) # lookup the category or create one cat_dict = self.category_dict.get(slug) or {"slug":slug, "name":name, "taxonomy":"category"} ret_dict['terms']['category'].append(cat_dict) elif e.tag[-3:] == 'tag': # get details slug = e.attrib.get("tag_slug") name = htmlparser.unescape(e.text) # lookup the tag or create one tag_dict = self.tags_dict.get(slug) or {"slug":slug, "name":name, "taxonomy":"post_tag"} ret_dict['terms']['post_tag'].append(tag_dict) # else use tagname:tag inner test else: ret_dict[e.tag] = e.text # remove empty accumulators empty_keys = [k for k,v in ret_dict["terms"].items() if not v] for k in empty_keys: ret_dict["terms"].pop(k) return ret_dict
[ "def", "item_dict", "(", "self", ",", "item", ")", ":", "# mocking wierd JSON structure", "ret_dict", "=", "{", "\"terms\"", ":", "{", "\"category\"", ":", "[", "]", ",", "\"post_tag\"", ":", "[", "]", "}", "}", "for", "e", "in", "item", ":", "# is it a ...
create a default dict of values, including category and tag lookup
[ "create", "a", "default", "dict", "of", "values", "including", "category", "and", "tag", "lookup" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L93-L129
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.convert_date
def convert_date(d, custom_date_string=None, fallback=None): """ for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000' shows up. >>> xp = XML_parser >>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000") '2015-03-30' """ if d == 'Mon, 30 Nov -0001 00:00:00 +0000' and fallback: d = fallback try: date = time.strftime("%Y-%m-%d", time.strptime(d, '%a, %d %b %Y %H:%M:%S %z')) except ValueError: date = time.strftime("%Y-%m-%d", time.strptime(d, '%Y-%m-%d %H:%M:%S')) except ValueError: date = custom_date_string or datetime.datetime.today().strftime("%Y-%m-%d") return date
python
def convert_date(d, custom_date_string=None, fallback=None): """ for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000' shows up. >>> xp = XML_parser >>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000") '2015-03-30' """ if d == 'Mon, 30 Nov -0001 00:00:00 +0000' and fallback: d = fallback try: date = time.strftime("%Y-%m-%d", time.strptime(d, '%a, %d %b %Y %H:%M:%S %z')) except ValueError: date = time.strftime("%Y-%m-%d", time.strptime(d, '%Y-%m-%d %H:%M:%S')) except ValueError: date = custom_date_string or datetime.datetime.today().strftime("%Y-%m-%d") return date
[ "def", "convert_date", "(", "d", ",", "custom_date_string", "=", "None", ",", "fallback", "=", "None", ")", ":", "if", "d", "==", "'Mon, 30 Nov -0001 00:00:00 +0000'", "and", "fallback", ":", "d", "=", "fallback", "try", ":", "date", "=", "time", ".", "str...
for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000' shows up. >>> xp = XML_parser >>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000") '2015-03-30'
[ "for", "whatever", "reason", "sometimes", "WP", "XML", "has", "unintelligible", "datetime", "strings", "for", "pubDate", ".", "In", "this", "case", "default", "to", "custom_date_string", "or", "today", "Use", "fallback", "in", "case", "a", "secondary", "date", ...
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L132-L153
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.translate_item
def translate_item(self, item_dict): """cleanup item keys to match API json format""" if not item_dict.get('title'): return None # Skip attachments if item_dict.get('{wp}post_type', None) == 'attachment': return None ret_dict = {} # slugify post title if no slug exists ret_dict['slug']= item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-') ret_dict['ID']= item_dict['guid'] ret_dict['title']= item_dict['title'] ret_dict['description']= item_dict['description'] ret_dict['content']= item_dict['{content}encoded'] # fake user object ret_dict['author']= {'username':item_dict['{dc}creator'], 'first_name':'', 'last_name':''} ret_dict['terms']= item_dict.get('terms') ret_dict['date']= self.convert_date( item_dict['pubDate'], fallback=item_dict.get('{wp}post_date','') ) return ret_dict
python
def translate_item(self, item_dict): """cleanup item keys to match API json format""" if not item_dict.get('title'): return None # Skip attachments if item_dict.get('{wp}post_type', None) == 'attachment': return None ret_dict = {} # slugify post title if no slug exists ret_dict['slug']= item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-') ret_dict['ID']= item_dict['guid'] ret_dict['title']= item_dict['title'] ret_dict['description']= item_dict['description'] ret_dict['content']= item_dict['{content}encoded'] # fake user object ret_dict['author']= {'username':item_dict['{dc}creator'], 'first_name':'', 'last_name':''} ret_dict['terms']= item_dict.get('terms') ret_dict['date']= self.convert_date( item_dict['pubDate'], fallback=item_dict.get('{wp}post_date','') ) return ret_dict
[ "def", "translate_item", "(", "self", ",", "item_dict", ")", ":", "if", "not", "item_dict", ".", "get", "(", "'title'", ")", ":", "return", "None", "# Skip attachments", "if", "item_dict", ".", "get", "(", "'{wp}post_type'", ",", "None", ")", "==", "'attac...
cleanup item keys to match API json format
[ "cleanup", "item", "keys", "to", "match", "API", "json", "format" ]
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L155-L178
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.translate_wp_comment
def translate_wp_comment(self, e): """ <wp:comment> <wp:comment_id>1234</wp:comment_id> <wp:comment_author><![CDATA[John Doe]]></wp:comment_author> <wp:comment_author_email><![CDATA[[email protected]]]></wp:comment_author_email> <wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url> <wp:comment_author_IP><![CDATA[12.123.123.123]]></wp:comment_author_IP> <wp:comment_date><![CDATA[2008-09-25 14:24:51]]></wp:comment_date> <wp:comment_date_gmt><![CDATA[2008-09-25 13:24:51]]></wp:comment_date_gmt> <wp:comment_content><![CDATA[Hey dude :)]]></wp:comment_content> <wp:comment_approved><![CDATA[1]]></wp:comment_approved> <wp:comment_type><![CDATA[]]></wp:comment_type> <wp:comment_parent>0</wp:comment_parent> <wp:comment_user_id>0</wp:comment_user_id> </wp:comment> """ comment_dict = {} comment_dict['ID'] = e.find('./{wp}comment_id').text comment_dict['date'] = e.find('{wp}comment_date').text comment_dict['content'] = e.find('{wp}comment_content').text comment_dict['status'] = e.find('{wp}comment_approved').text comment_dict['status'] = "approved" if comment_dict['status'] == "1" else "rejected" comment_dict['parent'] = e.find('{wp}comment_parent').text comment_dict['author'] = e.find('{wp}comment_author').text comment_dict['date'] = time.strptime(comment_dict['date'], '%Y-%m-%d %H:%M:%S') comment_dict['date'] = time.strftime('%Y-%m-%dT%H:%M:%S', comment_dict['date']) return comment_dict
python
def translate_wp_comment(self, e): """ <wp:comment> <wp:comment_id>1234</wp:comment_id> <wp:comment_author><![CDATA[John Doe]]></wp:comment_author> <wp:comment_author_email><![CDATA[[email protected]]]></wp:comment_author_email> <wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url> <wp:comment_author_IP><![CDATA[12.123.123.123]]></wp:comment_author_IP> <wp:comment_date><![CDATA[2008-09-25 14:24:51]]></wp:comment_date> <wp:comment_date_gmt><![CDATA[2008-09-25 13:24:51]]></wp:comment_date_gmt> <wp:comment_content><![CDATA[Hey dude :)]]></wp:comment_content> <wp:comment_approved><![CDATA[1]]></wp:comment_approved> <wp:comment_type><![CDATA[]]></wp:comment_type> <wp:comment_parent>0</wp:comment_parent> <wp:comment_user_id>0</wp:comment_user_id> </wp:comment> """ comment_dict = {} comment_dict['ID'] = e.find('./{wp}comment_id').text comment_dict['date'] = e.find('{wp}comment_date').text comment_dict['content'] = e.find('{wp}comment_content').text comment_dict['status'] = e.find('{wp}comment_approved').text comment_dict['status'] = "approved" if comment_dict['status'] == "1" else "rejected" comment_dict['parent'] = e.find('{wp}comment_parent').text comment_dict['author'] = e.find('{wp}comment_author').text comment_dict['date'] = time.strptime(comment_dict['date'], '%Y-%m-%d %H:%M:%S') comment_dict['date'] = time.strftime('%Y-%m-%dT%H:%M:%S', comment_dict['date']) return comment_dict
[ "def", "translate_wp_comment", "(", "self", ",", "e", ")", ":", "comment_dict", "=", "{", "}", "comment_dict", "[", "'ID'", "]", "=", "e", ".", "find", "(", "'./{wp}comment_id'", ")", ".", "text", "comment_dict", "[", "'date'", "]", "=", "e", ".", "fin...
<wp:comment> <wp:comment_id>1234</wp:comment_id> <wp:comment_author><![CDATA[John Doe]]></wp:comment_author> <wp:comment_author_email><![CDATA[[email protected]]]></wp:comment_author_email> <wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url> <wp:comment_author_IP><![CDATA[12.123.123.123]]></wp:comment_author_IP> <wp:comment_date><![CDATA[2008-09-25 14:24:51]]></wp:comment_date> <wp:comment_date_gmt><![CDATA[2008-09-25 13:24:51]]></wp:comment_date_gmt> <wp:comment_content><![CDATA[Hey dude :)]]></wp:comment_content> <wp:comment_approved><![CDATA[1]]></wp:comment_approved> <wp:comment_type><![CDATA[]]></wp:comment_type> <wp:comment_parent>0</wp:comment_parent> <wp:comment_user_id>0</wp:comment_user_id> </wp:comment>
[ "<wp", ":", "comment", ">", "<wp", ":", "comment_id", ">", "1234<", "/", "wp", ":", "comment_id", ">", "<wp", ":", "comment_author", ">", "<!", "[", "CDATA", "[", "John", "Doe", "]]", ">", "<", "/", "wp", ":", "comment_author", ">", "<wp", ":", "co...
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L181-L208
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.get_posts_data
def get_posts_data(self): """ given a WordPress xml export file, will return list of dictionaries with keys that match the expected json keys of a wordpress API call >>> xp = XML_parser('example_export.xml') >>> json_vals = {"slug","ID", "title","description", "content", "author", "terms", "date", } >>> data = xp.get_posts_data() >>> assert [ val in json_vals for val in data[0].keys() ] """ items = self.chan.findall("item") #(e for e in chan.getchildren() if e.tag=='item') # turn item element into a generic dict item_dict_gen = (self.item_dict(item) for item in items) # transform the generic dict to one with the expected JSON keys all_the_data = [self.translate_item(item) for item in item_dict_gen if self.translate_item(item)] return all_the_data
python
def get_posts_data(self): """ given a WordPress xml export file, will return list of dictionaries with keys that match the expected json keys of a wordpress API call >>> xp = XML_parser('example_export.xml') >>> json_vals = {"slug","ID", "title","description", "content", "author", "terms", "date", } >>> data = xp.get_posts_data() >>> assert [ val in json_vals for val in data[0].keys() ] """ items = self.chan.findall("item") #(e for e in chan.getchildren() if e.tag=='item') # turn item element into a generic dict item_dict_gen = (self.item_dict(item) for item in items) # transform the generic dict to one with the expected JSON keys all_the_data = [self.translate_item(item) for item in item_dict_gen if self.translate_item(item)] return all_the_data
[ "def", "get_posts_data", "(", "self", ")", ":", "items", "=", "self", ".", "chan", ".", "findall", "(", "\"item\"", ")", "#(e for e in chan.getchildren() if e.tag=='item')", "# turn item element into a generic dict", "item_dict_gen", "=", "(", "self", ".", "item_dict", ...
given a WordPress xml export file, will return list of dictionaries with keys that match the expected json keys of a wordpress API call >>> xp = XML_parser('example_export.xml') >>> json_vals = {"slug","ID", "title","description", "content", "author", "terms", "date", } >>> data = xp.get_posts_data() >>> assert [ val in json_vals for val in data[0].keys() ]
[ "given", "a", "WordPress", "xml", "export", "file", "will", "return", "list", "of", "dictionaries", "with", "keys", "that", "match", "the", "expected", "json", "keys", "of", "a", "wordpress", "API", "call", ">>>", "xp", "=", "XML_parser", "(", "example_expor...
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L211-L226
thelabnyc/wagtail_blog
blog/wp_xml_parser.py
XML_parser.get_comments_data
def get_comments_data(self, slug): """ Returns a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API. Keys: ('content', 'slug', 'date', 'status', 'author', 'ID', 'parent') date format: '%Y-%m-%dT%H:%M:%S' author: {'username': 'Name', 'URL': ''} """ all_the_data = [] for item in self.chan.findall("item"): if not item.find('{wp}post_name').text == slug: continue item_dict = self.item_dict(item) if not item_dict or not item_dict.get('title'): continue slug = item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-') for comment in item.findall("{wp}comment"): comment = self.translate_wp_comment(comment) comment['slug'] = slug all_the_data.append(comment) return all_the_data
python
def get_comments_data(self, slug): """ Returns a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API. Keys: ('content', 'slug', 'date', 'status', 'author', 'ID', 'parent') date format: '%Y-%m-%dT%H:%M:%S' author: {'username': 'Name', 'URL': ''} """ all_the_data = [] for item in self.chan.findall("item"): if not item.find('{wp}post_name').text == slug: continue item_dict = self.item_dict(item) if not item_dict or not item_dict.get('title'): continue slug = item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-') for comment in item.findall("{wp}comment"): comment = self.translate_wp_comment(comment) comment['slug'] = slug all_the_data.append(comment) return all_the_data
[ "def", "get_comments_data", "(", "self", ",", "slug", ")", ":", "all_the_data", "=", "[", "]", "for", "item", "in", "self", ".", "chan", ".", "findall", "(", "\"item\"", ")", ":", "if", "not", "item", ".", "find", "(", "'{wp}post_name'", ")", ".", "t...
Returns a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API. Keys: ('content', 'slug', 'date', 'status', 'author', 'ID', 'parent') date format: '%Y-%m-%dT%H:%M:%S' author: {'username': 'Name', 'URL': ''}
[ "Returns", "a", "flat", "list", "of", "all", "comments", "in", "XML", "dump", ".", "Formatted", "as", "the", "JSON", "output", "from", "Wordpress", "API", ".", "Keys", ":", "(", "content", "slug", "date", "status", "author", "ID", "parent", ")", "date", ...
train
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L229-L253
ajenhl/tacl
tacl/highlighter.py
HighlightReport._format_content
def _format_content(self, content): """Returns `content` with consecutive spaces converted to non-break spaces, and linebreak converted into HTML br elements. :param content: text to format :type content: `str` :rtype: `str` """ content = re.sub(r'\n', '<br/>\n', content) content = re.sub(r' ', '&#160;&#160;', content) content = re.sub(r'&#160; ', '&#160;&#160;', content) return content
python
def _format_content(self, content): """Returns `content` with consecutive spaces converted to non-break spaces, and linebreak converted into HTML br elements. :param content: text to format :type content: `str` :rtype: `str` """ content = re.sub(r'\n', '<br/>\n', content) content = re.sub(r' ', '&#160;&#160;', content) content = re.sub(r'&#160; ', '&#160;&#160;', content) return content
[ "def", "_format_content", "(", "self", ",", "content", ")", ":", "content", "=", "re", ".", "sub", "(", "r'\\n'", ",", "'<br/>\\n'", ",", "content", ")", "content", "=", "re", ".", "sub", "(", "r' '", ",", "'&#160;&#160;'", ",", "content", ")", "conte...
Returns `content` with consecutive spaces converted to non-break spaces, and linebreak converted into HTML br elements. :param content: text to format :type content: `str` :rtype: `str`
[ "Returns", "content", "with", "consecutive", "spaces", "converted", "to", "non", "-", "break", "spaces", "and", "linebreak", "converted", "into", "HTML", "br", "elements", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L24-L36
ajenhl/tacl
tacl/highlighter.py
HighlightReport._prepare_text
def _prepare_text(self, text): """Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str` """ # Remove characters that should be escaped for XML input (but # which cause problems when escaped, since they become # tokens). text = re.sub(r'[<>&]', '', text) pattern = r'({})'.format(self._tokenizer.pattern) return re.sub(pattern, self._base_token_markup, text)
python
def _prepare_text(self, text): """Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str` """ # Remove characters that should be escaped for XML input (but # which cause problems when escaped, since they become # tokens). text = re.sub(r'[<>&]', '', text) pattern = r'({})'.format(self._tokenizer.pattern) return re.sub(pattern, self._base_token_markup, text)
[ "def", "_prepare_text", "(", "self", ",", "text", ")", ":", "# Remove characters that should be escaped for XML input (but", "# which cause problems when escaped, since they become", "# tokens).", "text", "=", "re", ".", "sub", "(", "r'[<>&]'", ",", "''", ",", "text", ")"...
Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str`
[ "Returns", "text", "with", "each", "consituent", "token", "wrapped", "in", "HTML", "markup", "for", "later", "match", "annotation", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L52-L66
ajenhl/tacl
tacl/highlighter.py
NgramHighlightReport.generate
def generate(self, output_dir, work, ngrams, labels, minus_ngrams): """Generates HTML reports for each witness to `work`, showing its text with the n-grams in `ngrams` highlighted. Any n-grams in `minus_ngrams` have any highlighting of them (or subsets of them) removed. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type work: `str` :param ngrams: groups of n-grams to highlight :type ngrams: `list` of `list` of `str` :param labels: labels for the groups of n-grams :type labels: `list` of `str` :param minus_ngrams: n-grams to remove highlighting from :type minus_ngrams: `list` of `str` :rtype: `str` """ template = self._get_template() colours = generate_colours(len(ngrams)) for siglum in self._corpus.get_sigla(work): ngram_data = zip(labels, ngrams) content = self._generate_base(work, siglum) for ngrams_group in ngrams: content = self._highlight(content, ngrams_group, True) content = self._highlight(content, minus_ngrams, False) self._ngrams_count = 1 content = self._format_content(content) report_name = '{}-{}.html'.format(work, siglum) self._write(work, siglum, content, output_dir, report_name, template, ngram_data=ngram_data, minus_ngrams=minus_ngrams, colours=colours)
python
def generate(self, output_dir, work, ngrams, labels, minus_ngrams): """Generates HTML reports for each witness to `work`, showing its text with the n-grams in `ngrams` highlighted. Any n-grams in `minus_ngrams` have any highlighting of them (or subsets of them) removed. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type work: `str` :param ngrams: groups of n-grams to highlight :type ngrams: `list` of `list` of `str` :param labels: labels for the groups of n-grams :type labels: `list` of `str` :param minus_ngrams: n-grams to remove highlighting from :type minus_ngrams: `list` of `str` :rtype: `str` """ template = self._get_template() colours = generate_colours(len(ngrams)) for siglum in self._corpus.get_sigla(work): ngram_data = zip(labels, ngrams) content = self._generate_base(work, siglum) for ngrams_group in ngrams: content = self._highlight(content, ngrams_group, True) content = self._highlight(content, minus_ngrams, False) self._ngrams_count = 1 content = self._format_content(content) report_name = '{}-{}.html'.format(work, siglum) self._write(work, siglum, content, output_dir, report_name, template, ngram_data=ngram_data, minus_ngrams=minus_ngrams, colours=colours)
[ "def", "generate", "(", "self", ",", "output_dir", ",", "work", ",", "ngrams", ",", "labels", ",", "minus_ngrams", ")", ":", "template", "=", "self", ".", "_get_template", "(", ")", "colours", "=", "generate_colours", "(", "len", "(", "ngrams", ")", ")",...
Generates HTML reports for each witness to `work`, showing its text with the n-grams in `ngrams` highlighted. Any n-grams in `minus_ngrams` have any highlighting of them (or subsets of them) removed. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type work: `str` :param ngrams: groups of n-grams to highlight :type ngrams: `list` of `list` of `str` :param labels: labels for the groups of n-grams :type labels: `list` of `str` :param minus_ngrams: n-grams to remove highlighting from :type minus_ngrams: `list` of `str` :rtype: `str`
[ "Generates", "HTML", "reports", "for", "each", "witness", "to", "work", "showing", "its", "text", "with", "the", "n", "-", "grams", "in", "ngrams", "highlighted", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L94-L127
ajenhl/tacl
tacl/highlighter.py
NgramHighlightReport._highlight
def _highlight(self, content, ngrams, highlight): """Returns `content` with its n-grams from `ngrams` highlighted (if `add_class` is True) or unhighlighted. :param content: text to be modified :type content: `str` :param ngrams: n-grams to modify :type ngrams: `list` of `str` :param highlight: whether to highlight or unhighlight `ngrams` :type highlight: `bool` :rtype: `str` """ self._add_highlight = highlight for ngram in ngrams: pattern = self._get_regexp_pattern(ngram) content = re.sub(pattern, self._annotate_tokens, content) self._ngrams_count += 1 return content
python
def _highlight(self, content, ngrams, highlight): """Returns `content` with its n-grams from `ngrams` highlighted (if `add_class` is True) or unhighlighted. :param content: text to be modified :type content: `str` :param ngrams: n-grams to modify :type ngrams: `list` of `str` :param highlight: whether to highlight or unhighlight `ngrams` :type highlight: `bool` :rtype: `str` """ self._add_highlight = highlight for ngram in ngrams: pattern = self._get_regexp_pattern(ngram) content = re.sub(pattern, self._annotate_tokens, content) self._ngrams_count += 1 return content
[ "def", "_highlight", "(", "self", ",", "content", ",", "ngrams", ",", "highlight", ")", ":", "self", ".", "_add_highlight", "=", "highlight", "for", "ngram", "in", "ngrams", ":", "pattern", "=", "self", ".", "_get_regexp_pattern", "(", "ngram", ")", "conte...
Returns `content` with its n-grams from `ngrams` highlighted (if `add_class` is True) or unhighlighted. :param content: text to be modified :type content: `str` :param ngrams: n-grams to modify :type ngrams: `list` of `str` :param highlight: whether to highlight or unhighlight `ngrams` :type highlight: `bool` :rtype: `str`
[ "Returns", "content", "with", "its", "n", "-", "grams", "from", "ngrams", "highlighted", "(", "if", "add_class", "is", "True", ")", "or", "unhighlighted", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L129-L147
ajenhl/tacl
tacl/highlighter.py
ResultsHighlightReport.generate
def generate(self, output_dir, work, matches_filename): """Generates HTML reports showing the text of each witness to `work` with its matches in `matches` highlighted. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type text_name: `str` :param matches_filename: file containing matches to highlight :type matches_filename: `str` :rtype: `str` """ template = self._get_template() matches = pd.read_csv(matches_filename) for siglum in self._corpus.get_sigla(work): subm = matches[(matches[constants.WORK_FIELDNAME] != work) | (matches[constants.SIGLUM_FIELDNAME] != siglum)] content = self._generate_base(work, siglum) content = self._highlight(content, subm) content = self._format_content(content) text_list = self._generate_text_list(subm) report_name = '{}-{}.html'.format(work, siglum) self._write(work, siglum, content, output_dir, report_name, template, True, text_list=text_list)
python
def generate(self, output_dir, work, matches_filename): """Generates HTML reports showing the text of each witness to `work` with its matches in `matches` highlighted. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type text_name: `str` :param matches_filename: file containing matches to highlight :type matches_filename: `str` :rtype: `str` """ template = self._get_template() matches = pd.read_csv(matches_filename) for siglum in self._corpus.get_sigla(work): subm = matches[(matches[constants.WORK_FIELDNAME] != work) | (matches[constants.SIGLUM_FIELDNAME] != siglum)] content = self._generate_base(work, siglum) content = self._highlight(content, subm) content = self._format_content(content) text_list = self._generate_text_list(subm) report_name = '{}-{}.html'.format(work, siglum) self._write(work, siglum, content, output_dir, report_name, template, True, text_list=text_list)
[ "def", "generate", "(", "self", ",", "output_dir", ",", "work", ",", "matches_filename", ")", ":", "template", "=", "self", ".", "_get_template", "(", ")", "matches", "=", "pd", ".", "read_csv", "(", "matches_filename", ")", "for", "siglum", "in", "self", ...
Generates HTML reports showing the text of each witness to `work` with its matches in `matches` highlighted. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type text_name: `str` :param matches_filename: file containing matches to highlight :type matches_filename: `str` :rtype: `str`
[ "Generates", "HTML", "reports", "showing", "the", "text", "of", "each", "witness", "to", "work", "with", "its", "matches", "in", "matches", "highlighted", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L175-L199
SuperCowPowers/chains
chains/links/packet_meta.py
PacketMeta.packet_meta_data
def packet_meta_data(self): """Pull out the metadata about each packet from the input_stream Args: None Returns: generator (dictionary): a generator that contains packet meta data in the form of a dictionary""" # For each packet in the pcap process the contents for item in self.input_stream: # Output object output = {} # Grab the fields I need timestamp = item['timestamp'] buf = item['raw_buf'] # Print out the timestamp in UTC output['timestamp'] = datetime.datetime.utcfromtimestamp(timestamp) # Unpack the Ethernet frame (mac src/dst, ethertype) eth = dpkt.ethernet.Ethernet(buf) output['eth'] = {'src': eth.src, 'dst': eth.dst, 'type':eth.type, 'len': len(eth)} # Grab packet data packet = eth.data # Packet Type ('EtherType') (IP, ARP, PPPoE, IP6... see http://en.wikipedia.org/wiki/EtherType) if hasattr(packet, 'data'): output['packet'] = {'type': packet.__class__.__name__, 'data': packet.data} else: output['packet'] = {'type': None, 'data': None} # It this an IP packet? if output['packet']['type'] == 'IP': # Pull out fragment information (flags and offset all packed into off field, so use bitmasks) df = bool(packet.off & dpkt.ip.IP_DF) mf = bool(packet.off & dpkt.ip.IP_MF) offset = packet.off & dpkt.ip.IP_OFFMASK # Pulling out src, dst, length, fragment info, TTL, checksum and Protocol output['packet'].update({'src':packet.src, 'dst':packet.dst, 'p': packet.p, 'len':packet.len, 'ttl':packet.ttl, 'df':df, 'mf': mf, 'offset': offset, 'checksum': packet.sum}) # Is this an IPv6 packet? elif output['packet']['type'] == 'IP6': # Pulling out the IP6 fields output['packet'].update({'src':packet.src, 'dst':packet.dst, 'p': packet.p, 'len':packet.plen, 'ttl':packet.hlim}) # If the packet isn't IP or IPV6 just pack it as a dictionary else: output['packet'].update(data_utils.make_dict(packet)) # For the transport layer we're going to set the transport to None. and # hopefully a 'link' upstream will manage the transport functionality output['transport'] = None # For the application layer we're going to set the application to None. and # hopefully a 'link' upstream will manage the application functionality output['application'] = None # All done yield output
python
def packet_meta_data(self): """Pull out the metadata about each packet from the input_stream Args: None Returns: generator (dictionary): a generator that contains packet meta data in the form of a dictionary""" # For each packet in the pcap process the contents for item in self.input_stream: # Output object output = {} # Grab the fields I need timestamp = item['timestamp'] buf = item['raw_buf'] # Print out the timestamp in UTC output['timestamp'] = datetime.datetime.utcfromtimestamp(timestamp) # Unpack the Ethernet frame (mac src/dst, ethertype) eth = dpkt.ethernet.Ethernet(buf) output['eth'] = {'src': eth.src, 'dst': eth.dst, 'type':eth.type, 'len': len(eth)} # Grab packet data packet = eth.data # Packet Type ('EtherType') (IP, ARP, PPPoE, IP6... see http://en.wikipedia.org/wiki/EtherType) if hasattr(packet, 'data'): output['packet'] = {'type': packet.__class__.__name__, 'data': packet.data} else: output['packet'] = {'type': None, 'data': None} # It this an IP packet? if output['packet']['type'] == 'IP': # Pull out fragment information (flags and offset all packed into off field, so use bitmasks) df = bool(packet.off & dpkt.ip.IP_DF) mf = bool(packet.off & dpkt.ip.IP_MF) offset = packet.off & dpkt.ip.IP_OFFMASK # Pulling out src, dst, length, fragment info, TTL, checksum and Protocol output['packet'].update({'src':packet.src, 'dst':packet.dst, 'p': packet.p, 'len':packet.len, 'ttl':packet.ttl, 'df':df, 'mf': mf, 'offset': offset, 'checksum': packet.sum}) # Is this an IPv6 packet? elif output['packet']['type'] == 'IP6': # Pulling out the IP6 fields output['packet'].update({'src':packet.src, 'dst':packet.dst, 'p': packet.p, 'len':packet.plen, 'ttl':packet.hlim}) # If the packet isn't IP or IPV6 just pack it as a dictionary else: output['packet'].update(data_utils.make_dict(packet)) # For the transport layer we're going to set the transport to None. and # hopefully a 'link' upstream will manage the transport functionality output['transport'] = None # For the application layer we're going to set the application to None. and # hopefully a 'link' upstream will manage the application functionality output['application'] = None # All done yield output
[ "def", "packet_meta_data", "(", "self", ")", ":", "# For each packet in the pcap process the contents", "for", "item", "in", "self", ".", "input_stream", ":", "# Output object", "output", "=", "{", "}", "# Grab the fields I need", "timestamp", "=", "item", "[", "'time...
Pull out the metadata about each packet from the input_stream Args: None Returns: generator (dictionary): a generator that contains packet meta data in the form of a dictionary
[ "Pull", "out", "the", "metadata", "about", "each", "packet", "from", "the", "input_stream", "Args", ":", "None", "Returns", ":", "generator", "(", "dictionary", ")", ":", "a", "generator", "that", "contains", "packet", "meta", "data", "in", "the", "form", ...
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_meta.py#L23-L87
SuperCowPowers/chains
chains/links/flows.py
print_flow_info
def print_flow_info(flow): """Print a summary of the flow information""" print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']), len(flow['payload']), repr(flow['payload'])[:30]))
python
def print_flow_info(flow): """Print a summary of the flow information""" print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']), len(flow['payload']), repr(flow['payload'])[:30]))
[ "def", "print_flow_info", "(", "flow", ")", ":", "print", "(", "'Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...'", "%", "(", "flow", "[", "'flow_id'", "]", ",", "flow", "[", "'direction'", "]", ",", "len", "(", "flow", "[", "'packet_list'", "]", ")", ",", ...
Print a summary of the flow information
[ "Print", "a", "summary", "of", "the", "flow", "information" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/flows.py#L52-L55
SuperCowPowers/chains
chains/links/flows.py
Flows.packets_to_flows
def packets_to_flows(self): """Combine packets into flows""" # For each packet, place it into either an existing flow or a new flow for packet in self.input_stream: # Compute flow tuple and add the packet to the flow flow_id = flow_utils.flow_tuple(packet) self._flows[flow_id].add_packet(packet) # Yield flows that are ready to go for flow in list(self._flows.values()): if flow.ready(): flow_info = flow.get_flow() yield flow_info del self._flows[flow_info['flow_id']] # All done so just dump what we have left print('---- NO MORE INPUT ----') for flow in sorted(self._flows.values(), key=lambda x: x.meta['start']): yield flow.get_flow()
python
def packets_to_flows(self): """Combine packets into flows""" # For each packet, place it into either an existing flow or a new flow for packet in self.input_stream: # Compute flow tuple and add the packet to the flow flow_id = flow_utils.flow_tuple(packet) self._flows[flow_id].add_packet(packet) # Yield flows that are ready to go for flow in list(self._flows.values()): if flow.ready(): flow_info = flow.get_flow() yield flow_info del self._flows[flow_info['flow_id']] # All done so just dump what we have left print('---- NO MORE INPUT ----') for flow in sorted(self._flows.values(), key=lambda x: x.meta['start']): yield flow.get_flow()
[ "def", "packets_to_flows", "(", "self", ")", ":", "# For each packet, place it into either an existing flow or a new flow", "for", "packet", "in", "self", ".", "input_stream", ":", "# Compute flow tuple and add the packet to the flow", "flow_id", "=", "flow_utils", ".", "flow_t...
Combine packets into flows
[ "Combine", "packets", "into", "flows" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/flows.py#L30-L50
ajenhl/tacl
tacl/report.py
Report._copy_static_assets
def _copy_static_assets(self, output_dir): """Copy assets for the report to `output_dir`. :param output_dir: directory to output assets to :type output_dir: `str` """ base_directory = 'assets/{}'.format(self._report_name) for asset in resource_listdir(self._package_name, base_directory): filename = resource_filename( self._package_name, '{}/{}'.format(base_directory, asset)) shutil.copy2(filename, output_dir)
python
def _copy_static_assets(self, output_dir): """Copy assets for the report to `output_dir`. :param output_dir: directory to output assets to :type output_dir: `str` """ base_directory = 'assets/{}'.format(self._report_name) for asset in resource_listdir(self._package_name, base_directory): filename = resource_filename( self._package_name, '{}/{}'.format(base_directory, asset)) shutil.copy2(filename, output_dir)
[ "def", "_copy_static_assets", "(", "self", ",", "output_dir", ")", ":", "base_directory", "=", "'assets/{}'", ".", "format", "(", "self", ".", "_report_name", ")", "for", "asset", "in", "resource_listdir", "(", "self", ".", "_package_name", ",", "base_directory"...
Copy assets for the report to `output_dir`. :param output_dir: directory to output assets to :type output_dir: `str`
[ "Copy", "assets", "for", "the", "report", "to", "output_dir", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L29-L40
ajenhl/tacl
tacl/report.py
Report._get_template
def _get_template(self): """Returns a template for this report. :rtype: `jinja2.Template` """ loader = PackageLoader(self._package_name, 'assets/templates') env = Environment(extensions=['jinja2.ext.with_'], loader=loader) return env.get_template('{}.html'.format(self._report_name))
python
def _get_template(self): """Returns a template for this report. :rtype: `jinja2.Template` """ loader = PackageLoader(self._package_name, 'assets/templates') env = Environment(extensions=['jinja2.ext.with_'], loader=loader) return env.get_template('{}.html'.format(self._report_name))
[ "def", "_get_template", "(", "self", ")", ":", "loader", "=", "PackageLoader", "(", "self", ".", "_package_name", ",", "'assets/templates'", ")", "env", "=", "Environment", "(", "extensions", "=", "[", "'jinja2.ext.with_'", "]", ",", "loader", "=", "loader", ...
Returns a template for this report. :rtype: `jinja2.Template`
[ "Returns", "a", "template", "for", "this", "report", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L46-L54
ajenhl/tacl
tacl/report.py
Report._write
def _write(self, context, report_dir, report_name, assets_dir=None, template=None): """Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. If `template` is supplied, uses that template instead of automatically finding it. This is useful if a single report generates multiple files using the same template. :param context: context data to render within the template :type context: `dict` :param report_dir: directory to write the report to :type report_dir: `str` :param report_name: name of file to write the report to :type report_name: `str` :param assets_dir: optional directory to output report assets to :type assets_dir: `str` :param template: template to render and output :type template: `jinja2.Template` """ if template is None: template = self._get_template() report = template.render(context) output_file = os.path.join(report_dir, report_name) with open(output_file, 'w', encoding='utf-8') as fh: fh.write(report) if assets_dir: self._copy_static_assets(assets_dir)
python
def _write(self, context, report_dir, report_name, assets_dir=None, template=None): """Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. If `template` is supplied, uses that template instead of automatically finding it. This is useful if a single report generates multiple files using the same template. :param context: context data to render within the template :type context: `dict` :param report_dir: directory to write the report to :type report_dir: `str` :param report_name: name of file to write the report to :type report_name: `str` :param assets_dir: optional directory to output report assets to :type assets_dir: `str` :param template: template to render and output :type template: `jinja2.Template` """ if template is None: template = self._get_template() report = template.render(context) output_file = os.path.join(report_dir, report_name) with open(output_file, 'w', encoding='utf-8') as fh: fh.write(report) if assets_dir: self._copy_static_assets(assets_dir)
[ "def", "_write", "(", "self", ",", "context", ",", "report_dir", ",", "report_name", ",", "assets_dir", "=", "None", ",", "template", "=", "None", ")", ":", "if", "template", "is", "None", ":", "template", "=", "self", ".", "_get_template", "(", ")", "...
Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. If `template` is supplied, uses that template instead of automatically finding it. This is useful if a single report generates multiple files using the same template. :param context: context data to render within the template :type context: `dict` :param report_dir: directory to write the report to :type report_dir: `str` :param report_name: name of file to write the report to :type report_name: `str` :param assets_dir: optional directory to output report assets to :type assets_dir: `str` :param template: template to render and output :type template: `jinja2.Template`
[ "Writes", "the", "data", "in", "context", "in", "the", "report", "s", "template", "to", "report_name", "in", "report_dir", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L56-L87
SuperCowPowers/chains
chains/sinks/packet_summary.py
PacketSummary.pull
def pull(self): """Print out summary information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('%s -' % item['timestamp'], end='') # Transport info if item['transport']: print(item['transport']['type'], end='') # Print out the Packet info packet_type = item['packet']['type'] print(packet_type, end='') packet = item['packet'] if packet_type in ['IP', 'IP6']: # Is there domain info? if 'src_domain' in packet: print('%s(%s) --> %s(%s)' % (net_utils.inet_to_str(packet['src']), packet['src_domain'], net_utils.inet_to_str(packet['dst']), packet['dst_domain']), end='') else: print('%s --> %s' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst'])), end='') else: print(str(packet)) # Only include application if we have it if item['application']: print('Application: %s' % item['application']['type'], end='') print(str(item['application']), end='') # Just for newline print()
python
def pull(self): """Print out summary information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('%s -' % item['timestamp'], end='') # Transport info if item['transport']: print(item['transport']['type'], end='') # Print out the Packet info packet_type = item['packet']['type'] print(packet_type, end='') packet = item['packet'] if packet_type in ['IP', 'IP6']: # Is there domain info? if 'src_domain' in packet: print('%s(%s) --> %s(%s)' % (net_utils.inet_to_str(packet['src']), packet['src_domain'], net_utils.inet_to_str(packet['dst']), packet['dst_domain']), end='') else: print('%s --> %s' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst'])), end='') else: print(str(packet)) # Only include application if we have it if item['application']: print('Application: %s' % item['application']['type'], end='') print(str(item['application']), end='') # Just for newline print()
[ "def", "pull", "(", "self", ")", ":", "# For each packet in the pcap process the contents", "for", "item", "in", "self", ".", "input_stream", ":", "# Print out the timestamp in UTC", "print", "(", "'%s -'", "%", "item", "[", "'timestamp'", "]", ",", "end", "=", "'...
Print out summary information about each packet from the input_stream
[ "Print", "out", "summary", "information", "about", "each", "packet", "from", "the", "input_stream" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/sinks/packet_summary.py#L17-L50
SuperCowPowers/chains
chains/sinks/packet_printer.py
PacketPrinter.pull
def pull(self): """Print out information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('Timestamp: %s' % item['timestamp']) # Unpack the Ethernet frame (mac src/dst, ethertype) print('Ethernet Frame: %s --> %s (type: %d)' % \ (net_utils.mac_to_str(item['eth']['src']), net_utils.mac_to_str(item['eth']['dst']), item['eth']['type'])) # Print out the Packet info packet_type = item['packet']['type'] print('Packet: %s ' % packet_type, end='') packet = item['packet'] if packet_type in ['IP', 'IP6']: print('%s --> %s (len:%d ttl:%d)' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst']), packet['len'], packet['ttl']), end='') if packet_type == 'IP': print('-- Frag(df:%d mf:%d offset:%d)' % (packet['df'], packet['mf'], packet['offset'])) else: print() else: print(str(packet)) # Print out transport and application layers if item['transport']: transport_info = item['transport'] print('Transport: %s ' % transport_info['type'], end='') for key, value in compat.iteritems(transport_info): if key != 'data': print(key+':'+repr(value), end=' ') # Give summary info about data data = transport_info['data'] print('\nData: %d bytes' % len(data), end='') if data: print('(%s...)' % repr(data)[:30]) else: print() # Application data if item['application']: print('Application: %s' % item['application']['type'], end='') print(str(item['application'])) # Is there domain info? if 'src_domain' in packet: print('Domains: %s --> %s' % (packet['src_domain'], packet['dst_domain'])) # Tags if 'tags' in item: print(list(item['tags'])) print()
python
def pull(self): """Print out information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('Timestamp: %s' % item['timestamp']) # Unpack the Ethernet frame (mac src/dst, ethertype) print('Ethernet Frame: %s --> %s (type: %d)' % \ (net_utils.mac_to_str(item['eth']['src']), net_utils.mac_to_str(item['eth']['dst']), item['eth']['type'])) # Print out the Packet info packet_type = item['packet']['type'] print('Packet: %s ' % packet_type, end='') packet = item['packet'] if packet_type in ['IP', 'IP6']: print('%s --> %s (len:%d ttl:%d)' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst']), packet['len'], packet['ttl']), end='') if packet_type == 'IP': print('-- Frag(df:%d mf:%d offset:%d)' % (packet['df'], packet['mf'], packet['offset'])) else: print() else: print(str(packet)) # Print out transport and application layers if item['transport']: transport_info = item['transport'] print('Transport: %s ' % transport_info['type'], end='') for key, value in compat.iteritems(transport_info): if key != 'data': print(key+':'+repr(value), end=' ') # Give summary info about data data = transport_info['data'] print('\nData: %d bytes' % len(data), end='') if data: print('(%s...)' % repr(data)[:30]) else: print() # Application data if item['application']: print('Application: %s' % item['application']['type'], end='') print(str(item['application'])) # Is there domain info? if 'src_domain' in packet: print('Domains: %s --> %s' % (packet['src_domain'], packet['dst_domain'])) # Tags if 'tags' in item: print(list(item['tags'])) print()
[ "def", "pull", "(", "self", ")", ":", "# For each packet in the pcap process the contents", "for", "item", "in", "self", ".", "input_stream", ":", "# Print out the timestamp in UTC", "print", "(", "'Timestamp: %s'", "%", "item", "[", "'timestamp'", "]", ")", "# Unpack...
Print out information about each packet from the input_stream
[ "Print", "out", "information", "about", "each", "packet", "from", "the", "input_stream" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/sinks/packet_printer.py#L21-L76
peeringdb/django-peeringdb
django_peeringdb/client_adaptor/load.py
load_backend
def load_backend(**orm_config): """ Load the client adaptor module of django_peeringdb Assumes config is valid. """ settings = {} settings['SECRET_KEY'] = orm_config.get('secret_key', '') db_config = orm_config['database'] if db_config: settings['DATABASES'] = { 'default': database_settings(db_config) } from django_peeringdb.client_adaptor.setup import configure # Override defaults configure(**settings) # Must import implementation module after configure from django_peeringdb.client_adaptor import backend migrate = orm_config.get("migrate") if migrate and not backend.Backend().is_database_migrated(): backend.Backend().migrate_database() return backend
python
def load_backend(**orm_config): """ Load the client adaptor module of django_peeringdb Assumes config is valid. """ settings = {} settings['SECRET_KEY'] = orm_config.get('secret_key', '') db_config = orm_config['database'] if db_config: settings['DATABASES'] = { 'default': database_settings(db_config) } from django_peeringdb.client_adaptor.setup import configure # Override defaults configure(**settings) # Must import implementation module after configure from django_peeringdb.client_adaptor import backend migrate = orm_config.get("migrate") if migrate and not backend.Backend().is_database_migrated(): backend.Backend().migrate_database() return backend
[ "def", "load_backend", "(", "*", "*", "orm_config", ")", ":", "settings", "=", "{", "}", "settings", "[", "'SECRET_KEY'", "]", "=", "orm_config", ".", "get", "(", "'secret_key'", ",", "''", ")", "db_config", "=", "orm_config", "[", "'database'", "]", "if...
Load the client adaptor module of django_peeringdb Assumes config is valid.
[ "Load", "the", "client", "adaptor", "module", "of", "django_peeringdb", "Assumes", "config", "is", "valid", "." ]
train
https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/load.py#L22-L46
ajenhl/tacl
tacl/results.py
Results.add_label_count
def add_label_count(self): """Adds to each result row a count of the number of occurrences of that n-gram across all works within the label. This count uses the highest witness count for each work. """ self._logger.info('Adding label count') def add_label_count(df): # For each n-gram and label pair, we need the maximum count # among all witnesses to each work, and then the sum of those # across all works. work_maxima = df.groupby(constants.WORK_FIELDNAME, sort=False).max() df.loc[:, constants.LABEL_COUNT_FIELDNAME] = work_maxima[ constants.COUNT_FIELDNAME].sum() return df if self._matches.empty: self._matches[constants.LABEL_COUNT_FIELDNAME] = 0 else: self._matches.loc[:, constants.LABEL_COUNT_FIELDNAME] = 0 self._matches = self._matches.groupby( [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME], sort=False).apply(add_label_count) self._logger.info('Finished adding label count')
python
def add_label_count(self): """Adds to each result row a count of the number of occurrences of that n-gram across all works within the label. This count uses the highest witness count for each work. """ self._logger.info('Adding label count') def add_label_count(df): # For each n-gram and label pair, we need the maximum count # among all witnesses to each work, and then the sum of those # across all works. work_maxima = df.groupby(constants.WORK_FIELDNAME, sort=False).max() df.loc[:, constants.LABEL_COUNT_FIELDNAME] = work_maxima[ constants.COUNT_FIELDNAME].sum() return df if self._matches.empty: self._matches[constants.LABEL_COUNT_FIELDNAME] = 0 else: self._matches.loc[:, constants.LABEL_COUNT_FIELDNAME] = 0 self._matches = self._matches.groupby( [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME], sort=False).apply(add_label_count) self._logger.info('Finished adding label count')
[ "def", "add_label_count", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Adding label count'", ")", "def", "add_label_count", "(", "df", ")", ":", "# For each n-gram and label pair, we need the maximum count", "# among all witnesses to each work, and the...
Adds to each result row a count of the number of occurrences of that n-gram across all works within the label. This count uses the highest witness count for each work.
[ "Adds", "to", "each", "result", "row", "a", "count", "of", "the", "number", "of", "occurrences", "of", "that", "n", "-", "gram", "across", "all", "works", "within", "the", "label", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L58-L84
ajenhl/tacl
tacl/results.py
Results.add_label_work_count
def add_label_work_count(self): """Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a given work (possible with zero-fill followed by filtering by maximum count). """ self._logger.info('Adding label work count') def add_label_text_count(df): work_maxima = df.groupby(constants.WORK_FIELDNAME, sort=False).any() df.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = work_maxima[ constants.COUNT_FIELDNAME].sum() return df if self._matches.empty: self._matches[constants.LABEL_WORK_COUNT_FIELDNAME] = 0 else: self._matches.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = 0 self._matches = self._matches.groupby( [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME], sort=False).apply(add_label_text_count) self._logger.info('Finished adding label work count')
python
def add_label_work_count(self): """Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a given work (possible with zero-fill followed by filtering by maximum count). """ self._logger.info('Adding label work count') def add_label_text_count(df): work_maxima = df.groupby(constants.WORK_FIELDNAME, sort=False).any() df.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = work_maxima[ constants.COUNT_FIELDNAME].sum() return df if self._matches.empty: self._matches[constants.LABEL_WORK_COUNT_FIELDNAME] = 0 else: self._matches.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = 0 self._matches = self._matches.groupby( [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME], sort=False).apply(add_label_text_count) self._logger.info('Finished adding label work count')
[ "def", "add_label_work_count", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Adding label work count'", ")", "def", "add_label_text_count", "(", "df", ")", ":", "work_maxima", "=", "df", ".", "groupby", "(", "constants", ".", "WORK_FIELDNA...
Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a given work (possible with zero-fill followed by filtering by maximum count).
[ "Adds", "to", "each", "result", "row", "a", "count", "of", "the", "number", "of", "works", "within", "the", "label", "contain", "that", "n", "-", "gram", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L88-L116
ajenhl/tacl
tacl/results.py
Results._annotate_bifurcated_extend_data
def _annotate_bifurcated_extend_data(self, row, smaller, larger, tokenize, join): """Returns `row` annotated with whether it should be deleted or not. An n-gram is marked for deletion if: * its label count is 1 and its constituent (n-1)-grams also have a label count of 1; or * there is a containing (n+1)-gram that has the same label count. :param row: row of witness n-grams to annotate :type row: `pandas.Series` :param smaller: rows of (n-1)-grams for this witness :type smaller: `pandas.DataFrame` :param larger: rows of (n+1)-grams for this witness :type larger: `pandas.DataFrame` :param tokenize: function to tokenize an n-gram :param join: function to join tokens :rtype: `pandas.Series` """ lcf = constants.LABEL_COUNT_FIELDNAME nf = constants.NGRAM_FIELDNAME ngram = row[constants.NGRAM_FIELDNAME] label_count = row[constants.LABEL_COUNT_FIELDNAME] if label_count == 1 and not smaller.empty: # Keep a result with a label count of 1 if its # constituents do not also have a count of 1. ngram_tokens = tokenize(ngram) sub_ngram1 = join(ngram_tokens[:-1]) sub_ngram2 = join(ngram_tokens[1:]) pattern = FilteredWitnessText.get_filter_ngrams_pattern( [sub_ngram1, sub_ngram2]) if smaller[smaller[constants.NGRAM_FIELDNAME].str.match(pattern)][ constants.LABEL_COUNT_FIELDNAME].max() == 1: row[DELETE_FIELDNAME] = True elif not larger.empty and larger[larger[nf].str.contains( ngram, regex=False)][lcf].max() == label_count: # Remove a result if the label count of a containing # n-gram is equal to its label count. row[DELETE_FIELDNAME] = True return row
python
def _annotate_bifurcated_extend_data(self, row, smaller, larger, tokenize, join): """Returns `row` annotated with whether it should be deleted or not. An n-gram is marked for deletion if: * its label count is 1 and its constituent (n-1)-grams also have a label count of 1; or * there is a containing (n+1)-gram that has the same label count. :param row: row of witness n-grams to annotate :type row: `pandas.Series` :param smaller: rows of (n-1)-grams for this witness :type smaller: `pandas.DataFrame` :param larger: rows of (n+1)-grams for this witness :type larger: `pandas.DataFrame` :param tokenize: function to tokenize an n-gram :param join: function to join tokens :rtype: `pandas.Series` """ lcf = constants.LABEL_COUNT_FIELDNAME nf = constants.NGRAM_FIELDNAME ngram = row[constants.NGRAM_FIELDNAME] label_count = row[constants.LABEL_COUNT_FIELDNAME] if label_count == 1 and not smaller.empty: # Keep a result with a label count of 1 if its # constituents do not also have a count of 1. ngram_tokens = tokenize(ngram) sub_ngram1 = join(ngram_tokens[:-1]) sub_ngram2 = join(ngram_tokens[1:]) pattern = FilteredWitnessText.get_filter_ngrams_pattern( [sub_ngram1, sub_ngram2]) if smaller[smaller[constants.NGRAM_FIELDNAME].str.match(pattern)][ constants.LABEL_COUNT_FIELDNAME].max() == 1: row[DELETE_FIELDNAME] = True elif not larger.empty and larger[larger[nf].str.contains( ngram, regex=False)][lcf].max() == label_count: # Remove a result if the label count of a containing # n-gram is equal to its label count. row[DELETE_FIELDNAME] = True return row
[ "def", "_annotate_bifurcated_extend_data", "(", "self", ",", "row", ",", "smaller", ",", "larger", ",", "tokenize", ",", "join", ")", ":", "lcf", "=", "constants", ".", "LABEL_COUNT_FIELDNAME", "nf", "=", "constants", ".", "NGRAM_FIELDNAME", "ngram", "=", "row...
Returns `row` annotated with whether it should be deleted or not. An n-gram is marked for deletion if: * its label count is 1 and its constituent (n-1)-grams also have a label count of 1; or * there is a containing (n+1)-gram that has the same label count. :param row: row of witness n-grams to annotate :type row: `pandas.Series` :param smaller: rows of (n-1)-grams for this witness :type smaller: `pandas.DataFrame` :param larger: rows of (n+1)-grams for this witness :type larger: `pandas.DataFrame` :param tokenize: function to tokenize an n-gram :param join: function to join tokens :rtype: `pandas.Series`
[ "Returns", "row", "annotated", "with", "whether", "it", "should", "be", "deleted", "or", "not", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L118-L161
ajenhl/tacl
tacl/results.py
Results.bifurcated_extend
def bifurcated_extend(self, corpus, max_size): """Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works to which results belong :type corpus: `Corpus` :param max_size: maximum size of n-gram results to include :type max_size: `int` """ temp_fd, temp_path = tempfile.mkstemp(text=True) try: self._prepare_bifurcated_extend_data(corpus, max_size, temp_path, temp_fd) finally: try: os.remove(temp_path) except OSError as e: msg = ('Failed to remove temporary file containing unreduced ' 'results: {}') self._logger.error(msg.format(e)) self._bifurcated_extend()
python
def bifurcated_extend(self, corpus, max_size): """Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works to which results belong :type corpus: `Corpus` :param max_size: maximum size of n-gram results to include :type max_size: `int` """ temp_fd, temp_path = tempfile.mkstemp(text=True) try: self._prepare_bifurcated_extend_data(corpus, max_size, temp_path, temp_fd) finally: try: os.remove(temp_path) except OSError as e: msg = ('Failed to remove temporary file containing unreduced ' 'results: {}') self._logger.error(msg.format(e)) self._bifurcated_extend()
[ "def", "bifurcated_extend", "(", "self", ",", "corpus", ",", "max_size", ")", ":", "temp_fd", ",", "temp_path", "=", "tempfile", ".", "mkstemp", "(", "text", "=", "True", ")", "try", ":", "self", ".", "_prepare_bifurcated_extend_data", "(", "corpus", ",", ...
Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works to which results belong :type corpus: `Corpus` :param max_size: maximum size of n-gram results to include :type max_size: `int`
[ "Replaces", "the", "results", "with", "those", "n", "-", "grams", "that", "contain", "any", "of", "the", "original", "n", "-", "grams", "and", "that", "represent", "points", "at", "which", "an", "n", "-", "gram", "is", "a", "constituent", "of", "multiple...
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L166-L189
ajenhl/tacl
tacl/results.py
Results.collapse_witnesses
def collapse_witnesses(self): """Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to this, it is not necessarily possible to run other Results methods on results that have had their witnesses collapsed. """ # In order to allow for additional columns to be present in # the input data (such as label count), copy the siglum # information into a new final column, then put the sigla # information into the siglum field and finally rename it. # # This means that in merge_sigla below, the column names are # reversed from what would be expected. if self._matches.empty: self._matches.rename(columns={constants.SIGLUM_FIELDNAME: constants.SIGLA_FIELDNAME}, inplace=True) return self._matches.loc[:, constants.SIGLA_FIELDNAME] = \ self._matches[constants.SIGLUM_FIELDNAME] # This code makes the not unwarranted assumption that the same # n-gram means the same size and that the same work means the # same label. grouped = self._matches.groupby( [constants.WORK_FIELDNAME, constants.NGRAM_FIELDNAME, constants.COUNT_FIELDNAME], sort=False) def merge_sigla(df): # Take the first result row; only the siglum should differ # between them, and there may only be one row. merged = df[0:1] sigla = list(df[constants.SIGLA_FIELDNAME]) sigla.sort() merged[constants.SIGLUM_FIELDNAME] = ', '.join(sigla) return merged self._matches = grouped.apply(merge_sigla) del self._matches[constants.SIGLA_FIELDNAME] self._matches.rename(columns={constants.SIGLUM_FIELDNAME: constants.SIGLA_FIELDNAME}, inplace=True)
python
def collapse_witnesses(self): """Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to this, it is not necessarily possible to run other Results methods on results that have had their witnesses collapsed. """ # In order to allow for additional columns to be present in # the input data (such as label count), copy the siglum # information into a new final column, then put the sigla # information into the siglum field and finally rename it. # # This means that in merge_sigla below, the column names are # reversed from what would be expected. if self._matches.empty: self._matches.rename(columns={constants.SIGLUM_FIELDNAME: constants.SIGLA_FIELDNAME}, inplace=True) return self._matches.loc[:, constants.SIGLA_FIELDNAME] = \ self._matches[constants.SIGLUM_FIELDNAME] # This code makes the not unwarranted assumption that the same # n-gram means the same size and that the same work means the # same label. grouped = self._matches.groupby( [constants.WORK_FIELDNAME, constants.NGRAM_FIELDNAME, constants.COUNT_FIELDNAME], sort=False) def merge_sigla(df): # Take the first result row; only the siglum should differ # between them, and there may only be one row. merged = df[0:1] sigla = list(df[constants.SIGLA_FIELDNAME]) sigla.sort() merged[constants.SIGLUM_FIELDNAME] = ', '.join(sigla) return merged self._matches = grouped.apply(merge_sigla) del self._matches[constants.SIGLA_FIELDNAME] self._matches.rename(columns={constants.SIGLUM_FIELDNAME: constants.SIGLA_FIELDNAME}, inplace=True)
[ "def", "collapse_witnesses", "(", "self", ")", ":", "# In order to allow for additional columns to be present in", "# the input data (such as label count), copy the siglum", "# information into a new final column, then put the sigla", "# information into the siglum field and finally rename it.", ...
Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to this, it is not necessarily possible to run other Results methods on results that have had their witnesses collapsed.
[ "Groups", "together", "witnesses", "for", "the", "same", "n", "-", "gram", "and", "work", "that", "has", "the", "same", "count", "and", "outputs", "a", "single", "row", "for", "each", "group", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L222-L266
ajenhl/tacl
tacl/results.py
Results.csv
def csv(self, fh): """Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object """ self._matches.to_csv(fh, encoding='utf-8', float_format='%d', index=False) return fh
python
def csv(self, fh): """Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object """ self._matches.to_csv(fh, encoding='utf-8', float_format='%d', index=False) return fh
[ "def", "csv", "(", "self", ",", "fh", ")", ":", "self", ".", "_matches", ".", "to_csv", "(", "fh", ",", "encoding", "=", "'utf-8'", ",", "float_format", "=", "'%d'", ",", "index", "=", "False", ")", "return", "fh" ]
Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object
[ "Writes", "the", "results", "data", "to", "fh", "in", "CSV", "format", "and", "returns", "fh", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L268-L278
ajenhl/tacl
tacl/results.py
Results.excise
def excise(self, ngram): """Removes all rows whose n-gram contains `ngram`. This operation uses simple string containment matching. For tokens that consist of multiple characters, this means that `ngram` may be part of one or two tokens; eg, "he m" would match on "she may". :param ngram: n-gram to remove containing n-gram rows by :type ngram: `str` """ self._logger.info('Excising results containing "{}"'.format(ngram)) if not ngram: return self._matches = self._matches[~self._matches[ constants.NGRAM_FIELDNAME].str.contains(ngram, regex=False)]
python
def excise(self, ngram): """Removes all rows whose n-gram contains `ngram`. This operation uses simple string containment matching. For tokens that consist of multiple characters, this means that `ngram` may be part of one or two tokens; eg, "he m" would match on "she may". :param ngram: n-gram to remove containing n-gram rows by :type ngram: `str` """ self._logger.info('Excising results containing "{}"'.format(ngram)) if not ngram: return self._matches = self._matches[~self._matches[ constants.NGRAM_FIELDNAME].str.contains(ngram, regex=False)]
[ "def", "excise", "(", "self", ",", "ngram", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Excising results containing \"{}\"'", ".", "format", "(", "ngram", ")", ")", "if", "not", "ngram", ":", "return", "self", ".", "_matches", "=", "self", ".",...
Removes all rows whose n-gram contains `ngram`. This operation uses simple string containment matching. For tokens that consist of multiple characters, this means that `ngram` may be part of one or two tokens; eg, "he m" would match on "she may". :param ngram: n-gram to remove containing n-gram rows by :type ngram: `str`
[ "Removes", "all", "rows", "whose", "n", "-", "gram", "contains", "ngram", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L281-L297
ajenhl/tacl
tacl/results.py
Results.extend
def extend(self, corpus): """Adds rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus` """ self._logger.info('Extending results') if self._matches.empty: return highest_n = self._matches[constants.SIZE_FIELDNAME].max() if highest_n == 1: self._logger.warning( 'Extending results that contain only 1-grams is unsupported; ' 'the original results will be used') return # Determine if we are dealing with diff or intersect # results. In the latter case, we need to perform a reciprocal # remove as the final stage (since extended n-grams may exist # in works from more than one label). This test will think # that intersect results that have had all but one label # removed are difference results, which will cause the results # to be potentially incorrect. is_intersect = self._is_intersect_results(self._matches) # Supply the extender with only matches on the largest # n-grams. matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] == highest_n] extended_matches = pd.DataFrame(columns=constants.QUERY_FIELDNAMES) cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME] for index, (work, siglum, label) in \ matches[cols].drop_duplicates().iterrows(): extended_ngrams = self._generate_extended_ngrams( matches, work, siglum, label, corpus, highest_n) extended_matches = pd.concat( [extended_matches, self._generate_extended_matches( extended_ngrams, highest_n, work, siglum, label)], sort=False) extended_ngrams = None if is_intersect: extended_matches = self._reciprocal_remove(extended_matches) self._matches = self._matches.append( extended_matches, ignore_index=True).reindex( columns=constants.QUERY_FIELDNAMES)
python
def extend(self, corpus): """Adds rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus` """ self._logger.info('Extending results') if self._matches.empty: return highest_n = self._matches[constants.SIZE_FIELDNAME].max() if highest_n == 1: self._logger.warning( 'Extending results that contain only 1-grams is unsupported; ' 'the original results will be used') return # Determine if we are dealing with diff or intersect # results. In the latter case, we need to perform a reciprocal # remove as the final stage (since extended n-grams may exist # in works from more than one label). This test will think # that intersect results that have had all but one label # removed are difference results, which will cause the results # to be potentially incorrect. is_intersect = self._is_intersect_results(self._matches) # Supply the extender with only matches on the largest # n-grams. matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] == highest_n] extended_matches = pd.DataFrame(columns=constants.QUERY_FIELDNAMES) cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME] for index, (work, siglum, label) in \ matches[cols].drop_duplicates().iterrows(): extended_ngrams = self._generate_extended_ngrams( matches, work, siglum, label, corpus, highest_n) extended_matches = pd.concat( [extended_matches, self._generate_extended_matches( extended_ngrams, highest_n, work, siglum, label)], sort=False) extended_ngrams = None if is_intersect: extended_matches = self._reciprocal_remove(extended_matches) self._matches = self._matches.append( extended_matches, ignore_index=True).reindex( columns=constants.QUERY_FIELDNAMES)
[ "def", "extend", "(", "self", ",", "corpus", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Extending results'", ")", "if", "self", ".", "_matches", ".", "empty", ":", "return", "highest_n", "=", "self", ".", "_matches", "[", "constants", ".", "...
Adds rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus`
[ "Adds", "rows", "for", "all", "longer", "forms", "of", "n", "-", "grams", "in", "the", "results", "that", "are", "present", "in", "the", "witnesses", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L302-L349
ajenhl/tacl
tacl/results.py
Results._generate_extended_matches
def _generate_extended_matches(self, extended_ngrams, highest_n, work, siglum, label): """Returns extended match data derived from `extended_ngrams`. This extended match data are the counts for all intermediate n-grams within each extended n-gram. :param extended_ngrams: extended n-grams :type extended_ngrams: `list` of `str` :param highest_n: the highest degree of n-grams in the original results :type highest_n: `int` :param work: name of the work bearing `extended_ngrams` :type work: `str` :param siglum: siglum of the text bearing `extended_ngrams` :type siglum: `str` :param label: label associated with the text :type label: `str` :rtype: `pandas.DataFrame` """ # Add data for each n-gram within each extended n-gram. Since # this treats each extended piece of text separately, the same # n-gram may be generated more than once, so the complete set # of new possible matches for this filename needs to combine # the counts for such. rows_list = [] for extended_ngram in extended_ngrams: text = Text(extended_ngram, self._tokenizer) for size, ngrams in text.get_ngrams(highest_n+1, len(text.get_tokens())): data = [{constants.WORK_FIELDNAME: work, constants.SIGLUM_FIELDNAME: siglum, constants.LABEL_FIELDNAME: label, constants.SIZE_FIELDNAME: size, constants.NGRAM_FIELDNAME: ngram, constants.COUNT_FIELDNAME: count} for ngram, count in ngrams.items()] rows_list.extend(data) self._logger.debug('Number of extended results: {}'.format( len(rows_list))) extended_matches = pd.DataFrame(rows_list) rows_list = None self._logger.debug('Finished generating intermediate extended matches') # extended_matches may be an empty DataFrame, in which case # manipulating it on the basis of non-existing columns is not # going to go well. groupby_fields = [constants.NGRAM_FIELDNAME, constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.SIZE_FIELDNAME, constants.LABEL_FIELDNAME] if constants.NGRAM_FIELDNAME in extended_matches: extended_matches = extended_matches.groupby( groupby_fields, sort=False).sum().reset_index() return extended_matches
python
def _generate_extended_matches(self, extended_ngrams, highest_n, work, siglum, label): """Returns extended match data derived from `extended_ngrams`. This extended match data are the counts for all intermediate n-grams within each extended n-gram. :param extended_ngrams: extended n-grams :type extended_ngrams: `list` of `str` :param highest_n: the highest degree of n-grams in the original results :type highest_n: `int` :param work: name of the work bearing `extended_ngrams` :type work: `str` :param siglum: siglum of the text bearing `extended_ngrams` :type siglum: `str` :param label: label associated with the text :type label: `str` :rtype: `pandas.DataFrame` """ # Add data for each n-gram within each extended n-gram. Since # this treats each extended piece of text separately, the same # n-gram may be generated more than once, so the complete set # of new possible matches for this filename needs to combine # the counts for such. rows_list = [] for extended_ngram in extended_ngrams: text = Text(extended_ngram, self._tokenizer) for size, ngrams in text.get_ngrams(highest_n+1, len(text.get_tokens())): data = [{constants.WORK_FIELDNAME: work, constants.SIGLUM_FIELDNAME: siglum, constants.LABEL_FIELDNAME: label, constants.SIZE_FIELDNAME: size, constants.NGRAM_FIELDNAME: ngram, constants.COUNT_FIELDNAME: count} for ngram, count in ngrams.items()] rows_list.extend(data) self._logger.debug('Number of extended results: {}'.format( len(rows_list))) extended_matches = pd.DataFrame(rows_list) rows_list = None self._logger.debug('Finished generating intermediate extended matches') # extended_matches may be an empty DataFrame, in which case # manipulating it on the basis of non-existing columns is not # going to go well. groupby_fields = [constants.NGRAM_FIELDNAME, constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.SIZE_FIELDNAME, constants.LABEL_FIELDNAME] if constants.NGRAM_FIELDNAME in extended_matches: extended_matches = extended_matches.groupby( groupby_fields, sort=False).sum().reset_index() return extended_matches
[ "def", "_generate_extended_matches", "(", "self", ",", "extended_ngrams", ",", "highest_n", ",", "work", ",", "siglum", ",", "label", ")", ":", "# Add data for each n-gram within each extended n-gram. Since", "# this treats each extended piece of text separately, the same", "# n-...
Returns extended match data derived from `extended_ngrams`. This extended match data are the counts for all intermediate n-grams within each extended n-gram. :param extended_ngrams: extended n-grams :type extended_ngrams: `list` of `str` :param highest_n: the highest degree of n-grams in the original results :type highest_n: `int` :param work: name of the work bearing `extended_ngrams` :type work: `str` :param siglum: siglum of the text bearing `extended_ngrams` :type siglum: `str` :param label: label associated with the text :type label: `str` :rtype: `pandas.DataFrame`
[ "Returns", "extended", "match", "data", "derived", "from", "extended_ngrams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L351-L403
ajenhl/tacl
tacl/results.py
Results._generate_extended_ngrams
def _generate_extended_ngrams(self, matches, work, siglum, label, corpus, highest_n): """Returns the n-grams of the largest size that exist in `siglum` witness to `work` under `label`, generated from adding together overlapping n-grams in `matches`. :param matches: n-gram matches :type matches: `pandas.DataFrame` :param work: name of work whose results are being processed :type work: `str` :param siglum: siglum of witness whose results are being processed :type siglum: `str` :param label: label of witness whose results are being processed :type label: `str` :param corpus: corpus to which `filename` belongs :type corpus: `Corpus` :param highest_n: highest degree of n-gram in `matches` :type highest_n: `int` :rtype: `list` of `str` """ # For large result sets, this method may involve a lot of # processing within the for loop, so optimise even small # things, such as aliasing dotted calls here and below. t_join = self._tokenizer.joiner.join witness_matches = matches[ (matches[constants.WORK_FIELDNAME] == work) & (matches[constants.SIGLUM_FIELDNAME] == siglum) & (matches[constants.LABEL_FIELDNAME] == label)] text = corpus.get_witness(work, siglum).get_token_content() ngrams = [tuple(self._tokenizer.tokenize(ngram)) for ngram in list(witness_matches[constants.NGRAM_FIELDNAME])] # Go through the list of n-grams, and create a list of # extended n-grams by joining two n-grams together that # overlap (a[-overlap:] == b[:-1]) and checking that the result # occurs in text. working_ngrams = ngrams[:] extended_ngrams = set(ngrams) new_working_ngrams = [] overlap = highest_n - 1 # Create an index of n-grams by their overlapping portion, # pointing to the non-overlapping token. ngram_index = {} for ngram in ngrams: values = ngram_index.setdefault(ngram[:-1], []) values.append(ngram[-1:]) extended_add = extended_ngrams.add new_working_append = new_working_ngrams.append ngram_size = highest_n while working_ngrams: removals = set() ngram_size += 1 self._logger.debug( 'Iterating over {} n-grams to produce {}-grams'.format( len(working_ngrams), ngram_size)) for base in working_ngrams: remove_base = False base_overlap = base[-overlap:] for next_token in ngram_index.get(base_overlap, []): extension = base + next_token if t_join(extension) in text: extended_add(extension) new_working_append(extension) remove_base = True if remove_base: # Remove base from extended_ngrams, because it is # now encompassed by extension. removals.add(base) extended_ngrams -= removals working_ngrams = new_working_ngrams[:] new_working_ngrams = [] new_working_append = new_working_ngrams.append extended_ngrams = sorted(extended_ngrams, key=len, reverse=True) extended_ngrams = [t_join(ngram) for ngram in extended_ngrams] self._logger.debug('Generated {} extended n-grams'.format( len(extended_ngrams))) self._logger.debug('Longest generated n-gram: {}'.format( extended_ngrams[0])) # In order to get the counts correct in the next step of the # process, these n-grams must be overlaid over the text and # repeated as many times as there are matches. N-grams that do # not match (and they may not match on previously matched # parts of the text) are discarded. ngrams = [] for ngram in extended_ngrams: # Remove from the text those parts that match. Replace # them with a double space, which should prevent any # incorrect match on the text from each side of the match # that is now contiguous. text, count = re.subn(re.escape(ngram), ' ', text) ngrams.extend([ngram] * count) self._logger.debug('Aligned extended n-grams with the text; ' '{} distinct n-grams exist'.format(len(ngrams))) return ngrams
python
def _generate_extended_ngrams(self, matches, work, siglum, label, corpus, highest_n): """Returns the n-grams of the largest size that exist in `siglum` witness to `work` under `label`, generated from adding together overlapping n-grams in `matches`. :param matches: n-gram matches :type matches: `pandas.DataFrame` :param work: name of work whose results are being processed :type work: `str` :param siglum: siglum of witness whose results are being processed :type siglum: `str` :param label: label of witness whose results are being processed :type label: `str` :param corpus: corpus to which `filename` belongs :type corpus: `Corpus` :param highest_n: highest degree of n-gram in `matches` :type highest_n: `int` :rtype: `list` of `str` """ # For large result sets, this method may involve a lot of # processing within the for loop, so optimise even small # things, such as aliasing dotted calls here and below. t_join = self._tokenizer.joiner.join witness_matches = matches[ (matches[constants.WORK_FIELDNAME] == work) & (matches[constants.SIGLUM_FIELDNAME] == siglum) & (matches[constants.LABEL_FIELDNAME] == label)] text = corpus.get_witness(work, siglum).get_token_content() ngrams = [tuple(self._tokenizer.tokenize(ngram)) for ngram in list(witness_matches[constants.NGRAM_FIELDNAME])] # Go through the list of n-grams, and create a list of # extended n-grams by joining two n-grams together that # overlap (a[-overlap:] == b[:-1]) and checking that the result # occurs in text. working_ngrams = ngrams[:] extended_ngrams = set(ngrams) new_working_ngrams = [] overlap = highest_n - 1 # Create an index of n-grams by their overlapping portion, # pointing to the non-overlapping token. ngram_index = {} for ngram in ngrams: values = ngram_index.setdefault(ngram[:-1], []) values.append(ngram[-1:]) extended_add = extended_ngrams.add new_working_append = new_working_ngrams.append ngram_size = highest_n while working_ngrams: removals = set() ngram_size += 1 self._logger.debug( 'Iterating over {} n-grams to produce {}-grams'.format( len(working_ngrams), ngram_size)) for base in working_ngrams: remove_base = False base_overlap = base[-overlap:] for next_token in ngram_index.get(base_overlap, []): extension = base + next_token if t_join(extension) in text: extended_add(extension) new_working_append(extension) remove_base = True if remove_base: # Remove base from extended_ngrams, because it is # now encompassed by extension. removals.add(base) extended_ngrams -= removals working_ngrams = new_working_ngrams[:] new_working_ngrams = [] new_working_append = new_working_ngrams.append extended_ngrams = sorted(extended_ngrams, key=len, reverse=True) extended_ngrams = [t_join(ngram) for ngram in extended_ngrams] self._logger.debug('Generated {} extended n-grams'.format( len(extended_ngrams))) self._logger.debug('Longest generated n-gram: {}'.format( extended_ngrams[0])) # In order to get the counts correct in the next step of the # process, these n-grams must be overlaid over the text and # repeated as many times as there are matches. N-grams that do # not match (and they may not match on previously matched # parts of the text) are discarded. ngrams = [] for ngram in extended_ngrams: # Remove from the text those parts that match. Replace # them with a double space, which should prevent any # incorrect match on the text from each side of the match # that is now contiguous. text, count = re.subn(re.escape(ngram), ' ', text) ngrams.extend([ngram] * count) self._logger.debug('Aligned extended n-grams with the text; ' '{} distinct n-grams exist'.format(len(ngrams))) return ngrams
[ "def", "_generate_extended_ngrams", "(", "self", ",", "matches", ",", "work", ",", "siglum", ",", "label", ",", "corpus", ",", "highest_n", ")", ":", "# For large result sets, this method may involve a lot of", "# processing within the for loop, so optimise even small", "# th...
Returns the n-grams of the largest size that exist in `siglum` witness to `work` under `label`, generated from adding together overlapping n-grams in `matches`. :param matches: n-gram matches :type matches: `pandas.DataFrame` :param work: name of work whose results are being processed :type work: `str` :param siglum: siglum of witness whose results are being processed :type siglum: `str` :param label: label of witness whose results are being processed :type label: `str` :param corpus: corpus to which `filename` belongs :type corpus: `Corpus` :param highest_n: highest degree of n-gram in `matches` :type highest_n: `int` :rtype: `list` of `str`
[ "Returns", "the", "n", "-", "grams", "of", "the", "largest", "size", "that", "exist", "in", "siglum", "witness", "to", "work", "under", "label", "generated", "from", "adding", "together", "overlapping", "n", "-", "grams", "in", "matches", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L405-L498
ajenhl/tacl
tacl/results.py
Results._generate_filter_ngrams
def _generate_filter_ngrams(self, data, min_size): """Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` :rtype: `list` of `str` """ max_size = data[constants.SIZE_FIELDNAME].max() kept_ngrams = list(data[data[constants.SIZE_FIELDNAME] == min_size][ constants.NGRAM_FIELDNAME]) for size in range(min_size+1, max_size+1): pattern = FilteredWitnessText.get_filter_ngrams_pattern( kept_ngrams) potential_ngrams = list(data[data[constants.SIZE_FIELDNAME] == size][constants.NGRAM_FIELDNAME]) kept_ngrams.extend([ngram for ngram in potential_ngrams if pattern.search(ngram) is None]) return kept_ngrams
python
def _generate_filter_ngrams(self, data, min_size): """Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` :rtype: `list` of `str` """ max_size = data[constants.SIZE_FIELDNAME].max() kept_ngrams = list(data[data[constants.SIZE_FIELDNAME] == min_size][ constants.NGRAM_FIELDNAME]) for size in range(min_size+1, max_size+1): pattern = FilteredWitnessText.get_filter_ngrams_pattern( kept_ngrams) potential_ngrams = list(data[data[constants.SIZE_FIELDNAME] == size][constants.NGRAM_FIELDNAME]) kept_ngrams.extend([ngram for ngram in potential_ngrams if pattern.search(ngram) is None]) return kept_ngrams
[ "def", "_generate_filter_ngrams", "(", "self", ",", "data", ",", "min_size", ")", ":", "max_size", "=", "data", "[", "constants", ".", "SIZE_FIELDNAME", "]", ".", "max", "(", ")", "kept_ngrams", "=", "list", "(", "data", "[", "data", "[", "constants", "....
Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` :rtype: `list` of `str`
[ "Returns", "the", "n", "-", "grams", "in", "data", "that", "do", "not", "contain", "any", "other", "n", "-", "gram", "in", "data", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L500-L521
ajenhl/tacl
tacl/results.py
Results._generate_substrings
def _generate_substrings(self, ngram, size): """Returns a list of all substrings of `ngram`. :param ngram: n-gram to generate substrings of :type ngram: `str` :param size: size of `ngram` :type size: `int` :rtype: `list` """ text = Text(ngram, self._tokenizer) substrings = [] for sub_size, ngrams in text.get_ngrams(1, size-1): for sub_ngram, count in ngrams.items(): substrings.extend([sub_ngram] * count) return substrings
python
def _generate_substrings(self, ngram, size): """Returns a list of all substrings of `ngram`. :param ngram: n-gram to generate substrings of :type ngram: `str` :param size: size of `ngram` :type size: `int` :rtype: `list` """ text = Text(ngram, self._tokenizer) substrings = [] for sub_size, ngrams in text.get_ngrams(1, size-1): for sub_ngram, count in ngrams.items(): substrings.extend([sub_ngram] * count) return substrings
[ "def", "_generate_substrings", "(", "self", ",", "ngram", ",", "size", ")", ":", "text", "=", "Text", "(", "ngram", ",", "self", ".", "_tokenizer", ")", "substrings", "=", "[", "]", "for", "sub_size", ",", "ngrams", "in", "text", ".", "get_ngrams", "("...
Returns a list of all substrings of `ngram`. :param ngram: n-gram to generate substrings of :type ngram: `str` :param size: size of `ngram` :type size: `int` :rtype: `list`
[ "Returns", "a", "list", "of", "all", "substrings", "of", "ngram", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L523-L538
ajenhl/tacl
tacl/results.py
Results.group_by_ngram
def group_by_ngram(self, labels): """Groups result rows by n-gram and label, providing a single summary field giving the range of occurrences across each work's witnesses. Results are sorted by n-gram then by label (in the order given in `labels`). :param labels: labels to order on :type labels: `list` of `str` """ if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[ constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME, constants.LABEL_FIELDNAME, constants.WORK_COUNTS_FIELDNAME]) return label_order_col = 'label order' def work_summary(group): match = group.iloc[0] work = match[constants.WORK_FIELDNAME] minimum = group[constants.COUNT_FIELDNAME].min() maximum = group[constants.COUNT_FIELDNAME].max() if minimum == maximum: work_count = '{}({})'.format(work, minimum) else: work_count = '{}({}-{})'.format(work, minimum, maximum) match['work count'] = work_count return match def ngram_label_summary(group): match = group.iloc[0] summary = group.groupby(constants.WORK_FIELDNAME).apply( work_summary) work_counts = ', '.join(list(summary['work count'])) match[constants.WORK_COUNTS_FIELDNAME] = work_counts return match def add_label_order(row, labels): row[label_order_col] = labels.index(row[constants.LABEL_FIELDNAME]) return row group_cols = [constants.NGRAM_FIELDNAME, constants.LABEL_FIELDNAME] matches = self._matches.groupby(group_cols, sort=False).apply( ngram_label_summary) del matches[constants.WORK_FIELDNAME] del matches[constants.SIGLUM_FIELDNAME] del matches[constants.COUNT_FIELDNAME] matches = matches.apply(add_label_order, axis=1, args=(labels,)) matches.reset_index(drop=True, inplace=True) matches.sort_values(by=[constants.NGRAM_FIELDNAME, label_order_col], ascending=True, inplace=True) del matches[label_order_col] self._matches = matches
python
def group_by_ngram(self, labels): """Groups result rows by n-gram and label, providing a single summary field giving the range of occurrences across each work's witnesses. Results are sorted by n-gram then by label (in the order given in `labels`). :param labels: labels to order on :type labels: `list` of `str` """ if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[ constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME, constants.LABEL_FIELDNAME, constants.WORK_COUNTS_FIELDNAME]) return label_order_col = 'label order' def work_summary(group): match = group.iloc[0] work = match[constants.WORK_FIELDNAME] minimum = group[constants.COUNT_FIELDNAME].min() maximum = group[constants.COUNT_FIELDNAME].max() if minimum == maximum: work_count = '{}({})'.format(work, minimum) else: work_count = '{}({}-{})'.format(work, minimum, maximum) match['work count'] = work_count return match def ngram_label_summary(group): match = group.iloc[0] summary = group.groupby(constants.WORK_FIELDNAME).apply( work_summary) work_counts = ', '.join(list(summary['work count'])) match[constants.WORK_COUNTS_FIELDNAME] = work_counts return match def add_label_order(row, labels): row[label_order_col] = labels.index(row[constants.LABEL_FIELDNAME]) return row group_cols = [constants.NGRAM_FIELDNAME, constants.LABEL_FIELDNAME] matches = self._matches.groupby(group_cols, sort=False).apply( ngram_label_summary) del matches[constants.WORK_FIELDNAME] del matches[constants.SIGLUM_FIELDNAME] del matches[constants.COUNT_FIELDNAME] matches = matches.apply(add_label_order, axis=1, args=(labels,)) matches.reset_index(drop=True, inplace=True) matches.sort_values(by=[constants.NGRAM_FIELDNAME, label_order_col], ascending=True, inplace=True) del matches[label_order_col] self._matches = matches
[ "def", "group_by_ngram", "(", "self", ",", "labels", ")", ":", "if", "self", ".", "_matches", ".", "empty", ":", "# Ensure that the right columns are used, even though the", "# results are empty.", "self", ".", "_matches", "=", "pd", ".", "DataFrame", "(", "{", "}...
Groups result rows by n-gram and label, providing a single summary field giving the range of occurrences across each work's witnesses. Results are sorted by n-gram then by label (in the order given in `labels`). :param labels: labels to order on :type labels: `list` of `str`
[ "Groups", "result", "rows", "by", "n", "-", "gram", "and", "label", "providing", "a", "single", "summary", "field", "giving", "the", "range", "of", "occurrences", "across", "each", "work", "s", "witnesses", ".", "Results", "are", "sorted", "by", "n", "-", ...
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L551-L608
ajenhl/tacl
tacl/results.py
Results.group_by_witness
def group_by_witness(self): """Groups results by witness, providing a single summary field giving the n-grams found in it, a count of their number, and the count of their combined occurrences.""" if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME, constants.NGRAMS_FIELDNAME, constants.NUMBER_FIELDNAME, constants.TOTAL_COUNT_FIELDNAME]) return def witness_summary(group): matches = group.sort_values(by=[constants.NGRAM_FIELDNAME], ascending=[True]) match = matches.iloc[0] ngrams = ', '.join(list(matches[constants.NGRAM_FIELDNAME])) match[constants.NGRAMS_FIELDNAME] = ngrams match[constants.NUMBER_FIELDNAME] = len(matches) match[constants.TOTAL_COUNT_FIELDNAME] = matches[ constants.COUNT_FIELDNAME].sum() return match group_cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME] # Remove zero-count results. self._matches = self._matches[ self._matches[constants.COUNT_FIELDNAME] != 0] self._matches = self._matches.groupby(group_cols, sort=False).apply( witness_summary) del self._matches[constants.NGRAM_FIELDNAME] del self._matches[constants.SIZE_FIELDNAME] del self._matches[constants.COUNT_FIELDNAME]
python
def group_by_witness(self): """Groups results by witness, providing a single summary field giving the n-grams found in it, a count of their number, and the count of their combined occurrences.""" if self._matches.empty: # Ensure that the right columns are used, even though the # results are empty. self._matches = pd.DataFrame( {}, columns=[constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME, constants.NGRAMS_FIELDNAME, constants.NUMBER_FIELDNAME, constants.TOTAL_COUNT_FIELDNAME]) return def witness_summary(group): matches = group.sort_values(by=[constants.NGRAM_FIELDNAME], ascending=[True]) match = matches.iloc[0] ngrams = ', '.join(list(matches[constants.NGRAM_FIELDNAME])) match[constants.NGRAMS_FIELDNAME] = ngrams match[constants.NUMBER_FIELDNAME] = len(matches) match[constants.TOTAL_COUNT_FIELDNAME] = matches[ constants.COUNT_FIELDNAME].sum() return match group_cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME] # Remove zero-count results. self._matches = self._matches[ self._matches[constants.COUNT_FIELDNAME] != 0] self._matches = self._matches.groupby(group_cols, sort=False).apply( witness_summary) del self._matches[constants.NGRAM_FIELDNAME] del self._matches[constants.SIZE_FIELDNAME] del self._matches[constants.COUNT_FIELDNAME]
[ "def", "group_by_witness", "(", "self", ")", ":", "if", "self", ".", "_matches", ".", "empty", ":", "# Ensure that the right columns are used, even though the", "# results are empty.", "self", ".", "_matches", "=", "pd", ".", "DataFrame", "(", "{", "}", ",", "colu...
Groups results by witness, providing a single summary field giving the n-grams found in it, a count of their number, and the count of their combined occurrences.
[ "Groups", "results", "by", "witness", "providing", "a", "single", "summary", "field", "giving", "the", "n", "-", "grams", "found", "in", "it", "a", "count", "of", "their", "number", "and", "the", "count", "of", "their", "combined", "occurrences", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L613-L648
ajenhl/tacl
tacl/results.py
Results._is_intersect_results
def _is_intersect_results(results): """Returns False if `results` has an n-gram that exists in only one label, True otherwise. :param results: results to analyze :type results: `pandas.DataFrame` :rtype: `bool` """ sample = results.iloc[0] ngram = sample[constants.NGRAM_FIELDNAME] label = sample[constants.LABEL_FIELDNAME] return not(results[ (results[constants.NGRAM_FIELDNAME] == ngram) & (results[constants.LABEL_FIELDNAME] != label)].empty)
python
def _is_intersect_results(results): """Returns False if `results` has an n-gram that exists in only one label, True otherwise. :param results: results to analyze :type results: `pandas.DataFrame` :rtype: `bool` """ sample = results.iloc[0] ngram = sample[constants.NGRAM_FIELDNAME] label = sample[constants.LABEL_FIELDNAME] return not(results[ (results[constants.NGRAM_FIELDNAME] == ngram) & (results[constants.LABEL_FIELDNAME] != label)].empty)
[ "def", "_is_intersect_results", "(", "results", ")", ":", "sample", "=", "results", ".", "iloc", "[", "0", "]", "ngram", "=", "sample", "[", "constants", ".", "NGRAM_FIELDNAME", "]", "label", "=", "sample", "[", "constants", ".", "LABEL_FIELDNAME", "]", "r...
Returns False if `results` has an n-gram that exists in only one label, True otherwise. :param results: results to analyze :type results: `pandas.DataFrame` :rtype: `bool`
[ "Returns", "False", "if", "results", "has", "an", "n", "-", "gram", "that", "exists", "in", "only", "one", "label", "True", "otherwise", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L651-L665
ajenhl/tacl
tacl/results.py
Results.prune_by_ngram
def prune_by_ngram(self, ngrams): """Removes results rows whose n-gram is in `ngrams`. :param ngrams: n-grams to remove :type ngrams: `list` of `str` """ self._logger.info('Pruning results by n-gram') self._matches = self._matches[ ~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]
python
def prune_by_ngram(self, ngrams): """Removes results rows whose n-gram is in `ngrams`. :param ngrams: n-grams to remove :type ngrams: `list` of `str` """ self._logger.info('Pruning results by n-gram') self._matches = self._matches[ ~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]
[ "def", "prune_by_ngram", "(", "self", ",", "ngrams", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by n-gram'", ")", "self", ".", "_matches", "=", "self", ".", "_matches", "[", "~", "self", ".", "_matches", "[", "constants", ".", ...
Removes results rows whose n-gram is in `ngrams`. :param ngrams: n-grams to remove :type ngrams: `list` of `str`
[ "Removes", "results", "rows", "whose", "n", "-", "gram", "is", "in", "ngrams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L704-L713
ajenhl/tacl
tacl/results.py
Results.prune_by_ngram_count
def prune_by_ngram_count(self, minimum=None, maximum=None, label=None): """Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all works is the maximum count across the witnesses for that work. If `label` is specified, the works checked are restricted to those associated with `label`. :param minimum: minimum n-gram count :type minimum: `int` :param maximum: maximum n-gram count :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str` """ self._logger.info('Pruning results by n-gram count') def calculate_total(group): work_grouped = group.groupby(constants.WORK_FIELDNAME, sort=False) total_count = work_grouped[constants.COUNT_FIELDNAME].max().sum() group['total_count'] = pd.Series([total_count] * len(group.index), index=group.index) return group # self._matches may be empty, in which case not only is there # no point trying to do the pruning, but it will raise an # exception due to referencing the column 'total_count' which # won't have been added. Therefore just return immediately. if self._matches.empty: return matches = self._matches if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] matches = matches.groupby( constants.NGRAM_FIELDNAME, sort=False).apply(calculate_total) ngrams = None if minimum: ngrams = matches[matches['total_count'] >= minimum][ constants.NGRAM_FIELDNAME].unique() if maximum: max_ngrams = matches[matches['total_count'] <= maximum][ constants.NGRAM_FIELDNAME].unique() if ngrams is None: ngrams = max_ngrams else: ngrams = list(set(ngrams) & set(max_ngrams)) self._matches = self._matches[ self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]
python
def prune_by_ngram_count(self, minimum=None, maximum=None, label=None): """Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all works is the maximum count across the witnesses for that work. If `label` is specified, the works checked are restricted to those associated with `label`. :param minimum: minimum n-gram count :type minimum: `int` :param maximum: maximum n-gram count :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str` """ self._logger.info('Pruning results by n-gram count') def calculate_total(group): work_grouped = group.groupby(constants.WORK_FIELDNAME, sort=False) total_count = work_grouped[constants.COUNT_FIELDNAME].max().sum() group['total_count'] = pd.Series([total_count] * len(group.index), index=group.index) return group # self._matches may be empty, in which case not only is there # no point trying to do the pruning, but it will raise an # exception due to referencing the column 'total_count' which # won't have been added. Therefore just return immediately. if self._matches.empty: return matches = self._matches if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] matches = matches.groupby( constants.NGRAM_FIELDNAME, sort=False).apply(calculate_total) ngrams = None if minimum: ngrams = matches[matches['total_count'] >= minimum][ constants.NGRAM_FIELDNAME].unique() if maximum: max_ngrams = matches[matches['total_count'] <= maximum][ constants.NGRAM_FIELDNAME].unique() if ngrams is None: ngrams = max_ngrams else: ngrams = list(set(ngrams) & set(max_ngrams)) self._matches = self._matches[ self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)]
[ "def", "prune_by_ngram_count", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by n-gram count'", ")", "def", "calculate_total", "(", "gro...
Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all works is the maximum count across the witnesses for that work. If `label` is specified, the works checked are restricted to those associated with `label`. :param minimum: minimum n-gram count :type minimum: `int` :param maximum: maximum n-gram count :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str`
[ "Removes", "results", "rows", "whose", "total", "n", "-", "gram", "count", "(", "across", "all", "works", "bearing", "this", "n", "-", "gram", ")", "is", "outside", "the", "range", "specified", "by", "minimum", "and", "maximum", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L717-L768
ajenhl/tacl
tacl/results.py
Results.prune_by_ngram_count_per_work
def prune_by_ngram_count_per_work(self, minimum=None, maximum=None, label=None): """Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of a single work has an n-gram count that falls within the specified range, all result rows for that n-gram are kept. If `label` is specified, the works checked are restricted to those associated with `label`. :param minimum: minimum n-gram count :type minimum: `int` :param maximum: maximum n-gram count :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str` """ self._logger.info('Pruning results by n-gram count per work') matches = self._matches keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique() if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] if minimum and maximum: keep_ngrams = matches[ (matches[constants.COUNT_FIELDNAME] >= minimum) & (matches[constants.COUNT_FIELDNAME] <= maximum)][ constants.NGRAM_FIELDNAME].unique() elif minimum: keep_ngrams = matches[ matches[constants.COUNT_FIELDNAME] >= minimum][ constants.NGRAM_FIELDNAME].unique() elif maximum: keep_ngrams = matches[ self._matches[constants.COUNT_FIELDNAME] <= maximum][ constants.NGRAM_FIELDNAME].unique() self._matches = self._matches[self._matches[ constants.NGRAM_FIELDNAME].isin(keep_ngrams)]
python
def prune_by_ngram_count_per_work(self, minimum=None, maximum=None, label=None): """Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of a single work has an n-gram count that falls within the specified range, all result rows for that n-gram are kept. If `label` is specified, the works checked are restricted to those associated with `label`. :param minimum: minimum n-gram count :type minimum: `int` :param maximum: maximum n-gram count :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str` """ self._logger.info('Pruning results by n-gram count per work') matches = self._matches keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique() if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] if minimum and maximum: keep_ngrams = matches[ (matches[constants.COUNT_FIELDNAME] >= minimum) & (matches[constants.COUNT_FIELDNAME] <= maximum)][ constants.NGRAM_FIELDNAME].unique() elif minimum: keep_ngrams = matches[ matches[constants.COUNT_FIELDNAME] >= minimum][ constants.NGRAM_FIELDNAME].unique() elif maximum: keep_ngrams = matches[ self._matches[constants.COUNT_FIELDNAME] <= maximum][ constants.NGRAM_FIELDNAME].unique() self._matches = self._matches[self._matches[ constants.NGRAM_FIELDNAME].isin(keep_ngrams)]
[ "def", "prune_by_ngram_count_per_work", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by n-gram count per work'", ")", "matches", "=", "se...
Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of a single work has an n-gram count that falls within the specified range, all result rows for that n-gram are kept. If `label` is specified, the works checked are restricted to those associated with `label`. :param minimum: minimum n-gram count :type minimum: `int` :param maximum: maximum n-gram count :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str`
[ "Removes", "results", "rows", "if", "the", "n", "-", "gram", "count", "for", "all", "works", "bearing", "that", "n", "-", "gram", "is", "outside", "the", "range", "specified", "by", "minimum", "and", "maximum", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L771-L811
ajenhl/tacl
tacl/results.py
Results.prune_by_ngram_size
def prune_by_ngram_size(self, minimum=None, maximum=None): """Removes results rows whose n-gram size is outside the range specified by `minimum` and `maximum`. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` """ self._logger.info('Pruning results by n-gram size') if minimum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] >= minimum] if maximum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] <= maximum]
python
def prune_by_ngram_size(self, minimum=None, maximum=None): """Removes results rows whose n-gram size is outside the range specified by `minimum` and `maximum`. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` """ self._logger.info('Pruning results by n-gram size') if minimum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] >= minimum] if maximum: self._matches = self._matches[ self._matches[constants.SIZE_FIELDNAME] <= maximum]
[ "def", "prune_by_ngram_size", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by n-gram size'", ")", "if", "minimum", ":", "self", ".", "_matches", "=", "self", "....
Removes results rows whose n-gram size is outside the range specified by `minimum` and `maximum`. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int`
[ "Removes", "results", "rows", "whose", "n", "-", "gram", "size", "is", "outside", "the", "range", "specified", "by", "minimum", "and", "maximum", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L814-L830
ajenhl/tacl
tacl/results.py
Results.prune_by_work_count
def prune_by_work_count(self, minimum=None, maximum=None, label=None): """Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in multiple witnesses of the same work are counted as a single work. If `label` is specified, the works counted are restricted to those associated with `label`. :param minimum: minimum number of works :type minimum: `int` :param maximum: maximum number of works :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str` """ self._logger.info('Pruning results by work count') count_fieldname = 'tmp_count' matches = self._matches if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] filtered = matches[matches[constants.COUNT_FIELDNAME] > 0] grouped = filtered.groupby(constants.NGRAM_FIELDNAME, sort=False) counts = pd.DataFrame(grouped[constants.WORK_FIELDNAME].nunique()) counts.rename(columns={constants.WORK_FIELDNAME: count_fieldname}, inplace=True) if minimum: counts = counts[counts[count_fieldname] >= minimum] if maximum: counts = counts[counts[count_fieldname] <= maximum] self._matches = pd.merge(self._matches, counts, left_on=constants.NGRAM_FIELDNAME, right_index=True) del self._matches[count_fieldname]
python
def prune_by_work_count(self, minimum=None, maximum=None, label=None): """Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in multiple witnesses of the same work are counted as a single work. If `label` is specified, the works counted are restricted to those associated with `label`. :param minimum: minimum number of works :type minimum: `int` :param maximum: maximum number of works :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str` """ self._logger.info('Pruning results by work count') count_fieldname = 'tmp_count' matches = self._matches if label is not None: matches = matches[matches[constants.LABEL_FIELDNAME] == label] filtered = matches[matches[constants.COUNT_FIELDNAME] > 0] grouped = filtered.groupby(constants.NGRAM_FIELDNAME, sort=False) counts = pd.DataFrame(grouped[constants.WORK_FIELDNAME].nunique()) counts.rename(columns={constants.WORK_FIELDNAME: count_fieldname}, inplace=True) if minimum: counts = counts[counts[count_fieldname] >= minimum] if maximum: counts = counts[counts[count_fieldname] <= maximum] self._matches = pd.merge(self._matches, counts, left_on=constants.NGRAM_FIELDNAME, right_index=True) del self._matches[count_fieldname]
[ "def", "prune_by_work_count", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by work count'", ")", "count_fieldname", "=", "'tmp_count'", ...
Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in multiple witnesses of the same work are counted as a single work. If `label` is specified, the works counted are restricted to those associated with `label`. :param minimum: minimum number of works :type minimum: `int` :param maximum: maximum number of works :type maximum: `int` :param label: optional label to restrict requirement to :type label: `str`
[ "Removes", "results", "rows", "for", "n", "-", "grams", "that", "are", "not", "attested", "in", "a", "number", "of", "works", "in", "the", "range", "specified", "by", "minimum", "and", "maximum", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L834-L871
ajenhl/tacl
tacl/results.py
Results.reciprocal_remove
def reciprocal_remove(self): """Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.""" self._logger.info( 'Removing n-grams that are not attested in all labels') self._matches = self._reciprocal_remove(self._matches)
python
def reciprocal_remove(self): """Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.""" self._logger.info( 'Removing n-grams that are not attested in all labels') self._matches = self._reciprocal_remove(self._matches)
[ "def", "reciprocal_remove", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Removing n-grams that are not attested in all labels'", ")", "self", ".", "_matches", "=", "self", ".", "_reciprocal_remove", "(", "self", ".", "_matches", ")" ]
Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.
[ "Removes", "results", "rows", "for", "which", "the", "n", "-", "gram", "is", "not", "present", "in", "at", "least", "one", "text", "in", "each", "labelled", "set", "of", "texts", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L875-L880
ajenhl/tacl
tacl/results.py
Results.reduce
def reduce(self): """Removes results rows whose n-grams are contained in larger n-grams.""" self._logger.info('Reducing the n-grams') # This does not make use of any pandas functionality; it # probably could, and if so ought to. data = {} labels = {} # Derive a convenient data structure from the rows. for row_index, row in self._matches.iterrows(): work = row[constants.WORK_FIELDNAME] siglum = row[constants.SIGLUM_FIELDNAME] labels[work] = row[constants.LABEL_FIELDNAME] witness_data = data.setdefault((work, siglum), {}) witness_data[row[constants.NGRAM_FIELDNAME]] = { 'count': int(row[constants.COUNT_FIELDNAME]), 'size': int(row[constants.SIZE_FIELDNAME])} for witness_data in data.values(): ngrams = list(witness_data.keys()) ngrams.sort(key=lambda ngram: witness_data[ngram]['size'], reverse=True) for ngram in ngrams: if witness_data[ngram]['count'] > 0: self._reduce_by_ngram(witness_data, ngram) # Recreate rows from the modified data structure. rows = [] for (work, siglum), witness_data in data.items(): for ngram, ngram_data in witness_data.items(): count = ngram_data['count'] if count > 0: rows.append( {constants.NGRAM_FIELDNAME: ngram, constants.SIZE_FIELDNAME: ngram_data['size'], constants.WORK_FIELDNAME: work, constants.SIGLUM_FIELDNAME: siglum, constants.COUNT_FIELDNAME: count, constants.LABEL_FIELDNAME: labels[work]}) self._matches = pd.DataFrame( rows, columns=constants.QUERY_FIELDNAMES)
python
def reduce(self): """Removes results rows whose n-grams are contained in larger n-grams.""" self._logger.info('Reducing the n-grams') # This does not make use of any pandas functionality; it # probably could, and if so ought to. data = {} labels = {} # Derive a convenient data structure from the rows. for row_index, row in self._matches.iterrows(): work = row[constants.WORK_FIELDNAME] siglum = row[constants.SIGLUM_FIELDNAME] labels[work] = row[constants.LABEL_FIELDNAME] witness_data = data.setdefault((work, siglum), {}) witness_data[row[constants.NGRAM_FIELDNAME]] = { 'count': int(row[constants.COUNT_FIELDNAME]), 'size': int(row[constants.SIZE_FIELDNAME])} for witness_data in data.values(): ngrams = list(witness_data.keys()) ngrams.sort(key=lambda ngram: witness_data[ngram]['size'], reverse=True) for ngram in ngrams: if witness_data[ngram]['count'] > 0: self._reduce_by_ngram(witness_data, ngram) # Recreate rows from the modified data structure. rows = [] for (work, siglum), witness_data in data.items(): for ngram, ngram_data in witness_data.items(): count = ngram_data['count'] if count > 0: rows.append( {constants.NGRAM_FIELDNAME: ngram, constants.SIZE_FIELDNAME: ngram_data['size'], constants.WORK_FIELDNAME: work, constants.SIGLUM_FIELDNAME: siglum, constants.COUNT_FIELDNAME: count, constants.LABEL_FIELDNAME: labels[work]}) self._matches = pd.DataFrame( rows, columns=constants.QUERY_FIELDNAMES)
[ "def", "reduce", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Reducing the n-grams'", ")", "# This does not make use of any pandas functionality; it", "# probably could, and if so ought to.", "data", "=", "{", "}", "labels", "=", "{", "}", "# Der...
Removes results rows whose n-grams are contained in larger n-grams.
[ "Removes", "results", "rows", "whose", "n", "-", "grams", "are", "contained", "in", "larger", "n", "-", "grams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L892-L930
ajenhl/tacl
tacl/results.py
Results._reduce_by_ngram
def _reduce_by_ngram(self, data, ngram): """Lowers the counts of all n-grams in `data` that are substrings of `ngram` by `ngram`\'s count. Modifies `data` in place. :param data: row data dictionary for the current text :type data: `dict` :param ngram: n-gram being reduced :type ngram: `str` """ # Find all substrings of `ngram` and reduce their count by the # count of `ngram`. Substrings may not exist in `data`. count = data[ngram]['count'] for substring in self._generate_substrings(ngram, data[ngram]['size']): try: substring_data = data[substring] except KeyError: continue else: substring_data['count'] -= count
python
def _reduce_by_ngram(self, data, ngram): """Lowers the counts of all n-grams in `data` that are substrings of `ngram` by `ngram`\'s count. Modifies `data` in place. :param data: row data dictionary for the current text :type data: `dict` :param ngram: n-gram being reduced :type ngram: `str` """ # Find all substrings of `ngram` and reduce their count by the # count of `ngram`. Substrings may not exist in `data`. count = data[ngram]['count'] for substring in self._generate_substrings(ngram, data[ngram]['size']): try: substring_data = data[substring] except KeyError: continue else: substring_data['count'] -= count
[ "def", "_reduce_by_ngram", "(", "self", ",", "data", ",", "ngram", ")", ":", "# Find all substrings of `ngram` and reduce their count by the", "# count of `ngram`. Substrings may not exist in `data`.", "count", "=", "data", "[", "ngram", "]", "[", "'count'", "]", "for", "...
Lowers the counts of all n-grams in `data` that are substrings of `ngram` by `ngram`\'s count. Modifies `data` in place. :param data: row data dictionary for the current text :type data: `dict` :param ngram: n-gram being reduced :type ngram: `str`
[ "Lowers", "the", "counts", "of", "all", "n", "-", "grams", "in", "data", "that", "are", "substrings", "of", "ngram", "by", "ngram", "\\", "s", "count", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L932-L953
ajenhl/tacl
tacl/results.py
Results.relabel
def relabel(self, catalogue): """Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping of work names to labels :type catalogue: `Catalogue` """ for work, label in catalogue.items(): self._matches.loc[self._matches[constants.WORK_FIELDNAME] == work, constants.LABEL_FIELDNAME] = label
python
def relabel(self, catalogue): """Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping of work names to labels :type catalogue: `Catalogue` """ for work, label in catalogue.items(): self._matches.loc[self._matches[constants.WORK_FIELDNAME] == work, constants.LABEL_FIELDNAME] = label
[ "def", "relabel", "(", "self", ",", "catalogue", ")", ":", "for", "work", ",", "label", "in", "catalogue", ".", "items", "(", ")", ":", "self", ".", "_matches", ".", "loc", "[", "self", ".", "_matches", "[", "constants", ".", "WORK_FIELDNAME", "]", "...
Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping of work names to labels :type catalogue: `Catalogue`
[ "Relabels", "results", "rows", "according", "to", "catalogue", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L956-L969
ajenhl/tacl
tacl/results.py
Results.remove_label
def remove_label(self, label): """Removes all results rows associated with `label`. :param label: label to filter results on :type label: `str` """ self._logger.info('Removing label "{}"'.format(label)) count = self._matches[constants.LABEL_FIELDNAME].value_counts().get( label, 0) self._matches = self._matches[ self._matches[constants.LABEL_FIELDNAME] != label] self._logger.info('Removed {} labelled results'.format(count))
python
def remove_label(self, label): """Removes all results rows associated with `label`. :param label: label to filter results on :type label: `str` """ self._logger.info('Removing label "{}"'.format(label)) count = self._matches[constants.LABEL_FIELDNAME].value_counts().get( label, 0) self._matches = self._matches[ self._matches[constants.LABEL_FIELDNAME] != label] self._logger.info('Removed {} labelled results'.format(count))
[ "def", "remove_label", "(", "self", ",", "label", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Removing label \"{}\"'", ".", "format", "(", "label", ")", ")", "count", "=", "self", ".", "_matches", "[", "constants", ".", "LABEL_FIELDNAME", "]", ...
Removes all results rows associated with `label`. :param label: label to filter results on :type label: `str`
[ "Removes", "all", "results", "rows", "associated", "with", "label", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L972-L984
ajenhl/tacl
tacl/results.py
Results.sort
def sort(self): """Sorts all results rows. Sorts by: size (descending), n-gram, count (descending), label, text name, siglum. """ self._matches.sort_values( by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME, constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME, constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME], ascending=[False, True, False, True, True, True], inplace=True)
python
def sort(self): """Sorts all results rows. Sorts by: size (descending), n-gram, count (descending), label, text name, siglum. """ self._matches.sort_values( by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME, constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME, constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME], ascending=[False, True, False, True, True, True], inplace=True)
[ "def", "sort", "(", "self", ")", ":", "self", ".", "_matches", ".", "sort_values", "(", "by", "=", "[", "constants", ".", "SIZE_FIELDNAME", ",", "constants", ".", "NGRAM_FIELDNAME", ",", "constants", ".", "COUNT_FIELDNAME", ",", "constants", ".", "LABEL_FIEL...
Sorts all results rows. Sorts by: size (descending), n-gram, count (descending), label, text name, siglum.
[ "Sorts", "all", "results", "rows", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L989-L1000
ajenhl/tacl
tacl/results.py
Results.zero_fill
def zero_fill(self, corpus): """Adds rows to the results to ensure that, for every n-gram that is attested in at least one witness, every witness for that text has a row, with added rows having a count of zero. :param corpus: corpus containing the texts appearing in the results :type corpus: `Corpus` """ self._logger.info('Zero-filling results') zero_rows = [] work_sigla = {} grouping_cols = [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME, constants.WORK_FIELDNAME] grouped = self._matches.groupby(grouping_cols, sort=False) for (label, ngram, size, work), group in grouped: row_data = { constants.NGRAM_FIELDNAME: ngram, constants.LABEL_FIELDNAME: label, constants.SIZE_FIELDNAME: size, constants.COUNT_FIELDNAME: 0, constants.WORK_FIELDNAME: work, } if work not in work_sigla: work_sigla[work] = corpus.get_sigla(work) for siglum in work_sigla[work]: if group[group[constants.SIGLUM_FIELDNAME] == siglum].empty: row_data[constants.SIGLUM_FIELDNAME] = siglum zero_rows.append(row_data) zero_df = pd.DataFrame(zero_rows, columns=constants.QUERY_FIELDNAMES) self._matches = pd.concat([self._matches, zero_df], ignore_index=True, sort=False)
python
def zero_fill(self, corpus): """Adds rows to the results to ensure that, for every n-gram that is attested in at least one witness, every witness for that text has a row, with added rows having a count of zero. :param corpus: corpus containing the texts appearing in the results :type corpus: `Corpus` """ self._logger.info('Zero-filling results') zero_rows = [] work_sigla = {} grouping_cols = [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME, constants.WORK_FIELDNAME] grouped = self._matches.groupby(grouping_cols, sort=False) for (label, ngram, size, work), group in grouped: row_data = { constants.NGRAM_FIELDNAME: ngram, constants.LABEL_FIELDNAME: label, constants.SIZE_FIELDNAME: size, constants.COUNT_FIELDNAME: 0, constants.WORK_FIELDNAME: work, } if work not in work_sigla: work_sigla[work] = corpus.get_sigla(work) for siglum in work_sigla[work]: if group[group[constants.SIGLUM_FIELDNAME] == siglum].empty: row_data[constants.SIGLUM_FIELDNAME] = siglum zero_rows.append(row_data) zero_df = pd.DataFrame(zero_rows, columns=constants.QUERY_FIELDNAMES) self._matches = pd.concat([self._matches, zero_df], ignore_index=True, sort=False)
[ "def", "zero_fill", "(", "self", ",", "corpus", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Zero-filling results'", ")", "zero_rows", "=", "[", "]", "work_sigla", "=", "{", "}", "grouping_cols", "=", "[", "constants", ".", "LABEL_FIELDNAME", ",",...
Adds rows to the results to ensure that, for every n-gram that is attested in at least one witness, every witness for that text has a row, with added rows having a count of zero. :param corpus: corpus containing the texts appearing in the results :type corpus: `Corpus`
[ "Adds", "rows", "to", "the", "results", "to", "ensure", "that", "for", "every", "n", "-", "gram", "that", "is", "attested", "in", "at", "least", "one", "witness", "every", "witness", "for", "that", "text", "has", "a", "row", "with", "added", "rows", "h...
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L1005-L1036
SuperCowPowers/chains
chains/utils/log_utils.py
get_logger
def get_logger(): """Setup logging output defaults""" # Grab the logger if not hasattr(get_logger, 'logger'): # Setup the default logging config get_logger.logger = logging.getLogger('chains') format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s' logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, format=format_str) # Return the logger return get_logger.logger
python
def get_logger(): """Setup logging output defaults""" # Grab the logger if not hasattr(get_logger, 'logger'): # Setup the default logging config get_logger.logger = logging.getLogger('chains') format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s' logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, format=format_str) # Return the logger return get_logger.logger
[ "def", "get_logger", "(", ")", ":", "# Grab the logger", "if", "not", "hasattr", "(", "get_logger", ",", "'logger'", ")", ":", "# Setup the default logging config", "get_logger", ".", "logger", "=", "logging", ".", "getLogger", "(", "'chains'", ")", "format_str", ...
Setup logging output defaults
[ "Setup", "logging", "output", "defaults" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/log_utils.py#L7-L19
SuperCowPowers/chains
chains/sources/packet_streamer.py
PacketStreamer.read_interface
def read_interface(self): """Read Packets from the packet capture interface""" # Spin up the packet capture if self._iface_is_file(): self.pcap = pcapy.open_offline(self.iface_name) else: try: # self.pcap = pcap.pcap(name=self.iface_name, promisc=True, immediate=True) # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) self.pcap = pcapy.open_live(self.iface_name, 65536 , 1 , 0) except OSError: try: logger.warning('Could not get promisc mode, turning flag off') self.pcap = pcapy.open_live(self.iface_name, 65536 , 0 , 0) except OSError: log_utils.panic('Could no open interface with any options (may need to be sudo)') # Add the BPF if it's specified if self.bpf: self.pcap.setfilter(self.bpf) print('listening on %s: %s' % (self.iface_name, self.bpf)) # For each packet in the pcap process the contents _packets = 0 while True: # Grab the next header and packet buffer header, raw_buf = self.pcap.next() # If we don't get a packet header break out of the loop if not header: break; # Extract the timestamp from the header and yield the packet seconds, micro_sec = header.getts() timestamp = seconds + micro_sec * 10**-6 yield {'timestamp': timestamp, 'raw_buf': raw_buf, 'packet_num': _packets} _packets += 1 # Is there a max packets set if so break on it if self.max_packets and _packets >= self.max_packets: break # All done so report and raise a StopIteration try: print('Packet stats: %d received, %d dropped, %d dropped by interface' % self.pcap.stats()) except pcapy.PcapError: print('No stats available...') raise StopIteration
python
def read_interface(self): """Read Packets from the packet capture interface""" # Spin up the packet capture if self._iface_is_file(): self.pcap = pcapy.open_offline(self.iface_name) else: try: # self.pcap = pcap.pcap(name=self.iface_name, promisc=True, immediate=True) # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) self.pcap = pcapy.open_live(self.iface_name, 65536 , 1 , 0) except OSError: try: logger.warning('Could not get promisc mode, turning flag off') self.pcap = pcapy.open_live(self.iface_name, 65536 , 0 , 0) except OSError: log_utils.panic('Could no open interface with any options (may need to be sudo)') # Add the BPF if it's specified if self.bpf: self.pcap.setfilter(self.bpf) print('listening on %s: %s' % (self.iface_name, self.bpf)) # For each packet in the pcap process the contents _packets = 0 while True: # Grab the next header and packet buffer header, raw_buf = self.pcap.next() # If we don't get a packet header break out of the loop if not header: break; # Extract the timestamp from the header and yield the packet seconds, micro_sec = header.getts() timestamp = seconds + micro_sec * 10**-6 yield {'timestamp': timestamp, 'raw_buf': raw_buf, 'packet_num': _packets} _packets += 1 # Is there a max packets set if so break on it if self.max_packets and _packets >= self.max_packets: break # All done so report and raise a StopIteration try: print('Packet stats: %d received, %d dropped, %d dropped by interface' % self.pcap.stats()) except pcapy.PcapError: print('No stats available...') raise StopIteration
[ "def", "read_interface", "(", "self", ")", ":", "# Spin up the packet capture", "if", "self", ".", "_iface_is_file", "(", ")", ":", "self", ".", "pcap", "=", "pcapy", ".", "open_offline", "(", "self", ".", "iface_name", ")", "else", ":", "try", ":", "# sel...
Read Packets from the packet capture interface
[ "Read", "Packets", "from", "the", "packet", "capture", "interface" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/sources/packet_streamer.py#L64-L114
ajenhl/tacl
tacl/__main__.py
generate_parser
def generate_parser(): """Returns a parser configured with sub-commands and arguments.""" parser = argparse.ArgumentParser( description=constants.TACL_DESCRIPTION, formatter_class=ParagraphFormatter) subparsers = parser.add_subparsers(title='subcommands') generate_align_subparser(subparsers) generate_catalogue_subparser(subparsers) generate_counts_subparser(subparsers) generate_diff_subparser(subparsers) generate_excise_subparser(subparsers) generate_highlight_subparser(subparsers) generate_intersect_subparser(subparsers) generate_lifetime_subparser(subparsers) generate_ngrams_subparser(subparsers) generate_prepare_subparser(subparsers) generate_results_subparser(subparsers) generate_supplied_diff_subparser(subparsers) generate_search_subparser(subparsers) generate_supplied_intersect_subparser(subparsers) generate_statistics_subparser(subparsers) generate_strip_subparser(subparsers) return parser
python
def generate_parser(): """Returns a parser configured with sub-commands and arguments.""" parser = argparse.ArgumentParser( description=constants.TACL_DESCRIPTION, formatter_class=ParagraphFormatter) subparsers = parser.add_subparsers(title='subcommands') generate_align_subparser(subparsers) generate_catalogue_subparser(subparsers) generate_counts_subparser(subparsers) generate_diff_subparser(subparsers) generate_excise_subparser(subparsers) generate_highlight_subparser(subparsers) generate_intersect_subparser(subparsers) generate_lifetime_subparser(subparsers) generate_ngrams_subparser(subparsers) generate_prepare_subparser(subparsers) generate_results_subparser(subparsers) generate_supplied_diff_subparser(subparsers) generate_search_subparser(subparsers) generate_supplied_intersect_subparser(subparsers) generate_statistics_subparser(subparsers) generate_strip_subparser(subparsers) return parser
[ "def", "generate_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "constants", ".", "TACL_DESCRIPTION", ",", "formatter_class", "=", "ParagraphFormatter", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(...
Returns a parser configured with sub-commands and arguments.
[ "Returns", "a", "parser", "configured", "with", "sub", "-", "commands", "and", "arguments", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L73-L95
ajenhl/tacl
tacl/__main__.py
generate_align_subparser
def generate_align_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate aligned sequences from a set of results.""" parser = subparsers.add_parser( 'align', description=constants.ALIGN_DESCRIPTION, epilog=constants.ALIGN_EPILOG, formatter_class=ParagraphFormatter, help=constants.ALIGN_HELP) parser.set_defaults(func=align_results) utils.add_common_arguments(parser) parser.add_argument('-m', '--minimum', default=20, help=constants.ALIGN_MINIMUM_SIZE_HELP, type=int) utils.add_corpus_arguments(parser) parser.add_argument('output', help=constants.ALIGN_OUTPUT_HELP, metavar='OUTPUT') parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP, metavar='RESULTS')
python
def generate_align_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate aligned sequences from a set of results.""" parser = subparsers.add_parser( 'align', description=constants.ALIGN_DESCRIPTION, epilog=constants.ALIGN_EPILOG, formatter_class=ParagraphFormatter, help=constants.ALIGN_HELP) parser.set_defaults(func=align_results) utils.add_common_arguments(parser) parser.add_argument('-m', '--minimum', default=20, help=constants.ALIGN_MINIMUM_SIZE_HELP, type=int) utils.add_corpus_arguments(parser) parser.add_argument('output', help=constants.ALIGN_OUTPUT_HELP, metavar='OUTPUT') parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP, metavar='RESULTS')
[ "def", "generate_align_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'align'", ",", "description", "=", "constants", ".", "ALIGN_DESCRIPTION", ",", "epilog", "=", "constants", ".", "ALIGN_EPILOG", ",", "formatter_cl...
Adds a sub-command parser to `subparsers` to generate aligned sequences from a set of results.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "generate", "aligned", "sequences", "from", "a", "set", "of", "results", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L98-L113
ajenhl/tacl
tacl/__main__.py
generate_catalogue
def generate_catalogue(args, parser): """Generates and saves a catalogue file.""" catalogue = tacl.Catalogue() catalogue.generate(args.corpus, args.label) catalogue.save(args.catalogue)
python
def generate_catalogue(args, parser): """Generates and saves a catalogue file.""" catalogue = tacl.Catalogue() catalogue.generate(args.corpus, args.label) catalogue.save(args.catalogue)
[ "def", "generate_catalogue", "(", "args", ",", "parser", ")", ":", "catalogue", "=", "tacl", ".", "Catalogue", "(", ")", "catalogue", ".", "generate", "(", "args", ".", "corpus", ",", "args", ".", "label", ")", "catalogue", ".", "save", "(", "args", "....
Generates and saves a catalogue file.
[ "Generates", "and", "saves", "a", "catalogue", "file", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L116-L120
ajenhl/tacl
tacl/__main__.py
generate_catalogue_subparser
def generate_catalogue_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate and save a catalogue file.""" parser = subparsers.add_parser( 'catalogue', description=constants.CATALOGUE_DESCRIPTION, epilog=constants.CATALOGUE_EPILOG, formatter_class=ParagraphFormatter, help=constants.CATALOGUE_HELP) utils.add_common_arguments(parser) parser.set_defaults(func=generate_catalogue) parser.add_argument('corpus', help=constants.DB_CORPUS_HELP, metavar='CORPUS') utils.add_query_arguments(parser) parser.add_argument('-l', '--label', default='', help=constants.CATALOGUE_LABEL_HELP)
python
def generate_catalogue_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate and save a catalogue file.""" parser = subparsers.add_parser( 'catalogue', description=constants.CATALOGUE_DESCRIPTION, epilog=constants.CATALOGUE_EPILOG, formatter_class=ParagraphFormatter, help=constants.CATALOGUE_HELP) utils.add_common_arguments(parser) parser.set_defaults(func=generate_catalogue) parser.add_argument('corpus', help=constants.DB_CORPUS_HELP, metavar='CORPUS') utils.add_query_arguments(parser) parser.add_argument('-l', '--label', default='', help=constants.CATALOGUE_LABEL_HELP)
[ "def", "generate_catalogue_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'catalogue'", ",", "description", "=", "constants", ".", "CATALOGUE_DESCRIPTION", ",", "epilog", "=", "constants", ".", "CATALOGUE_EPILOG", ",",...
Adds a sub-command parser to `subparsers` to generate and save a catalogue file.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "generate", "and", "save", "a", "catalogue", "file", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L123-L136
ajenhl/tacl
tacl/__main__.py
generate_counts_subparser
def generate_counts_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a counts query.""" parser = subparsers.add_parser( 'counts', description=constants.COUNTS_DESCRIPTION, epilog=constants.COUNTS_EPILOG, formatter_class=ParagraphFormatter, help=constants.COUNTS_HELP) parser.set_defaults(func=ngram_counts) utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser)
python
def generate_counts_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a counts query.""" parser = subparsers.add_parser( 'counts', description=constants.COUNTS_DESCRIPTION, epilog=constants.COUNTS_EPILOG, formatter_class=ParagraphFormatter, help=constants.COUNTS_HELP) parser.set_defaults(func=ngram_counts) utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser)
[ "def", "generate_counts_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'counts'", ",", "description", "=", "constants", ".", "COUNTS_DESCRIPTION", ",", "epilog", "=", "constants", ".", "COUNTS_EPILOG", ",", "formatte...
Adds a sub-command parser to `subparsers` to make a counts query.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "make", "a", "counts", "query", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L139-L150
ajenhl/tacl
tacl/__main__.py
generate_diff_subparser
def generate_diff_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a diff query.""" parser = subparsers.add_parser( 'diff', description=constants.DIFF_DESCRIPTION, epilog=constants.DIFF_EPILOG, formatter_class=ParagraphFormatter, help=constants.DIFF_HELP) parser.set_defaults(func=ngram_diff) group = parser.add_mutually_exclusive_group() group.add_argument('-a', '--asymmetric', help=constants.ASYMMETRIC_HELP, metavar='LABEL') utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser)
python
def generate_diff_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a diff query.""" parser = subparsers.add_parser( 'diff', description=constants.DIFF_DESCRIPTION, epilog=constants.DIFF_EPILOG, formatter_class=ParagraphFormatter, help=constants.DIFF_HELP) parser.set_defaults(func=ngram_diff) group = parser.add_mutually_exclusive_group() group.add_argument('-a', '--asymmetric', help=constants.ASYMMETRIC_HELP, metavar='LABEL') utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser)
[ "def", "generate_diff_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'diff'", ",", "description", "=", "constants", ".", "DIFF_DESCRIPTION", ",", "epilog", "=", "constants", ".", "DIFF_EPILOG", ",", "formatter_class"...
Adds a sub-command parser to `subparsers` to make a diff query.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "make", "a", "diff", "query", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L153-L167
ajenhl/tacl
tacl/__main__.py
generate_excise_subparser
def generate_excise_subparser(subparsers): """Adds a sub-command parser to `subparsers` to excise n-grams from witnesses.""" parser = subparsers.add_parser( 'excise', description=constants.EXCISE_DESCRIPTION, help=constants.EXCISE_HELP) parser.set_defaults(func=excise) utils.add_common_arguments(parser) parser.add_argument('ngrams', metavar='NGRAMS', help=constants.EXCISE_NGRAMS_HELP) parser.add_argument('replacement', metavar='REPLACEMENT', help=constants.EXCISE_REPLACEMENT_HELP) parser.add_argument('output', metavar='OUTPUT', help=constants.EXCISE_OUTPUT_HELP) utils.add_corpus_arguments(parser) parser.add_argument('works', metavar='WORK', help=constants.EXCISE_WORKS_HELP, nargs='+')
python
def generate_excise_subparser(subparsers): """Adds a sub-command parser to `subparsers` to excise n-grams from witnesses.""" parser = subparsers.add_parser( 'excise', description=constants.EXCISE_DESCRIPTION, help=constants.EXCISE_HELP) parser.set_defaults(func=excise) utils.add_common_arguments(parser) parser.add_argument('ngrams', metavar='NGRAMS', help=constants.EXCISE_NGRAMS_HELP) parser.add_argument('replacement', metavar='REPLACEMENT', help=constants.EXCISE_REPLACEMENT_HELP) parser.add_argument('output', metavar='OUTPUT', help=constants.EXCISE_OUTPUT_HELP) utils.add_corpus_arguments(parser) parser.add_argument('works', metavar='WORK', help=constants.EXCISE_WORKS_HELP, nargs='+')
[ "def", "generate_excise_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'excise'", ",", "description", "=", "constants", ".", "EXCISE_DESCRIPTION", ",", "help", "=", "constants", ".", "EXCISE_HELP", ")", "parser", "...
Adds a sub-command parser to `subparsers` to excise n-grams from witnesses.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "excise", "n", "-", "grams", "from", "witnesses", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L170-L186
ajenhl/tacl
tacl/__main__.py
generate_highlight_subparser
def generate_highlight_subparser(subparsers): """Adds a sub-command parser to `subparsers` to highlight a witness' text with its matches in a result.""" parser = subparsers.add_parser( 'highlight', description=constants.HIGHLIGHT_DESCRIPTION, epilog=constants.HIGHLIGHT_EPILOG, formatter_class=ParagraphFormatter, help=constants.HIGHLIGHT_HELP) parser.set_defaults(func=highlight_text) utils.add_common_arguments(parser) parser.add_argument('-m', '--minus-ngrams', metavar='NGRAMS', help=constants.HIGHLIGHT_MINUS_NGRAMS_HELP) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-n', '--ngrams', action='append', metavar='NGRAMS', help=constants.HIGHLIGHT_NGRAMS_HELP) group.add_argument('-r', '--results', metavar='RESULTS', help=constants.HIGHLIGHT_RESULTS_HELP) parser.add_argument('-l', '--label', action='append', metavar='LABEL', help=constants.HIGHLIGHT_LABEL_HELP) utils.add_corpus_arguments(parser) parser.add_argument('base_name', help=constants.HIGHLIGHT_BASE_NAME_HELP, metavar='BASE_NAME') parser.add_argument('output', metavar='OUTPUT', help=constants.REPORT_OUTPUT_HELP)
python
def generate_highlight_subparser(subparsers): """Adds a sub-command parser to `subparsers` to highlight a witness' text with its matches in a result.""" parser = subparsers.add_parser( 'highlight', description=constants.HIGHLIGHT_DESCRIPTION, epilog=constants.HIGHLIGHT_EPILOG, formatter_class=ParagraphFormatter, help=constants.HIGHLIGHT_HELP) parser.set_defaults(func=highlight_text) utils.add_common_arguments(parser) parser.add_argument('-m', '--minus-ngrams', metavar='NGRAMS', help=constants.HIGHLIGHT_MINUS_NGRAMS_HELP) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-n', '--ngrams', action='append', metavar='NGRAMS', help=constants.HIGHLIGHT_NGRAMS_HELP) group.add_argument('-r', '--results', metavar='RESULTS', help=constants.HIGHLIGHT_RESULTS_HELP) parser.add_argument('-l', '--label', action='append', metavar='LABEL', help=constants.HIGHLIGHT_LABEL_HELP) utils.add_corpus_arguments(parser) parser.add_argument('base_name', help=constants.HIGHLIGHT_BASE_NAME_HELP, metavar='BASE_NAME') parser.add_argument('output', metavar='OUTPUT', help=constants.REPORT_OUTPUT_HELP)
[ "def", "generate_highlight_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'highlight'", ",", "description", "=", "constants", ".", "HIGHLIGHT_DESCRIPTION", ",", "epilog", "=", "constants", ".", "HIGHLIGHT_EPILOG", ",",...
Adds a sub-command parser to `subparsers` to highlight a witness' text with its matches in a result.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "highlight", "a", "witness", "text", "with", "its", "matches", "in", "a", "result", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L189-L211
ajenhl/tacl
tacl/__main__.py
generate_intersect_subparser
def generate_intersect_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make an intersection query.""" parser = subparsers.add_parser( 'intersect', description=constants.INTERSECT_DESCRIPTION, epilog=constants.INTERSECT_EPILOG, formatter_class=ParagraphFormatter, help=constants.INTERSECT_HELP) parser.set_defaults(func=ngram_intersection) utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser)
python
def generate_intersect_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make an intersection query.""" parser = subparsers.add_parser( 'intersect', description=constants.INTERSECT_DESCRIPTION, epilog=constants.INTERSECT_EPILOG, formatter_class=ParagraphFormatter, help=constants.INTERSECT_HELP) parser.set_defaults(func=ngram_intersection) utils.add_common_arguments(parser) utils.add_db_arguments(parser) utils.add_corpus_arguments(parser) utils.add_query_arguments(parser)
[ "def", "generate_intersect_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'intersect'", ",", "description", "=", "constants", ".", "INTERSECT_DESCRIPTION", ",", "epilog", "=", "constants", ".", "INTERSECT_EPILOG", ",",...
Adds a sub-command parser to `subparsers` to make an intersection query.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "make", "an", "intersection", "query", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L214-L225