repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Yubico/yubikey-manager | ykman/cli/oath.py | add | def add(ctx, secret, name, issuer, period, oath_type, digits, touch, algorithm,
counter, force):
"""
Add a new credential.
This will add a new credential to your YubiKey.
"""
oath_type = OATH_TYPE[oath_type]
algorithm = ALGO[algorithm]
digits = int(digits)
if not secret:
while True:
secret = click.prompt('Enter a secret key (base32)', err=True)
try:
secret = parse_b32_key(secret)
break
except Exception as e:
click.echo(e)
ensure_validated(ctx)
_add_cred(ctx, CredentialData(secret, issuer, name, oath_type, algorithm,
digits, period, counter, touch), force) | python | def add(ctx, secret, name, issuer, period, oath_type, digits, touch, algorithm,
counter, force):
"""
Add a new credential.
This will add a new credential to your YubiKey.
"""
oath_type = OATH_TYPE[oath_type]
algorithm = ALGO[algorithm]
digits = int(digits)
if not secret:
while True:
secret = click.prompt('Enter a secret key (base32)', err=True)
try:
secret = parse_b32_key(secret)
break
except Exception as e:
click.echo(e)
ensure_validated(ctx)
_add_cred(ctx, CredentialData(secret, issuer, name, oath_type, algorithm,
digits, period, counter, touch), force) | [
"def",
"add",
"(",
"ctx",
",",
"secret",
",",
"name",
",",
"issuer",
",",
"period",
",",
"oath_type",
",",
"digits",
",",
"touch",
",",
"algorithm",
",",
"counter",
",",
"force",
")",
":",
"oath_type",
"=",
"OATH_TYPE",
"[",
"oath_type",
"]",
"algorithm",
"=",
"ALGO",
"[",
"algorithm",
"]",
"digits",
"=",
"int",
"(",
"digits",
")",
"if",
"not",
"secret",
":",
"while",
"True",
":",
"secret",
"=",
"click",
".",
"prompt",
"(",
"'Enter a secret key (base32)'",
",",
"err",
"=",
"True",
")",
"try",
":",
"secret",
"=",
"parse_b32_key",
"(",
"secret",
")",
"break",
"except",
"Exception",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"e",
")",
"ensure_validated",
"(",
"ctx",
")",
"_add_cred",
"(",
"ctx",
",",
"CredentialData",
"(",
"secret",
",",
"issuer",
",",
"name",
",",
"oath_type",
",",
"algorithm",
",",
"digits",
",",
"period",
",",
"counter",
",",
"touch",
")",
",",
"force",
")"
]
| Add a new credential.
This will add a new credential to your YubiKey. | [
"Add",
"a",
"new",
"credential",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L192-L216 | train |
Yubico/yubikey-manager | ykman/cli/oath.py | uri | def uri(ctx, uri, touch, force):
"""
Add a new credential from URI.
Use a URI to add a new credential to your YubiKey.
"""
if not uri:
while True:
uri = click.prompt('Enter an OATH URI', err=True)
try:
uri = CredentialData.from_uri(uri)
break
except Exception as e:
click.echo(e)
ensure_validated(ctx)
data = uri
# Steam is a special case where we allow the otpauth
# URI to contain a 'digits' value of '5'.
if data.digits == 5 and data.issuer == 'Steam':
data.digits = 6
data.touch = touch
_add_cred(ctx, data, force=force) | python | def uri(ctx, uri, touch, force):
"""
Add a new credential from URI.
Use a URI to add a new credential to your YubiKey.
"""
if not uri:
while True:
uri = click.prompt('Enter an OATH URI', err=True)
try:
uri = CredentialData.from_uri(uri)
break
except Exception as e:
click.echo(e)
ensure_validated(ctx)
data = uri
# Steam is a special case where we allow the otpauth
# URI to contain a 'digits' value of '5'.
if data.digits == 5 and data.issuer == 'Steam':
data.digits = 6
data.touch = touch
_add_cred(ctx, data, force=force) | [
"def",
"uri",
"(",
"ctx",
",",
"uri",
",",
"touch",
",",
"force",
")",
":",
"if",
"not",
"uri",
":",
"while",
"True",
":",
"uri",
"=",
"click",
".",
"prompt",
"(",
"'Enter an OATH URI'",
",",
"err",
"=",
"True",
")",
"try",
":",
"uri",
"=",
"CredentialData",
".",
"from_uri",
"(",
"uri",
")",
"break",
"except",
"Exception",
"as",
"e",
":",
"click",
".",
"echo",
"(",
"e",
")",
"ensure_validated",
"(",
"ctx",
")",
"data",
"=",
"uri",
"# Steam is a special case where we allow the otpauth",
"# URI to contain a 'digits' value of '5'.",
"if",
"data",
".",
"digits",
"==",
"5",
"and",
"data",
".",
"issuer",
"==",
"'Steam'",
":",
"data",
".",
"digits",
"=",
"6",
"data",
".",
"touch",
"=",
"touch",
"_add_cred",
"(",
"ctx",
",",
"data",
",",
"force",
"=",
"force",
")"
]
| Add a new credential from URI.
Use a URI to add a new credential to your YubiKey. | [
"Add",
"a",
"new",
"credential",
"from",
"URI",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L224-L250 | train |
Yubico/yubikey-manager | ykman/cli/oath.py | list | def list(ctx, show_hidden, oath_type, period):
"""
List all credentials.
List all credentials stored on your YubiKey.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = [cred
for cred in controller.list()
if show_hidden or not cred.is_hidden
]
creds.sort()
for cred in creds:
click.echo(cred.printable_key, nl=False)
if oath_type:
click.echo(u', {}'.format(cred.oath_type.name), nl=False)
if period:
click.echo(', {}'.format(cred.period), nl=False)
click.echo() | python | def list(ctx, show_hidden, oath_type, period):
"""
List all credentials.
List all credentials stored on your YubiKey.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = [cred
for cred in controller.list()
if show_hidden or not cred.is_hidden
]
creds.sort()
for cred in creds:
click.echo(cred.printable_key, nl=False)
if oath_type:
click.echo(u', {}'.format(cred.oath_type.name), nl=False)
if period:
click.echo(', {}'.format(cred.period), nl=False)
click.echo() | [
"def",
"list",
"(",
"ctx",
",",
"show_hidden",
",",
"oath_type",
",",
"period",
")",
":",
"ensure_validated",
"(",
"ctx",
")",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"creds",
"=",
"[",
"cred",
"for",
"cred",
"in",
"controller",
".",
"list",
"(",
")",
"if",
"show_hidden",
"or",
"not",
"cred",
".",
"is_hidden",
"]",
"creds",
".",
"sort",
"(",
")",
"for",
"cred",
"in",
"creds",
":",
"click",
".",
"echo",
"(",
"cred",
".",
"printable_key",
",",
"nl",
"=",
"False",
")",
"if",
"oath_type",
":",
"click",
".",
"echo",
"(",
"u', {}'",
".",
"format",
"(",
"cred",
".",
"oath_type",
".",
"name",
")",
",",
"nl",
"=",
"False",
")",
"if",
"period",
":",
"click",
".",
"echo",
"(",
"', {}'",
".",
"format",
"(",
"cred",
".",
"period",
")",
",",
"nl",
"=",
"False",
")",
"click",
".",
"echo",
"(",
")"
]
| List all credentials.
List all credentials stored on your YubiKey. | [
"List",
"all",
"credentials",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L307-L326 | train |
Yubico/yubikey-manager | ykman/cli/oath.py | code | def code(ctx, show_hidden, query, single):
"""
Generate codes.
Generate codes from credentials stored on your YubiKey.
Provide a query string to match one or more specific credentials.
Touch and HOTP credentials require a single match to be triggered.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = [(cr, c)
for (cr, c) in controller.calculate_all()
if show_hidden or not cr.is_hidden
]
creds = _search(creds, query)
if len(creds) == 1:
cred, code = creds[0]
if cred.touch:
prompt_for_touch()
try:
if cred.oath_type == OATH_TYPE.HOTP:
# HOTP might require touch, we don't know.
# Assume yes after 500ms.
hotp_touch_timer = Timer(0.500, prompt_for_touch)
hotp_touch_timer.start()
creds = [(cred, controller.calculate(cred))]
hotp_touch_timer.cancel()
elif code is None:
creds = [(cred, controller.calculate(cred))]
except APDUError as e:
if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED:
ctx.fail('Touch credential timed out!')
elif single:
_error_multiple_hits(ctx, [cr for cr, c in creds])
if single:
click.echo(creds[0][1].value)
else:
creds.sort()
outputs = [
(
cr.printable_key,
c.value if c
else '[Touch Credential]' if cr.touch
else '[HOTP Credential]' if cr.oath_type == OATH_TYPE.HOTP
else ''
) for (cr, c) in creds
]
longest_name = max(len(n) for (n, c) in outputs) if outputs else 0
longest_code = max(len(c) for (n, c) in outputs) if outputs else 0
format_str = u'{:<%d} {:>%d}' % (longest_name, longest_code)
for name, result in outputs:
click.echo(format_str.format(name, result)) | python | def code(ctx, show_hidden, query, single):
"""
Generate codes.
Generate codes from credentials stored on your YubiKey.
Provide a query string to match one or more specific credentials.
Touch and HOTP credentials require a single match to be triggered.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = [(cr, c)
for (cr, c) in controller.calculate_all()
if show_hidden or not cr.is_hidden
]
creds = _search(creds, query)
if len(creds) == 1:
cred, code = creds[0]
if cred.touch:
prompt_for_touch()
try:
if cred.oath_type == OATH_TYPE.HOTP:
# HOTP might require touch, we don't know.
# Assume yes after 500ms.
hotp_touch_timer = Timer(0.500, prompt_for_touch)
hotp_touch_timer.start()
creds = [(cred, controller.calculate(cred))]
hotp_touch_timer.cancel()
elif code is None:
creds = [(cred, controller.calculate(cred))]
except APDUError as e:
if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED:
ctx.fail('Touch credential timed out!')
elif single:
_error_multiple_hits(ctx, [cr for cr, c in creds])
if single:
click.echo(creds[0][1].value)
else:
creds.sort()
outputs = [
(
cr.printable_key,
c.value if c
else '[Touch Credential]' if cr.touch
else '[HOTP Credential]' if cr.oath_type == OATH_TYPE.HOTP
else ''
) for (cr, c) in creds
]
longest_name = max(len(n) for (n, c) in outputs) if outputs else 0
longest_code = max(len(c) for (n, c) in outputs) if outputs else 0
format_str = u'{:<%d} {:>%d}' % (longest_name, longest_code)
for name, result in outputs:
click.echo(format_str.format(name, result)) | [
"def",
"code",
"(",
"ctx",
",",
"show_hidden",
",",
"query",
",",
"single",
")",
":",
"ensure_validated",
"(",
"ctx",
")",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"creds",
"=",
"[",
"(",
"cr",
",",
"c",
")",
"for",
"(",
"cr",
",",
"c",
")",
"in",
"controller",
".",
"calculate_all",
"(",
")",
"if",
"show_hidden",
"or",
"not",
"cr",
".",
"is_hidden",
"]",
"creds",
"=",
"_search",
"(",
"creds",
",",
"query",
")",
"if",
"len",
"(",
"creds",
")",
"==",
"1",
":",
"cred",
",",
"code",
"=",
"creds",
"[",
"0",
"]",
"if",
"cred",
".",
"touch",
":",
"prompt_for_touch",
"(",
")",
"try",
":",
"if",
"cred",
".",
"oath_type",
"==",
"OATH_TYPE",
".",
"HOTP",
":",
"# HOTP might require touch, we don't know.",
"# Assume yes after 500ms.",
"hotp_touch_timer",
"=",
"Timer",
"(",
"0.500",
",",
"prompt_for_touch",
")",
"hotp_touch_timer",
".",
"start",
"(",
")",
"creds",
"=",
"[",
"(",
"cred",
",",
"controller",
".",
"calculate",
"(",
"cred",
")",
")",
"]",
"hotp_touch_timer",
".",
"cancel",
"(",
")",
"elif",
"code",
"is",
"None",
":",
"creds",
"=",
"[",
"(",
"cred",
",",
"controller",
".",
"calculate",
"(",
"cred",
")",
")",
"]",
"except",
"APDUError",
"as",
"e",
":",
"if",
"e",
".",
"sw",
"==",
"SW",
".",
"SECURITY_CONDITION_NOT_SATISFIED",
":",
"ctx",
".",
"fail",
"(",
"'Touch credential timed out!'",
")",
"elif",
"single",
":",
"_error_multiple_hits",
"(",
"ctx",
",",
"[",
"cr",
"for",
"cr",
",",
"c",
"in",
"creds",
"]",
")",
"if",
"single",
":",
"click",
".",
"echo",
"(",
"creds",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"value",
")",
"else",
":",
"creds",
".",
"sort",
"(",
")",
"outputs",
"=",
"[",
"(",
"cr",
".",
"printable_key",
",",
"c",
".",
"value",
"if",
"c",
"else",
"'[Touch Credential]'",
"if",
"cr",
".",
"touch",
"else",
"'[HOTP Credential]'",
"if",
"cr",
".",
"oath_type",
"==",
"OATH_TYPE",
".",
"HOTP",
"else",
"''",
")",
"for",
"(",
"cr",
",",
"c",
")",
"in",
"creds",
"]",
"longest_name",
"=",
"max",
"(",
"len",
"(",
"n",
")",
"for",
"(",
"n",
",",
"c",
")",
"in",
"outputs",
")",
"if",
"outputs",
"else",
"0",
"longest_code",
"=",
"max",
"(",
"len",
"(",
"c",
")",
"for",
"(",
"n",
",",
"c",
")",
"in",
"outputs",
")",
"if",
"outputs",
"else",
"0",
"format_str",
"=",
"u'{:<%d} {:>%d}'",
"%",
"(",
"longest_name",
",",
"longest_code",
")",
"for",
"name",
",",
"result",
"in",
"outputs",
":",
"click",
".",
"echo",
"(",
"format_str",
".",
"format",
"(",
"name",
",",
"result",
")",
")"
]
| Generate codes.
Generate codes from credentials stored on your YubiKey.
Provide a query string to match one or more specific credentials.
Touch and HOTP credentials require a single match to be triggered. | [
"Generate",
"codes",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L335-L395 | train |
Yubico/yubikey-manager | ykman/cli/oath.py | delete | def delete(ctx, query, force):
"""
Delete a credential.
Delete a credential from your YubiKey.
Provide a query string to match the credential to delete.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = controller.list()
hits = _search(creds, query)
if len(hits) == 0:
click.echo('No matches, nothing to be done.')
elif len(hits) == 1:
cred = hits[0]
if force or (click.confirm(
u'Delete credential: {} ?'.format(cred.printable_key),
default=False, err=True
)):
controller.delete(cred)
click.echo(u'Deleted {}.'.format(cred.printable_key))
else:
click.echo('Deletion aborted by user.')
else:
_error_multiple_hits(ctx, hits) | python | def delete(ctx, query, force):
"""
Delete a credential.
Delete a credential from your YubiKey.
Provide a query string to match the credential to delete.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = controller.list()
hits = _search(creds, query)
if len(hits) == 0:
click.echo('No matches, nothing to be done.')
elif len(hits) == 1:
cred = hits[0]
if force or (click.confirm(
u'Delete credential: {} ?'.format(cred.printable_key),
default=False, err=True
)):
controller.delete(cred)
click.echo(u'Deleted {}.'.format(cred.printable_key))
else:
click.echo('Deletion aborted by user.')
else:
_error_multiple_hits(ctx, hits) | [
"def",
"delete",
"(",
"ctx",
",",
"query",
",",
"force",
")",
":",
"ensure_validated",
"(",
"ctx",
")",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"creds",
"=",
"controller",
".",
"list",
"(",
")",
"hits",
"=",
"_search",
"(",
"creds",
",",
"query",
")",
"if",
"len",
"(",
"hits",
")",
"==",
"0",
":",
"click",
".",
"echo",
"(",
"'No matches, nothing to be done.'",
")",
"elif",
"len",
"(",
"hits",
")",
"==",
"1",
":",
"cred",
"=",
"hits",
"[",
"0",
"]",
"if",
"force",
"or",
"(",
"click",
".",
"confirm",
"(",
"u'Delete credential: {} ?'",
".",
"format",
"(",
"cred",
".",
"printable_key",
")",
",",
"default",
"=",
"False",
",",
"err",
"=",
"True",
")",
")",
":",
"controller",
".",
"delete",
"(",
"cred",
")",
"click",
".",
"echo",
"(",
"u'Deleted {}.'",
".",
"format",
"(",
"cred",
".",
"printable_key",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'Deletion aborted by user.'",
")",
"else",
":",
"_error_multiple_hits",
"(",
"ctx",
",",
"hits",
")"
]
| Delete a credential.
Delete a credential from your YubiKey.
Provide a query string to match the credential to delete. | [
"Delete",
"a",
"credential",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L403-L429 | train |
Yubico/yubikey-manager | ykman/cli/oath.py | set_password | def set_password(ctx, new_password, remember):
"""
Password protect the OATH credentials.
Allows you to set a password that will be required to access the OATH
credentials stored on your YubiKey.
"""
ensure_validated(ctx, prompt='Enter your current password')
if not new_password:
new_password = click.prompt(
'Enter your new password',
hide_input=True,
confirmation_prompt=True,
err=True)
controller = ctx.obj['controller']
settings = ctx.obj['settings']
keys = settings.setdefault('keys', {})
key = controller.set_password(new_password)
click.echo('Password updated.')
if remember:
keys[controller.id] = b2a_hex(key).decode()
settings.write()
click.echo('Password remembered')
elif controller.id in keys:
del keys[controller.id]
settings.write() | python | def set_password(ctx, new_password, remember):
"""
Password protect the OATH credentials.
Allows you to set a password that will be required to access the OATH
credentials stored on your YubiKey.
"""
ensure_validated(ctx, prompt='Enter your current password')
if not new_password:
new_password = click.prompt(
'Enter your new password',
hide_input=True,
confirmation_prompt=True,
err=True)
controller = ctx.obj['controller']
settings = ctx.obj['settings']
keys = settings.setdefault('keys', {})
key = controller.set_password(new_password)
click.echo('Password updated.')
if remember:
keys[controller.id] = b2a_hex(key).decode()
settings.write()
click.echo('Password remembered')
elif controller.id in keys:
del keys[controller.id]
settings.write() | [
"def",
"set_password",
"(",
"ctx",
",",
"new_password",
",",
"remember",
")",
":",
"ensure_validated",
"(",
"ctx",
",",
"prompt",
"=",
"'Enter your current password'",
")",
"if",
"not",
"new_password",
":",
"new_password",
"=",
"click",
".",
"prompt",
"(",
"'Enter your new password'",
",",
"hide_input",
"=",
"True",
",",
"confirmation_prompt",
"=",
"True",
",",
"err",
"=",
"True",
")",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"settings",
"=",
"ctx",
".",
"obj",
"[",
"'settings'",
"]",
"keys",
"=",
"settings",
".",
"setdefault",
"(",
"'keys'",
",",
"{",
"}",
")",
"key",
"=",
"controller",
".",
"set_password",
"(",
"new_password",
")",
"click",
".",
"echo",
"(",
"'Password updated.'",
")",
"if",
"remember",
":",
"keys",
"[",
"controller",
".",
"id",
"]",
"=",
"b2a_hex",
"(",
"key",
")",
".",
"decode",
"(",
")",
"settings",
".",
"write",
"(",
")",
"click",
".",
"echo",
"(",
"'Password remembered'",
")",
"elif",
"controller",
".",
"id",
"in",
"keys",
":",
"del",
"keys",
"[",
"controller",
".",
"id",
"]",
"settings",
".",
"write",
"(",
")"
]
| Password protect the OATH credentials.
Allows you to set a password that will be required to access the OATH
credentials stored on your YubiKey. | [
"Password",
"protect",
"the",
"OATH",
"credentials",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L442-L468 | train |
Yubico/yubikey-manager | ykman/cli/oath.py | remember_password | def remember_password(ctx, forget, clear_all):
"""
Manage local password storage.
Store your YubiKeys password on this computer to avoid having to enter it
on each use, or delete stored passwords.
"""
controller = ctx.obj['controller']
settings = ctx.obj['settings']
keys = settings.setdefault('keys', {})
if clear_all:
del settings['keys']
settings.write()
click.echo('All passwords have been cleared.')
elif forget:
if controller.id in keys:
del keys[controller.id]
settings.write()
click.echo('Password forgotten.')
else:
ensure_validated(ctx, remember=True) | python | def remember_password(ctx, forget, clear_all):
"""
Manage local password storage.
Store your YubiKeys password on this computer to avoid having to enter it
on each use, or delete stored passwords.
"""
controller = ctx.obj['controller']
settings = ctx.obj['settings']
keys = settings.setdefault('keys', {})
if clear_all:
del settings['keys']
settings.write()
click.echo('All passwords have been cleared.')
elif forget:
if controller.id in keys:
del keys[controller.id]
settings.write()
click.echo('Password forgotten.')
else:
ensure_validated(ctx, remember=True) | [
"def",
"remember_password",
"(",
"ctx",
",",
"forget",
",",
"clear_all",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"settings",
"=",
"ctx",
".",
"obj",
"[",
"'settings'",
"]",
"keys",
"=",
"settings",
".",
"setdefault",
"(",
"'keys'",
",",
"{",
"}",
")",
"if",
"clear_all",
":",
"del",
"settings",
"[",
"'keys'",
"]",
"settings",
".",
"write",
"(",
")",
"click",
".",
"echo",
"(",
"'All passwords have been cleared.'",
")",
"elif",
"forget",
":",
"if",
"controller",
".",
"id",
"in",
"keys",
":",
"del",
"keys",
"[",
"controller",
".",
"id",
"]",
"settings",
".",
"write",
"(",
")",
"click",
".",
"echo",
"(",
"'Password forgotten.'",
")",
"else",
":",
"ensure_validated",
"(",
"ctx",
",",
"remember",
"=",
"True",
")"
]
| Manage local password storage.
Store your YubiKeys password on this computer to avoid having to enter it
on each use, or delete stored passwords. | [
"Manage",
"local",
"password",
"storage",
"."
]
| 3ac27bc59ae76a59db9d09a530494add2edbbabf | https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L476-L496 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.refresh_balance | def refresh_balance(self):
"""
Recalculate self.balance and self.depth based on child node values.
"""
left_depth = self.left_node.depth if self.left_node else 0
right_depth = self.right_node.depth if self.right_node else 0
self.depth = 1 + max(left_depth, right_depth)
self.balance = right_depth - left_depth | python | def refresh_balance(self):
"""
Recalculate self.balance and self.depth based on child node values.
"""
left_depth = self.left_node.depth if self.left_node else 0
right_depth = self.right_node.depth if self.right_node else 0
self.depth = 1 + max(left_depth, right_depth)
self.balance = right_depth - left_depth | [
"def",
"refresh_balance",
"(",
"self",
")",
":",
"left_depth",
"=",
"self",
".",
"left_node",
".",
"depth",
"if",
"self",
".",
"left_node",
"else",
"0",
"right_depth",
"=",
"self",
".",
"right_node",
".",
"depth",
"if",
"self",
".",
"right_node",
"else",
"0",
"self",
".",
"depth",
"=",
"1",
"+",
"max",
"(",
"left_depth",
",",
"right_depth",
")",
"self",
".",
"balance",
"=",
"right_depth",
"-",
"left_depth"
]
| Recalculate self.balance and self.depth based on child node values. | [
"Recalculate",
"self",
".",
"balance",
"and",
"self",
".",
"depth",
"based",
"on",
"child",
"node",
"values",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L100-L107 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.compute_depth | def compute_depth(self):
"""
Recursively computes true depth of the subtree. Should only
be needed for debugging. Unless something is wrong, the
depth field should reflect the correct depth of the subtree.
"""
left_depth = self.left_node.compute_depth() if self.left_node else 0
right_depth = self.right_node.compute_depth() if self.right_node else 0
return 1 + max(left_depth, right_depth) | python | def compute_depth(self):
"""
Recursively computes true depth of the subtree. Should only
be needed for debugging. Unless something is wrong, the
depth field should reflect the correct depth of the subtree.
"""
left_depth = self.left_node.compute_depth() if self.left_node else 0
right_depth = self.right_node.compute_depth() if self.right_node else 0
return 1 + max(left_depth, right_depth) | [
"def",
"compute_depth",
"(",
"self",
")",
":",
"left_depth",
"=",
"self",
".",
"left_node",
".",
"compute_depth",
"(",
")",
"if",
"self",
".",
"left_node",
"else",
"0",
"right_depth",
"=",
"self",
".",
"right_node",
".",
"compute_depth",
"(",
")",
"if",
"self",
".",
"right_node",
"else",
"0",
"return",
"1",
"+",
"max",
"(",
"left_depth",
",",
"right_depth",
")"
]
| Recursively computes true depth of the subtree. Should only
be needed for debugging. Unless something is wrong, the
depth field should reflect the correct depth of the subtree. | [
"Recursively",
"computes",
"true",
"depth",
"of",
"the",
"subtree",
".",
"Should",
"only",
"be",
"needed",
"for",
"debugging",
".",
"Unless",
"something",
"is",
"wrong",
"the",
"depth",
"field",
"should",
"reflect",
"the",
"correct",
"depth",
"of",
"the",
"subtree",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L109-L117 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.rotate | def rotate(self):
"""
Does rotating, if necessary, to balance this node, and
returns the new top node.
"""
self.refresh_balance()
if abs(self.balance) < 2:
return self
# balance > 0 is the heavy side
my_heavy = self.balance > 0
child_heavy = self[my_heavy].balance > 0
if my_heavy == child_heavy or self[my_heavy].balance == 0:
## Heavy sides same
# self save
# save -> 1 self
# 1
#
## Heavy side balanced
# self save save
# save -> 1 self -> 1 self.rot()
# 1 2 2
return self.srotate()
else:
return self.drotate() | python | def rotate(self):
"""
Does rotating, if necessary, to balance this node, and
returns the new top node.
"""
self.refresh_balance()
if abs(self.balance) < 2:
return self
# balance > 0 is the heavy side
my_heavy = self.balance > 0
child_heavy = self[my_heavy].balance > 0
if my_heavy == child_heavy or self[my_heavy].balance == 0:
## Heavy sides same
# self save
# save -> 1 self
# 1
#
## Heavy side balanced
# self save save
# save -> 1 self -> 1 self.rot()
# 1 2 2
return self.srotate()
else:
return self.drotate() | [
"def",
"rotate",
"(",
"self",
")",
":",
"self",
".",
"refresh_balance",
"(",
")",
"if",
"abs",
"(",
"self",
".",
"balance",
")",
"<",
"2",
":",
"return",
"self",
"# balance > 0 is the heavy side",
"my_heavy",
"=",
"self",
".",
"balance",
">",
"0",
"child_heavy",
"=",
"self",
"[",
"my_heavy",
"]",
".",
"balance",
">",
"0",
"if",
"my_heavy",
"==",
"child_heavy",
"or",
"self",
"[",
"my_heavy",
"]",
".",
"balance",
"==",
"0",
":",
"## Heavy sides same",
"# self save",
"# save -> 1 self",
"# 1",
"#",
"## Heavy side balanced",
"# self save save",
"# save -> 1 self -> 1 self.rot()",
"# 1 2 2",
"return",
"self",
".",
"srotate",
"(",
")",
"else",
":",
"return",
"self",
".",
"drotate",
"(",
")"
]
| Does rotating, if necessary, to balance this node, and
returns the new top node. | [
"Does",
"rotating",
"if",
"necessary",
"to",
"balance",
"this",
"node",
"and",
"returns",
"the",
"new",
"top",
"node",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L119-L142 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.srotate | def srotate(self):
"""Single rotation. Assumes that balance is +-2."""
# self save save
# save 3 -> 1 self -> 1 self.rot()
# 1 2 2 3
#
# self save save
# 3 save -> self 1 -> self.rot() 1
# 2 1 3 2
#assert(self.balance != 0)
heavy = self.balance > 0
light = not heavy
save = self[heavy]
#print("srotate: bal={},{}".format(self.balance, save.balance))
#self.print_structure()
self[heavy] = save[light] # 2
#assert(save[light])
save[light] = self.rotate() # Needed to ensure the 2 and 3 are balanced under new subnode
# Some intervals may overlap both self.x_center and save.x_center
# Promote those to the new tip of the tree
promotees = [iv for iv in save[light].s_center if save.center_hit(iv)]
if promotees:
for iv in promotees:
save[light] = save[light].remove(iv) # may trigger pruning
# TODO: Use Node.add() here, to simplify future balancing improvements.
# For now, this is the same as augmenting save.s_center, but that may
# change.
save.s_center.update(promotees)
save.refresh_balance()
return save | python | def srotate(self):
"""Single rotation. Assumes that balance is +-2."""
# self save save
# save 3 -> 1 self -> 1 self.rot()
# 1 2 2 3
#
# self save save
# 3 save -> self 1 -> self.rot() 1
# 2 1 3 2
#assert(self.balance != 0)
heavy = self.balance > 0
light = not heavy
save = self[heavy]
#print("srotate: bal={},{}".format(self.balance, save.balance))
#self.print_structure()
self[heavy] = save[light] # 2
#assert(save[light])
save[light] = self.rotate() # Needed to ensure the 2 and 3 are balanced under new subnode
# Some intervals may overlap both self.x_center and save.x_center
# Promote those to the new tip of the tree
promotees = [iv for iv in save[light].s_center if save.center_hit(iv)]
if promotees:
for iv in promotees:
save[light] = save[light].remove(iv) # may trigger pruning
# TODO: Use Node.add() here, to simplify future balancing improvements.
# For now, this is the same as augmenting save.s_center, but that may
# change.
save.s_center.update(promotees)
save.refresh_balance()
return save | [
"def",
"srotate",
"(",
"self",
")",
":",
"# self save save",
"# save 3 -> 1 self -> 1 self.rot()",
"# 1 2 2 3",
"#",
"# self save save",
"# 3 save -> self 1 -> self.rot() 1",
"# 2 1 3 2",
"#assert(self.balance != 0)",
"heavy",
"=",
"self",
".",
"balance",
">",
"0",
"light",
"=",
"not",
"heavy",
"save",
"=",
"self",
"[",
"heavy",
"]",
"#print(\"srotate: bal={},{}\".format(self.balance, save.balance))",
"#self.print_structure()",
"self",
"[",
"heavy",
"]",
"=",
"save",
"[",
"light",
"]",
"# 2",
"#assert(save[light])",
"save",
"[",
"light",
"]",
"=",
"self",
".",
"rotate",
"(",
")",
"# Needed to ensure the 2 and 3 are balanced under new subnode",
"# Some intervals may overlap both self.x_center and save.x_center",
"# Promote those to the new tip of the tree",
"promotees",
"=",
"[",
"iv",
"for",
"iv",
"in",
"save",
"[",
"light",
"]",
".",
"s_center",
"if",
"save",
".",
"center_hit",
"(",
"iv",
")",
"]",
"if",
"promotees",
":",
"for",
"iv",
"in",
"promotees",
":",
"save",
"[",
"light",
"]",
"=",
"save",
"[",
"light",
"]",
".",
"remove",
"(",
"iv",
")",
"# may trigger pruning",
"# TODO: Use Node.add() here, to simplify future balancing improvements.",
"# For now, this is the same as augmenting save.s_center, but that may",
"# change.",
"save",
".",
"s_center",
".",
"update",
"(",
"promotees",
")",
"save",
".",
"refresh_balance",
"(",
")",
"return",
"save"
]
| Single rotation. Assumes that balance is +-2. | [
"Single",
"rotation",
".",
"Assumes",
"that",
"balance",
"is",
"+",
"-",
"2",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L144-L175 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.add | def add(self, interval):
"""
Returns self after adding the interval and balancing.
"""
if self.center_hit(interval):
self.s_center.add(interval)
return self
else:
direction = self.hit_branch(interval)
if not self[direction]:
self[direction] = Node.from_interval(interval)
self.refresh_balance()
return self
else:
self[direction] = self[direction].add(interval)
return self.rotate() | python | def add(self, interval):
"""
Returns self after adding the interval and balancing.
"""
if self.center_hit(interval):
self.s_center.add(interval)
return self
else:
direction = self.hit_branch(interval)
if not self[direction]:
self[direction] = Node.from_interval(interval)
self.refresh_balance()
return self
else:
self[direction] = self[direction].add(interval)
return self.rotate() | [
"def",
"add",
"(",
"self",
",",
"interval",
")",
":",
"if",
"self",
".",
"center_hit",
"(",
"interval",
")",
":",
"self",
".",
"s_center",
".",
"add",
"(",
"interval",
")",
"return",
"self",
"else",
":",
"direction",
"=",
"self",
".",
"hit_branch",
"(",
"interval",
")",
"if",
"not",
"self",
"[",
"direction",
"]",
":",
"self",
"[",
"direction",
"]",
"=",
"Node",
".",
"from_interval",
"(",
"interval",
")",
"self",
".",
"refresh_balance",
"(",
")",
"return",
"self",
"else",
":",
"self",
"[",
"direction",
"]",
"=",
"self",
"[",
"direction",
"]",
".",
"add",
"(",
"interval",
")",
"return",
"self",
".",
"rotate",
"(",
")"
]
| Returns self after adding the interval and balancing. | [
"Returns",
"self",
"after",
"adding",
"the",
"interval",
"and",
"balancing",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L188-L203 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.remove | def remove(self, interval):
"""
Returns self after removing the interval and balancing.
If interval is not present, raise ValueError.
"""
# since this is a list, called methods can set this to [1],
# making it true
done = []
return self.remove_interval_helper(interval, done, should_raise_error=True) | python | def remove(self, interval):
"""
Returns self after removing the interval and balancing.
If interval is not present, raise ValueError.
"""
# since this is a list, called methods can set this to [1],
# making it true
done = []
return self.remove_interval_helper(interval, done, should_raise_error=True) | [
"def",
"remove",
"(",
"self",
",",
"interval",
")",
":",
"# since this is a list, called methods can set this to [1],",
"# making it true",
"done",
"=",
"[",
"]",
"return",
"self",
".",
"remove_interval_helper",
"(",
"interval",
",",
"done",
",",
"should_raise_error",
"=",
"True",
")"
]
| Returns self after removing the interval and balancing.
If interval is not present, raise ValueError. | [
"Returns",
"self",
"after",
"removing",
"the",
"interval",
"and",
"balancing",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L205-L214 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.discard | def discard(self, interval):
"""
Returns self after removing interval and balancing.
If interval is not present, do nothing.
"""
done = []
return self.remove_interval_helper(interval, done, should_raise_error=False) | python | def discard(self, interval):
"""
Returns self after removing interval and balancing.
If interval is not present, do nothing.
"""
done = []
return self.remove_interval_helper(interval, done, should_raise_error=False) | [
"def",
"discard",
"(",
"self",
",",
"interval",
")",
":",
"done",
"=",
"[",
"]",
"return",
"self",
".",
"remove_interval_helper",
"(",
"interval",
",",
"done",
",",
"should_raise_error",
"=",
"False",
")"
]
| Returns self after removing interval and balancing.
If interval is not present, do nothing. | [
"Returns",
"self",
"after",
"removing",
"interval",
"and",
"balancing",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L216-L223 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.remove_interval_helper | def remove_interval_helper(self, interval, done, should_raise_error):
"""
Returns self after removing interval and balancing.
If interval doesn't exist, raise ValueError.
This method may set done to [1] to tell all callers that
rebalancing has completed.
See Eternally Confuzzled's jsw_remove_r function (lines 1-32)
in his AVL tree article for reference.
"""
#trace = interval.begin == 347 and interval.end == 353
#if trace: print('\nRemoving from {} interval {}'.format(
# self.x_center, interval))
if self.center_hit(interval):
#if trace: print('Hit at {}'.format(self.x_center))
if not should_raise_error and interval not in self.s_center:
done.append(1)
#if trace: print('Doing nothing.')
return self
try:
# raises error if interval not present - this is
# desired.
self.s_center.remove(interval)
except:
self.print_structure()
raise KeyError(interval)
if self.s_center: # keep this node
done.append(1) # no rebalancing necessary
#if trace: print('Removed, no rebalancing.')
return self
# If we reach here, no intervals are left in self.s_center.
# So, prune self.
return self.prune()
else: # interval not in s_center
direction = self.hit_branch(interval)
if not self[direction]:
if should_raise_error:
raise ValueError
done.append(1)
return self
#if trace:
# print('Descending to {} branch'.format(
# ['left', 'right'][direction]
# ))
self[direction] = self[direction].remove_interval_helper(interval, done, should_raise_error)
# Clean up
if not done:
#if trace:
# print('Rotating {}'.format(self.x_center))
# self.print_structure()
return self.rotate()
return self | python | def remove_interval_helper(self, interval, done, should_raise_error):
"""
Returns self after removing interval and balancing.
If interval doesn't exist, raise ValueError.
This method may set done to [1] to tell all callers that
rebalancing has completed.
See Eternally Confuzzled's jsw_remove_r function (lines 1-32)
in his AVL tree article for reference.
"""
#trace = interval.begin == 347 and interval.end == 353
#if trace: print('\nRemoving from {} interval {}'.format(
# self.x_center, interval))
if self.center_hit(interval):
#if trace: print('Hit at {}'.format(self.x_center))
if not should_raise_error and interval not in self.s_center:
done.append(1)
#if trace: print('Doing nothing.')
return self
try:
# raises error if interval not present - this is
# desired.
self.s_center.remove(interval)
except:
self.print_structure()
raise KeyError(interval)
if self.s_center: # keep this node
done.append(1) # no rebalancing necessary
#if trace: print('Removed, no rebalancing.')
return self
# If we reach here, no intervals are left in self.s_center.
# So, prune self.
return self.prune()
else: # interval not in s_center
direction = self.hit_branch(interval)
if not self[direction]:
if should_raise_error:
raise ValueError
done.append(1)
return self
#if trace:
# print('Descending to {} branch'.format(
# ['left', 'right'][direction]
# ))
self[direction] = self[direction].remove_interval_helper(interval, done, should_raise_error)
# Clean up
if not done:
#if trace:
# print('Rotating {}'.format(self.x_center))
# self.print_structure()
return self.rotate()
return self | [
"def",
"remove_interval_helper",
"(",
"self",
",",
"interval",
",",
"done",
",",
"should_raise_error",
")",
":",
"#trace = interval.begin == 347 and interval.end == 353",
"#if trace: print('\\nRemoving from {} interval {}'.format(",
"# self.x_center, interval))",
"if",
"self",
".",
"center_hit",
"(",
"interval",
")",
":",
"#if trace: print('Hit at {}'.format(self.x_center))",
"if",
"not",
"should_raise_error",
"and",
"interval",
"not",
"in",
"self",
".",
"s_center",
":",
"done",
".",
"append",
"(",
"1",
")",
"#if trace: print('Doing nothing.')",
"return",
"self",
"try",
":",
"# raises error if interval not present - this is",
"# desired.",
"self",
".",
"s_center",
".",
"remove",
"(",
"interval",
")",
"except",
":",
"self",
".",
"print_structure",
"(",
")",
"raise",
"KeyError",
"(",
"interval",
")",
"if",
"self",
".",
"s_center",
":",
"# keep this node",
"done",
".",
"append",
"(",
"1",
")",
"# no rebalancing necessary",
"#if trace: print('Removed, no rebalancing.')",
"return",
"self",
"# If we reach here, no intervals are left in self.s_center.",
"# So, prune self.",
"return",
"self",
".",
"prune",
"(",
")",
"else",
":",
"# interval not in s_center",
"direction",
"=",
"self",
".",
"hit_branch",
"(",
"interval",
")",
"if",
"not",
"self",
"[",
"direction",
"]",
":",
"if",
"should_raise_error",
":",
"raise",
"ValueError",
"done",
".",
"append",
"(",
"1",
")",
"return",
"self",
"#if trace:",
"# print('Descending to {} branch'.format(",
"# ['left', 'right'][direction]",
"# ))",
"self",
"[",
"direction",
"]",
"=",
"self",
"[",
"direction",
"]",
".",
"remove_interval_helper",
"(",
"interval",
",",
"done",
",",
"should_raise_error",
")",
"# Clean up",
"if",
"not",
"done",
":",
"#if trace:",
"# print('Rotating {}'.format(self.x_center))",
"# self.print_structure()",
"return",
"self",
".",
"rotate",
"(",
")",
"return",
"self"
]
| Returns self after removing interval and balancing.
If interval doesn't exist, raise ValueError.
This method may set done to [1] to tell all callers that
rebalancing has completed.
See Eternally Confuzzled's jsw_remove_r function (lines 1-32)
in his AVL tree article for reference. | [
"Returns",
"self",
"after",
"removing",
"interval",
"and",
"balancing",
".",
"If",
"interval",
"doesn",
"t",
"exist",
"raise",
"ValueError",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L225-L281 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.search_overlap | def search_overlap(self, point_list):
"""
Returns all intervals that overlap the point_list.
"""
result = set()
for j in point_list:
self.search_point(j, result)
return result | python | def search_overlap(self, point_list):
"""
Returns all intervals that overlap the point_list.
"""
result = set()
for j in point_list:
self.search_point(j, result)
return result | [
"def",
"search_overlap",
"(",
"self",
",",
"point_list",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"j",
"in",
"point_list",
":",
"self",
".",
"search_point",
"(",
"j",
",",
"result",
")",
"return",
"result"
]
| Returns all intervals that overlap the point_list. | [
"Returns",
"all",
"intervals",
"that",
"overlap",
"the",
"point_list",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L283-L290 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.search_point | def search_point(self, point, result):
"""
Returns all intervals that contain point.
"""
for k in self.s_center:
if k.begin <= point < k.end:
result.add(k)
if point < self.x_center and self[0]:
return self[0].search_point(point, result)
elif point > self.x_center and self[1]:
return self[1].search_point(point, result)
return result | python | def search_point(self, point, result):
"""
Returns all intervals that contain point.
"""
for k in self.s_center:
if k.begin <= point < k.end:
result.add(k)
if point < self.x_center and self[0]:
return self[0].search_point(point, result)
elif point > self.x_center and self[1]:
return self[1].search_point(point, result)
return result | [
"def",
"search_point",
"(",
"self",
",",
"point",
",",
"result",
")",
":",
"for",
"k",
"in",
"self",
".",
"s_center",
":",
"if",
"k",
".",
"begin",
"<=",
"point",
"<",
"k",
".",
"end",
":",
"result",
".",
"add",
"(",
"k",
")",
"if",
"point",
"<",
"self",
".",
"x_center",
"and",
"self",
"[",
"0",
"]",
":",
"return",
"self",
"[",
"0",
"]",
".",
"search_point",
"(",
"point",
",",
"result",
")",
"elif",
"point",
">",
"self",
".",
"x_center",
"and",
"self",
"[",
"1",
"]",
":",
"return",
"self",
"[",
"1",
"]",
".",
"search_point",
"(",
"point",
",",
"result",
")",
"return",
"result"
]
| Returns all intervals that contain point. | [
"Returns",
"all",
"intervals",
"that",
"contain",
"point",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L292-L303 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.prune | def prune(self):
"""
On a subtree where the root node's s_center is empty,
return a new subtree with no empty s_centers.
"""
if not self[0] or not self[1]: # if I have an empty branch
direction = not self[0] # graft the other branch here
#if trace:
# print('Grafting {} branch'.format(
# 'right' if direction else 'left'))
result = self[direction]
#if result: result.verify()
return result
else:
# Replace the root node with the greatest predecessor.
heir, self[0] = self[0].pop_greatest_child()
#if trace:
# print('Replacing {} with {}.'.format(
# self.x_center, heir.x_center
# ))
# print('Removed greatest predecessor:')
# self.print_structure()
#if self[0]: self[0].verify()
#if self[1]: self[1].verify()
# Set up the heir as the new root node
(heir[0], heir[1]) = (self[0], self[1])
#if trace: print('Setting up the heir:')
#if trace: heir.print_structure()
# popping the predecessor may have unbalanced this node;
# fix it
heir.refresh_balance()
heir = heir.rotate()
#heir.verify()
#if trace: print('Rotated the heir:')
#if trace: heir.print_structure()
return heir | python | def prune(self):
"""
On a subtree where the root node's s_center is empty,
return a new subtree with no empty s_centers.
"""
if not self[0] or not self[1]: # if I have an empty branch
direction = not self[0] # graft the other branch here
#if trace:
# print('Grafting {} branch'.format(
# 'right' if direction else 'left'))
result = self[direction]
#if result: result.verify()
return result
else:
# Replace the root node with the greatest predecessor.
heir, self[0] = self[0].pop_greatest_child()
#if trace:
# print('Replacing {} with {}.'.format(
# self.x_center, heir.x_center
# ))
# print('Removed greatest predecessor:')
# self.print_structure()
#if self[0]: self[0].verify()
#if self[1]: self[1].verify()
# Set up the heir as the new root node
(heir[0], heir[1]) = (self[0], self[1])
#if trace: print('Setting up the heir:')
#if trace: heir.print_structure()
# popping the predecessor may have unbalanced this node;
# fix it
heir.refresh_balance()
heir = heir.rotate()
#heir.verify()
#if trace: print('Rotated the heir:')
#if trace: heir.print_structure()
return heir | [
"def",
"prune",
"(",
"self",
")",
":",
"if",
"not",
"self",
"[",
"0",
"]",
"or",
"not",
"self",
"[",
"1",
"]",
":",
"# if I have an empty branch",
"direction",
"=",
"not",
"self",
"[",
"0",
"]",
"# graft the other branch here",
"#if trace:",
"# print('Grafting {} branch'.format(",
"# 'right' if direction else 'left'))",
"result",
"=",
"self",
"[",
"direction",
"]",
"#if result: result.verify()",
"return",
"result",
"else",
":",
"# Replace the root node with the greatest predecessor.",
"heir",
",",
"self",
"[",
"0",
"]",
"=",
"self",
"[",
"0",
"]",
".",
"pop_greatest_child",
"(",
")",
"#if trace:",
"# print('Replacing {} with {}.'.format(",
"# self.x_center, heir.x_center",
"# ))",
"# print('Removed greatest predecessor:')",
"# self.print_structure()",
"#if self[0]: self[0].verify()",
"#if self[1]: self[1].verify()",
"# Set up the heir as the new root node",
"(",
"heir",
"[",
"0",
"]",
",",
"heir",
"[",
"1",
"]",
")",
"=",
"(",
"self",
"[",
"0",
"]",
",",
"self",
"[",
"1",
"]",
")",
"#if trace: print('Setting up the heir:')",
"#if trace: heir.print_structure()",
"# popping the predecessor may have unbalanced this node;",
"# fix it",
"heir",
".",
"refresh_balance",
"(",
")",
"heir",
"=",
"heir",
".",
"rotate",
"(",
")",
"#heir.verify()",
"#if trace: print('Rotated the heir:')",
"#if trace: heir.print_structure()",
"return",
"heir"
]
| On a subtree where the root node's s_center is empty,
return a new subtree with no empty s_centers. | [
"On",
"a",
"subtree",
"where",
"the",
"root",
"node",
"s",
"s_center",
"is",
"empty",
"return",
"a",
"new",
"subtree",
"with",
"no",
"empty",
"s_centers",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L305-L344 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.contains_point | def contains_point(self, p):
"""
Returns whether this node or a child overlaps p.
"""
for iv in self.s_center:
if iv.contains_point(p):
return True
branch = self[p > self.x_center]
return branch and branch.contains_point(p) | python | def contains_point(self, p):
"""
Returns whether this node or a child overlaps p.
"""
for iv in self.s_center:
if iv.contains_point(p):
return True
branch = self[p > self.x_center]
return branch and branch.contains_point(p) | [
"def",
"contains_point",
"(",
"self",
",",
"p",
")",
":",
"for",
"iv",
"in",
"self",
".",
"s_center",
":",
"if",
"iv",
".",
"contains_point",
"(",
"p",
")",
":",
"return",
"True",
"branch",
"=",
"self",
"[",
"p",
">",
"self",
".",
"x_center",
"]",
"return",
"branch",
"and",
"branch",
".",
"contains_point",
"(",
"p",
")"
]
| Returns whether this node or a child overlaps p. | [
"Returns",
"whether",
"this",
"node",
"or",
"a",
"child",
"overlaps",
"p",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L425-L433 | train |
chaimleib/intervaltree | intervaltree/node.py | Node.print_structure | def print_structure(self, indent=0, tostring=False):
"""
For debugging.
"""
nl = '\n'
sp = indent * ' '
rlist = [str(self) + nl]
if self.s_center:
for iv in sorted(self.s_center):
rlist.append(sp + ' ' + repr(iv) + nl)
if self.left_node:
rlist.append(sp + '<: ') # no CR
rlist.append(self.left_node.print_structure(indent + 1, True))
if self.right_node:
rlist.append(sp + '>: ') # no CR
rlist.append(self.right_node.print_structure(indent + 1, True))
result = ''.join(rlist)
if tostring:
return result
else:
print(result) | python | def print_structure(self, indent=0, tostring=False):
"""
For debugging.
"""
nl = '\n'
sp = indent * ' '
rlist = [str(self) + nl]
if self.s_center:
for iv in sorted(self.s_center):
rlist.append(sp + ' ' + repr(iv) + nl)
if self.left_node:
rlist.append(sp + '<: ') # no CR
rlist.append(self.left_node.print_structure(indent + 1, True))
if self.right_node:
rlist.append(sp + '>: ') # no CR
rlist.append(self.right_node.print_structure(indent + 1, True))
result = ''.join(rlist)
if tostring:
return result
else:
print(result) | [
"def",
"print_structure",
"(",
"self",
",",
"indent",
"=",
"0",
",",
"tostring",
"=",
"False",
")",
":",
"nl",
"=",
"'\\n'",
"sp",
"=",
"indent",
"*",
"' '",
"rlist",
"=",
"[",
"str",
"(",
"self",
")",
"+",
"nl",
"]",
"if",
"self",
".",
"s_center",
":",
"for",
"iv",
"in",
"sorted",
"(",
"self",
".",
"s_center",
")",
":",
"rlist",
".",
"append",
"(",
"sp",
"+",
"' '",
"+",
"repr",
"(",
"iv",
")",
"+",
"nl",
")",
"if",
"self",
".",
"left_node",
":",
"rlist",
".",
"append",
"(",
"sp",
"+",
"'<: '",
")",
"# no CR",
"rlist",
".",
"append",
"(",
"self",
".",
"left_node",
".",
"print_structure",
"(",
"indent",
"+",
"1",
",",
"True",
")",
")",
"if",
"self",
".",
"right_node",
":",
"rlist",
".",
"append",
"(",
"sp",
"+",
"'>: '",
")",
"# no CR",
"rlist",
".",
"append",
"(",
"self",
".",
"right_node",
".",
"print_structure",
"(",
"indent",
"+",
"1",
",",
"True",
")",
")",
"result",
"=",
"''",
".",
"join",
"(",
"rlist",
")",
"if",
"tostring",
":",
"return",
"result",
"else",
":",
"print",
"(",
"result",
")"
]
| For debugging. | [
"For",
"debugging",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L572-L593 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.from_tuples | def from_tuples(cls, tups):
"""
Create a new IntervalTree from an iterable of 2- or 3-tuples,
where the tuple lists begin, end, and optionally data.
"""
ivs = [Interval(*t) for t in tups]
return IntervalTree(ivs) | python | def from_tuples(cls, tups):
"""
Create a new IntervalTree from an iterable of 2- or 3-tuples,
where the tuple lists begin, end, and optionally data.
"""
ivs = [Interval(*t) for t in tups]
return IntervalTree(ivs) | [
"def",
"from_tuples",
"(",
"cls",
",",
"tups",
")",
":",
"ivs",
"=",
"[",
"Interval",
"(",
"*",
"t",
")",
"for",
"t",
"in",
"tups",
"]",
"return",
"IntervalTree",
"(",
"ivs",
")"
]
| Create a new IntervalTree from an iterable of 2- or 3-tuples,
where the tuple lists begin, end, and optionally data. | [
"Create",
"a",
"new",
"IntervalTree",
"from",
"an",
"iterable",
"of",
"2",
"-",
"or",
"3",
"-",
"tuples",
"where",
"the",
"tuple",
"lists",
"begin",
"end",
"and",
"optionally",
"data",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L244-L250 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree._add_boundaries | def _add_boundaries(self, interval):
"""
Records the boundaries of the interval in the boundary table.
"""
begin = interval.begin
end = interval.end
if begin in self.boundary_table:
self.boundary_table[begin] += 1
else:
self.boundary_table[begin] = 1
if end in self.boundary_table:
self.boundary_table[end] += 1
else:
self.boundary_table[end] = 1 | python | def _add_boundaries(self, interval):
"""
Records the boundaries of the interval in the boundary table.
"""
begin = interval.begin
end = interval.end
if begin in self.boundary_table:
self.boundary_table[begin] += 1
else:
self.boundary_table[begin] = 1
if end in self.boundary_table:
self.boundary_table[end] += 1
else:
self.boundary_table[end] = 1 | [
"def",
"_add_boundaries",
"(",
"self",
",",
"interval",
")",
":",
"begin",
"=",
"interval",
".",
"begin",
"end",
"=",
"interval",
".",
"end",
"if",
"begin",
"in",
"self",
".",
"boundary_table",
":",
"self",
".",
"boundary_table",
"[",
"begin",
"]",
"+=",
"1",
"else",
":",
"self",
".",
"boundary_table",
"[",
"begin",
"]",
"=",
"1",
"if",
"end",
"in",
"self",
".",
"boundary_table",
":",
"self",
".",
"boundary_table",
"[",
"end",
"]",
"+=",
"1",
"else",
":",
"self",
".",
"boundary_table",
"[",
"end",
"]",
"=",
"1"
]
| Records the boundaries of the interval in the boundary table. | [
"Records",
"the",
"boundaries",
"of",
"the",
"interval",
"in",
"the",
"boundary",
"table",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L282-L296 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree._remove_boundaries | def _remove_boundaries(self, interval):
"""
Removes the boundaries of the interval from the boundary table.
"""
begin = interval.begin
end = interval.end
if self.boundary_table[begin] == 1:
del self.boundary_table[begin]
else:
self.boundary_table[begin] -= 1
if self.boundary_table[end] == 1:
del self.boundary_table[end]
else:
self.boundary_table[end] -= 1 | python | def _remove_boundaries(self, interval):
"""
Removes the boundaries of the interval from the boundary table.
"""
begin = interval.begin
end = interval.end
if self.boundary_table[begin] == 1:
del self.boundary_table[begin]
else:
self.boundary_table[begin] -= 1
if self.boundary_table[end] == 1:
del self.boundary_table[end]
else:
self.boundary_table[end] -= 1 | [
"def",
"_remove_boundaries",
"(",
"self",
",",
"interval",
")",
":",
"begin",
"=",
"interval",
".",
"begin",
"end",
"=",
"interval",
".",
"end",
"if",
"self",
".",
"boundary_table",
"[",
"begin",
"]",
"==",
"1",
":",
"del",
"self",
".",
"boundary_table",
"[",
"begin",
"]",
"else",
":",
"self",
".",
"boundary_table",
"[",
"begin",
"]",
"-=",
"1",
"if",
"self",
".",
"boundary_table",
"[",
"end",
"]",
"==",
"1",
":",
"del",
"self",
".",
"boundary_table",
"[",
"end",
"]",
"else",
":",
"self",
".",
"boundary_table",
"[",
"end",
"]",
"-=",
"1"
]
| Removes the boundaries of the interval from the boundary table. | [
"Removes",
"the",
"boundaries",
"of",
"the",
"interval",
"from",
"the",
"boundary",
"table",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L298-L312 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.add | def add(self, interval):
"""
Adds an interval to the tree, if not already present.
Completes in O(log n) time.
"""
if interval in self:
return
if interval.is_null():
raise ValueError(
"IntervalTree: Null Interval objects not allowed in IntervalTree:"
" {0}".format(interval)
)
if not self.top_node:
self.top_node = Node.from_interval(interval)
else:
self.top_node = self.top_node.add(interval)
self.all_intervals.add(interval)
self._add_boundaries(interval) | python | def add(self, interval):
"""
Adds an interval to the tree, if not already present.
Completes in O(log n) time.
"""
if interval in self:
return
if interval.is_null():
raise ValueError(
"IntervalTree: Null Interval objects not allowed in IntervalTree:"
" {0}".format(interval)
)
if not self.top_node:
self.top_node = Node.from_interval(interval)
else:
self.top_node = self.top_node.add(interval)
self.all_intervals.add(interval)
self._add_boundaries(interval) | [
"def",
"add",
"(",
"self",
",",
"interval",
")",
":",
"if",
"interval",
"in",
"self",
":",
"return",
"if",
"interval",
".",
"is_null",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"IntervalTree: Null Interval objects not allowed in IntervalTree:\"",
"\" {0}\"",
".",
"format",
"(",
"interval",
")",
")",
"if",
"not",
"self",
".",
"top_node",
":",
"self",
".",
"top_node",
"=",
"Node",
".",
"from_interval",
"(",
"interval",
")",
"else",
":",
"self",
".",
"top_node",
"=",
"self",
".",
"top_node",
".",
"add",
"(",
"interval",
")",
"self",
".",
"all_intervals",
".",
"add",
"(",
"interval",
")",
"self",
".",
"_add_boundaries",
"(",
"interval",
")"
]
| Adds an interval to the tree, if not already present.
Completes in O(log n) time. | [
"Adds",
"an",
"interval",
"to",
"the",
"tree",
"if",
"not",
"already",
"present",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L314-L334 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.remove | def remove(self, interval):
"""
Removes an interval from the tree, if present. If not, raises
ValueError.
Completes in O(log n) time.
"""
#self.verify()
if interval not in self:
#print(self.all_intervals)
raise ValueError
self.top_node = self.top_node.remove(interval)
self.all_intervals.remove(interval)
self._remove_boundaries(interval) | python | def remove(self, interval):
"""
Removes an interval from the tree, if present. If not, raises
ValueError.
Completes in O(log n) time.
"""
#self.verify()
if interval not in self:
#print(self.all_intervals)
raise ValueError
self.top_node = self.top_node.remove(interval)
self.all_intervals.remove(interval)
self._remove_boundaries(interval) | [
"def",
"remove",
"(",
"self",
",",
"interval",
")",
":",
"#self.verify()",
"if",
"interval",
"not",
"in",
"self",
":",
"#print(self.all_intervals)",
"raise",
"ValueError",
"self",
".",
"top_node",
"=",
"self",
".",
"top_node",
".",
"remove",
"(",
"interval",
")",
"self",
".",
"all_intervals",
".",
"remove",
"(",
"interval",
")",
"self",
".",
"_remove_boundaries",
"(",
"interval",
")"
]
| Removes an interval from the tree, if present. If not, raises
ValueError.
Completes in O(log n) time. | [
"Removes",
"an",
"interval",
"from",
"the",
"tree",
"if",
"present",
".",
"If",
"not",
"raises",
"ValueError",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L356-L369 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.discard | def discard(self, interval):
"""
Removes an interval from the tree, if present. If not, does
nothing.
Completes in O(log n) time.
"""
if interval not in self:
return
self.all_intervals.discard(interval)
self.top_node = self.top_node.discard(interval)
self._remove_boundaries(interval) | python | def discard(self, interval):
"""
Removes an interval from the tree, if present. If not, does
nothing.
Completes in O(log n) time.
"""
if interval not in self:
return
self.all_intervals.discard(interval)
self.top_node = self.top_node.discard(interval)
self._remove_boundaries(interval) | [
"def",
"discard",
"(",
"self",
",",
"interval",
")",
":",
"if",
"interval",
"not",
"in",
"self",
":",
"return",
"self",
".",
"all_intervals",
".",
"discard",
"(",
"interval",
")",
"self",
".",
"top_node",
"=",
"self",
".",
"top_node",
".",
"discard",
"(",
"interval",
")",
"self",
".",
"_remove_boundaries",
"(",
"interval",
")"
]
| Removes an interval from the tree, if present. If not, does
nothing.
Completes in O(log n) time. | [
"Removes",
"an",
"interval",
"from",
"the",
"tree",
"if",
"present",
".",
"If",
"not",
"does",
"nothing",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L380-L391 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.difference | def difference(self, other):
"""
Returns a new tree, comprising all intervals in self but not
in other.
"""
ivs = set()
for iv in self:
if iv not in other:
ivs.add(iv)
return IntervalTree(ivs) | python | def difference(self, other):
"""
Returns a new tree, comprising all intervals in self but not
in other.
"""
ivs = set()
for iv in self:
if iv not in other:
ivs.add(iv)
return IntervalTree(ivs) | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"ivs",
"=",
"set",
"(",
")",
"for",
"iv",
"in",
"self",
":",
"if",
"iv",
"not",
"in",
"other",
":",
"ivs",
".",
"add",
"(",
"iv",
")",
"return",
"IntervalTree",
"(",
"ivs",
")"
]
| Returns a new tree, comprising all intervals in self but not
in other. | [
"Returns",
"a",
"new",
"tree",
"comprising",
"all",
"intervals",
"in",
"self",
"but",
"not",
"in",
"other",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L401-L410 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.intersection | def intersection(self, other):
"""
Returns a new tree of all intervals common to both self and
other.
"""
ivs = set()
shorter, longer = sorted([self, other], key=len)
for iv in shorter:
if iv in longer:
ivs.add(iv)
return IntervalTree(ivs) | python | def intersection(self, other):
"""
Returns a new tree of all intervals common to both self and
other.
"""
ivs = set()
shorter, longer = sorted([self, other], key=len)
for iv in shorter:
if iv in longer:
ivs.add(iv)
return IntervalTree(ivs) | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"ivs",
"=",
"set",
"(",
")",
"shorter",
",",
"longer",
"=",
"sorted",
"(",
"[",
"self",
",",
"other",
"]",
",",
"key",
"=",
"len",
")",
"for",
"iv",
"in",
"shorter",
":",
"if",
"iv",
"in",
"longer",
":",
"ivs",
".",
"add",
"(",
"iv",
")",
"return",
"IntervalTree",
"(",
"ivs",
")"
]
| Returns a new tree of all intervals common to both self and
other. | [
"Returns",
"a",
"new",
"tree",
"of",
"all",
"intervals",
"common",
"to",
"both",
"self",
"and",
"other",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L426-L436 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.intersection_update | def intersection_update(self, other):
"""
Removes intervals from self unless they also exist in other.
"""
ivs = list(self)
for iv in ivs:
if iv not in other:
self.remove(iv) | python | def intersection_update(self, other):
"""
Removes intervals from self unless they also exist in other.
"""
ivs = list(self)
for iv in ivs:
if iv not in other:
self.remove(iv) | [
"def",
"intersection_update",
"(",
"self",
",",
"other",
")",
":",
"ivs",
"=",
"list",
"(",
"self",
")",
"for",
"iv",
"in",
"ivs",
":",
"if",
"iv",
"not",
"in",
"other",
":",
"self",
".",
"remove",
"(",
"iv",
")"
]
| Removes intervals from self unless they also exist in other. | [
"Removes",
"intervals",
"from",
"self",
"unless",
"they",
"also",
"exist",
"in",
"other",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L438-L445 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.symmetric_difference | def symmetric_difference(self, other):
"""
Return a tree with elements only in self or other but not
both.
"""
if not isinstance(other, set): other = set(other)
me = set(self)
ivs = me.difference(other).union(other.difference(me))
return IntervalTree(ivs) | python | def symmetric_difference(self, other):
"""
Return a tree with elements only in self or other but not
both.
"""
if not isinstance(other, set): other = set(other)
me = set(self)
ivs = me.difference(other).union(other.difference(me))
return IntervalTree(ivs) | [
"def",
"symmetric_difference",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"set",
")",
":",
"other",
"=",
"set",
"(",
"other",
")",
"me",
"=",
"set",
"(",
"self",
")",
"ivs",
"=",
"me",
".",
"difference",
"(",
"other",
")",
".",
"union",
"(",
"other",
".",
"difference",
"(",
"me",
")",
")",
"return",
"IntervalTree",
"(",
"ivs",
")"
]
| Return a tree with elements only in self or other but not
both. | [
"Return",
"a",
"tree",
"with",
"elements",
"only",
"in",
"self",
"or",
"other",
"but",
"not",
"both",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L447-L455 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.symmetric_difference_update | def symmetric_difference_update(self, other):
"""
Throws out all intervals except those only in self or other,
not both.
"""
other = set(other)
ivs = list(self)
for iv in ivs:
if iv in other:
self.remove(iv)
other.remove(iv)
self.update(other) | python | def symmetric_difference_update(self, other):
"""
Throws out all intervals except those only in self or other,
not both.
"""
other = set(other)
ivs = list(self)
for iv in ivs:
if iv in other:
self.remove(iv)
other.remove(iv)
self.update(other) | [
"def",
"symmetric_difference_update",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"set",
"(",
"other",
")",
"ivs",
"=",
"list",
"(",
"self",
")",
"for",
"iv",
"in",
"ivs",
":",
"if",
"iv",
"in",
"other",
":",
"self",
".",
"remove",
"(",
"iv",
")",
"other",
".",
"remove",
"(",
"iv",
")",
"self",
".",
"update",
"(",
"other",
")"
]
| Throws out all intervals except those only in self or other,
not both. | [
"Throws",
"out",
"all",
"intervals",
"except",
"those",
"only",
"in",
"self",
"or",
"other",
"not",
"both",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L457-L468 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.remove_overlap | def remove_overlap(self, begin, end=None):
"""
Removes all intervals overlapping the given point or range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range (this is 1 for a point)
"""
hitlist = self.at(begin) if end is None else self.overlap(begin, end)
for iv in hitlist:
self.remove(iv) | python | def remove_overlap(self, begin, end=None):
"""
Removes all intervals overlapping the given point or range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range (this is 1 for a point)
"""
hitlist = self.at(begin) if end is None else self.overlap(begin, end)
for iv in hitlist:
self.remove(iv) | [
"def",
"remove_overlap",
"(",
"self",
",",
"begin",
",",
"end",
"=",
"None",
")",
":",
"hitlist",
"=",
"self",
".",
"at",
"(",
"begin",
")",
"if",
"end",
"is",
"None",
"else",
"self",
".",
"overlap",
"(",
"begin",
",",
"end",
")",
"for",
"iv",
"in",
"hitlist",
":",
"self",
".",
"remove",
"(",
"iv",
")"
]
| Removes all intervals overlapping the given point or range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range (this is 1 for a point) | [
"Removes",
"all",
"intervals",
"overlapping",
"the",
"given",
"point",
"or",
"range",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L470-L481 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.remove_envelop | def remove_envelop(self, begin, end):
"""
Removes all intervals completely enveloped in the given range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range
"""
hitlist = self.envelop(begin, end)
for iv in hitlist:
self.remove(iv) | python | def remove_envelop(self, begin, end):
"""
Removes all intervals completely enveloped in the given range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range
"""
hitlist = self.envelop(begin, end)
for iv in hitlist:
self.remove(iv) | [
"def",
"remove_envelop",
"(",
"self",
",",
"begin",
",",
"end",
")",
":",
"hitlist",
"=",
"self",
".",
"envelop",
"(",
"begin",
",",
"end",
")",
"for",
"iv",
"in",
"hitlist",
":",
"self",
".",
"remove",
"(",
"iv",
")"
]
| Removes all intervals completely enveloped in the given range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range | [
"Removes",
"all",
"intervals",
"completely",
"enveloped",
"in",
"the",
"given",
"range",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L483-L494 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.find_nested | def find_nested(self):
"""
Returns a dictionary mapping parent intervals to sets of
intervals overlapped by and contained in the parent.
Completes in O(n^2) time.
:rtype: dict of [Interval, set of Interval]
"""
result = {}
def add_if_nested():
if parent.contains_interval(child):
if parent not in result:
result[parent] = set()
result[parent].add(child)
long_ivs = sorted(self.all_intervals, key=Interval.length, reverse=True)
for i, parent in enumerate(long_ivs):
for child in long_ivs[i + 1:]:
add_if_nested()
return result | python | def find_nested(self):
"""
Returns a dictionary mapping parent intervals to sets of
intervals overlapped by and contained in the parent.
Completes in O(n^2) time.
:rtype: dict of [Interval, set of Interval]
"""
result = {}
def add_if_nested():
if parent.contains_interval(child):
if parent not in result:
result[parent] = set()
result[parent].add(child)
long_ivs = sorted(self.all_intervals, key=Interval.length, reverse=True)
for i, parent in enumerate(long_ivs):
for child in long_ivs[i + 1:]:
add_if_nested()
return result | [
"def",
"find_nested",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"def",
"add_if_nested",
"(",
")",
":",
"if",
"parent",
".",
"contains_interval",
"(",
"child",
")",
":",
"if",
"parent",
"not",
"in",
"result",
":",
"result",
"[",
"parent",
"]",
"=",
"set",
"(",
")",
"result",
"[",
"parent",
"]",
".",
"add",
"(",
"child",
")",
"long_ivs",
"=",
"sorted",
"(",
"self",
".",
"all_intervals",
",",
"key",
"=",
"Interval",
".",
"length",
",",
"reverse",
"=",
"True",
")",
"for",
"i",
",",
"parent",
"in",
"enumerate",
"(",
"long_ivs",
")",
":",
"for",
"child",
"in",
"long_ivs",
"[",
"i",
"+",
"1",
":",
"]",
":",
"add_if_nested",
"(",
")",
"return",
"result"
]
| Returns a dictionary mapping parent intervals to sets of
intervals overlapped by and contained in the parent.
Completes in O(n^2) time.
:rtype: dict of [Interval, set of Interval] | [
"Returns",
"a",
"dictionary",
"mapping",
"parent",
"intervals",
"to",
"sets",
"of",
"intervals",
"overlapped",
"by",
"and",
"contained",
"in",
"the",
"parent",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L551-L571 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.overlaps | def overlaps(self, begin, end=None):
"""
Returns whether some interval in the tree overlaps the given
point or range.
Completes in O(r*log n) time, where r is the size of the
search range.
:rtype: bool
"""
if end is not None:
return self.overlaps_range(begin, end)
elif isinstance(begin, Number):
return self.overlaps_point(begin)
else:
return self.overlaps_range(begin.begin, begin.end) | python | def overlaps(self, begin, end=None):
"""
Returns whether some interval in the tree overlaps the given
point or range.
Completes in O(r*log n) time, where r is the size of the
search range.
:rtype: bool
"""
if end is not None:
return self.overlaps_range(begin, end)
elif isinstance(begin, Number):
return self.overlaps_point(begin)
else:
return self.overlaps_range(begin.begin, begin.end) | [
"def",
"overlaps",
"(",
"self",
",",
"begin",
",",
"end",
"=",
"None",
")",
":",
"if",
"end",
"is",
"not",
"None",
":",
"return",
"self",
".",
"overlaps_range",
"(",
"begin",
",",
"end",
")",
"elif",
"isinstance",
"(",
"begin",
",",
"Number",
")",
":",
"return",
"self",
".",
"overlaps_point",
"(",
"begin",
")",
"else",
":",
"return",
"self",
".",
"overlaps_range",
"(",
"begin",
".",
"begin",
",",
"begin",
".",
"end",
")"
]
| Returns whether some interval in the tree overlaps the given
point or range.
Completes in O(r*log n) time, where r is the size of the
search range.
:rtype: bool | [
"Returns",
"whether",
"some",
"interval",
"in",
"the",
"tree",
"overlaps",
"the",
"given",
"point",
"or",
"range",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L573-L587 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.overlaps_point | def overlaps_point(self, p):
"""
Returns whether some interval in the tree overlaps p.
Completes in O(log n) time.
:rtype: bool
"""
if self.is_empty():
return False
return bool(self.top_node.contains_point(p)) | python | def overlaps_point(self, p):
"""
Returns whether some interval in the tree overlaps p.
Completes in O(log n) time.
:rtype: bool
"""
if self.is_empty():
return False
return bool(self.top_node.contains_point(p)) | [
"def",
"overlaps_point",
"(",
"self",
",",
"p",
")",
":",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
"return",
"False",
"return",
"bool",
"(",
"self",
".",
"top_node",
".",
"contains_point",
"(",
"p",
")",
")"
]
| Returns whether some interval in the tree overlaps p.
Completes in O(log n) time.
:rtype: bool | [
"Returns",
"whether",
"some",
"interval",
"in",
"the",
"tree",
"overlaps",
"p",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L589-L598 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.overlaps_range | def overlaps_range(self, begin, end):
"""
Returns whether some interval in the tree overlaps the given
range. Returns False if given a null interval over which to
test.
Completes in O(r*log n) time, where r is the range length and n
is the table size.
:rtype: bool
"""
if self.is_empty():
return False
elif begin >= end:
return False
elif self.overlaps_point(begin):
return True
return any(
self.overlaps_point(bound)
for bound in self.boundary_table
if begin < bound < end
) | python | def overlaps_range(self, begin, end):
"""
Returns whether some interval in the tree overlaps the given
range. Returns False if given a null interval over which to
test.
Completes in O(r*log n) time, where r is the range length and n
is the table size.
:rtype: bool
"""
if self.is_empty():
return False
elif begin >= end:
return False
elif self.overlaps_point(begin):
return True
return any(
self.overlaps_point(bound)
for bound in self.boundary_table
if begin < bound < end
) | [
"def",
"overlaps_range",
"(",
"self",
",",
"begin",
",",
"end",
")",
":",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
"return",
"False",
"elif",
"begin",
">=",
"end",
":",
"return",
"False",
"elif",
"self",
".",
"overlaps_point",
"(",
"begin",
")",
":",
"return",
"True",
"return",
"any",
"(",
"self",
".",
"overlaps_point",
"(",
"bound",
")",
"for",
"bound",
"in",
"self",
".",
"boundary_table",
"if",
"begin",
"<",
"bound",
"<",
"end",
")"
]
| Returns whether some interval in the tree overlaps the given
range. Returns False if given a null interval over which to
test.
Completes in O(r*log n) time, where r is the range length and n
is the table size.
:rtype: bool | [
"Returns",
"whether",
"some",
"interval",
"in",
"the",
"tree",
"overlaps",
"the",
"given",
"range",
".",
"Returns",
"False",
"if",
"given",
"a",
"null",
"interval",
"over",
"which",
"to",
"test",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L600-L620 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.split_overlaps | def split_overlaps(self):
"""
Finds all intervals with overlapping ranges and splits them
along the range boundaries.
Completes in worst-case O(n^2*log n) time (many interval
boundaries are inside many intervals), best-case O(n*log n)
time (small number of overlaps << n per interval).
"""
if not self:
return
if len(self.boundary_table) == 2:
return
bounds = sorted(self.boundary_table) # get bound locations
new_ivs = set()
for lbound, ubound in zip(bounds[:-1], bounds[1:]):
for iv in self[lbound]:
new_ivs.add(Interval(lbound, ubound, iv.data))
self.__init__(new_ivs) | python | def split_overlaps(self):
"""
Finds all intervals with overlapping ranges and splits them
along the range boundaries.
Completes in worst-case O(n^2*log n) time (many interval
boundaries are inside many intervals), best-case O(n*log n)
time (small number of overlaps << n per interval).
"""
if not self:
return
if len(self.boundary_table) == 2:
return
bounds = sorted(self.boundary_table) # get bound locations
new_ivs = set()
for lbound, ubound in zip(bounds[:-1], bounds[1:]):
for iv in self[lbound]:
new_ivs.add(Interval(lbound, ubound, iv.data))
self.__init__(new_ivs) | [
"def",
"split_overlaps",
"(",
"self",
")",
":",
"if",
"not",
"self",
":",
"return",
"if",
"len",
"(",
"self",
".",
"boundary_table",
")",
"==",
"2",
":",
"return",
"bounds",
"=",
"sorted",
"(",
"self",
".",
"boundary_table",
")",
"# get bound locations",
"new_ivs",
"=",
"set",
"(",
")",
"for",
"lbound",
",",
"ubound",
"in",
"zip",
"(",
"bounds",
"[",
":",
"-",
"1",
"]",
",",
"bounds",
"[",
"1",
":",
"]",
")",
":",
"for",
"iv",
"in",
"self",
"[",
"lbound",
"]",
":",
"new_ivs",
".",
"add",
"(",
"Interval",
"(",
"lbound",
",",
"ubound",
",",
"iv",
".",
"data",
")",
")",
"self",
".",
"__init__",
"(",
"new_ivs",
")"
]
| Finds all intervals with overlapping ranges and splits them
along the range boundaries.
Completes in worst-case O(n^2*log n) time (many interval
boundaries are inside many intervals), best-case O(n*log n)
time (small number of overlaps << n per interval). | [
"Finds",
"all",
"intervals",
"with",
"overlapping",
"ranges",
"and",
"splits",
"them",
"along",
"the",
"range",
"boundaries",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L622-L643 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.at | def at(self, p):
"""
Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval
"""
root = self.top_node
if not root:
return set()
return root.search_point(p, set()) | python | def at(self, p):
"""
Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval
"""
root = self.top_node
if not root:
return set()
return root.search_point(p, set()) | [
"def",
"at",
"(",
"self",
",",
"p",
")",
":",
"root",
"=",
"self",
".",
"top_node",
"if",
"not",
"root",
":",
"return",
"set",
"(",
")",
"return",
"root",
".",
"search_point",
"(",
"p",
",",
"set",
"(",
")",
")"
]
| Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval | [
"Returns",
"the",
"set",
"of",
"all",
"intervals",
"that",
"contain",
"p",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L788-L800 | train |
chaimleib/intervaltree | intervaltree/intervaltree.py | IntervalTree.envelop | def envelop(self, begin, end=None):
"""
Returns the set of all intervals fully contained in the range
[begin, end).
Completes in O(m + k*log n) time, where:
* n = size of the tree
* m = number of matches
* k = size of the search range
:rtype: set of Interval
"""
root = self.top_node
if not root:
return set()
if end is None:
iv = begin
return self.envelop(iv.begin, iv.end)
elif begin >= end:
return set()
result = root.search_point(begin, set()) # bound_begin might be greater
boundary_table = self.boundary_table
bound_begin = boundary_table.bisect_left(begin)
bound_end = boundary_table.bisect_left(end) # up to, but not including end
result.update(root.search_overlap(
# slice notation is slightly slower
boundary_table.keys()[index] for index in xrange(bound_begin, bound_end)
))
# TODO: improve envelop() to use node info instead of less-efficient filtering
result = set(
iv for iv in result
if iv.begin >= begin and iv.end <= end
)
return result | python | def envelop(self, begin, end=None):
"""
Returns the set of all intervals fully contained in the range
[begin, end).
Completes in O(m + k*log n) time, where:
* n = size of the tree
* m = number of matches
* k = size of the search range
:rtype: set of Interval
"""
root = self.top_node
if not root:
return set()
if end is None:
iv = begin
return self.envelop(iv.begin, iv.end)
elif begin >= end:
return set()
result = root.search_point(begin, set()) # bound_begin might be greater
boundary_table = self.boundary_table
bound_begin = boundary_table.bisect_left(begin)
bound_end = boundary_table.bisect_left(end) # up to, but not including end
result.update(root.search_overlap(
# slice notation is slightly slower
boundary_table.keys()[index] for index in xrange(bound_begin, bound_end)
))
# TODO: improve envelop() to use node info instead of less-efficient filtering
result = set(
iv for iv in result
if iv.begin >= begin and iv.end <= end
)
return result | [
"def",
"envelop",
"(",
"self",
",",
"begin",
",",
"end",
"=",
"None",
")",
":",
"root",
"=",
"self",
".",
"top_node",
"if",
"not",
"root",
":",
"return",
"set",
"(",
")",
"if",
"end",
"is",
"None",
":",
"iv",
"=",
"begin",
"return",
"self",
".",
"envelop",
"(",
"iv",
".",
"begin",
",",
"iv",
".",
"end",
")",
"elif",
"begin",
">=",
"end",
":",
"return",
"set",
"(",
")",
"result",
"=",
"root",
".",
"search_point",
"(",
"begin",
",",
"set",
"(",
")",
")",
"# bound_begin might be greater",
"boundary_table",
"=",
"self",
".",
"boundary_table",
"bound_begin",
"=",
"boundary_table",
".",
"bisect_left",
"(",
"begin",
")",
"bound_end",
"=",
"boundary_table",
".",
"bisect_left",
"(",
"end",
")",
"# up to, but not including end",
"result",
".",
"update",
"(",
"root",
".",
"search_overlap",
"(",
"# slice notation is slightly slower",
"boundary_table",
".",
"keys",
"(",
")",
"[",
"index",
"]",
"for",
"index",
"in",
"xrange",
"(",
"bound_begin",
",",
"bound_end",
")",
")",
")",
"# TODO: improve envelop() to use node info instead of less-efficient filtering",
"result",
"=",
"set",
"(",
"iv",
"for",
"iv",
"in",
"result",
"if",
"iv",
".",
"begin",
">=",
"begin",
"and",
"iv",
".",
"end",
"<=",
"end",
")",
"return",
"result"
]
| Returns the set of all intervals fully contained in the range
[begin, end).
Completes in O(m + k*log n) time, where:
* n = size of the tree
* m = number of matches
* k = size of the search range
:rtype: set of Interval | [
"Returns",
"the",
"set",
"of",
"all",
"intervals",
"fully",
"contained",
"in",
"the",
"range",
"[",
"begin",
"end",
")",
"."
]
| ffb2b1667f8b832e89324a75a175be8440504c9d | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L802-L835 | train |
jazzband/inflect | inflect.py | engine.defnoun | def defnoun(self, singular, plural):
"""
Set the noun plural of singular to plural.
"""
self.checkpat(singular)
self.checkpatplural(plural)
self.pl_sb_user_defined.extend((singular, plural))
self.si_sb_user_defined.extend((plural, singular))
return 1 | python | def defnoun(self, singular, plural):
"""
Set the noun plural of singular to plural.
"""
self.checkpat(singular)
self.checkpatplural(plural)
self.pl_sb_user_defined.extend((singular, plural))
self.si_sb_user_defined.extend((plural, singular))
return 1 | [
"def",
"defnoun",
"(",
"self",
",",
"singular",
",",
"plural",
")",
":",
"self",
".",
"checkpat",
"(",
"singular",
")",
"self",
".",
"checkpatplural",
"(",
"plural",
")",
"self",
".",
"pl_sb_user_defined",
".",
"extend",
"(",
"(",
"singular",
",",
"plural",
")",
")",
"self",
".",
"si_sb_user_defined",
".",
"extend",
"(",
"(",
"plural",
",",
"singular",
")",
")",
"return",
"1"
]
| Set the noun plural of singular to plural. | [
"Set",
"the",
"noun",
"plural",
"of",
"singular",
"to",
"plural",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1951-L1960 | train |
jazzband/inflect | inflect.py | engine.defverb | def defverb(self, s1, p1, s2, p2, s3, p3):
"""
Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively.
Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb.
"""
self.checkpat(s1)
self.checkpat(s2)
self.checkpat(s3)
self.checkpatplural(p1)
self.checkpatplural(p2)
self.checkpatplural(p3)
self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3))
return 1 | python | def defverb(self, s1, p1, s2, p2, s3, p3):
"""
Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively.
Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb.
"""
self.checkpat(s1)
self.checkpat(s2)
self.checkpat(s3)
self.checkpatplural(p1)
self.checkpatplural(p2)
self.checkpatplural(p3)
self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3))
return 1 | [
"def",
"defverb",
"(",
"self",
",",
"s1",
",",
"p1",
",",
"s2",
",",
"p2",
",",
"s3",
",",
"p3",
")",
":",
"self",
".",
"checkpat",
"(",
"s1",
")",
"self",
".",
"checkpat",
"(",
"s2",
")",
"self",
".",
"checkpat",
"(",
"s3",
")",
"self",
".",
"checkpatplural",
"(",
"p1",
")",
"self",
".",
"checkpatplural",
"(",
"p2",
")",
"self",
".",
"checkpatplural",
"(",
"p3",
")",
"self",
".",
"pl_v_user_defined",
".",
"extend",
"(",
"(",
"s1",
",",
"p1",
",",
"s2",
",",
"p2",
",",
"s3",
",",
"p3",
")",
")",
"return",
"1"
]
| Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively.
Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb. | [
"Set",
"the",
"verb",
"plurals",
"for",
"s1",
"s2",
"and",
"s3",
"to",
"p1",
"p2",
"and",
"p3",
"respectively",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1962-L1976 | train |
jazzband/inflect | inflect.py | engine.defadj | def defadj(self, singular, plural):
"""
Set the adjective plural of singular to plural.
"""
self.checkpat(singular)
self.checkpatplural(plural)
self.pl_adj_user_defined.extend((singular, plural))
return 1 | python | def defadj(self, singular, plural):
"""
Set the adjective plural of singular to plural.
"""
self.checkpat(singular)
self.checkpatplural(plural)
self.pl_adj_user_defined.extend((singular, plural))
return 1 | [
"def",
"defadj",
"(",
"self",
",",
"singular",
",",
"plural",
")",
":",
"self",
".",
"checkpat",
"(",
"singular",
")",
"self",
".",
"checkpatplural",
"(",
"plural",
")",
"self",
".",
"pl_adj_user_defined",
".",
"extend",
"(",
"(",
"singular",
",",
"plural",
")",
")",
"return",
"1"
]
| Set the adjective plural of singular to plural. | [
"Set",
"the",
"adjective",
"plural",
"of",
"singular",
"to",
"plural",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1978-L1986 | train |
jazzband/inflect | inflect.py | engine.defa | def defa(self, pattern):
"""
Define the indefinate article as 'a' for words matching pattern.
"""
self.checkpat(pattern)
self.A_a_user_defined.extend((pattern, "a"))
return 1 | python | def defa(self, pattern):
"""
Define the indefinate article as 'a' for words matching pattern.
"""
self.checkpat(pattern)
self.A_a_user_defined.extend((pattern, "a"))
return 1 | [
"def",
"defa",
"(",
"self",
",",
"pattern",
")",
":",
"self",
".",
"checkpat",
"(",
"pattern",
")",
"self",
".",
"A_a_user_defined",
".",
"extend",
"(",
"(",
"pattern",
",",
"\"a\"",
")",
")",
"return",
"1"
]
| Define the indefinate article as 'a' for words matching pattern. | [
"Define",
"the",
"indefinate",
"article",
"as",
"a",
"for",
"words",
"matching",
"pattern",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1988-L1995 | train |
jazzband/inflect | inflect.py | engine.defan | def defan(self, pattern):
"""
Define the indefinate article as 'an' for words matching pattern.
"""
self.checkpat(pattern)
self.A_a_user_defined.extend((pattern, "an"))
return 1 | python | def defan(self, pattern):
"""
Define the indefinate article as 'an' for words matching pattern.
"""
self.checkpat(pattern)
self.A_a_user_defined.extend((pattern, "an"))
return 1 | [
"def",
"defan",
"(",
"self",
",",
"pattern",
")",
":",
"self",
".",
"checkpat",
"(",
"pattern",
")",
"self",
".",
"A_a_user_defined",
".",
"extend",
"(",
"(",
"pattern",
",",
"\"an\"",
")",
")",
"return",
"1"
]
| Define the indefinate article as 'an' for words matching pattern. | [
"Define",
"the",
"indefinate",
"article",
"as",
"an",
"for",
"words",
"matching",
"pattern",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1997-L2004 | train |
jazzband/inflect | inflect.py | engine.checkpat | def checkpat(self, pattern):
"""
check for errors in a regex pattern
"""
if pattern is None:
return
try:
re.match(pattern, "")
except re.error:
print3("\nBad user-defined singular pattern:\n\t%s\n" % pattern)
raise BadUserDefinedPatternError | python | def checkpat(self, pattern):
"""
check for errors in a regex pattern
"""
if pattern is None:
return
try:
re.match(pattern, "")
except re.error:
print3("\nBad user-defined singular pattern:\n\t%s\n" % pattern)
raise BadUserDefinedPatternError | [
"def",
"checkpat",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"pattern",
"is",
"None",
":",
"return",
"try",
":",
"re",
".",
"match",
"(",
"pattern",
",",
"\"\"",
")",
"except",
"re",
".",
"error",
":",
"print3",
"(",
"\"\\nBad user-defined singular pattern:\\n\\t%s\\n\"",
"%",
"pattern",
")",
"raise",
"BadUserDefinedPatternError"
]
| check for errors in a regex pattern | [
"check",
"for",
"errors",
"in",
"a",
"regex",
"pattern"
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2006-L2016 | train |
jazzband/inflect | inflect.py | engine.classical | def classical(self, **kwargs):
"""
turn classical mode on and off for various categories
turn on all classical modes:
classical()
classical(all=True)
turn on or off specific claassical modes:
e.g.
classical(herd=True)
classical(names=False)
By default all classical modes are off except names.
unknown value in args or key in kwargs rasies
exception: UnknownClasicalModeError
"""
classical_mode = list(def_classical.keys())
if not kwargs:
self.classical_dict = all_classical.copy()
return
if "all" in kwargs:
if kwargs["all"]:
self.classical_dict = all_classical.copy()
else:
self.classical_dict = no_classical.copy()
for k, v in list(kwargs.items()):
if k in classical_mode:
self.classical_dict[k] = v
else:
raise UnknownClassicalModeError | python | def classical(self, **kwargs):
"""
turn classical mode on and off for various categories
turn on all classical modes:
classical()
classical(all=True)
turn on or off specific claassical modes:
e.g.
classical(herd=True)
classical(names=False)
By default all classical modes are off except names.
unknown value in args or key in kwargs rasies
exception: UnknownClasicalModeError
"""
classical_mode = list(def_classical.keys())
if not kwargs:
self.classical_dict = all_classical.copy()
return
if "all" in kwargs:
if kwargs["all"]:
self.classical_dict = all_classical.copy()
else:
self.classical_dict = no_classical.copy()
for k, v in list(kwargs.items()):
if k in classical_mode:
self.classical_dict[k] = v
else:
raise UnknownClassicalModeError | [
"def",
"classical",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"classical_mode",
"=",
"list",
"(",
"def_classical",
".",
"keys",
"(",
")",
")",
"if",
"not",
"kwargs",
":",
"self",
".",
"classical_dict",
"=",
"all_classical",
".",
"copy",
"(",
")",
"return",
"if",
"\"all\"",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"\"all\"",
"]",
":",
"self",
".",
"classical_dict",
"=",
"all_classical",
".",
"copy",
"(",
")",
"else",
":",
"self",
".",
"classical_dict",
"=",
"no_classical",
".",
"copy",
"(",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
":",
"if",
"k",
"in",
"classical_mode",
":",
"self",
".",
"classical_dict",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"raise",
"UnknownClassicalModeError"
]
| turn classical mode on and off for various categories
turn on all classical modes:
classical()
classical(all=True)
turn on or off specific claassical modes:
e.g.
classical(herd=True)
classical(names=False)
By default all classical modes are off except names.
unknown value in args or key in kwargs rasies
exception: UnknownClasicalModeError | [
"turn",
"classical",
"mode",
"on",
"and",
"off",
"for",
"various",
"categories"
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2036-L2069 | train |
jazzband/inflect | inflect.py | engine.num | def num(self, count=None, show=None): # (;$count,$show)
"""
Set the number to be used in other method calls.
Returns count.
Set show to False to return '' instead.
"""
if count is not None:
try:
self.persistent_count = int(count)
except ValueError:
raise BadNumValueError
if (show is None) or show:
return str(count)
else:
self.persistent_count = None
return "" | python | def num(self, count=None, show=None): # (;$count,$show)
"""
Set the number to be used in other method calls.
Returns count.
Set show to False to return '' instead.
"""
if count is not None:
try:
self.persistent_count = int(count)
except ValueError:
raise BadNumValueError
if (show is None) or show:
return str(count)
else:
self.persistent_count = None
return "" | [
"def",
"num",
"(",
"self",
",",
"count",
"=",
"None",
",",
"show",
"=",
"None",
")",
":",
"# (;$count,$show)",
"if",
"count",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"persistent_count",
"=",
"int",
"(",
"count",
")",
"except",
"ValueError",
":",
"raise",
"BadNumValueError",
"if",
"(",
"show",
"is",
"None",
")",
"or",
"show",
":",
"return",
"str",
"(",
"count",
")",
"else",
":",
"self",
".",
"persistent_count",
"=",
"None",
"return",
"\"\""
]
| Set the number to be used in other method calls.
Returns count.
Set show to False to return '' instead. | [
"Set",
"the",
"number",
"to",
"be",
"used",
"in",
"other",
"method",
"calls",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2071-L2089 | train |
jazzband/inflect | inflect.py | engine._get_value_from_ast | def _get_value_from_ast(self, obj):
"""
Return the value of the ast object.
"""
if isinstance(obj, ast.Num):
return obj.n
elif isinstance(obj, ast.Str):
return obj.s
elif isinstance(obj, ast.List):
return [self._get_value_from_ast(e) for e in obj.elts]
elif isinstance(obj, ast.Tuple):
return tuple([self._get_value_from_ast(e) for e in obj.elts])
# None, True and False are NameConstants in Py3.4 and above.
elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
return obj.value
# For python versions below 3.4
elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
return string_to_constant[obj.id]
# Probably passed a variable name.
# Or passed a single word without wrapping it in quotes as an argument
# ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
raise NameError("name '%s' is not defined" % obj.id) | python | def _get_value_from_ast(self, obj):
"""
Return the value of the ast object.
"""
if isinstance(obj, ast.Num):
return obj.n
elif isinstance(obj, ast.Str):
return obj.s
elif isinstance(obj, ast.List):
return [self._get_value_from_ast(e) for e in obj.elts]
elif isinstance(obj, ast.Tuple):
return tuple([self._get_value_from_ast(e) for e in obj.elts])
# None, True and False are NameConstants in Py3.4 and above.
elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
return obj.value
# For python versions below 3.4
elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
return string_to_constant[obj.id]
# Probably passed a variable name.
# Or passed a single word without wrapping it in quotes as an argument
# ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
raise NameError("name '%s' is not defined" % obj.id) | [
"def",
"_get_value_from_ast",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"Num",
")",
":",
"return",
"obj",
".",
"n",
"elif",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"Str",
")",
":",
"return",
"obj",
".",
"s",
"elif",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"List",
")",
":",
"return",
"[",
"self",
".",
"_get_value_from_ast",
"(",
"e",
")",
"for",
"e",
"in",
"obj",
".",
"elts",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"Tuple",
")",
":",
"return",
"tuple",
"(",
"[",
"self",
".",
"_get_value_from_ast",
"(",
"e",
")",
"for",
"e",
"in",
"obj",
".",
"elts",
"]",
")",
"# None, True and False are NameConstants in Py3.4 and above.",
"elif",
"sys",
".",
"version_info",
".",
"major",
">=",
"3",
"and",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"NameConstant",
")",
":",
"return",
"obj",
".",
"value",
"# For python versions below 3.4",
"elif",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"Name",
")",
"and",
"(",
"obj",
".",
"id",
"in",
"[",
"\"True\"",
",",
"\"False\"",
",",
"\"None\"",
"]",
")",
":",
"return",
"string_to_constant",
"[",
"obj",
".",
"id",
"]",
"# Probably passed a variable name.",
"# Or passed a single word without wrapping it in quotes as an argument",
"# ex: p.inflect(\"I plural(see)\") instead of p.inflect(\"I plural('see')\")",
"raise",
"NameError",
"(",
"\"name '%s' is not defined\"",
"%",
"obj",
".",
"id",
")"
]
| Return the value of the ast object. | [
"Return",
"the",
"value",
"of",
"the",
"ast",
"object",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2108-L2132 | train |
jazzband/inflect | inflect.py | engine._string_to_substitute | def _string_to_substitute(self, mo, methods_dict):
"""
Return the string to be substituted for the match.
"""
matched_text, f_name = mo.groups()
# matched_text is the complete match string. e.g. plural_noun(cat)
# f_name is the function name. e.g. plural_noun
# Return matched_text if function name is not in methods_dict
if f_name not in methods_dict:
return matched_text
# Parse the matched text
a_tree = ast.parse(matched_text)
# get the args and kwargs from ast objects
args_list = [self._get_value_from_ast(a) for a in a_tree.body[0].value.args]
kwargs_list = {
kw.arg: self._get_value_from_ast(kw.value)
for kw in a_tree.body[0].value.keywords
}
# Call the corresponding function
return methods_dict[f_name](*args_list, **kwargs_list) | python | def _string_to_substitute(self, mo, methods_dict):
"""
Return the string to be substituted for the match.
"""
matched_text, f_name = mo.groups()
# matched_text is the complete match string. e.g. plural_noun(cat)
# f_name is the function name. e.g. plural_noun
# Return matched_text if function name is not in methods_dict
if f_name not in methods_dict:
return matched_text
# Parse the matched text
a_tree = ast.parse(matched_text)
# get the args and kwargs from ast objects
args_list = [self._get_value_from_ast(a) for a in a_tree.body[0].value.args]
kwargs_list = {
kw.arg: self._get_value_from_ast(kw.value)
for kw in a_tree.body[0].value.keywords
}
# Call the corresponding function
return methods_dict[f_name](*args_list, **kwargs_list) | [
"def",
"_string_to_substitute",
"(",
"self",
",",
"mo",
",",
"methods_dict",
")",
":",
"matched_text",
",",
"f_name",
"=",
"mo",
".",
"groups",
"(",
")",
"# matched_text is the complete match string. e.g. plural_noun(cat)",
"# f_name is the function name. e.g. plural_noun",
"# Return matched_text if function name is not in methods_dict",
"if",
"f_name",
"not",
"in",
"methods_dict",
":",
"return",
"matched_text",
"# Parse the matched text",
"a_tree",
"=",
"ast",
".",
"parse",
"(",
"matched_text",
")",
"# get the args and kwargs from ast objects",
"args_list",
"=",
"[",
"self",
".",
"_get_value_from_ast",
"(",
"a",
")",
"for",
"a",
"in",
"a_tree",
".",
"body",
"[",
"0",
"]",
".",
"value",
".",
"args",
"]",
"kwargs_list",
"=",
"{",
"kw",
".",
"arg",
":",
"self",
".",
"_get_value_from_ast",
"(",
"kw",
".",
"value",
")",
"for",
"kw",
"in",
"a_tree",
".",
"body",
"[",
"0",
"]",
".",
"value",
".",
"keywords",
"}",
"# Call the corresponding function",
"return",
"methods_dict",
"[",
"f_name",
"]",
"(",
"*",
"args_list",
",",
"*",
"*",
"kwargs_list",
")"
]
| Return the string to be substituted for the match. | [
"Return",
"the",
"string",
"to",
"be",
"substituted",
"for",
"the",
"match",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2134-L2157 | train |
jazzband/inflect | inflect.py | engine.inflect | def inflect(self, text):
"""
Perform inflections in a string.
e.g. inflect('The plural of cat is plural(cat)') returns
'The plural of cat is cats'
can use plural, plural_noun, plural_verb, plural_adj,
singular_noun, a, an, no, ordinal, number_to_words,
and prespart
"""
save_persistent_count = self.persistent_count
# Dictionary of allowed methods
methods_dict = {
"plural": self.plural,
"plural_adj": self.plural_adj,
"plural_noun": self.plural_noun,
"plural_verb": self.plural_verb,
"singular_noun": self.singular_noun,
"a": self.a,
"an": self.a,
"no": self.no,
"ordinal": self.ordinal,
"number_to_words": self.number_to_words,
"present_participle": self.present_participle,
"num": self.num,
}
# Regular expression to find Python's function call syntax
functions_re = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE)
output = functions_re.sub(
lambda mo: self._string_to_substitute(mo, methods_dict), text
)
self.persistent_count = save_persistent_count
return output | python | def inflect(self, text):
"""
Perform inflections in a string.
e.g. inflect('The plural of cat is plural(cat)') returns
'The plural of cat is cats'
can use plural, plural_noun, plural_verb, plural_adj,
singular_noun, a, an, no, ordinal, number_to_words,
and prespart
"""
save_persistent_count = self.persistent_count
# Dictionary of allowed methods
methods_dict = {
"plural": self.plural,
"plural_adj": self.plural_adj,
"plural_noun": self.plural_noun,
"plural_verb": self.plural_verb,
"singular_noun": self.singular_noun,
"a": self.a,
"an": self.a,
"no": self.no,
"ordinal": self.ordinal,
"number_to_words": self.number_to_words,
"present_participle": self.present_participle,
"num": self.num,
}
# Regular expression to find Python's function call syntax
functions_re = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE)
output = functions_re.sub(
lambda mo: self._string_to_substitute(mo, methods_dict), text
)
self.persistent_count = save_persistent_count
return output | [
"def",
"inflect",
"(",
"self",
",",
"text",
")",
":",
"save_persistent_count",
"=",
"self",
".",
"persistent_count",
"# Dictionary of allowed methods",
"methods_dict",
"=",
"{",
"\"plural\"",
":",
"self",
".",
"plural",
",",
"\"plural_adj\"",
":",
"self",
".",
"plural_adj",
",",
"\"plural_noun\"",
":",
"self",
".",
"plural_noun",
",",
"\"plural_verb\"",
":",
"self",
".",
"plural_verb",
",",
"\"singular_noun\"",
":",
"self",
".",
"singular_noun",
",",
"\"a\"",
":",
"self",
".",
"a",
",",
"\"an\"",
":",
"self",
".",
"a",
",",
"\"no\"",
":",
"self",
".",
"no",
",",
"\"ordinal\"",
":",
"self",
".",
"ordinal",
",",
"\"number_to_words\"",
":",
"self",
".",
"number_to_words",
",",
"\"present_participle\"",
":",
"self",
".",
"present_participle",
",",
"\"num\"",
":",
"self",
".",
"num",
",",
"}",
"# Regular expression to find Python's function call syntax",
"functions_re",
"=",
"re",
".",
"compile",
"(",
"r\"((\\w+)\\([^)]*\\)*)\"",
",",
"re",
".",
"IGNORECASE",
")",
"output",
"=",
"functions_re",
".",
"sub",
"(",
"lambda",
"mo",
":",
"self",
".",
"_string_to_substitute",
"(",
"mo",
",",
"methods_dict",
")",
",",
"text",
")",
"self",
".",
"persistent_count",
"=",
"save_persistent_count",
"return",
"output"
]
| Perform inflections in a string.
e.g. inflect('The plural of cat is plural(cat)') returns
'The plural of cat is cats'
can use plural, plural_noun, plural_verb, plural_adj,
singular_noun, a, an, no, ordinal, number_to_words,
and prespart | [
"Perform",
"inflections",
"in",
"a",
"string",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2161-L2197 | train |
jazzband/inflect | inflect.py | engine.plural | def plural(self, text, count=None):
"""
Return the plural of text.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(
word,
self._pl_special_adjective(word, count)
or self._pl_special_verb(word, count)
or self._plnoun(word, count),
)
return "{}{}{}".format(pre, plural, post) | python | def plural(self, text, count=None):
"""
Return the plural of text.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(
word,
self._pl_special_adjective(word, count)
or self._pl_special_verb(word, count)
or self._plnoun(word, count),
)
return "{}{}{}".format(pre, plural, post) | [
"def",
"plural",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"plural",
"=",
"self",
".",
"postprocess",
"(",
"word",
",",
"self",
".",
"_pl_special_adjective",
"(",
"word",
",",
"count",
")",
"or",
"self",
".",
"_pl_special_verb",
"(",
"word",
",",
"count",
")",
"or",
"self",
".",
"_plnoun",
"(",
"word",
",",
"count",
")",
",",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"plural",
",",
"post",
")"
]
| Return the plural of text.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved. | [
"Return",
"the",
"plural",
"of",
"text",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2226-L2246 | train |
jazzband/inflect | inflect.py | engine.plural_noun | def plural_noun(self, text, count=None):
"""
Return the plural of text, where text is a noun.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(word, self._plnoun(word, count))
return "{}{}{}".format(pre, plural, post) | python | def plural_noun(self, text, count=None):
"""
Return the plural of text, where text is a noun.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(word, self._plnoun(word, count))
return "{}{}{}".format(pre, plural, post) | [
"def",
"plural_noun",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"plural",
"=",
"self",
".",
"postprocess",
"(",
"word",
",",
"self",
".",
"_plnoun",
"(",
"word",
",",
"count",
")",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"plural",
",",
"post",
")"
]
| Return the plural of text, where text is a noun.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved. | [
"Return",
"the",
"plural",
"of",
"text",
"where",
"text",
"is",
"a",
"noun",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2248-L2263 | train |
jazzband/inflect | inflect.py | engine.plural_verb | def plural_verb(self, text, count=None):
"""
Return the plural of text, where text is a verb.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(
word,
self._pl_special_verb(word, count) or self._pl_general_verb(word, count),
)
return "{}{}{}".format(pre, plural, post) | python | def plural_verb(self, text, count=None):
"""
Return the plural of text, where text is a verb.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(
word,
self._pl_special_verb(word, count) or self._pl_general_verb(word, count),
)
return "{}{}{}".format(pre, plural, post) | [
"def",
"plural_verb",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"plural",
"=",
"self",
".",
"postprocess",
"(",
"word",
",",
"self",
".",
"_pl_special_verb",
"(",
"word",
",",
"count",
")",
"or",
"self",
".",
"_pl_general_verb",
"(",
"word",
",",
"count",
")",
",",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"plural",
",",
"post",
")"
]
| Return the plural of text, where text is a verb.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved. | [
"Return",
"the",
"plural",
"of",
"text",
"where",
"text",
"is",
"a",
"verb",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2265-L2283 | train |
jazzband/inflect | inflect.py | engine.plural_adj | def plural_adj(self, text, count=None):
"""
Return the plural of text, where text is an adjective.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(word, self._pl_special_adjective(word, count) or word)
return "{}{}{}".format(pre, plural, post) | python | def plural_adj(self, text, count=None):
"""
Return the plural of text, where text is an adjective.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
plural = self.postprocess(word, self._pl_special_adjective(word, count) or word)
return "{}{}{}".format(pre, plural, post) | [
"def",
"plural_adj",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"plural",
"=",
"self",
".",
"postprocess",
"(",
"word",
",",
"self",
".",
"_pl_special_adjective",
"(",
"word",
",",
"count",
")",
"or",
"word",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"plural",
",",
"post",
")"
]
| Return the plural of text, where text is an adjective.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end is preserved. | [
"Return",
"the",
"plural",
"of",
"text",
"where",
"text",
"is",
"an",
"adjective",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2285-L2300 | train |
jazzband/inflect | inflect.py | engine.compare | def compare(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return (
self._plequal(word1, word2, self.plural_noun)
or self._plequal(word1, word2, self.plural_verb)
or self._plequal(word1, word2, self.plural_adj)
) | python | def compare(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return (
self._plequal(word1, word2, self.plural_noun)
or self._plequal(word1, word2, self.plural_verb)
or self._plequal(word1, word2, self.plural_adj)
) | [
"def",
"compare",
"(",
"self",
",",
"word1",
",",
"word2",
")",
":",
"return",
"(",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_noun",
")",
"or",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_verb",
")",
"or",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_adj",
")",
")"
]
| compare word1 and word2 for equality regardless of plurality
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise | [
"compare",
"word1",
"and",
"word2",
"for",
"equality",
"regardless",
"of",
"plurality"
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2302-L2318 | train |
jazzband/inflect | inflect.py | engine.compare_nouns | def compare_nouns(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as nouns
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_noun) | python | def compare_nouns(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as nouns
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_noun) | [
"def",
"compare_nouns",
"(",
"self",
",",
"word1",
",",
"word2",
")",
":",
"return",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_noun",
")"
]
| compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as nouns
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise | [
"compare",
"word1",
"and",
"word2",
"for",
"equality",
"regardless",
"of",
"plurality",
"word1",
"and",
"word2",
"are",
"to",
"be",
"treated",
"as",
"nouns"
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2320-L2333 | train |
jazzband/inflect | inflect.py | engine.compare_verbs | def compare_verbs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as verbs
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_verb) | python | def compare_verbs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as verbs
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_verb) | [
"def",
"compare_verbs",
"(",
"self",
",",
"word1",
",",
"word2",
")",
":",
"return",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_verb",
")"
]
| compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as verbs
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise | [
"compare",
"word1",
"and",
"word2",
"for",
"equality",
"regardless",
"of",
"plurality",
"word1",
"and",
"word2",
"are",
"to",
"be",
"treated",
"as",
"verbs"
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2335-L2348 | train |
jazzband/inflect | inflect.py | engine.compare_adjs | def compare_adjs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_adj) | python | def compare_adjs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_adj) | [
"def",
"compare_adjs",
"(",
"self",
",",
"word1",
",",
"word2",
")",
":",
"return",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_adj",
")"
]
| compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise | [
"compare",
"word1",
"and",
"word2",
"for",
"equality",
"regardless",
"of",
"plurality",
"word1",
"and",
"word2",
"are",
"to",
"be",
"treated",
"as",
"adjectives"
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2350-L2363 | train |
jazzband/inflect | inflect.py | engine.singular_noun | def singular_noun(self, text, count=None, gender=None):
"""
Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
sing = self._sinoun(word, count=count, gender=gender)
if sing is not False:
plural = self.postprocess(
word, self._sinoun(word, count=count, gender=gender)
)
return "{}{}{}".format(pre, plural, post)
return False | python | def singular_noun(self, text, count=None, gender=None):
"""
Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
sing = self._sinoun(word, count=count, gender=gender)
if sing is not False:
plural = self.postprocess(
word, self._sinoun(word, count=count, gender=gender)
)
return "{}{}{}".format(pre, plural, post)
return False | [
"def",
"singular_noun",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
",",
"gender",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"sing",
"=",
"self",
".",
"_sinoun",
"(",
"word",
",",
"count",
"=",
"count",
",",
"gender",
"=",
"gender",
")",
"if",
"sing",
"is",
"not",
"False",
":",
"plural",
"=",
"self",
".",
"postprocess",
"(",
"word",
",",
"self",
".",
"_sinoun",
"(",
"word",
",",
"count",
"=",
"count",
",",
"gender",
"=",
"gender",
")",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"plural",
",",
"post",
")",
"return",
"False"
]
| Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved. | [
"Return",
"the",
"singular",
"of",
"text",
"where",
"text",
"is",
"a",
"plural",
"noun",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2365-L2385 | train |
jazzband/inflect | inflect.py | engine.a | def a(self, text, count=1):
"""
Return the appropriate indefinite article followed by text.
The indefinite article is either 'a' or 'an'.
If count is not one, then return count followed by text
instead of 'a' or 'an'.
Whitespace at the start and end is preserved.
"""
mo = re.search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", text, re.IGNORECASE)
if mo:
word = mo.group(2)
if not word:
return text
pre = mo.group(1)
post = mo.group(3)
result = self._indef_article(word, count)
return "{}{}{}".format(pre, result, post)
return "" | python | def a(self, text, count=1):
"""
Return the appropriate indefinite article followed by text.
The indefinite article is either 'a' or 'an'.
If count is not one, then return count followed by text
instead of 'a' or 'an'.
Whitespace at the start and end is preserved.
"""
mo = re.search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", text, re.IGNORECASE)
if mo:
word = mo.group(2)
if not word:
return text
pre = mo.group(1)
post = mo.group(3)
result = self._indef_article(word, count)
return "{}{}{}".format(pre, result, post)
return "" | [
"def",
"a",
"(",
"self",
",",
"text",
",",
"count",
"=",
"1",
")",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r\"\\A(\\s*)(?:an?\\s+)?(.+?)(\\s*)\\Z\"",
",",
"text",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"mo",
":",
"word",
"=",
"mo",
".",
"group",
"(",
"2",
")",
"if",
"not",
"word",
":",
"return",
"text",
"pre",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"post",
"=",
"mo",
".",
"group",
"(",
"3",
")",
"result",
"=",
"self",
".",
"_indef_article",
"(",
"word",
",",
"count",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"result",
",",
"post",
")",
"return",
"\"\""
]
| Return the appropriate indefinite article followed by text.
The indefinite article is either 'a' or 'an'.
If count is not one, then return count followed by text
instead of 'a' or 'an'.
Whitespace at the start and end is preserved. | [
"Return",
"the",
"appropriate",
"indefinite",
"article",
"followed",
"by",
"text",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3259-L3280 | train |
jazzband/inflect | inflect.py | engine.no | def no(self, text, count=None):
"""
If count is 0, no, zero or nil, return 'no' followed by the plural
of text.
If count is one of:
1, a, an, one, each, every, this, that
return count followed by text.
Otherwise return count follow by the plural of text.
In the return value count is always followed by a space.
Whitespace at the start and end is preserved.
"""
if count is None and self.persistent_count is not None:
count = self.persistent_count
if count is None:
count = 0
mo = re.search(r"\A(\s*)(.+?)(\s*)\Z", text)
pre = mo.group(1)
word = mo.group(2)
post = mo.group(3)
if str(count).lower() in pl_count_zero:
return "{}no {}{}".format(pre, self.plural(word, 0), post)
else:
return "{}{} {}{}".format(pre, count, self.plural(word, count), post) | python | def no(self, text, count=None):
"""
If count is 0, no, zero or nil, return 'no' followed by the plural
of text.
If count is one of:
1, a, an, one, each, every, this, that
return count followed by text.
Otherwise return count follow by the plural of text.
In the return value count is always followed by a space.
Whitespace at the start and end is preserved.
"""
if count is None and self.persistent_count is not None:
count = self.persistent_count
if count is None:
count = 0
mo = re.search(r"\A(\s*)(.+?)(\s*)\Z", text)
pre = mo.group(1)
word = mo.group(2)
post = mo.group(3)
if str(count).lower() in pl_count_zero:
return "{}no {}{}".format(pre, self.plural(word, 0), post)
else:
return "{}{} {}{}".format(pre, count, self.plural(word, count), post) | [
"def",
"no",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
"and",
"self",
".",
"persistent_count",
"is",
"not",
"None",
":",
"count",
"=",
"self",
".",
"persistent_count",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"0",
"mo",
"=",
"re",
".",
"search",
"(",
"r\"\\A(\\s*)(.+?)(\\s*)\\Z\"",
",",
"text",
")",
"pre",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"word",
"=",
"mo",
".",
"group",
"(",
"2",
")",
"post",
"=",
"mo",
".",
"group",
"(",
"3",
")",
"if",
"str",
"(",
"count",
")",
".",
"lower",
"(",
")",
"in",
"pl_count_zero",
":",
"return",
"\"{}no {}{}\"",
".",
"format",
"(",
"pre",
",",
"self",
".",
"plural",
"(",
"word",
",",
"0",
")",
",",
"post",
")",
"else",
":",
"return",
"\"{}{} {}{}\"",
".",
"format",
"(",
"pre",
",",
"count",
",",
"self",
".",
"plural",
"(",
"word",
",",
"count",
")",
",",
"post",
")"
]
| If count is 0, no, zero or nil, return 'no' followed by the plural
of text.
If count is one of:
1, a, an, one, each, every, this, that
return count followed by text.
Otherwise return count follow by the plural of text.
In the return value count is always followed by a space.
Whitespace at the start and end is preserved. | [
"If",
"count",
"is",
"0",
"no",
"zero",
"or",
"nil",
"return",
"no",
"followed",
"by",
"the",
"plural",
"of",
"text",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3369-L3398 | train |
jazzband/inflect | inflect.py | engine.present_participle | def present_participle(self, word):
"""
Return the present participle for word.
word is the 3rd person singular verb.
"""
plv = self.plural_verb(word, 2)
for pat, repl in (
(r"ie$", r"y"),
(r"ue$", r"u"), # TODO: isn't ue$ -> u encompassed in the following rule?
(r"([auy])e$", r"\g<1>"),
(r"ski$", r"ski"),
(r"[^b]i$", r""),
(r"^(are|were)$", r"be"),
(r"^(had)$", r"hav"),
(r"^(hoe)$", r"\g<1>"),
(r"([^e])e$", r"\g<1>"),
(r"er$", r"er"),
(r"([^aeiou][aeiouy]([bdgmnprst]))$", r"\g<1>\g<2>"),
):
(ans, num) = re.subn(pat, repl, plv)
if num:
return "%sing" % ans
return "%sing" % ans | python | def present_participle(self, word):
"""
Return the present participle for word.
word is the 3rd person singular verb.
"""
plv = self.plural_verb(word, 2)
for pat, repl in (
(r"ie$", r"y"),
(r"ue$", r"u"), # TODO: isn't ue$ -> u encompassed in the following rule?
(r"([auy])e$", r"\g<1>"),
(r"ski$", r"ski"),
(r"[^b]i$", r""),
(r"^(are|were)$", r"be"),
(r"^(had)$", r"hav"),
(r"^(hoe)$", r"\g<1>"),
(r"([^e])e$", r"\g<1>"),
(r"er$", r"er"),
(r"([^aeiou][aeiouy]([bdgmnprst]))$", r"\g<1>\g<2>"),
):
(ans, num) = re.subn(pat, repl, plv)
if num:
return "%sing" % ans
return "%sing" % ans | [
"def",
"present_participle",
"(",
"self",
",",
"word",
")",
":",
"plv",
"=",
"self",
".",
"plural_verb",
"(",
"word",
",",
"2",
")",
"for",
"pat",
",",
"repl",
"in",
"(",
"(",
"r\"ie$\"",
",",
"r\"y\"",
")",
",",
"(",
"r\"ue$\"",
",",
"r\"u\"",
")",
",",
"# TODO: isn't ue$ -> u encompassed in the following rule?",
"(",
"r\"([auy])e$\"",
",",
"r\"\\g<1>\"",
")",
",",
"(",
"r\"ski$\"",
",",
"r\"ski\"",
")",
",",
"(",
"r\"[^b]i$\"",
",",
"r\"\"",
")",
",",
"(",
"r\"^(are|were)$\"",
",",
"r\"be\"",
")",
",",
"(",
"r\"^(had)$\"",
",",
"r\"hav\"",
")",
",",
"(",
"r\"^(hoe)$\"",
",",
"r\"\\g<1>\"",
")",
",",
"(",
"r\"([^e])e$\"",
",",
"r\"\\g<1>\"",
")",
",",
"(",
"r\"er$\"",
",",
"r\"er\"",
")",
",",
"(",
"r\"([^aeiou][aeiouy]([bdgmnprst]))$\"",
",",
"r\"\\g<1>\\g<2>\"",
")",
",",
")",
":",
"(",
"ans",
",",
"num",
")",
"=",
"re",
".",
"subn",
"(",
"pat",
",",
"repl",
",",
"plv",
")",
"if",
"num",
":",
"return",
"\"%sing\"",
"%",
"ans",
"return",
"\"%sing\"",
"%",
"ans"
]
| Return the present participle for word.
word is the 3rd person singular verb. | [
"Return",
"the",
"present",
"participle",
"for",
"word",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3402-L3427 | train |
jazzband/inflect | inflect.py | engine.ordinal | def ordinal(self, num):
"""
Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first'
"""
if re.match(r"\d", str(num)):
try:
num % 2
n = num
except TypeError:
if "." in str(num):
try:
# numbers after decimal,
# so only need last one for ordinal
n = int(num[-1])
except ValueError: # ends with '.', so need to use whole string
n = int(num[:-1])
else:
n = int(num)
try:
post = nth[n % 100]
except KeyError:
post = nth[n % 10]
return "{}{}".format(num, post)
else:
mo = re.search(r"(%s)\Z" % ordinal_suff, num)
try:
post = ordinal[mo.group(1)]
return re.sub(r"(%s)\Z" % ordinal_suff, post, num)
except AttributeError:
return "%sth" % num | python | def ordinal(self, num):
"""
Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first'
"""
if re.match(r"\d", str(num)):
try:
num % 2
n = num
except TypeError:
if "." in str(num):
try:
# numbers after decimal,
# so only need last one for ordinal
n = int(num[-1])
except ValueError: # ends with '.', so need to use whole string
n = int(num[:-1])
else:
n = int(num)
try:
post = nth[n % 100]
except KeyError:
post = nth[n % 10]
return "{}{}".format(num, post)
else:
mo = re.search(r"(%s)\Z" % ordinal_suff, num)
try:
post = ordinal[mo.group(1)]
return re.sub(r"(%s)\Z" % ordinal_suff, post, num)
except AttributeError:
return "%sth" % num | [
"def",
"ordinal",
"(",
"self",
",",
"num",
")",
":",
"if",
"re",
".",
"match",
"(",
"r\"\\d\"",
",",
"str",
"(",
"num",
")",
")",
":",
"try",
":",
"num",
"%",
"2",
"n",
"=",
"num",
"except",
"TypeError",
":",
"if",
"\".\"",
"in",
"str",
"(",
"num",
")",
":",
"try",
":",
"# numbers after decimal,",
"# so only need last one for ordinal",
"n",
"=",
"int",
"(",
"num",
"[",
"-",
"1",
"]",
")",
"except",
"ValueError",
":",
"# ends with '.', so need to use whole string",
"n",
"=",
"int",
"(",
"num",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"n",
"=",
"int",
"(",
"num",
")",
"try",
":",
"post",
"=",
"nth",
"[",
"n",
"%",
"100",
"]",
"except",
"KeyError",
":",
"post",
"=",
"nth",
"[",
"n",
"%",
"10",
"]",
"return",
"\"{}{}\"",
".",
"format",
"(",
"num",
",",
"post",
")",
"else",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r\"(%s)\\Z\"",
"%",
"ordinal_suff",
",",
"num",
")",
"try",
":",
"post",
"=",
"ordinal",
"[",
"mo",
".",
"group",
"(",
"1",
")",
"]",
"return",
"re",
".",
"sub",
"(",
"r\"(%s)\\Z\"",
"%",
"ordinal_suff",
",",
"post",
",",
"num",
")",
"except",
"AttributeError",
":",
"return",
"\"%sth\"",
"%",
"num"
]
| Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first' | [
"Return",
"the",
"ordinal",
"of",
"num",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3431-L3467 | train |
jazzband/inflect | inflect.py | engine.join | def join(
self,
words,
sep=None,
sep_spaced=True,
final_sep=None,
conj="and",
conj_spaced=True,
):
"""
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spaced: boolean. Should conj have spaces around it
"""
if not words:
return ""
if len(words) == 1:
return words[0]
if conj_spaced:
if conj == "":
conj = " "
else:
conj = " %s " % conj
if len(words) == 2:
return "{}{}{}".format(words[0], conj, words[1])
if sep is None:
if "," in "".join(words):
sep = ";"
else:
sep = ","
if final_sep is None:
final_sep = sep
final_sep = "{}{}".format(final_sep, conj)
if sep_spaced:
sep += " "
return "{}{}{}".format(sep.join(words[0:-1]), final_sep, words[-1]) | python | def join(
self,
words,
sep=None,
sep_spaced=True,
final_sep=None,
conj="and",
conj_spaced=True,
):
"""
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spaced: boolean. Should conj have spaces around it
"""
if not words:
return ""
if len(words) == 1:
return words[0]
if conj_spaced:
if conj == "":
conj = " "
else:
conj = " %s " % conj
if len(words) == 2:
return "{}{}{}".format(words[0], conj, words[1])
if sep is None:
if "," in "".join(words):
sep = ";"
else:
sep = ","
if final_sep is None:
final_sep = sep
final_sep = "{}{}".format(final_sep, conj)
if sep_spaced:
sep += " "
return "{}{}{}".format(sep.join(words[0:-1]), final_sep, words[-1]) | [
"def",
"join",
"(",
"self",
",",
"words",
",",
"sep",
"=",
"None",
",",
"sep_spaced",
"=",
"True",
",",
"final_sep",
"=",
"None",
",",
"conj",
"=",
"\"and\"",
",",
"conj_spaced",
"=",
"True",
",",
")",
":",
"if",
"not",
"words",
":",
"return",
"\"\"",
"if",
"len",
"(",
"words",
")",
"==",
"1",
":",
"return",
"words",
"[",
"0",
"]",
"if",
"conj_spaced",
":",
"if",
"conj",
"==",
"\"\"",
":",
"conj",
"=",
"\" \"",
"else",
":",
"conj",
"=",
"\" %s \"",
"%",
"conj",
"if",
"len",
"(",
"words",
")",
"==",
"2",
":",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"words",
"[",
"0",
"]",
",",
"conj",
",",
"words",
"[",
"1",
"]",
")",
"if",
"sep",
"is",
"None",
":",
"if",
"\",\"",
"in",
"\"\"",
".",
"join",
"(",
"words",
")",
":",
"sep",
"=",
"\";\"",
"else",
":",
"sep",
"=",
"\",\"",
"if",
"final_sep",
"is",
"None",
":",
"final_sep",
"=",
"sep",
"final_sep",
"=",
"\"{}{}\"",
".",
"format",
"(",
"final_sep",
",",
"conj",
")",
"if",
"sep_spaced",
":",
"sep",
"+=",
"\" \"",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"sep",
".",
"join",
"(",
"words",
"[",
"0",
":",
"-",
"1",
"]",
")",
",",
"final_sep",
",",
"words",
"[",
"-",
"1",
"]",
")"
]
| Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spaced: boolean. Should conj have spaces around it | [
"Join",
"words",
"into",
"a",
"list",
"."
]
| c2a3df74725990c195a5d7f37199de56873962e9 | https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3756-L3804 | train |
libtcod/python-tcod | tcod/tcod.py | _int | def _int(int_or_str: Any) -> int:
"return an integer where a single character string may be expected"
if isinstance(int_or_str, str):
return ord(int_or_str)
if isinstance(int_or_str, bytes):
return int_or_str[0]
return int(int_or_str) | python | def _int(int_or_str: Any) -> int:
"return an integer where a single character string may be expected"
if isinstance(int_or_str, str):
return ord(int_or_str)
if isinstance(int_or_str, bytes):
return int_or_str[0]
return int(int_or_str) | [
"def",
"_int",
"(",
"int_or_str",
":",
"Any",
")",
"->",
"int",
":",
"if",
"isinstance",
"(",
"int_or_str",
",",
"str",
")",
":",
"return",
"ord",
"(",
"int_or_str",
")",
"if",
"isinstance",
"(",
"int_or_str",
",",
"bytes",
")",
":",
"return",
"int_or_str",
"[",
"0",
"]",
"return",
"int",
"(",
"int_or_str",
")"
]
| return an integer where a single character string may be expected | [
"return",
"an",
"integer",
"where",
"a",
"single",
"character",
"string",
"may",
"be",
"expected"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tcod.py#L15-L21 | train |
libtcod/python-tcod | tcod/tcod.py | _console | def _console(console: Any) -> Any:
"""Return a cffi console."""
try:
return console.console_c
except AttributeError:
warnings.warn(
(
"Falsy console parameters are deprecated, "
"always use the root console instance returned by "
"console_init_root."
),
DeprecationWarning,
stacklevel=3,
)
return ffi.NULL | python | def _console(console: Any) -> Any:
"""Return a cffi console."""
try:
return console.console_c
except AttributeError:
warnings.warn(
(
"Falsy console parameters are deprecated, "
"always use the root console instance returned by "
"console_init_root."
),
DeprecationWarning,
stacklevel=3,
)
return ffi.NULL | [
"def",
"_console",
"(",
"console",
":",
"Any",
")",
"->",
"Any",
":",
"try",
":",
"return",
"console",
".",
"console_c",
"except",
"AttributeError",
":",
"warnings",
".",
"warn",
"(",
"(",
"\"Falsy console parameters are deprecated, \"",
"\"always use the root console instance returned by \"",
"\"console_init_root.\"",
")",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
",",
")",
"return",
"ffi",
".",
"NULL"
]
| Return a cffi console. | [
"Return",
"a",
"cffi",
"console",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tcod.py#L139-L153 | train |
libtcod/python-tcod | tcod/color.py | Color._new_from_cdata | def _new_from_cdata(cls, cdata: Any) -> "Color":
"""new in libtcod-cffi"""
return cls(cdata.r, cdata.g, cdata.b) | python | def _new_from_cdata(cls, cdata: Any) -> "Color":
"""new in libtcod-cffi"""
return cls(cdata.r, cdata.g, cdata.b) | [
"def",
"_new_from_cdata",
"(",
"cls",
",",
"cdata",
":",
"Any",
")",
"->",
"\"Color\"",
":",
"return",
"cls",
"(",
"cdata",
".",
"r",
",",
"cdata",
".",
"g",
",",
"cdata",
".",
"b",
")"
]
| new in libtcod-cffi | [
"new",
"in",
"libtcod",
"-",
"cffi"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/color.py#L66-L68 | train |
libtcod/python-tcod | tcod/event.py | _describe_bitmask | def _describe_bitmask(
bits: int, table: Dict[Any, str], default: str = "0"
) -> str:
"""Returns a bitmask in human readable form.
This is a private function, used internally.
Args:
bits (int): The bitmask to be represented.
table (Dict[Any,str]): A reverse lookup table.
default (Any): A default return value when bits is 0.
Returns: str: A printable version of the bits variable.
"""
result = []
for bit, name in table.items():
if bit & bits:
result.append(name)
if not result:
return default
return "|".join(result) | python | def _describe_bitmask(
bits: int, table: Dict[Any, str], default: str = "0"
) -> str:
"""Returns a bitmask in human readable form.
This is a private function, used internally.
Args:
bits (int): The bitmask to be represented.
table (Dict[Any,str]): A reverse lookup table.
default (Any): A default return value when bits is 0.
Returns: str: A printable version of the bits variable.
"""
result = []
for bit, name in table.items():
if bit & bits:
result.append(name)
if not result:
return default
return "|".join(result) | [
"def",
"_describe_bitmask",
"(",
"bits",
":",
"int",
",",
"table",
":",
"Dict",
"[",
"Any",
",",
"str",
"]",
",",
"default",
":",
"str",
"=",
"\"0\"",
")",
"->",
"str",
":",
"result",
"=",
"[",
"]",
"for",
"bit",
",",
"name",
"in",
"table",
".",
"items",
"(",
")",
":",
"if",
"bit",
"&",
"bits",
":",
"result",
".",
"append",
"(",
"name",
")",
"if",
"not",
"result",
":",
"return",
"default",
"return",
"\"|\"",
".",
"join",
"(",
"result",
")"
]
| Returns a bitmask in human readable form.
This is a private function, used internally.
Args:
bits (int): The bitmask to be represented.
table (Dict[Any,str]): A reverse lookup table.
default (Any): A default return value when bits is 0.
Returns: str: A printable version of the bits variable. | [
"Returns",
"a",
"bitmask",
"in",
"human",
"readable",
"form",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L25-L45 | train |
libtcod/python-tcod | tcod/event.py | _pixel_to_tile | def _pixel_to_tile(x: float, y: float) -> Tuple[float, float]:
"""Convert pixel coordinates to tile coordinates."""
xy = tcod.ffi.new("double[2]", (x, y))
tcod.lib.TCOD_sys_pixel_to_tile(xy, xy + 1)
return xy[0], xy[1] | python | def _pixel_to_tile(x: float, y: float) -> Tuple[float, float]:
"""Convert pixel coordinates to tile coordinates."""
xy = tcod.ffi.new("double[2]", (x, y))
tcod.lib.TCOD_sys_pixel_to_tile(xy, xy + 1)
return xy[0], xy[1] | [
"def",
"_pixel_to_tile",
"(",
"x",
":",
"float",
",",
"y",
":",
"float",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"xy",
"=",
"tcod",
".",
"ffi",
".",
"new",
"(",
"\"double[2]\"",
",",
"(",
"x",
",",
"y",
")",
")",
"tcod",
".",
"lib",
".",
"TCOD_sys_pixel_to_tile",
"(",
"xy",
",",
"xy",
"+",
"1",
")",
"return",
"xy",
"[",
"0",
"]",
",",
"xy",
"[",
"1",
"]"
]
| Convert pixel coordinates to tile coordinates. | [
"Convert",
"pixel",
"coordinates",
"to",
"tile",
"coordinates",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L48-L52 | train |
libtcod/python-tcod | tcod/event.py | get | def get() -> Iterator[Any]:
"""Return an iterator for all pending events.
Events are processed as the iterator is consumed. Breaking out of, or
discarding the iterator will leave the remaining events on the event queue.
Example::
for event in tcod.event.get():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
sdl_event = tcod.ffi.new("SDL_Event*")
while tcod.lib.SDL_PollEvent(sdl_event):
if sdl_event.type in _SDL_TO_CLASS_TABLE:
yield _SDL_TO_CLASS_TABLE[sdl_event.type].from_sdl_event(sdl_event)
else:
yield Undefined.from_sdl_event(sdl_event) | python | def get() -> Iterator[Any]:
"""Return an iterator for all pending events.
Events are processed as the iterator is consumed. Breaking out of, or
discarding the iterator will leave the remaining events on the event queue.
Example::
for event in tcod.event.get():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
sdl_event = tcod.ffi.new("SDL_Event*")
while tcod.lib.SDL_PollEvent(sdl_event):
if sdl_event.type in _SDL_TO_CLASS_TABLE:
yield _SDL_TO_CLASS_TABLE[sdl_event.type].from_sdl_event(sdl_event)
else:
yield Undefined.from_sdl_event(sdl_event) | [
"def",
"get",
"(",
")",
"->",
"Iterator",
"[",
"Any",
"]",
":",
"sdl_event",
"=",
"tcod",
".",
"ffi",
".",
"new",
"(",
"\"SDL_Event*\"",
")",
"while",
"tcod",
".",
"lib",
".",
"SDL_PollEvent",
"(",
"sdl_event",
")",
":",
"if",
"sdl_event",
".",
"type",
"in",
"_SDL_TO_CLASS_TABLE",
":",
"yield",
"_SDL_TO_CLASS_TABLE",
"[",
"sdl_event",
".",
"type",
"]",
".",
"from_sdl_event",
"(",
"sdl_event",
")",
"else",
":",
"yield",
"Undefined",
".",
"from_sdl_event",
"(",
"sdl_event",
")"
]
| Return an iterator for all pending events.
Events are processed as the iterator is consumed. Breaking out of, or
discarding the iterator will leave the remaining events on the event queue.
Example::
for event in tcod.event.get():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event) | [
"Return",
"an",
"iterator",
"for",
"all",
"pending",
"events",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L564-L590 | train |
libtcod/python-tcod | tcod/event.py | wait | def wait(timeout: Optional[float] = None) -> Iterator[Any]:
"""Block until events exist, then return an event iterator.
`timeout` is the maximum number of seconds to wait as a floating point
number with millisecond precision, or it can be None to wait forever.
Returns the same iterator as a call to :any:`tcod.event.get`.
Example::
for event in tcod.event.wait():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
if timeout is not None:
tcod.lib.SDL_WaitEventTimeout(tcod.ffi.NULL, int(timeout * 1000))
else:
tcod.lib.SDL_WaitEvent(tcod.ffi.NULL)
return get() | python | def wait(timeout: Optional[float] = None) -> Iterator[Any]:
"""Block until events exist, then return an event iterator.
`timeout` is the maximum number of seconds to wait as a floating point
number with millisecond precision, or it can be None to wait forever.
Returns the same iterator as a call to :any:`tcod.event.get`.
Example::
for event in tcod.event.wait():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
if timeout is not None:
tcod.lib.SDL_WaitEventTimeout(tcod.ffi.NULL, int(timeout * 1000))
else:
tcod.lib.SDL_WaitEvent(tcod.ffi.NULL)
return get() | [
"def",
"wait",
"(",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
")",
"->",
"Iterator",
"[",
"Any",
"]",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"tcod",
".",
"lib",
".",
"SDL_WaitEventTimeout",
"(",
"tcod",
".",
"ffi",
".",
"NULL",
",",
"int",
"(",
"timeout",
"*",
"1000",
")",
")",
"else",
":",
"tcod",
".",
"lib",
".",
"SDL_WaitEvent",
"(",
"tcod",
".",
"ffi",
".",
"NULL",
")",
"return",
"get",
"(",
")"
]
| Block until events exist, then return an event iterator.
`timeout` is the maximum number of seconds to wait as a floating point
number with millisecond precision, or it can be None to wait forever.
Returns the same iterator as a call to :any:`tcod.event.get`.
Example::
for event in tcod.event.wait():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event) | [
"Block",
"until",
"events",
"exist",
"then",
"return",
"an",
"event",
"iterator",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L593-L620 | train |
libtcod/python-tcod | tcod/event.py | get_mouse_state | def get_mouse_state() -> MouseState:
"""Return the current state of the mouse.
.. addedversion:: 9.3
"""
xy = tcod.ffi.new("int[2]")
buttons = tcod.lib.SDL_GetMouseState(xy, xy + 1)
x, y = _pixel_to_tile(*xy)
return MouseState((xy[0], xy[1]), (int(x), int(y)), buttons) | python | def get_mouse_state() -> MouseState:
"""Return the current state of the mouse.
.. addedversion:: 9.3
"""
xy = tcod.ffi.new("int[2]")
buttons = tcod.lib.SDL_GetMouseState(xy, xy + 1)
x, y = _pixel_to_tile(*xy)
return MouseState((xy[0], xy[1]), (int(x), int(y)), buttons) | [
"def",
"get_mouse_state",
"(",
")",
"->",
"MouseState",
":",
"xy",
"=",
"tcod",
".",
"ffi",
".",
"new",
"(",
"\"int[2]\"",
")",
"buttons",
"=",
"tcod",
".",
"lib",
".",
"SDL_GetMouseState",
"(",
"xy",
",",
"xy",
"+",
"1",
")",
"x",
",",
"y",
"=",
"_pixel_to_tile",
"(",
"*",
"xy",
")",
"return",
"MouseState",
"(",
"(",
"xy",
"[",
"0",
"]",
",",
"xy",
"[",
"1",
"]",
")",
",",
"(",
"int",
"(",
"x",
")",
",",
"int",
"(",
"y",
")",
")",
",",
"buttons",
")"
]
| Return the current state of the mouse.
.. addedversion:: 9.3 | [
"Return",
"the",
"current",
"state",
"of",
"the",
"mouse",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L749-L757 | train |
libtcod/python-tcod | tcod/_internal.py | deprecate | def deprecate(
message: str, category: Any = DeprecationWarning, stacklevel: int = 0
) -> Callable[[F], F]:
"""Return a decorator which adds a warning to functions."""
def decorator(func: F) -> F:
if not __debug__:
return func
@functools.wraps(func)
def wrapper(*args, **kargs): # type: ignore
warnings.warn(message, category, stacklevel=stacklevel + 2)
return func(*args, **kargs)
return cast(F, wrapper)
return decorator | python | def deprecate(
message: str, category: Any = DeprecationWarning, stacklevel: int = 0
) -> Callable[[F], F]:
"""Return a decorator which adds a warning to functions."""
def decorator(func: F) -> F:
if not __debug__:
return func
@functools.wraps(func)
def wrapper(*args, **kargs): # type: ignore
warnings.warn(message, category, stacklevel=stacklevel + 2)
return func(*args, **kargs)
return cast(F, wrapper)
return decorator | [
"def",
"deprecate",
"(",
"message",
":",
"str",
",",
"category",
":",
"Any",
"=",
"DeprecationWarning",
",",
"stacklevel",
":",
"int",
"=",
"0",
")",
"->",
"Callable",
"[",
"[",
"F",
"]",
",",
"F",
"]",
":",
"def",
"decorator",
"(",
"func",
":",
"F",
")",
"->",
"F",
":",
"if",
"not",
"__debug__",
":",
"return",
"func",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"# type: ignore",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
",",
"stacklevel",
"=",
"stacklevel",
"+",
"2",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"return",
"cast",
"(",
"F",
",",
"wrapper",
")",
"return",
"decorator"
]
| Return a decorator which adds a warning to functions. | [
"Return",
"a",
"decorator",
"which",
"adds",
"a",
"warning",
"to",
"functions",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/_internal.py#L9-L25 | train |
libtcod/python-tcod | tcod/_internal.py | pending_deprecate | def pending_deprecate(
message: str = "This function may be deprecated in the future."
" Consider raising an issue on GitHub if you need this feature.",
category: Any = PendingDeprecationWarning,
stacklevel: int = 0,
) -> Callable[[F], F]:
"""Like deprecate, but the default parameters are filled out for a generic
pending deprecation warning."""
return deprecate(message, category, stacklevel) | python | def pending_deprecate(
message: str = "This function may be deprecated in the future."
" Consider raising an issue on GitHub if you need this feature.",
category: Any = PendingDeprecationWarning,
stacklevel: int = 0,
) -> Callable[[F], F]:
"""Like deprecate, but the default parameters are filled out for a generic
pending deprecation warning."""
return deprecate(message, category, stacklevel) | [
"def",
"pending_deprecate",
"(",
"message",
":",
"str",
"=",
"\"This function may be deprecated in the future.\"",
"\" Consider raising an issue on GitHub if you need this feature.\"",
",",
"category",
":",
"Any",
"=",
"PendingDeprecationWarning",
",",
"stacklevel",
":",
"int",
"=",
"0",
",",
")",
"->",
"Callable",
"[",
"[",
"F",
"]",
",",
"F",
"]",
":",
"return",
"deprecate",
"(",
"message",
",",
"category",
",",
"stacklevel",
")"
]
| Like deprecate, but the default parameters are filled out for a generic
pending deprecation warning. | [
"Like",
"deprecate",
"but",
"the",
"default",
"parameters",
"are",
"filled",
"out",
"for",
"a",
"generic",
"pending",
"deprecation",
"warning",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/_internal.py#L28-L36 | train |
libtcod/python-tcod | tdl/__init__.py | _format_char | def _format_char(char):
"""Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
"""
if char is None:
return -1
if isinstance(char, _STRTYPES) and len(char) == 1:
return ord(char)
try:
return int(char) # allow all int-like objects
except:
raise TypeError('char single character string, integer, or None\nReceived: ' + repr(char)) | python | def _format_char(char):
"""Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
"""
if char is None:
return -1
if isinstance(char, _STRTYPES) and len(char) == 1:
return ord(char)
try:
return int(char) # allow all int-like objects
except:
raise TypeError('char single character string, integer, or None\nReceived: ' + repr(char)) | [
"def",
"_format_char",
"(",
"char",
")",
":",
"if",
"char",
"is",
"None",
":",
"return",
"-",
"1",
"if",
"isinstance",
"(",
"char",
",",
"_STRTYPES",
")",
"and",
"len",
"(",
"char",
")",
"==",
"1",
":",
"return",
"ord",
"(",
"char",
")",
"try",
":",
"return",
"int",
"(",
"char",
")",
"# allow all int-like objects",
"except",
":",
"raise",
"TypeError",
"(",
"'char single character string, integer, or None\\nReceived: '",
"+",
"repr",
"(",
"char",
")",
")"
]
| Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible. | [
"Prepares",
"a",
"single",
"character",
"for",
"passing",
"to",
"ctypes",
"calls",
"needs",
"to",
"return",
"an",
"integer",
"but",
"can",
"also",
"pass",
"None",
"which",
"will",
"keep",
"the",
"current",
"character",
"instead",
"of",
"overwriting",
"it",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L101-L115 | train |
libtcod/python-tcod | tdl/__init__.py | _format_str | def _format_str(string):
"""Attempt fast string handing by decoding directly into an array."""
if isinstance(string, _STRTYPES):
if _IS_PYTHON3:
array = _array.array('I')
array.frombytes(string.encode(_utf32_codec))
else: # Python 2
if isinstance(string, unicode):
array = _array.array(b'I')
array.fromstring(string.encode(_utf32_codec))
else:
array = _array.array(b'B')
array.fromstring(string)
return array
return string | python | def _format_str(string):
"""Attempt fast string handing by decoding directly into an array."""
if isinstance(string, _STRTYPES):
if _IS_PYTHON3:
array = _array.array('I')
array.frombytes(string.encode(_utf32_codec))
else: # Python 2
if isinstance(string, unicode):
array = _array.array(b'I')
array.fromstring(string.encode(_utf32_codec))
else:
array = _array.array(b'B')
array.fromstring(string)
return array
return string | [
"def",
"_format_str",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"_STRTYPES",
")",
":",
"if",
"_IS_PYTHON3",
":",
"array",
"=",
"_array",
".",
"array",
"(",
"'I'",
")",
"array",
".",
"frombytes",
"(",
"string",
".",
"encode",
"(",
"_utf32_codec",
")",
")",
"else",
":",
"# Python 2",
"if",
"isinstance",
"(",
"string",
",",
"unicode",
")",
":",
"array",
"=",
"_array",
".",
"array",
"(",
"b'I'",
")",
"array",
".",
"fromstring",
"(",
"string",
".",
"encode",
"(",
"_utf32_codec",
")",
")",
"else",
":",
"array",
"=",
"_array",
".",
"array",
"(",
"b'B'",
")",
"array",
".",
"fromstring",
"(",
"string",
")",
"return",
"array",
"return",
"string"
]
| Attempt fast string handing by decoding directly into an array. | [
"Attempt",
"fast",
"string",
"handing",
"by",
"decoding",
"directly",
"into",
"an",
"array",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L119-L133 | train |
libtcod/python-tcod | tdl/__init__.py | _getImageSize | def _getImageSize(filename):
"""Try to get the width and height of a bmp of png image file"""
result = None
file = open(filename, 'rb')
if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
while 1:
length, = _struct.unpack('>i', file.read(4))
chunkID = file.read(4)
if chunkID == '': # EOF
break
if chunkID == b'IHDR':
# return width, height
result = _struct.unpack('>ii', file.read(8))
break
file.seek(4 + length, 1)
file.close()
return result
file.seek(0)
if file.read(8) == b'BM': # Bitmap
file.seek(18, 0) # skip to size data
result = _struct.unpack('<ii', file.read(8))
file.close()
return result | python | def _getImageSize(filename):
"""Try to get the width and height of a bmp of png image file"""
result = None
file = open(filename, 'rb')
if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
while 1:
length, = _struct.unpack('>i', file.read(4))
chunkID = file.read(4)
if chunkID == '': # EOF
break
if chunkID == b'IHDR':
# return width, height
result = _struct.unpack('>ii', file.read(8))
break
file.seek(4 + length, 1)
file.close()
return result
file.seek(0)
if file.read(8) == b'BM': # Bitmap
file.seek(18, 0) # skip to size data
result = _struct.unpack('<ii', file.read(8))
file.close()
return result | [
"def",
"_getImageSize",
"(",
"filename",
")",
":",
"result",
"=",
"None",
"file",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"if",
"file",
".",
"read",
"(",
"8",
")",
"==",
"b'\\x89PNG\\r\\n\\x1a\\n'",
":",
"# PNG",
"while",
"1",
":",
"length",
",",
"=",
"_struct",
".",
"unpack",
"(",
"'>i'",
",",
"file",
".",
"read",
"(",
"4",
")",
")",
"chunkID",
"=",
"file",
".",
"read",
"(",
"4",
")",
"if",
"chunkID",
"==",
"''",
":",
"# EOF",
"break",
"if",
"chunkID",
"==",
"b'IHDR'",
":",
"# return width, height",
"result",
"=",
"_struct",
".",
"unpack",
"(",
"'>ii'",
",",
"file",
".",
"read",
"(",
"8",
")",
")",
"break",
"file",
".",
"seek",
"(",
"4",
"+",
"length",
",",
"1",
")",
"file",
".",
"close",
"(",
")",
"return",
"result",
"file",
".",
"seek",
"(",
"0",
")",
"if",
"file",
".",
"read",
"(",
"8",
")",
"==",
"b'BM'",
":",
"# Bitmap",
"file",
".",
"seek",
"(",
"18",
",",
"0",
")",
"# skip to size data",
"result",
"=",
"_struct",
".",
"unpack",
"(",
"'<ii'",
",",
"file",
".",
"read",
"(",
"8",
")",
")",
"file",
".",
"close",
"(",
")",
"return",
"result"
]
| Try to get the width and height of a bmp of png image file | [
"Try",
"to",
"get",
"the",
"width",
"and",
"height",
"of",
"a",
"bmp",
"of",
"png",
"image",
"file"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L165-L187 | train |
libtcod/python-tcod | tdl/__init__.py | init | def init(width, height, title=None, fullscreen=False, renderer='SDL'):
"""Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
Args:
width (int): width of the root console (in tiles)
height (int): height of the root console (in tiles)
title (Optiona[Text]):
Text to display as the window title.
If left None it defaults to the running scripts filename.
fullscreen (bool): Can be set to True to start in fullscreen mode.
renderer (Text): Can be one of 'GLSL', 'OPENGL', or 'SDL'.
Due to way Python works you're unlikely to see much of an
improvement by using 'GLSL' over 'OPENGL' as most of the
time Python is slow interacting with the console and the
rendering itself is pretty fast even on 'SDL'.
Returns:
tdl.Console: The root console.
Only what is drawn on the root console is
what's visible after a call to :any:`tdl.flush`.
After the root console is garbage collected, the window made by
this function will close.
.. seealso::
:any:`Console` :any:`set_font`
"""
RENDERERS = {'GLSL': 0, 'OPENGL': 1, 'SDL': 2}
global _rootinitialized, _rootConsoleRef
if not _fontinitialized: # set the default font to the one that comes with tdl
set_font(_os.path.join(__path__[0], 'terminal8x8.png'),
None, None, True, True)
if renderer.upper() not in RENDERERS:
raise TDLError('No such render type "%s", expected one of "%s"' % (renderer, '", "'.join(RENDERERS)))
renderer = RENDERERS[renderer.upper()]
# If a console already exists then make a clone to replace it
if _rootConsoleRef and _rootConsoleRef():
# unhook the root console, turning into a regular console and deleting
# the root console from libTCOD
_rootConsoleRef()._root_unhook()
if title is None: # use a default title
if _sys.argv:
# Use the script filename as the title.
title = _os.path.basename(_sys.argv[0])
else:
title = 'python-tdl'
_lib.TCOD_console_init_root(width, height, _encodeString(title), fullscreen, renderer)
#event.get() # flush the libtcod event queue to fix some issues
# issues may be fixed already
event._eventsflushed = False
_rootinitialized = True
rootconsole = Console._newConsole(_ffi.NULL)
_rootConsoleRef = _weakref.ref(rootconsole)
return rootconsole | python | def init(width, height, title=None, fullscreen=False, renderer='SDL'):
"""Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
Args:
width (int): width of the root console (in tiles)
height (int): height of the root console (in tiles)
title (Optiona[Text]):
Text to display as the window title.
If left None it defaults to the running scripts filename.
fullscreen (bool): Can be set to True to start in fullscreen mode.
renderer (Text): Can be one of 'GLSL', 'OPENGL', or 'SDL'.
Due to way Python works you're unlikely to see much of an
improvement by using 'GLSL' over 'OPENGL' as most of the
time Python is slow interacting with the console and the
rendering itself is pretty fast even on 'SDL'.
Returns:
tdl.Console: The root console.
Only what is drawn on the root console is
what's visible after a call to :any:`tdl.flush`.
After the root console is garbage collected, the window made by
this function will close.
.. seealso::
:any:`Console` :any:`set_font`
"""
RENDERERS = {'GLSL': 0, 'OPENGL': 1, 'SDL': 2}
global _rootinitialized, _rootConsoleRef
if not _fontinitialized: # set the default font to the one that comes with tdl
set_font(_os.path.join(__path__[0], 'terminal8x8.png'),
None, None, True, True)
if renderer.upper() not in RENDERERS:
raise TDLError('No such render type "%s", expected one of "%s"' % (renderer, '", "'.join(RENDERERS)))
renderer = RENDERERS[renderer.upper()]
# If a console already exists then make a clone to replace it
if _rootConsoleRef and _rootConsoleRef():
# unhook the root console, turning into a regular console and deleting
# the root console from libTCOD
_rootConsoleRef()._root_unhook()
if title is None: # use a default title
if _sys.argv:
# Use the script filename as the title.
title = _os.path.basename(_sys.argv[0])
else:
title = 'python-tdl'
_lib.TCOD_console_init_root(width, height, _encodeString(title), fullscreen, renderer)
#event.get() # flush the libtcod event queue to fix some issues
# issues may be fixed already
event._eventsflushed = False
_rootinitialized = True
rootconsole = Console._newConsole(_ffi.NULL)
_rootConsoleRef = _weakref.ref(rootconsole)
return rootconsole | [
"def",
"init",
"(",
"width",
",",
"height",
",",
"title",
"=",
"None",
",",
"fullscreen",
"=",
"False",
",",
"renderer",
"=",
"'SDL'",
")",
":",
"RENDERERS",
"=",
"{",
"'GLSL'",
":",
"0",
",",
"'OPENGL'",
":",
"1",
",",
"'SDL'",
":",
"2",
"}",
"global",
"_rootinitialized",
",",
"_rootConsoleRef",
"if",
"not",
"_fontinitialized",
":",
"# set the default font to the one that comes with tdl",
"set_font",
"(",
"_os",
".",
"path",
".",
"join",
"(",
"__path__",
"[",
"0",
"]",
",",
"'terminal8x8.png'",
")",
",",
"None",
",",
"None",
",",
"True",
",",
"True",
")",
"if",
"renderer",
".",
"upper",
"(",
")",
"not",
"in",
"RENDERERS",
":",
"raise",
"TDLError",
"(",
"'No such render type \"%s\", expected one of \"%s\"'",
"%",
"(",
"renderer",
",",
"'\", \"'",
".",
"join",
"(",
"RENDERERS",
")",
")",
")",
"renderer",
"=",
"RENDERERS",
"[",
"renderer",
".",
"upper",
"(",
")",
"]",
"# If a console already exists then make a clone to replace it",
"if",
"_rootConsoleRef",
"and",
"_rootConsoleRef",
"(",
")",
":",
"# unhook the root console, turning into a regular console and deleting",
"# the root console from libTCOD",
"_rootConsoleRef",
"(",
")",
".",
"_root_unhook",
"(",
")",
"if",
"title",
"is",
"None",
":",
"# use a default title",
"if",
"_sys",
".",
"argv",
":",
"# Use the script filename as the title.",
"title",
"=",
"_os",
".",
"path",
".",
"basename",
"(",
"_sys",
".",
"argv",
"[",
"0",
"]",
")",
"else",
":",
"title",
"=",
"'python-tdl'",
"_lib",
".",
"TCOD_console_init_root",
"(",
"width",
",",
"height",
",",
"_encodeString",
"(",
"title",
")",
",",
"fullscreen",
",",
"renderer",
")",
"#event.get() # flush the libtcod event queue to fix some issues",
"# issues may be fixed already",
"event",
".",
"_eventsflushed",
"=",
"False",
"_rootinitialized",
"=",
"True",
"rootconsole",
"=",
"Console",
".",
"_newConsole",
"(",
"_ffi",
".",
"NULL",
")",
"_rootConsoleRef",
"=",
"_weakref",
".",
"ref",
"(",
"rootconsole",
")",
"return",
"rootconsole"
]
| Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
Args:
width (int): width of the root console (in tiles)
height (int): height of the root console (in tiles)
title (Optiona[Text]):
Text to display as the window title.
If left None it defaults to the running scripts filename.
fullscreen (bool): Can be set to True to start in fullscreen mode.
renderer (Text): Can be one of 'GLSL', 'OPENGL', or 'SDL'.
Due to way Python works you're unlikely to see much of an
improvement by using 'GLSL' over 'OPENGL' as most of the
time Python is slow interacting with the console and the
rendering itself is pretty fast even on 'SDL'.
Returns:
tdl.Console: The root console.
Only what is drawn on the root console is
what's visible after a call to :any:`tdl.flush`.
After the root console is garbage collected, the window made by
this function will close.
.. seealso::
:any:`Console` :any:`set_font` | [
"Start",
"the",
"main",
"console",
"with",
"the",
"given",
"width",
"and",
"height",
"and",
"return",
"the",
"root",
"console",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L1014-L1080 | train |
libtcod/python-tcod | tdl/__init__.py | screenshot | def screenshot(path=None):
"""Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot.
"""
if not _rootinitialized:
raise TDLError('Initialize first with tdl.init')
if isinstance(path, str):
_lib.TCOD_sys_save_screenshot(_encodeString(path))
elif path is None: # save to screenshot001.png, screenshot002.png, ...
filelist = _os.listdir('.')
n = 1
filename = 'screenshot%.3i.png' % n
while filename in filelist:
n += 1
filename = 'screenshot%.3i.png' % n
_lib.TCOD_sys_save_screenshot(_encodeString(filename))
else: # assume file like obj
#save to temp file and copy to file-like obj
tmpname = _os.tempnam()
_lib.TCOD_sys_save_screenshot(_encodeString(tmpname))
with tmpname as tmpfile:
path.write(tmpfile.read())
_os.remove(tmpname) | python | def screenshot(path=None):
"""Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot.
"""
if not _rootinitialized:
raise TDLError('Initialize first with tdl.init')
if isinstance(path, str):
_lib.TCOD_sys_save_screenshot(_encodeString(path))
elif path is None: # save to screenshot001.png, screenshot002.png, ...
filelist = _os.listdir('.')
n = 1
filename = 'screenshot%.3i.png' % n
while filename in filelist:
n += 1
filename = 'screenshot%.3i.png' % n
_lib.TCOD_sys_save_screenshot(_encodeString(filename))
else: # assume file like obj
#save to temp file and copy to file-like obj
tmpname = _os.tempnam()
_lib.TCOD_sys_save_screenshot(_encodeString(tmpname))
with tmpname as tmpfile:
path.write(tmpfile.read())
_os.remove(tmpname) | [
"def",
"screenshot",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"_rootinitialized",
":",
"raise",
"TDLError",
"(",
"'Initialize first with tdl.init'",
")",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"_lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_encodeString",
"(",
"path",
")",
")",
"elif",
"path",
"is",
"None",
":",
"# save to screenshot001.png, screenshot002.png, ...",
"filelist",
"=",
"_os",
".",
"listdir",
"(",
"'.'",
")",
"n",
"=",
"1",
"filename",
"=",
"'screenshot%.3i.png'",
"%",
"n",
"while",
"filename",
"in",
"filelist",
":",
"n",
"+=",
"1",
"filename",
"=",
"'screenshot%.3i.png'",
"%",
"n",
"_lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_encodeString",
"(",
"filename",
")",
")",
"else",
":",
"# assume file like obj",
"#save to temp file and copy to file-like obj",
"tmpname",
"=",
"_os",
".",
"tempnam",
"(",
")",
"_lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_encodeString",
"(",
"tmpname",
")",
")",
"with",
"tmpname",
"as",
"tmpfile",
":",
"path",
".",
"write",
"(",
"tmpfile",
".",
"read",
"(",
")",
")",
"_os",
".",
"remove",
"(",
"tmpname",
")"
]
| Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot. | [
"Capture",
"the",
"screen",
"and",
"save",
"it",
"as",
"a",
"png",
"file",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L1243-L1271 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole._normalizePoint | def _normalizePoint(self, x, y):
"""Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
"""
# cast to int, always faster than type checking
x = int(x)
y = int(y)
assert (-self.width <= x < self.width) and \
(-self.height <= y < self.height), \
('(%i, %i) is an invalid postition on %s' % (x, y, self))
# handle negative indexes
return (x % self.width, y % self.height) | python | def _normalizePoint(self, x, y):
"""Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
"""
# cast to int, always faster than type checking
x = int(x)
y = int(y)
assert (-self.width <= x < self.width) and \
(-self.height <= y < self.height), \
('(%i, %i) is an invalid postition on %s' % (x, y, self))
# handle negative indexes
return (x % self.width, y % self.height) | [
"def",
"_normalizePoint",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# cast to int, always faster than type checking",
"x",
"=",
"int",
"(",
"x",
")",
"y",
"=",
"int",
"(",
"y",
")",
"assert",
"(",
"-",
"self",
".",
"width",
"<=",
"x",
"<",
"self",
".",
"width",
")",
"and",
"(",
"-",
"self",
".",
"height",
"<=",
"y",
"<",
"self",
".",
"height",
")",
",",
"(",
"'(%i, %i) is an invalid postition on %s'",
"%",
"(",
"x",
",",
"y",
",",
"self",
")",
")",
"# handle negative indexes",
"return",
"(",
"x",
"%",
"self",
".",
"width",
",",
"y",
"%",
"self",
".",
"height",
")"
]
| Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function | [
"Check",
"if",
"a",
"point",
"is",
"in",
"bounds",
"and",
"make",
"minor",
"adjustments",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L208-L223 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole._normalizeRect | def _normalizeRect(self, x, y, width, height):
"""Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems
"""
x, y = self._normalizePoint(x, y) # inherit _normalizePoint logic
assert width is None or isinstance(width, _INTTYPES), 'width must be an integer or None, got %s' % repr(width)
assert height is None or isinstance(height, _INTTYPES), 'height must be an integer or None, got %s' % repr(height)
# if width or height are None then extend them to the edge
if width is None:
width = self.width - x
elif width < 0: # handle negative numbers
width += self.width
width = max(0, width) # a 'too big' negative is clamped zero
if height is None:
height = self.height - y
height = max(0, height)
elif height < 0:
height += self.height
# reduce rect size to bounds
width = min(width, self.width - x)
height = min(height, self.height - y)
return x, y, width, height | python | def _normalizeRect(self, x, y, width, height):
"""Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems
"""
x, y = self._normalizePoint(x, y) # inherit _normalizePoint logic
assert width is None or isinstance(width, _INTTYPES), 'width must be an integer or None, got %s' % repr(width)
assert height is None or isinstance(height, _INTTYPES), 'height must be an integer or None, got %s' % repr(height)
# if width or height are None then extend them to the edge
if width is None:
width = self.width - x
elif width < 0: # handle negative numbers
width += self.width
width = max(0, width) # a 'too big' negative is clamped zero
if height is None:
height = self.height - y
height = max(0, height)
elif height < 0:
height += self.height
# reduce rect size to bounds
width = min(width, self.width - x)
height = min(height, self.height - y)
return x, y, width, height | [
"def",
"_normalizeRect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_normalizePoint",
"(",
"x",
",",
"y",
")",
"# inherit _normalizePoint logic",
"assert",
"width",
"is",
"None",
"or",
"isinstance",
"(",
"width",
",",
"_INTTYPES",
")",
",",
"'width must be an integer or None, got %s'",
"%",
"repr",
"(",
"width",
")",
"assert",
"height",
"is",
"None",
"or",
"isinstance",
"(",
"height",
",",
"_INTTYPES",
")",
",",
"'height must be an integer or None, got %s'",
"%",
"repr",
"(",
"height",
")",
"# if width or height are None then extend them to the edge",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"self",
".",
"width",
"-",
"x",
"elif",
"width",
"<",
"0",
":",
"# handle negative numbers",
"width",
"+=",
"self",
".",
"width",
"width",
"=",
"max",
"(",
"0",
",",
"width",
")",
"# a 'too big' negative is clamped zero",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"self",
".",
"height",
"-",
"y",
"height",
"=",
"max",
"(",
"0",
",",
"height",
")",
"elif",
"height",
"<",
"0",
":",
"height",
"+=",
"self",
".",
"height",
"# reduce rect size to bounds",
"width",
"=",
"min",
"(",
"width",
",",
"self",
".",
"width",
"-",
"x",
")",
"height",
"=",
"min",
"(",
"height",
",",
"self",
".",
"height",
"-",
"y",
")",
"return",
"x",
",",
"y",
",",
"width",
",",
"height"
]
| Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems | [
"Check",
"if",
"the",
"rectangle",
"is",
"in",
"bounds",
"and",
"make",
"minor",
"adjustments",
".",
"raise",
"AssertionError",
"s",
"for",
"any",
"problems"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L225-L250 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole._normalizeCursor | def _normalizeCursor(self, x, y):
"""return the normalized the cursor position."""
width, height = self.get_size()
assert width != 0 and height != 0, 'can not print on a console with a width or height of zero'
while x >= width:
x -= width
y += 1
while y >= height:
if self._scrollMode == 'scroll':
y -= 1
self.scroll(0, -1)
elif self._scrollMode == 'error':
# reset the cursor on error
self._cursor = (0, 0)
raise TDLError('Cursor has reached the end of the console')
return (x, y) | python | def _normalizeCursor(self, x, y):
"""return the normalized the cursor position."""
width, height = self.get_size()
assert width != 0 and height != 0, 'can not print on a console with a width or height of zero'
while x >= width:
x -= width
y += 1
while y >= height:
if self._scrollMode == 'scroll':
y -= 1
self.scroll(0, -1)
elif self._scrollMode == 'error':
# reset the cursor on error
self._cursor = (0, 0)
raise TDLError('Cursor has reached the end of the console')
return (x, y) | [
"def",
"_normalizeCursor",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"assert",
"width",
"!=",
"0",
"and",
"height",
"!=",
"0",
",",
"'can not print on a console with a width or height of zero'",
"while",
"x",
">=",
"width",
":",
"x",
"-=",
"width",
"y",
"+=",
"1",
"while",
"y",
">=",
"height",
":",
"if",
"self",
".",
"_scrollMode",
"==",
"'scroll'",
":",
"y",
"-=",
"1",
"self",
".",
"scroll",
"(",
"0",
",",
"-",
"1",
")",
"elif",
"self",
".",
"_scrollMode",
"==",
"'error'",
":",
"# reset the cursor on error",
"self",
".",
"_cursor",
"=",
"(",
"0",
",",
"0",
")",
"raise",
"TDLError",
"(",
"'Cursor has reached the end of the console'",
")",
"return",
"(",
"x",
",",
"y",
")"
]
| return the normalized the cursor position. | [
"return",
"the",
"normalized",
"the",
"cursor",
"position",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L252-L267 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.set_mode | def set_mode(self, mode):
"""Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str`
"""
MODES = ['error', 'scroll']
if mode.lower() not in MODES:
raise TDLError('mode must be one of %s, got %s' % (MODES, repr(mode)))
self._scrollMode = mode.lower() | python | def set_mode(self, mode):
"""Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str`
"""
MODES = ['error', 'scroll']
if mode.lower() not in MODES:
raise TDLError('mode must be one of %s, got %s' % (MODES, repr(mode)))
self._scrollMode = mode.lower() | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"MODES",
"=",
"[",
"'error'",
",",
"'scroll'",
"]",
"if",
"mode",
".",
"lower",
"(",
")",
"not",
"in",
"MODES",
":",
"raise",
"TDLError",
"(",
"'mode must be one of %s, got %s'",
"%",
"(",
"MODES",
",",
"repr",
"(",
"mode",
")",
")",
")",
"self",
".",
"_scrollMode",
"=",
"mode",
".",
"lower",
"(",
")"
]
| Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str` | [
"Configure",
"how",
"this",
"console",
"will",
"react",
"to",
"the",
"cursor",
"writing",
"past",
"the",
"end",
"if",
"the",
"console",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L269-L295 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.print_str | def print_str(self, string):
"""Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window`
"""
x, y = self._cursor
for char in string:
if char == '\n': # line break
x = 0
y += 1
continue
if char == '\r': # return
x = 0
continue
x, y = self._normalizeCursor(x, y)
self.draw_char(x, y, char, self._fg, self._bg)
x += 1
self._cursor = (x, y) | python | def print_str(self, string):
"""Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window`
"""
x, y = self._cursor
for char in string:
if char == '\n': # line break
x = 0
y += 1
continue
if char == '\r': # return
x = 0
continue
x, y = self._normalizeCursor(x, y)
self.draw_char(x, y, char, self._fg, self._bg)
x += 1
self._cursor = (x, y) | [
"def",
"print_str",
"(",
"self",
",",
"string",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_cursor",
"for",
"char",
"in",
"string",
":",
"if",
"char",
"==",
"'\\n'",
":",
"# line break",
"x",
"=",
"0",
"y",
"+=",
"1",
"continue",
"if",
"char",
"==",
"'\\r'",
":",
"# return",
"x",
"=",
"0",
"continue",
"x",
",",
"y",
"=",
"self",
".",
"_normalizeCursor",
"(",
"x",
",",
"y",
")",
"self",
".",
"draw_char",
"(",
"x",
",",
"y",
",",
"char",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"x",
"+=",
"1",
"self",
".",
"_cursor",
"=",
"(",
"x",
",",
"y",
")"
]
| Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window` | [
"Print",
"a",
"string",
"at",
"the",
"virtual",
"cursor",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L312-L340 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.write | def write(self, string):
"""This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`
"""
# some 'basic' line buffer stuff.
# there must be an easier way to do this. The textwrap module didn't
# help much.
x, y = self._normalizeCursor(*self._cursor)
width, height = self.get_size()
wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)
writeLines = []
for line in string.split('\n'):
if line:
writeLines += wrapper.wrap(line)
wrapper.initial_indent = ''
else:
writeLines.append([])
for line in writeLines:
x, y = self._normalizeCursor(x, y)
self.draw_str(x, y, line[x:], self._fg, self._bg)
y += 1
x = 0
y -= 1
self._cursor = (x, y) | python | def write(self, string):
"""This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`
"""
# some 'basic' line buffer stuff.
# there must be an easier way to do this. The textwrap module didn't
# help much.
x, y = self._normalizeCursor(*self._cursor)
width, height = self.get_size()
wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)
writeLines = []
for line in string.split('\n'):
if line:
writeLines += wrapper.wrap(line)
wrapper.initial_indent = ''
else:
writeLines.append([])
for line in writeLines:
x, y = self._normalizeCursor(x, y)
self.draw_str(x, y, line[x:], self._fg, self._bg)
y += 1
x = 0
y -= 1
self._cursor = (x, y) | [
"def",
"write",
"(",
"self",
",",
"string",
")",
":",
"# some 'basic' line buffer stuff.",
"# there must be an easier way to do this. The textwrap module didn't",
"# help much.",
"x",
",",
"y",
"=",
"self",
".",
"_normalizeCursor",
"(",
"*",
"self",
".",
"_cursor",
")",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"wrapper",
"=",
"_textwrap",
".",
"TextWrapper",
"(",
"initial_indent",
"=",
"(",
"' '",
"*",
"x",
")",
",",
"width",
"=",
"width",
")",
"writeLines",
"=",
"[",
"]",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
":",
"writeLines",
"+=",
"wrapper",
".",
"wrap",
"(",
"line",
")",
"wrapper",
".",
"initial_indent",
"=",
"''",
"else",
":",
"writeLines",
".",
"append",
"(",
"[",
"]",
")",
"for",
"line",
"in",
"writeLines",
":",
"x",
",",
"y",
"=",
"self",
".",
"_normalizeCursor",
"(",
"x",
",",
"y",
")",
"self",
".",
"draw_str",
"(",
"x",
",",
"y",
",",
"line",
"[",
"x",
":",
"]",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"y",
"+=",
"1",
"x",
"=",
"0",
"y",
"-=",
"1",
"self",
".",
"_cursor",
"=",
"(",
"x",
",",
"y",
")"
]
| This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window` | [
"This",
"method",
"mimics",
"basic",
"file",
"-",
"like",
"behaviour",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L342-L376 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.draw_char | def draw_char(self, x, y, char, fg=Ellipsis, bg=Ellipsis):
"""Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char`
"""
#x, y = self._normalizePoint(x, y)
_put_char_ex(self.console_c, x, y, _format_char(char),
_format_color(fg, self._fg), _format_color(bg, self._bg), 1) | python | def draw_char(self, x, y, char, fg=Ellipsis, bg=Ellipsis):
"""Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char`
"""
#x, y = self._normalizePoint(x, y)
_put_char_ex(self.console_c, x, y, _format_char(char),
_format_color(fg, self._fg), _format_color(bg, self._bg), 1) | [
"def",
"draw_char",
"(",
"self",
",",
"x",
",",
"y",
",",
"char",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"#x, y = self._normalizePoint(x, y)",
"_put_char_ex",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"_format_char",
"(",
"char",
")",
",",
"_format_color",
"(",
"fg",
",",
"self",
".",
"_fg",
")",
",",
"_format_color",
"(",
"bg",
",",
"self",
".",
"_bg",
")",
",",
"1",
")"
]
| Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char` | [
"Draws",
"a",
"single",
"character",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L378-L401 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.draw_str | def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str`
"""
x, y = self._normalizePoint(x, y)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
width, height = self.get_size()
def _drawStrGen(x=x, y=y, string=string, width=width, height=height):
"""Generator for draw_str
Iterates over ((x, y), ch) data for _set_batch, raising an
error if the end of the console is reached.
"""
for char in _format_str(string):
if y == height:
raise TDLError('End of console reached.')
yield((x, y), char)
x += 1 # advance cursor
if x == width: # line break
x = 0
y += 1
self._set_batch(_drawStrGen(), fg, bg) | python | def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str`
"""
x, y = self._normalizePoint(x, y)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
width, height = self.get_size()
def _drawStrGen(x=x, y=y, string=string, width=width, height=height):
"""Generator for draw_str
Iterates over ((x, y), ch) data for _set_batch, raising an
error if the end of the console is reached.
"""
for char in _format_str(string):
if y == height:
raise TDLError('End of console reached.')
yield((x, y), char)
x += 1 # advance cursor
if x == width: # line break
x = 0
y += 1
self._set_batch(_drawStrGen(), fg, bg) | [
"def",
"draw_str",
"(",
"self",
",",
"x",
",",
"y",
",",
"string",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_normalizePoint",
"(",
"x",
",",
"y",
")",
"fg",
",",
"bg",
"=",
"_format_color",
"(",
"fg",
",",
"self",
".",
"_fg",
")",
",",
"_format_color",
"(",
"bg",
",",
"self",
".",
"_bg",
")",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"def",
"_drawStrGen",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"string",
"=",
"string",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
":",
"\"\"\"Generator for draw_str\n\n Iterates over ((x, y), ch) data for _set_batch, raising an\n error if the end of the console is reached.\n \"\"\"",
"for",
"char",
"in",
"_format_str",
"(",
"string",
")",
":",
"if",
"y",
"==",
"height",
":",
"raise",
"TDLError",
"(",
"'End of console reached.'",
")",
"yield",
"(",
"(",
"x",
",",
"y",
")",
",",
"char",
")",
"x",
"+=",
"1",
"# advance cursor",
"if",
"x",
"==",
"width",
":",
"# line break",
"x",
"=",
"0",
"y",
"+=",
"1",
"self",
".",
"_set_batch",
"(",
"_drawStrGen",
"(",
")",
",",
"fg",
",",
"bg",
")"
]
| Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str` | [
"Draws",
"a",
"string",
"starting",
"at",
"x",
"and",
"y",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L403-L457 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.draw_rect | def draw_rect(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame`
"""
x, y, width, height = self._normalizeRect(x, y, width, height)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
char = _format_char(string)
# use itertools to make an x,y grid
# using ctypes here reduces type converstions later
#grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),
# (_ctypes.c_int(y) for y in range(y, y + height)))
grid = _itertools.product((x for x in range(x, x + width)),
(y for y in range(y, y + height)))
# zip the single character in a batch variable
batch = zip(grid, _itertools.repeat(char, width * height))
self._set_batch(batch, fg, bg, nullChar=(char is None)) | python | def draw_rect(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame`
"""
x, y, width, height = self._normalizeRect(x, y, width, height)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
char = _format_char(string)
# use itertools to make an x,y grid
# using ctypes here reduces type converstions later
#grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),
# (_ctypes.c_int(y) for y in range(y, y + height)))
grid = _itertools.product((x for x in range(x, x + width)),
(y for y in range(y, y + height)))
# zip the single character in a batch variable
batch = zip(grid, _itertools.repeat(char, width * height))
self._set_batch(batch, fg, bg, nullChar=(char is None)) | [
"def",
"draw_rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"string",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"self",
".",
"_normalizeRect",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"fg",
",",
"bg",
"=",
"_format_color",
"(",
"fg",
",",
"self",
".",
"_fg",
")",
",",
"_format_color",
"(",
"bg",
",",
"self",
".",
"_bg",
")",
"char",
"=",
"_format_char",
"(",
"string",
")",
"# use itertools to make an x,y grid",
"# using ctypes here reduces type converstions later",
"#grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),",
"# (_ctypes.c_int(y) for y in range(y, y + height)))",
"grid",
"=",
"_itertools",
".",
"product",
"(",
"(",
"x",
"for",
"x",
"in",
"range",
"(",
"x",
",",
"x",
"+",
"width",
")",
")",
",",
"(",
"y",
"for",
"y",
"in",
"range",
"(",
"y",
",",
"y",
"+",
"height",
")",
")",
")",
"# zip the single character in a batch variable",
"batch",
"=",
"zip",
"(",
"grid",
",",
"_itertools",
".",
"repeat",
"(",
"char",
",",
"width",
"*",
"height",
")",
")",
"self",
".",
"_set_batch",
"(",
"batch",
",",
"fg",
",",
"bg",
",",
"nullChar",
"=",
"(",
"char",
"is",
"None",
")",
")"
]
| Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame` | [
"Draws",
"a",
"rectangle",
"starting",
"from",
"x",
"and",
"y",
"and",
"extending",
"to",
"width",
"and",
"height",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L459-L500 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.blit | def blit(self, source, x=0, y=0, width=None, height=None, srcX=0, srcY=0,
fg_alpha=1.0, bg_alpha=1.0):
"""Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha.
"""
assert isinstance(source, (Console, Window)), "source muse be a Window or Console instance"
# handle negative indexes and rects
# negative width and height will be set realtive to the destination
# and will also be clamped to the smallest Console
x, y, width, height = self._normalizeRect(x, y, width, height)
srcX, srcY, width, height = source._normalizeRect(srcX, srcY, width, height)
# translate source and self if any of them are Window instances
srcX, srcY = source._translate(srcX, srcY)
source = source.console
x, y = self._translate(x, y)
self = self.console
if self == source:
# if we are the same console then we need a third console to hold
# onto the data, otherwise it tries to copy into itself and
# starts destroying everything
tmp = Console(width, height)
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
tmp.console_c, 0, 0, fg_alpha, bg_alpha)
_lib.TCOD_console_blit(tmp.console_c, 0, 0, width, height,
self.console_c, x, y, fg_alpha, bg_alpha)
else:
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
self.console_c, x, y, fg_alpha, bg_alpha) | python | def blit(self, source, x=0, y=0, width=None, height=None, srcX=0, srcY=0,
fg_alpha=1.0, bg_alpha=1.0):
"""Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha.
"""
assert isinstance(source, (Console, Window)), "source muse be a Window or Console instance"
# handle negative indexes and rects
# negative width and height will be set realtive to the destination
# and will also be clamped to the smallest Console
x, y, width, height = self._normalizeRect(x, y, width, height)
srcX, srcY, width, height = source._normalizeRect(srcX, srcY, width, height)
# translate source and self if any of them are Window instances
srcX, srcY = source._translate(srcX, srcY)
source = source.console
x, y = self._translate(x, y)
self = self.console
if self == source:
# if we are the same console then we need a third console to hold
# onto the data, otherwise it tries to copy into itself and
# starts destroying everything
tmp = Console(width, height)
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
tmp.console_c, 0, 0, fg_alpha, bg_alpha)
_lib.TCOD_console_blit(tmp.console_c, 0, 0, width, height,
self.console_c, x, y, fg_alpha, bg_alpha)
else:
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
self.console_c, x, y, fg_alpha, bg_alpha) | [
"def",
"blit",
"(",
"self",
",",
"source",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"srcX",
"=",
"0",
",",
"srcY",
"=",
"0",
",",
"fg_alpha",
"=",
"1.0",
",",
"bg_alpha",
"=",
"1.0",
")",
":",
"assert",
"isinstance",
"(",
"source",
",",
"(",
"Console",
",",
"Window",
")",
")",
",",
"\"source muse be a Window or Console instance\"",
"# handle negative indexes and rects",
"# negative width and height will be set realtive to the destination",
"# and will also be clamped to the smallest Console",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"self",
".",
"_normalizeRect",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
"=",
"source",
".",
"_normalizeRect",
"(",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
")",
"# translate source and self if any of them are Window instances",
"srcX",
",",
"srcY",
"=",
"source",
".",
"_translate",
"(",
"srcX",
",",
"srcY",
")",
"source",
"=",
"source",
".",
"console",
"x",
",",
"y",
"=",
"self",
".",
"_translate",
"(",
"x",
",",
"y",
")",
"self",
"=",
"self",
".",
"console",
"if",
"self",
"==",
"source",
":",
"# if we are the same console then we need a third console to hold",
"# onto the data, otherwise it tries to copy into itself and",
"# starts destroying everything",
"tmp",
"=",
"Console",
"(",
"width",
",",
"height",
")",
"_lib",
".",
"TCOD_console_blit",
"(",
"source",
".",
"console_c",
",",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
",",
"tmp",
".",
"console_c",
",",
"0",
",",
"0",
",",
"fg_alpha",
",",
"bg_alpha",
")",
"_lib",
".",
"TCOD_console_blit",
"(",
"tmp",
".",
"console_c",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
",",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"fg_alpha",
",",
"bg_alpha",
")",
"else",
":",
"_lib",
".",
"TCOD_console_blit",
"(",
"source",
".",
"console_c",
",",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
",",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"fg_alpha",
",",
"bg_alpha",
")"
]
| Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha. | [
"Blit",
"another",
"console",
"or",
"Window",
"onto",
"the",
"current",
"console",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L542-L591 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.get_cursor | def get_cursor(self):
"""Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move`
"""
x, y = self._cursor
width, height = self.parent.get_size()
while x >= width:
x -= width
y += 1
if y >= height and self.scrollMode == 'scroll':
y = height - 1
return x, y | python | def get_cursor(self):
"""Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move`
"""
x, y = self._cursor
width, height = self.parent.get_size()
while x >= width:
x -= width
y += 1
if y >= height and self.scrollMode == 'scroll':
y = height - 1
return x, y | [
"def",
"get_cursor",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_cursor",
"width",
",",
"height",
"=",
"self",
".",
"parent",
".",
"get_size",
"(",
")",
"while",
"x",
">=",
"width",
":",
"x",
"-=",
"width",
"y",
"+=",
"1",
"if",
"y",
">=",
"height",
"and",
"self",
".",
"scrollMode",
"==",
"'scroll'",
":",
"y",
"=",
"height",
"-",
"1",
"return",
"x",
",",
"y"
]
| Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move` | [
"Return",
"the",
"virtual",
"cursor",
"position",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L593-L611 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.move | def move(self, x, y):
"""Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
"""
self._cursor = self._normalizePoint(x, y) | python | def move(self, x, y):
"""Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
"""
self._cursor = self._normalizePoint(x, y) | [
"def",
"move",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"_cursor",
"=",
"self",
".",
"_normalizePoint",
"(",
"x",
",",
"y",
")"
]
| Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write` | [
"Move",
"the",
"virtual",
"cursor",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L632-L641 | train |
libtcod/python-tcod | tdl/__init__.py | _BaseConsole.scroll | def scroll(self, x, y):
"""Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors`
"""
assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x)
assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x)
def getSlide(x, length):
"""get the parameters needed to scroll the console in the given
direction with x
returns (x, length, srcx)
"""
if x > 0:
srcx = 0
length -= x
elif x < 0:
srcx = abs(x)
x = 0
length -= srcx
else:
srcx = 0
return x, length, srcx
def getCover(x, length):
"""return the (x, width) ranges of what is covered and uncovered"""
cover = (0, length) # everything covered
uncover = None # nothing uncovered
if x > 0: # left side uncovered
cover = (x, length - x)
uncover = (0, x)
elif x < 0: # right side uncovered
x = abs(x)
cover = (0, length - x)
uncover = (length - x, x)
return cover, uncover
width, height = self.get_size()
if abs(x) >= width or abs(y) >= height:
return self.clear() # just clear the console normally
# get the ranges of the areas that will be uncovered
coverX, uncoverX = getCover(x, width)
coverY, uncoverY = getCover(y, height)
# so at this point we know that coverX and coverY makes a rect that
# encases the area that we end up blitting to. uncoverX/Y makes a
# rect in the corner of the uncovered area. So we need to combine
# the uncoverX/Y with coverY/X to make what's left of the uncovered
# area. Explaining it makes it mush easier to do now.
# But first we need to blit.
x, width, srcx = getSlide(x, width)
y, height, srcy = getSlide(y, height)
self.blit(self, x, y, width, height, srcx, srcy)
if uncoverX: # clear sides (0x20 is space)
self.draw_rect(uncoverX[0], coverY[0], uncoverX[1], coverY[1],
0x20, self._fg, self._bg)
if uncoverY: # clear top/bottom
self.draw_rect(coverX[0], uncoverY[0], coverX[1], uncoverY[1],
0x20, self._fg, self._bg)
if uncoverX and uncoverY: # clear corner
self.draw_rect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1],
0x20, self._fg, self._bg) | python | def scroll(self, x, y):
"""Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors`
"""
assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x)
assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x)
def getSlide(x, length):
"""get the parameters needed to scroll the console in the given
direction with x
returns (x, length, srcx)
"""
if x > 0:
srcx = 0
length -= x
elif x < 0:
srcx = abs(x)
x = 0
length -= srcx
else:
srcx = 0
return x, length, srcx
def getCover(x, length):
"""return the (x, width) ranges of what is covered and uncovered"""
cover = (0, length) # everything covered
uncover = None # nothing uncovered
if x > 0: # left side uncovered
cover = (x, length - x)
uncover = (0, x)
elif x < 0: # right side uncovered
x = abs(x)
cover = (0, length - x)
uncover = (length - x, x)
return cover, uncover
width, height = self.get_size()
if abs(x) >= width or abs(y) >= height:
return self.clear() # just clear the console normally
# get the ranges of the areas that will be uncovered
coverX, uncoverX = getCover(x, width)
coverY, uncoverY = getCover(y, height)
# so at this point we know that coverX and coverY makes a rect that
# encases the area that we end up blitting to. uncoverX/Y makes a
# rect in the corner of the uncovered area. So we need to combine
# the uncoverX/Y with coverY/X to make what's left of the uncovered
# area. Explaining it makes it mush easier to do now.
# But first we need to blit.
x, width, srcx = getSlide(x, width)
y, height, srcy = getSlide(y, height)
self.blit(self, x, y, width, height, srcx, srcy)
if uncoverX: # clear sides (0x20 is space)
self.draw_rect(uncoverX[0], coverY[0], uncoverX[1], coverY[1],
0x20, self._fg, self._bg)
if uncoverY: # clear top/bottom
self.draw_rect(coverX[0], uncoverY[0], coverX[1], uncoverY[1],
0x20, self._fg, self._bg)
if uncoverX and uncoverY: # clear corner
self.draw_rect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1],
0x20, self._fg, self._bg) | [
"def",
"scroll",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"assert",
"isinstance",
"(",
"x",
",",
"_INTTYPES",
")",
",",
"\"x must be an integer, got %s\"",
"%",
"repr",
"(",
"x",
")",
"assert",
"isinstance",
"(",
"y",
",",
"_INTTYPES",
")",
",",
"\"y must be an integer, got %s\"",
"%",
"repr",
"(",
"x",
")",
"def",
"getSlide",
"(",
"x",
",",
"length",
")",
":",
"\"\"\"get the parameters needed to scroll the console in the given\n direction with x\n returns (x, length, srcx)\n \"\"\"",
"if",
"x",
">",
"0",
":",
"srcx",
"=",
"0",
"length",
"-=",
"x",
"elif",
"x",
"<",
"0",
":",
"srcx",
"=",
"abs",
"(",
"x",
")",
"x",
"=",
"0",
"length",
"-=",
"srcx",
"else",
":",
"srcx",
"=",
"0",
"return",
"x",
",",
"length",
",",
"srcx",
"def",
"getCover",
"(",
"x",
",",
"length",
")",
":",
"\"\"\"return the (x, width) ranges of what is covered and uncovered\"\"\"",
"cover",
"=",
"(",
"0",
",",
"length",
")",
"# everything covered",
"uncover",
"=",
"None",
"# nothing uncovered",
"if",
"x",
">",
"0",
":",
"# left side uncovered",
"cover",
"=",
"(",
"x",
",",
"length",
"-",
"x",
")",
"uncover",
"=",
"(",
"0",
",",
"x",
")",
"elif",
"x",
"<",
"0",
":",
"# right side uncovered",
"x",
"=",
"abs",
"(",
"x",
")",
"cover",
"=",
"(",
"0",
",",
"length",
"-",
"x",
")",
"uncover",
"=",
"(",
"length",
"-",
"x",
",",
"x",
")",
"return",
"cover",
",",
"uncover",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"if",
"abs",
"(",
"x",
")",
">=",
"width",
"or",
"abs",
"(",
"y",
")",
">=",
"height",
":",
"return",
"self",
".",
"clear",
"(",
")",
"# just clear the console normally",
"# get the ranges of the areas that will be uncovered",
"coverX",
",",
"uncoverX",
"=",
"getCover",
"(",
"x",
",",
"width",
")",
"coverY",
",",
"uncoverY",
"=",
"getCover",
"(",
"y",
",",
"height",
")",
"# so at this point we know that coverX and coverY makes a rect that",
"# encases the area that we end up blitting to. uncoverX/Y makes a",
"# rect in the corner of the uncovered area. So we need to combine",
"# the uncoverX/Y with coverY/X to make what's left of the uncovered",
"# area. Explaining it makes it mush easier to do now.",
"# But first we need to blit.",
"x",
",",
"width",
",",
"srcx",
"=",
"getSlide",
"(",
"x",
",",
"width",
")",
"y",
",",
"height",
",",
"srcy",
"=",
"getSlide",
"(",
"y",
",",
"height",
")",
"self",
".",
"blit",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"srcx",
",",
"srcy",
")",
"if",
"uncoverX",
":",
"# clear sides (0x20 is space)",
"self",
".",
"draw_rect",
"(",
"uncoverX",
"[",
"0",
"]",
",",
"coverY",
"[",
"0",
"]",
",",
"uncoverX",
"[",
"1",
"]",
",",
"coverY",
"[",
"1",
"]",
",",
"0x20",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"if",
"uncoverY",
":",
"# clear top/bottom",
"self",
".",
"draw_rect",
"(",
"coverX",
"[",
"0",
"]",
",",
"uncoverY",
"[",
"0",
"]",
",",
"coverX",
"[",
"1",
"]",
",",
"uncoverY",
"[",
"1",
"]",
",",
"0x20",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"if",
"uncoverX",
"and",
"uncoverY",
":",
"# clear corner",
"self",
".",
"draw_rect",
"(",
"uncoverX",
"[",
"0",
"]",
",",
"uncoverY",
"[",
"0",
"]",
",",
"uncoverX",
"[",
"1",
"]",
",",
"uncoverY",
"[",
"1",
"]",
",",
"0x20",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")"
]
| Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors` | [
"Scroll",
"the",
"contents",
"of",
"the",
"console",
"in",
"the",
"direction",
"of",
"x",
"y",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L643-L714 | train |
libtcod/python-tcod | tdl/__init__.py | Console._newConsole | def _newConsole(cls, console):
"""Make a Console instance, from a console ctype"""
self = cls.__new__(cls)
_BaseConsole.__init__(self)
self.console_c = console
self.console = self
self.width = _lib.TCOD_console_get_width(console)
self.height = _lib.TCOD_console_get_height(console)
return self | python | def _newConsole(cls, console):
"""Make a Console instance, from a console ctype"""
self = cls.__new__(cls)
_BaseConsole.__init__(self)
self.console_c = console
self.console = self
self.width = _lib.TCOD_console_get_width(console)
self.height = _lib.TCOD_console_get_height(console)
return self | [
"def",
"_newConsole",
"(",
"cls",
",",
"console",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"_BaseConsole",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"console_c",
"=",
"console",
"self",
".",
"console",
"=",
"self",
"self",
".",
"width",
"=",
"_lib",
".",
"TCOD_console_get_width",
"(",
"console",
")",
"self",
".",
"height",
"=",
"_lib",
".",
"TCOD_console_get_height",
"(",
"console",
")",
"return",
"self"
]
| Make a Console instance, from a console ctype | [
"Make",
"a",
"Console",
"instance",
"from",
"a",
"console",
"ctype"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L787-L795 | train |
libtcod/python-tcod | tdl/__init__.py | Console._root_unhook | def _root_unhook(self):
"""Change this root console into a normal Console object and
delete the root console from TCOD
"""
global _rootinitialized, _rootConsoleRef
# do we recognise this as the root console?
# if not then assume the console has already been taken care of
if(_rootConsoleRef and _rootConsoleRef() is self):
# turn this console into a regular console
unhooked = _lib.TCOD_console_new(self.width, self.height)
_lib.TCOD_console_blit(self.console_c,
0, 0, self.width, self.height,
unhooked, 0, 0, 1, 1)
# delete root console from TDL and TCOD
_rootinitialized = False
_rootConsoleRef = None
_lib.TCOD_console_delete(self.console_c)
# this Console object is now a regular console
self.console_c = unhooked | python | def _root_unhook(self):
"""Change this root console into a normal Console object and
delete the root console from TCOD
"""
global _rootinitialized, _rootConsoleRef
# do we recognise this as the root console?
# if not then assume the console has already been taken care of
if(_rootConsoleRef and _rootConsoleRef() is self):
# turn this console into a regular console
unhooked = _lib.TCOD_console_new(self.width, self.height)
_lib.TCOD_console_blit(self.console_c,
0, 0, self.width, self.height,
unhooked, 0, 0, 1, 1)
# delete root console from TDL and TCOD
_rootinitialized = False
_rootConsoleRef = None
_lib.TCOD_console_delete(self.console_c)
# this Console object is now a regular console
self.console_c = unhooked | [
"def",
"_root_unhook",
"(",
"self",
")",
":",
"global",
"_rootinitialized",
",",
"_rootConsoleRef",
"# do we recognise this as the root console?",
"# if not then assume the console has already been taken care of",
"if",
"(",
"_rootConsoleRef",
"and",
"_rootConsoleRef",
"(",
")",
"is",
"self",
")",
":",
"# turn this console into a regular console",
"unhooked",
"=",
"_lib",
".",
"TCOD_console_new",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"_lib",
".",
"TCOD_console_blit",
"(",
"self",
".",
"console_c",
",",
"0",
",",
"0",
",",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"unhooked",
",",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
"# delete root console from TDL and TCOD",
"_rootinitialized",
"=",
"False",
"_rootConsoleRef",
"=",
"None",
"_lib",
".",
"TCOD_console_delete",
"(",
"self",
".",
"console_c",
")",
"# this Console object is now a regular console",
"self",
".",
"console_c",
"=",
"unhooked"
]
| Change this root console into a normal Console object and
delete the root console from TCOD | [
"Change",
"this",
"root",
"console",
"into",
"a",
"normal",
"Console",
"object",
"and",
"delete",
"the",
"root",
"console",
"from",
"TCOD"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L797-L815 | train |
libtcod/python-tcod | tdl/__init__.py | Console._set_char | def _set_char(self, x, y, char, fg=None, bg=None,
bgblend=_lib.TCOD_BKGND_SET):
"""
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this."""
# values are already formatted, honestly this function is redundant
return _put_char_ex(self.console_c, x, y, char, fg, bg, bgblend) | python | def _set_char(self, x, y, char, fg=None, bg=None,
bgblend=_lib.TCOD_BKGND_SET):
"""
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this."""
# values are already formatted, honestly this function is redundant
return _put_char_ex(self.console_c, x, y, char, fg, bg, bgblend) | [
"def",
"_set_char",
"(",
"self",
",",
"x",
",",
"y",
",",
"char",
",",
"fg",
"=",
"None",
",",
"bg",
"=",
"None",
",",
"bgblend",
"=",
"_lib",
".",
"TCOD_BKGND_SET",
")",
":",
"# values are already formatted, honestly this function is redundant",
"return",
"_put_char_ex",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"char",
",",
"fg",
",",
"bg",
",",
"bgblend",
")"
]
| Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this. | [
"Sets",
"a",
"character",
".",
"This",
"is",
"called",
"often",
"and",
"is",
"designed",
"to",
"be",
"as",
"fast",
"as",
"possible",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L871-L881 | train |
libtcod/python-tcod | tdl/__init__.py | Console._set_batch | def _set_batch(self, batch, fg, bg, bgblend=1, nullChar=False):
"""
Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items
"""
for (x, y), char in batch:
self._set_char(x, y, char, fg, bg, bgblend) | python | def _set_batch(self, batch, fg, bg, bgblend=1, nullChar=False):
"""
Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items
"""
for (x, y), char in batch:
self._set_char(x, y, char, fg, bg, bgblend) | [
"def",
"_set_batch",
"(",
"self",
",",
"batch",
",",
"fg",
",",
"bg",
",",
"bgblend",
"=",
"1",
",",
"nullChar",
"=",
"False",
")",
":",
"for",
"(",
"x",
",",
"y",
")",
",",
"char",
"in",
"batch",
":",
"self",
".",
"_set_char",
"(",
"x",
",",
"y",
",",
"char",
",",
"fg",
",",
"bg",
",",
"bgblend",
")"
]
| Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items | [
"Try",
"to",
"perform",
"a",
"batch",
"operation",
"otherwise",
"fall",
"back",
"to",
"_set_char",
".",
"If",
"fg",
"and",
"bg",
"are",
"defined",
"then",
"this",
"is",
"faster",
"but",
"not",
"by",
"very",
"much",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L883-L894 | train |
libtcod/python-tcod | tdl/__init__.py | Window._translate | def _translate(self, x, y):
"""Convertion x and y to their position on the root Console"""
# we add our position relative to our parent and then call then next parent up
return self.parent._translate((x + self.x), (y + self.y)) | python | def _translate(self, x, y):
"""Convertion x and y to their position on the root Console"""
# we add our position relative to our parent and then call then next parent up
return self.parent._translate((x + self.x), (y + self.y)) | [
"def",
"_translate",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# we add our position relative to our parent and then call then next parent up",
"return",
"self",
".",
"parent",
".",
"_translate",
"(",
"(",
"x",
"+",
"self",
".",
"x",
")",
",",
"(",
"y",
"+",
"self",
".",
"y",
")",
")"
]
| Convertion x and y to their position on the root Console | [
"Convertion",
"x",
"and",
"y",
"to",
"their",
"position",
"on",
"the",
"root",
"Console"
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L948-L951 | train |
libtcod/python-tcod | tcod/path.py | _pycall_path_old | def _pycall_path_old(x1: int, y1: int, x2: int, y2: int, handle: Any) -> float:
"""libtcodpy style callback, needs to preserve the old userData issue."""
func, userData = ffi.from_handle(handle)
return func(x1, y1, x2, y2, userData) | python | def _pycall_path_old(x1: int, y1: int, x2: int, y2: int, handle: Any) -> float:
"""libtcodpy style callback, needs to preserve the old userData issue."""
func, userData = ffi.from_handle(handle)
return func(x1, y1, x2, y2, userData) | [
"def",
"_pycall_path_old",
"(",
"x1",
":",
"int",
",",
"y1",
":",
"int",
",",
"x2",
":",
"int",
",",
"y2",
":",
"int",
",",
"handle",
":",
"Any",
")",
"->",
"float",
":",
"func",
",",
"userData",
"=",
"ffi",
".",
"from_handle",
"(",
"handle",
")",
"return",
"func",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"userData",
")"
]
| libtcodpy style callback, needs to preserve the old userData issue. | [
"libtcodpy",
"style",
"callback",
"needs",
"to",
"preserve",
"the",
"old",
"userData",
"issue",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/path.py#L52-L55 | train |
libtcod/python-tcod | tcod/path.py | _pycall_path_simple | def _pycall_path_simple(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""Does less and should run faster, just calls the handle function."""
return ffi.from_handle(handle)(x1, y1, x2, y2) | python | def _pycall_path_simple(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""Does less and should run faster, just calls the handle function."""
return ffi.from_handle(handle)(x1, y1, x2, y2) | [
"def",
"_pycall_path_simple",
"(",
"x1",
":",
"int",
",",
"y1",
":",
"int",
",",
"x2",
":",
"int",
",",
"y2",
":",
"int",
",",
"handle",
":",
"Any",
")",
"->",
"float",
":",
"return",
"ffi",
".",
"from_handle",
"(",
"handle",
")",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")"
]
| Does less and should run faster, just calls the handle function. | [
"Does",
"less",
"and",
"should",
"run",
"faster",
"just",
"calls",
"the",
"handle",
"function",
"."
]
| 8ba10c5cfb813eaf3e834de971ba2d6acb7838e4 | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/path.py#L59-L63 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.