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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
vintasoftware/django-role-permissions | rolepermissions/loader.py | get_app_name | def get_app_name(app_name):
"""
Returns a app name from new app config if is
a class or the same app name if is not a class.
"""
type_ = locate(app_name)
if inspect.isclass(type_):
return type_.name
return app_name | python | def get_app_name(app_name):
"""
Returns a app name from new app config if is
a class or the same app name if is not a class.
"""
type_ = locate(app_name)
if inspect.isclass(type_):
return type_.name
return app_name | [
"def",
"get_app_name",
"(",
"app_name",
")",
":",
"type_",
"=",
"locate",
"(",
"app_name",
")",
"if",
"inspect",
".",
"isclass",
"(",
"type_",
")",
":",
"return",
"type_",
".",
"name",
"return",
"app_name"
] | Returns a app name from new app config if is
a class or the same app name if is not a class. | [
"Returns",
"a",
"app",
"name",
"from",
"new",
"app",
"config",
"if",
"is",
"a",
"class",
"or",
"the",
"same",
"app",
"name",
"if",
"is",
"not",
"a",
"class",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/loader.py#L11-L19 | train | 209,900 |
vintasoftware/django-role-permissions | rolepermissions/checkers.py | has_role | def has_role(user, roles):
"""Check if a user has any of the given roles."""
if user and user.is_superuser:
return True
if not isinstance(roles, list):
roles = [roles]
normalized_roles = []
for role in roles:
if not inspect.isclass(role):
role = RolesManager.retrieve_role(role)
normalized_roles.append(role)
user_roles = get_user_roles(user)
return any([role in user_roles for role in normalized_roles]) | python | def has_role(user, roles):
"""Check if a user has any of the given roles."""
if user and user.is_superuser:
return True
if not isinstance(roles, list):
roles = [roles]
normalized_roles = []
for role in roles:
if not inspect.isclass(role):
role = RolesManager.retrieve_role(role)
normalized_roles.append(role)
user_roles = get_user_roles(user)
return any([role in user_roles for role in normalized_roles]) | [
"def",
"has_role",
"(",
"user",
",",
"roles",
")",
":",
"if",
"user",
"and",
"user",
".",
"is_superuser",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"roles",
",",
"list",
")",
":",
"roles",
"=",
"[",
"roles",
"]",
"normalized_roles",
"=",
... | Check if a user has any of the given roles. | [
"Check",
"if",
"a",
"user",
"has",
"any",
"of",
"the",
"given",
"roles",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/checkers.py#L11-L28 | train | 209,901 |
vintasoftware/django-role-permissions | rolepermissions/checkers.py | has_permission | def has_permission(user, permission_name):
"""Check if a user has a given permission."""
if user and user.is_superuser:
return True
return permission_name in available_perm_names(user) | python | def has_permission(user, permission_name):
"""Check if a user has a given permission."""
if user and user.is_superuser:
return True
return permission_name in available_perm_names(user) | [
"def",
"has_permission",
"(",
"user",
",",
"permission_name",
")",
":",
"if",
"user",
"and",
"user",
".",
"is_superuser",
":",
"return",
"True",
"return",
"permission_name",
"in",
"available_perm_names",
"(",
"user",
")"
] | Check if a user has a given permission. | [
"Check",
"if",
"a",
"user",
"has",
"a",
"given",
"permission",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/checkers.py#L31-L36 | train | 209,902 |
vintasoftware/django-role-permissions | rolepermissions/checkers.py | has_object_permission | def has_object_permission(checker_name, user, obj):
"""Check if a user has permission to perform an action on an object."""
if user and user.is_superuser:
return True
checker = PermissionsManager.retrieve_checker(checker_name)
user_roles = get_user_roles(user)
if not user_roles:
user_roles = [None]
return any([checker(user_role, user, obj) for user_role in user_roles]) | python | def has_object_permission(checker_name, user, obj):
"""Check if a user has permission to perform an action on an object."""
if user and user.is_superuser:
return True
checker = PermissionsManager.retrieve_checker(checker_name)
user_roles = get_user_roles(user)
if not user_roles:
user_roles = [None]
return any([checker(user_role, user, obj) for user_role in user_roles]) | [
"def",
"has_object_permission",
"(",
"checker_name",
",",
"user",
",",
"obj",
")",
":",
"if",
"user",
"and",
"user",
".",
"is_superuser",
":",
"return",
"True",
"checker",
"=",
"PermissionsManager",
".",
"retrieve_checker",
"(",
"checker_name",
")",
"user_roles"... | Check if a user has permission to perform an action on an object. | [
"Check",
"if",
"a",
"user",
"has",
"permission",
"to",
"perform",
"an",
"action",
"on",
"an",
"object",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/checkers.py#L38-L49 | train | 209,903 |
vintasoftware/django-role-permissions | rolepermissions/roles.py | get_or_create_permission | def get_or_create_permission(codename, name=camel_or_snake_to_title):
"""
Get a Permission object from a permission name.
@:param codename: permission code name
@:param name: human-readable permissions name (str) or callable that takes codename as
argument and returns str
"""
user_ct = ContentType.objects.get_for_model(get_user_model())
return Permission.objects.get_or_create(content_type=user_ct, codename=codename,
defaults={'name': name(codename) if callable(name) else name}) | python | def get_or_create_permission(codename, name=camel_or_snake_to_title):
"""
Get a Permission object from a permission name.
@:param codename: permission code name
@:param name: human-readable permissions name (str) or callable that takes codename as
argument and returns str
"""
user_ct = ContentType.objects.get_for_model(get_user_model())
return Permission.objects.get_or_create(content_type=user_ct, codename=codename,
defaults={'name': name(codename) if callable(name) else name}) | [
"def",
"get_or_create_permission",
"(",
"codename",
",",
"name",
"=",
"camel_or_snake_to_title",
")",
":",
"user_ct",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"get_user_model",
"(",
")",
")",
"return",
"Permission",
".",
"objects",
".",
"ge... | Get a Permission object from a permission name.
@:param codename: permission code name
@:param name: human-readable permissions name (str) or callable that takes codename as
argument and returns str | [
"Get",
"a",
"Permission",
"object",
"from",
"a",
"permission",
"name",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/roles.py#L183-L192 | train | 209,904 |
vintasoftware/django-role-permissions | rolepermissions/roles.py | get_user_roles | def get_user_roles(user):
"""Get a list of a users's roles."""
if user:
groups = user.groups.all() # Important! all() query may be cached on User with prefetch_related.
roles = (RolesManager.retrieve_role(group.name) for group in groups if group.name in RolesManager.get_roles_names())
return sorted(roles, key=lambda r: r.get_name() )
else:
return [] | python | def get_user_roles(user):
"""Get a list of a users's roles."""
if user:
groups = user.groups.all() # Important! all() query may be cached on User with prefetch_related.
roles = (RolesManager.retrieve_role(group.name) for group in groups if group.name in RolesManager.get_roles_names())
return sorted(roles, key=lambda r: r.get_name() )
else:
return [] | [
"def",
"get_user_roles",
"(",
"user",
")",
":",
"if",
"user",
":",
"groups",
"=",
"user",
".",
"groups",
".",
"all",
"(",
")",
"# Important! all() query may be cached on User with prefetch_related.",
"roles",
"=",
"(",
"RolesManager",
".",
"retrieve_role",
"(",
"g... | Get a list of a users's roles. | [
"Get",
"a",
"list",
"of",
"a",
"users",
"s",
"roles",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/roles.py#L200-L207 | train | 209,905 |
vintasoftware/django-role-permissions | rolepermissions/roles.py | clear_roles | def clear_roles(user):
"""Remove all roles from a user."""
roles = get_user_roles(user)
for role in roles:
role.remove_role_from_user(user)
return roles | python | def clear_roles(user):
"""Remove all roles from a user."""
roles = get_user_roles(user)
for role in roles:
role.remove_role_from_user(user)
return roles | [
"def",
"clear_roles",
"(",
"user",
")",
":",
"roles",
"=",
"get_user_roles",
"(",
"user",
")",
"for",
"role",
"in",
"roles",
":",
"role",
".",
"remove_role_from_user",
"(",
"user",
")",
"return",
"roles"
] | Remove all roles from a user. | [
"Remove",
"all",
"roles",
"from",
"a",
"user",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/roles.py#L233-L240 | train | 209,906 |
vintasoftware/django-role-permissions | rolepermissions/permissions.py | available_perm_status | def available_perm_status(user):
"""
Get a boolean map of the permissions available to a user
based on that user's roles.
"""
roles = get_user_roles(user)
permission_hash = {}
for role in roles:
permission_names = role.permission_names_list()
for permission_name in permission_names:
permission_hash[permission_name] = get_permission(
permission_name) in user.user_permissions.all()
return permission_hash | python | def available_perm_status(user):
"""
Get a boolean map of the permissions available to a user
based on that user's roles.
"""
roles = get_user_roles(user)
permission_hash = {}
for role in roles:
permission_names = role.permission_names_list()
for permission_name in permission_names:
permission_hash[permission_name] = get_permission(
permission_name) in user.user_permissions.all()
return permission_hash | [
"def",
"available_perm_status",
"(",
"user",
")",
":",
"roles",
"=",
"get_user_roles",
"(",
"user",
")",
"permission_hash",
"=",
"{",
"}",
"for",
"role",
"in",
"roles",
":",
"permission_names",
"=",
"role",
".",
"permission_names_list",
"(",
")",
"for",
"per... | Get a boolean map of the permissions available to a user
based on that user's roles. | [
"Get",
"a",
"boolean",
"map",
"of",
"the",
"permissions",
"available",
"to",
"a",
"user",
"based",
"on",
"that",
"user",
"s",
"roles",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/permissions.py#L41-L56 | train | 209,907 |
vintasoftware/django-role-permissions | rolepermissions/permissions.py | grant_permission | def grant_permission(user, permission_name):
"""
Grant a user a specified permission.
Permissions are only granted if they are in the scope any of the
user's roles. If the permission is out of scope,
a RolePermissionScopeException is raised.
"""
roles = get_user_roles(user)
for role in roles:
if permission_name in role.permission_names_list():
permission = get_permission(permission_name)
user.user_permissions.add(permission)
return
raise RolePermissionScopeException(
"This permission isn't in the scope of "
"any of this user's roles.") | python | def grant_permission(user, permission_name):
"""
Grant a user a specified permission.
Permissions are only granted if they are in the scope any of the
user's roles. If the permission is out of scope,
a RolePermissionScopeException is raised.
"""
roles = get_user_roles(user)
for role in roles:
if permission_name in role.permission_names_list():
permission = get_permission(permission_name)
user.user_permissions.add(permission)
return
raise RolePermissionScopeException(
"This permission isn't in the scope of "
"any of this user's roles.") | [
"def",
"grant_permission",
"(",
"user",
",",
"permission_name",
")",
":",
"roles",
"=",
"get_user_roles",
"(",
"user",
")",
"for",
"role",
"in",
"roles",
":",
"if",
"permission_name",
"in",
"role",
".",
"permission_names_list",
"(",
")",
":",
"permission",
"... | Grant a user a specified permission.
Permissions are only granted if they are in the scope any of the
user's roles. If the permission is out of scope,
a RolePermissionScopeException is raised. | [
"Grant",
"a",
"user",
"a",
"specified",
"permission",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/permissions.py#L73-L91 | train | 209,908 |
vintasoftware/django-role-permissions | rolepermissions/permissions.py | revoke_permission | def revoke_permission(user, permission_name):
"""
Revoke a specified permission from a user.
Permissions are only revoked if they are in the scope any of the user's
roles. If the permission is out of scope, a RolePermissionScopeException
is raised.
"""
roles = get_user_roles(user)
for role in roles:
if permission_name in role.permission_names_list():
permission = get_permission(permission_name)
user.user_permissions.remove(permission)
return
raise RolePermissionScopeException(
"This permission isn't in the scope of "
"any of this user's roles.") | python | def revoke_permission(user, permission_name):
"""
Revoke a specified permission from a user.
Permissions are only revoked if they are in the scope any of the user's
roles. If the permission is out of scope, a RolePermissionScopeException
is raised.
"""
roles = get_user_roles(user)
for role in roles:
if permission_name in role.permission_names_list():
permission = get_permission(permission_name)
user.user_permissions.remove(permission)
return
raise RolePermissionScopeException(
"This permission isn't in the scope of "
"any of this user's roles.") | [
"def",
"revoke_permission",
"(",
"user",
",",
"permission_name",
")",
":",
"roles",
"=",
"get_user_roles",
"(",
"user",
")",
"for",
"role",
"in",
"roles",
":",
"if",
"permission_name",
"in",
"role",
".",
"permission_names_list",
"(",
")",
":",
"permission",
... | Revoke a specified permission from a user.
Permissions are only revoked if they are in the scope any of the user's
roles. If the permission is out of scope, a RolePermissionScopeException
is raised. | [
"Revoke",
"a",
"specified",
"permission",
"from",
"a",
"user",
"."
] | 28924361e689e994e0c3575e18104a1a5abd8de6 | https://github.com/vintasoftware/django-role-permissions/blob/28924361e689e994e0c3575e18104a1a5abd8de6/rolepermissions/permissions.py#L94-L112 | train | 209,909 |
zapier/django-rest-hooks | rest_hooks/models.py | model_saved | def model_saved(sender, instance,
created,
raw,
using,
**kwargs):
"""
Automatically triggers "created" and "updated" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_name])
action = 'created' if created else 'updated'
distill_model_event(instance, model, action) | python | def model_saved(sender, instance,
created,
raw,
using,
**kwargs):
"""
Automatically triggers "created" and "updated" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_name])
action = 'created' if created else 'updated'
distill_model_event(instance, model, action) | [
"def",
"model_saved",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"raw",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"get_opts",
"(",
"instance",
")",
"model",
"=",
"'.'",
".",
"join",
"(",
"[",
"opts",
".",
"app_label",
... | Automatically triggers "created" and "updated" actions. | [
"Automatically",
"triggers",
"created",
"and",
"updated",
"actions",
"."
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/models.py#L131-L142 | train | 209,910 |
zapier/django-rest-hooks | rest_hooks/models.py | model_deleted | def model_deleted(sender, instance,
using,
**kwargs):
"""
Automatically triggers "deleted" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_name])
distill_model_event(instance, model, 'deleted') | python | def model_deleted(sender, instance,
using,
**kwargs):
"""
Automatically triggers "deleted" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_name])
distill_model_event(instance, model, 'deleted') | [
"def",
"model_deleted",
"(",
"sender",
",",
"instance",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"get_opts",
"(",
"instance",
")",
"model",
"=",
"'.'",
".",
"join",
"(",
"[",
"opts",
".",
"app_label",
",",
"opts",
".",
"object_na... | Automatically triggers "deleted" actions. | [
"Automatically",
"triggers",
"deleted",
"actions",
"."
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/models.py#L146-L154 | train | 209,911 |
zapier/django-rest-hooks | rest_hooks/models.py | raw_custom_event | def raw_custom_event(sender, event_name,
payload,
user,
send_hook_meta=True,
instance=None,
**kwargs):
"""
Give a full payload
"""
HookModel = get_hook_model()
hooks = HookModel.objects.filter(user=user, event=event_name)
for hook in hooks:
new_payload = payload
if send_hook_meta:
new_payload = {
'hook': hook.dict(),
'data': payload
}
hook.deliver_hook(instance, payload_override=new_payload) | python | def raw_custom_event(sender, event_name,
payload,
user,
send_hook_meta=True,
instance=None,
**kwargs):
"""
Give a full payload
"""
HookModel = get_hook_model()
hooks = HookModel.objects.filter(user=user, event=event_name)
for hook in hooks:
new_payload = payload
if send_hook_meta:
new_payload = {
'hook': hook.dict(),
'data': payload
}
hook.deliver_hook(instance, payload_override=new_payload) | [
"def",
"raw_custom_event",
"(",
"sender",
",",
"event_name",
",",
"payload",
",",
"user",
",",
"send_hook_meta",
"=",
"True",
",",
"instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"HookModel",
"=",
"get_hook_model",
"(",
")",
"hooks",
"=",
"Ho... | Give a full payload | [
"Give",
"a",
"full",
"payload"
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/models.py#L171-L191 | train | 209,912 |
zapier/django-rest-hooks | rest_hooks/models.py | AbstractHook.clean | def clean(self):
""" Validation for events. """
if self.event not in HOOK_EVENTS.keys():
raise ValidationError(
"Invalid hook event {evt}.".format(evt=self.event)
) | python | def clean(self):
""" Validation for events. """
if self.event not in HOOK_EVENTS.keys():
raise ValidationError(
"Invalid hook event {evt}.".format(evt=self.event)
) | [
"def",
"clean",
"(",
"self",
")",
":",
"if",
"self",
".",
"event",
"not",
"in",
"HOOK_EVENTS",
".",
"keys",
"(",
")",
":",
"raise",
"ValidationError",
"(",
"\"Invalid hook event {evt}.\"",
".",
"format",
"(",
"evt",
"=",
"self",
".",
"event",
")",
")"
] | Validation for events. | [
"Validation",
"for",
"events",
"."
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/models.py#L50-L55 | train | 209,913 |
zapier/django-rest-hooks | rest_hooks/utils.py | get_module | def get_module(path):
"""
A modified duplicate from Django's built in backend
retriever.
slugify = get_module('django.template.defaultfilters.slugify')
"""
try:
from importlib import import_module
except ImportError as e:
from django.utils.importlib import import_module
try:
mod_name, func_name = path.rsplit('.', 1)
mod = import_module(mod_name)
except ImportError as e:
raise ImportError(
'Error importing alert function {0}: "{1}"'.format(mod_name, e))
try:
func = getattr(mod, func_name)
except AttributeError:
raise ImportError(
('Module "{0}" does not define a "{1}" function'
).format(mod_name, func_name))
return func | python | def get_module(path):
"""
A modified duplicate from Django's built in backend
retriever.
slugify = get_module('django.template.defaultfilters.slugify')
"""
try:
from importlib import import_module
except ImportError as e:
from django.utils.importlib import import_module
try:
mod_name, func_name = path.rsplit('.', 1)
mod = import_module(mod_name)
except ImportError as e:
raise ImportError(
'Error importing alert function {0}: "{1}"'.format(mod_name, e))
try:
func = getattr(mod, func_name)
except AttributeError:
raise ImportError(
('Module "{0}" does not define a "{1}" function'
).format(mod_name, func_name))
return func | [
"def",
"get_module",
"(",
"path",
")",
":",
"try",
":",
"from",
"importlib",
"import",
"import_module",
"except",
"ImportError",
"as",
"e",
":",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"try",
":",
"mod_name",
",",
"func_n... | A modified duplicate from Django's built in backend
retriever.
slugify = get_module('django.template.defaultfilters.slugify') | [
"A",
"modified",
"duplicate",
"from",
"Django",
"s",
"built",
"in",
"backend",
"retriever",
"."
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/utils.py#L4-L30 | train | 209,914 |
zapier/django-rest-hooks | rest_hooks/utils.py | get_hook_model | def get_hook_model():
"""
Returns the Custom Hook model if defined in settings,
otherwise the default Hook model.
"""
from rest_hooks.models import Hook
HookModel = Hook
if getattr(settings, 'HOOK_CUSTOM_MODEL', None):
HookModel = get_module(settings.HOOK_CUSTOM_MODEL)
return HookModel | python | def get_hook_model():
"""
Returns the Custom Hook model if defined in settings,
otherwise the default Hook model.
"""
from rest_hooks.models import Hook
HookModel = Hook
if getattr(settings, 'HOOK_CUSTOM_MODEL', None):
HookModel = get_module(settings.HOOK_CUSTOM_MODEL)
return HookModel | [
"def",
"get_hook_model",
"(",
")",
":",
"from",
"rest_hooks",
".",
"models",
"import",
"Hook",
"HookModel",
"=",
"Hook",
"if",
"getattr",
"(",
"settings",
",",
"'HOOK_CUSTOM_MODEL'",
",",
"None",
")",
":",
"HookModel",
"=",
"get_module",
"(",
"settings",
"."... | Returns the Custom Hook model if defined in settings,
otherwise the default Hook model. | [
"Returns",
"the",
"Custom",
"Hook",
"model",
"if",
"defined",
"in",
"settings",
"otherwise",
"the",
"default",
"Hook",
"model",
"."
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/utils.py#L32-L41 | train | 209,915 |
zapier/django-rest-hooks | rest_hooks/utils.py | find_and_fire_hook | def find_and_fire_hook(event_name, instance, user_override=None):
"""
Look up Hooks that apply
"""
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
from rest_hooks.models import HOOK_EVENTS
if not event_name in HOOK_EVENTS.keys():
raise Exception(
'"{}" does not exist in `settings.HOOK_EVENTS`.'.format(event_name)
)
filters = {'event': event_name}
# Ignore the user if the user_override is False
if user_override is not False:
if user_override:
filters['user'] = user_override
elif hasattr(instance, 'user'):
filters['user'] = instance.user
elif isinstance(instance, User):
filters['user'] = instance
else:
raise Exception(
'{} has no `user` property. REST Hooks needs this.'.format(repr(instance))
)
# NOTE: This is probably up for discussion, but I think, in this
# case, instead of raising an error, we should fire the hook for
# all users/accounts it is subscribed to. That would be a genuine
# usecase rather than erroring because no user is associated with
# this event.
HookModel = get_hook_model()
hooks = HookModel.objects.filter(**filters)
for hook in hooks:
hook.deliver_hook(instance) | python | def find_and_fire_hook(event_name, instance, user_override=None):
"""
Look up Hooks that apply
"""
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
from rest_hooks.models import HOOK_EVENTS
if not event_name in HOOK_EVENTS.keys():
raise Exception(
'"{}" does not exist in `settings.HOOK_EVENTS`.'.format(event_name)
)
filters = {'event': event_name}
# Ignore the user if the user_override is False
if user_override is not False:
if user_override:
filters['user'] = user_override
elif hasattr(instance, 'user'):
filters['user'] = instance.user
elif isinstance(instance, User):
filters['user'] = instance
else:
raise Exception(
'{} has no `user` property. REST Hooks needs this.'.format(repr(instance))
)
# NOTE: This is probably up for discussion, but I think, in this
# case, instead of raising an error, we should fire the hook for
# all users/accounts it is subscribed to. That would be a genuine
# usecase rather than erroring because no user is associated with
# this event.
HookModel = get_hook_model()
hooks = HookModel.objects.filter(**filters)
for hook in hooks:
hook.deliver_hook(instance) | [
"def",
"find_and_fire_hook",
"(",
"event_name",
",",
"instance",
",",
"user_override",
"=",
"None",
")",
":",
"try",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"get_user_model",
"User",
"=",
"get_user_model",
"(",
")",
"except",
"ImportError... | Look up Hooks that apply | [
"Look",
"up",
"Hooks",
"that",
"apply"
] | cf4f9588cd9f2d4696f2f0654a205722ee19b80e | https://github.com/zapier/django-rest-hooks/blob/cf4f9588cd9f2d4696f2f0654a205722ee19b80e/rest_hooks/utils.py#L44-L84 | train | 209,916 |
KrishnaswamyLab/PHATE | Python/phate/plot.py | _get_plot_data | def _get_plot_data(data, ndim=None):
"""Get plot data out of an input object
Parameters
----------
data : array-like, `phate.PHATE` or `scanpy.AnnData`
ndim : int, optional (default: None)
Minimum number of dimensions
"""
out = data
if isinstance(data, PHATE):
out = data.transform()
else:
try:
if isinstance(data, anndata.AnnData):
try:
out = data.obsm['X_phate']
except KeyError:
raise RuntimeError(
"data.obsm['X_phate'] not found. "
"Please run `sc.tl.phate(adata)` before plotting.")
except NameError:
# anndata not installed
pass
if ndim is not None and out[0].shape[0] < ndim:
if isinstance(data, PHATE):
data.set_params(n_components=ndim)
out = data.transform()
else:
raise ValueError(
"Expected at least {}-dimensional data, got {}".format(
ndim, out[0].shape[0]))
return out | python | def _get_plot_data(data, ndim=None):
"""Get plot data out of an input object
Parameters
----------
data : array-like, `phate.PHATE` or `scanpy.AnnData`
ndim : int, optional (default: None)
Minimum number of dimensions
"""
out = data
if isinstance(data, PHATE):
out = data.transform()
else:
try:
if isinstance(data, anndata.AnnData):
try:
out = data.obsm['X_phate']
except KeyError:
raise RuntimeError(
"data.obsm['X_phate'] not found. "
"Please run `sc.tl.phate(adata)` before plotting.")
except NameError:
# anndata not installed
pass
if ndim is not None and out[0].shape[0] < ndim:
if isinstance(data, PHATE):
data.set_params(n_components=ndim)
out = data.transform()
else:
raise ValueError(
"Expected at least {}-dimensional data, got {}".format(
ndim, out[0].shape[0]))
return out | [
"def",
"_get_plot_data",
"(",
"data",
",",
"ndim",
"=",
"None",
")",
":",
"out",
"=",
"data",
"if",
"isinstance",
"(",
"data",
",",
"PHATE",
")",
":",
"out",
"=",
"data",
".",
"transform",
"(",
")",
"else",
":",
"try",
":",
"if",
"isinstance",
"(",... | Get plot data out of an input object
Parameters
----------
data : array-like, `phate.PHATE` or `scanpy.AnnData`
ndim : int, optional (default: None)
Minimum number of dimensions | [
"Get",
"plot",
"data",
"out",
"of",
"an",
"input",
"object"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/plot.py#L17-L49 | train | 209,917 |
KrishnaswamyLab/PHATE | Python/phate/plot.py | scatter | def scatter(x, y, z=None,
c=None, cmap=None, s=None, discrete=None,
ax=None, legend=None, figsize=None,
xticks=False,
yticks=False,
zticks=False,
xticklabels=True,
yticklabels=True,
zticklabels=True,
label_prefix="PHATE",
xlabel=None,
ylabel=None,
zlabel=None,
title=None,
legend_title="",
legend_loc='best',
filename=None,
dpi=None,
**plot_kwargs):
"""Create a scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better. For easy access, use
`scatter2d` or `scatter3d`.
Parameters
----------
x : list-like
data for x axis
y : list-like
data for y axis
z : list-like, optional (default: None)
data for z axis
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array of these of length n_samples, or a list of
discrete or continuous values of any data type. If `c` is not a single
or list of matplotlib colors, the values in `c` will be used to
populate the legend / colorbar with colors from `cmap`
cmap : `matplotlib` colormap, str, dict or None, optional (default: None)
matplotlib colormap. If None, uses `tab20` for discrete data and
`inferno` for continuous data. If a dictionary, expects one key
for every unique value in `c`, where values are valid matplotlib colors
(hsv, rbg, rgba, or named colors)
s : float, optional (default: 1)
Point size.
discrete : bool or None, optional (default: None)
If True, the legend is categorical. If False, the legend is a colorbar.
If None, discreteness is detected automatically. Data containing
non-numeric `c` is always discrete, and numeric data with 20 or less
unique values is discrete.
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
legend : bool, optional (default: True)
States whether or not to create a legend. If data is continuous,
the legend is a colorbar.
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
xticks : True, False, or list-like (default: False)
If True, keeps default x ticks. If False, removes x ticks.
If a list, sets custom x ticks
yticks : True, False, or list-like (default: False)
If True, keeps default y ticks. If False, removes y ticks.
If a list, sets custom y ticks
zticks : True, False, or list-like (default: False)
If True, keeps default z ticks. If False, removes z ticks.
If a list, sets custom z ticks. Only used for 3D plots.
xticklabels : True, False, or list-like (default: True)
If True, keeps default x tick labels. If False, removes x tick labels.
If a list, sets custom x tick labels
yticklabels : True, False, or list-like (default: True)
If True, keeps default y tick labels. If False, removes y tick labels.
If a list, sets custom y tick labels
zticklabels : True, False, or list-like (default: True)
If True, keeps default z tick labels. If False, removes z tick labels.
If a list, sets custom z tick labels. Only used for 3D plots.
label_prefix : str or None (default: "PHATE")
Prefix for all axis labels. Axes will be labelled `label_prefix`1,
`label_prefix`2, etc. Can be overriden by setting `xlabel`,
`ylabel`, and `zlabel`.
xlabel : str or None (default : None)
Label for the x axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
ylabel : str or None (default : None)
Label for the y axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. If None, no title is set.
legend_title : str (default: "")
title for the colorbar of legend. Only used for discrete data.
legend_loc : int or string or pair of floats, default: 'best'
Matplotlib legend location. Only used for discrete data.
See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html>
for details.
filename : str or None (default: None)
file to which the output is saved
dpi : int or None, optional (default: None)
The resolution in dots per inch. If None it will default to the value
savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi
to be the value of the figure. Only used if filename is not None.
**plot_kwargs : keyword arguments
Extra arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
ax : `matplotlib.Axes`
axis on which plot was drawn
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> ###
>>> # Running PHATE
>>> ###
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> ###
>>> # Plotting using phate.plot
>>> ###
>>> phate.plot.scatter2d(tree_phate, c=tree_clusters)
>>> # You can also pass the PHATE operator instead of data
>>> phate.plot.scatter2d(phate_operator, c=tree_clusters)
>>> phate.plot.scatter3d(phate_operator, c=tree_clusters)
>>> ###
>>> # Using a cmap dictionary
>>> ###
>>> import numpy as np
>>> X = np.random.normal(0,1,[1000,2])
>>> c = np.random.choice(['a','b'], 1000, replace=True)
>>> X[c=='a'] += 10
>>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
"""
warnings.warn("`phate.plot.scatter` is deprecated. "
"Use `scprep.plot.scatter` instead.",
FutureWarning)
return scprep.plot.scatter(x=x, y=y, z=z,
c=c, cmap=cmap, s=s, discrete=discrete,
ax=ax, legend=legend, figsize=figsize,
xticks=xticks,
yticks=yticks,
zticks=zticks,
xticklabels=xticklabels,
yticklabels=yticklabels,
zticklabels=zticklabels,
label_prefix=label_prefix,
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
title=title,
legend_title=legend_title,
legend_loc=legend_loc,
filename=filename,
dpi=dpi,
**plot_kwargs) | python | def scatter(x, y, z=None,
c=None, cmap=None, s=None, discrete=None,
ax=None, legend=None, figsize=None,
xticks=False,
yticks=False,
zticks=False,
xticklabels=True,
yticklabels=True,
zticklabels=True,
label_prefix="PHATE",
xlabel=None,
ylabel=None,
zlabel=None,
title=None,
legend_title="",
legend_loc='best',
filename=None,
dpi=None,
**plot_kwargs):
"""Create a scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better. For easy access, use
`scatter2d` or `scatter3d`.
Parameters
----------
x : list-like
data for x axis
y : list-like
data for y axis
z : list-like, optional (default: None)
data for z axis
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array of these of length n_samples, or a list of
discrete or continuous values of any data type. If `c` is not a single
or list of matplotlib colors, the values in `c` will be used to
populate the legend / colorbar with colors from `cmap`
cmap : `matplotlib` colormap, str, dict or None, optional (default: None)
matplotlib colormap. If None, uses `tab20` for discrete data and
`inferno` for continuous data. If a dictionary, expects one key
for every unique value in `c`, where values are valid matplotlib colors
(hsv, rbg, rgba, or named colors)
s : float, optional (default: 1)
Point size.
discrete : bool or None, optional (default: None)
If True, the legend is categorical. If False, the legend is a colorbar.
If None, discreteness is detected automatically. Data containing
non-numeric `c` is always discrete, and numeric data with 20 or less
unique values is discrete.
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
legend : bool, optional (default: True)
States whether or not to create a legend. If data is continuous,
the legend is a colorbar.
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
xticks : True, False, or list-like (default: False)
If True, keeps default x ticks. If False, removes x ticks.
If a list, sets custom x ticks
yticks : True, False, or list-like (default: False)
If True, keeps default y ticks. If False, removes y ticks.
If a list, sets custom y ticks
zticks : True, False, or list-like (default: False)
If True, keeps default z ticks. If False, removes z ticks.
If a list, sets custom z ticks. Only used for 3D plots.
xticklabels : True, False, or list-like (default: True)
If True, keeps default x tick labels. If False, removes x tick labels.
If a list, sets custom x tick labels
yticklabels : True, False, or list-like (default: True)
If True, keeps default y tick labels. If False, removes y tick labels.
If a list, sets custom y tick labels
zticklabels : True, False, or list-like (default: True)
If True, keeps default z tick labels. If False, removes z tick labels.
If a list, sets custom z tick labels. Only used for 3D plots.
label_prefix : str or None (default: "PHATE")
Prefix for all axis labels. Axes will be labelled `label_prefix`1,
`label_prefix`2, etc. Can be overriden by setting `xlabel`,
`ylabel`, and `zlabel`.
xlabel : str or None (default : None)
Label for the x axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
ylabel : str or None (default : None)
Label for the y axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. If None, no title is set.
legend_title : str (default: "")
title for the colorbar of legend. Only used for discrete data.
legend_loc : int or string or pair of floats, default: 'best'
Matplotlib legend location. Only used for discrete data.
See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html>
for details.
filename : str or None (default: None)
file to which the output is saved
dpi : int or None, optional (default: None)
The resolution in dots per inch. If None it will default to the value
savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi
to be the value of the figure. Only used if filename is not None.
**plot_kwargs : keyword arguments
Extra arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
ax : `matplotlib.Axes`
axis on which plot was drawn
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> ###
>>> # Running PHATE
>>> ###
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> ###
>>> # Plotting using phate.plot
>>> ###
>>> phate.plot.scatter2d(tree_phate, c=tree_clusters)
>>> # You can also pass the PHATE operator instead of data
>>> phate.plot.scatter2d(phate_operator, c=tree_clusters)
>>> phate.plot.scatter3d(phate_operator, c=tree_clusters)
>>> ###
>>> # Using a cmap dictionary
>>> ###
>>> import numpy as np
>>> X = np.random.normal(0,1,[1000,2])
>>> c = np.random.choice(['a','b'], 1000, replace=True)
>>> X[c=='a'] += 10
>>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
"""
warnings.warn("`phate.plot.scatter` is deprecated. "
"Use `scprep.plot.scatter` instead.",
FutureWarning)
return scprep.plot.scatter(x=x, y=y, z=z,
c=c, cmap=cmap, s=s, discrete=discrete,
ax=ax, legend=legend, figsize=figsize,
xticks=xticks,
yticks=yticks,
zticks=zticks,
xticklabels=xticklabels,
yticklabels=yticklabels,
zticklabels=zticklabels,
label_prefix=label_prefix,
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
title=title,
legend_title=legend_title,
legend_loc=legend_loc,
filename=filename,
dpi=dpi,
**plot_kwargs) | [
"def",
"scatter",
"(",
"x",
",",
"y",
",",
"z",
"=",
"None",
",",
"c",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"s",
"=",
"None",
",",
"discrete",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"legend",
"=",
"None",
",",
"figsize",
"=",
"None"... | Create a scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better. For easy access, use
`scatter2d` or `scatter3d`.
Parameters
----------
x : list-like
data for x axis
y : list-like
data for y axis
z : list-like, optional (default: None)
data for z axis
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array of these of length n_samples, or a list of
discrete or continuous values of any data type. If `c` is not a single
or list of matplotlib colors, the values in `c` will be used to
populate the legend / colorbar with colors from `cmap`
cmap : `matplotlib` colormap, str, dict or None, optional (default: None)
matplotlib colormap. If None, uses `tab20` for discrete data and
`inferno` for continuous data. If a dictionary, expects one key
for every unique value in `c`, where values are valid matplotlib colors
(hsv, rbg, rgba, or named colors)
s : float, optional (default: 1)
Point size.
discrete : bool or None, optional (default: None)
If True, the legend is categorical. If False, the legend is a colorbar.
If None, discreteness is detected automatically. Data containing
non-numeric `c` is always discrete, and numeric data with 20 or less
unique values is discrete.
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
legend : bool, optional (default: True)
States whether or not to create a legend. If data is continuous,
the legend is a colorbar.
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
xticks : True, False, or list-like (default: False)
If True, keeps default x ticks. If False, removes x ticks.
If a list, sets custom x ticks
yticks : True, False, or list-like (default: False)
If True, keeps default y ticks. If False, removes y ticks.
If a list, sets custom y ticks
zticks : True, False, or list-like (default: False)
If True, keeps default z ticks. If False, removes z ticks.
If a list, sets custom z ticks. Only used for 3D plots.
xticklabels : True, False, or list-like (default: True)
If True, keeps default x tick labels. If False, removes x tick labels.
If a list, sets custom x tick labels
yticklabels : True, False, or list-like (default: True)
If True, keeps default y tick labels. If False, removes y tick labels.
If a list, sets custom y tick labels
zticklabels : True, False, or list-like (default: True)
If True, keeps default z tick labels. If False, removes z tick labels.
If a list, sets custom z tick labels. Only used for 3D plots.
label_prefix : str or None (default: "PHATE")
Prefix for all axis labels. Axes will be labelled `label_prefix`1,
`label_prefix`2, etc. Can be overriden by setting `xlabel`,
`ylabel`, and `zlabel`.
xlabel : str or None (default : None)
Label for the x axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
ylabel : str or None (default : None)
Label for the y axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. If None, no title is set.
legend_title : str (default: "")
title for the colorbar of legend. Only used for discrete data.
legend_loc : int or string or pair of floats, default: 'best'
Matplotlib legend location. Only used for discrete data.
See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html>
for details.
filename : str or None (default: None)
file to which the output is saved
dpi : int or None, optional (default: None)
The resolution in dots per inch. If None it will default to the value
savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi
to be the value of the figure. Only used if filename is not None.
**plot_kwargs : keyword arguments
Extra arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
ax : `matplotlib.Axes`
axis on which plot was drawn
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> ###
>>> # Running PHATE
>>> ###
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> ###
>>> # Plotting using phate.plot
>>> ###
>>> phate.plot.scatter2d(tree_phate, c=tree_clusters)
>>> # You can also pass the PHATE operator instead of data
>>> phate.plot.scatter2d(phate_operator, c=tree_clusters)
>>> phate.plot.scatter3d(phate_operator, c=tree_clusters)
>>> ###
>>> # Using a cmap dictionary
>>> ###
>>> import numpy as np
>>> X = np.random.normal(0,1,[1000,2])
>>> c = np.random.choice(['a','b'], 1000, replace=True)
>>> X[c=='a'] += 10
>>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'}) | [
"Create",
"a",
"scatter",
"plot"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/plot.py#L52-L217 | train | 209,918 |
KrishnaswamyLab/PHATE | Python/phate/plot.py | scatter2d | def scatter2d(data, **kwargs):
"""Create a 2D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, shape=[n_samples, n_features]
Input data. Only the first two components will be used.
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array of these of length n_samples, or a list of
discrete or continuous values of any data type. If `c` is not a single
or list of matplotlib colors, the values in `c` will be used to
populate the legend / colorbar with colors from `cmap`
cmap : `matplotlib` colormap, str, dict or None, optional (default: None)
matplotlib colormap. If None, uses `tab20` for discrete data and
`inferno` for continuous data. If a dictionary, expects one key
for every unique value in `c`, where values are valid matplotlib colors
(hsv, rbg, rgba, or named colors)
s : float, optional (default: 1)
Point size.
discrete : bool or None, optional (default: None)
If True, the legend is categorical. If False, the legend is a colorbar.
If None, discreteness is detected automatically. Data containing
non-numeric `c` is always discrete, and numeric data with 20 or less
unique values is discrete.
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
legend : bool, optional (default: True)
States whether or not to create a legend. If data is continuous,
the legend is a colorbar.
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
xticks : True, False, or list-like (default: False)
If True, keeps default x ticks. If False, removes x ticks.
If a list, sets custom x ticks
yticks : True, False, or list-like (default: False)
If True, keeps default y ticks. If False, removes y ticks.
If a list, sets custom y ticks
zticks : True, False, or list-like (default: False)
If True, keeps default z ticks. If False, removes z ticks.
If a list, sets custom z ticks. Only used for 3D plots.
xticklabels : True, False, or list-like (default: True)
If True, keeps default x tick labels. If False, removes x tick labels.
If a list, sets custom x tick labels
yticklabels : True, False, or list-like (default: True)
If True, keeps default y tick labels. If False, removes y tick labels.
If a list, sets custom y tick labels
zticklabels : True, False, or list-like (default: True)
If True, keeps default z tick labels. If False, removes z tick labels.
If a list, sets custom z tick labels. Only used for 3D plots.
label_prefix : str or None (default: "PHATE")
Prefix for all axis labels. Axes will be labelled `label_prefix`1,
`label_prefix`2, etc. Can be overriden by setting `xlabel`,
`ylabel`, and `zlabel`.
xlabel : str or None (default : None)
Label for the x axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
ylabel : str or None (default : None)
Label for the y axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. If None, no title is set.
legend_title : str (default: "")
title for the colorbar of legend
legend_loc : int or string or pair of floats, default: 'best'
Matplotlib legend location. Only used for discrete data.
See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html>
for details.
filename : str or None (default: None)
file to which the output is saved
dpi : int or None, optional (default: None)
The resolution in dots per inch. If None it will default to the value
savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi
to be the value of the figure. Only used if filename is not None.
**plot_kwargs : keyword arguments
Extra arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
ax : `matplotlib.Axes`
axis on which plot was drawn
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> ###
>>> # Running PHATE
>>> ###
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> ###
>>> # Plotting using phate.plot
>>> ###
>>> phate.plot.scatter2d(tree_phate, c=tree_clusters)
>>> # You can also pass the PHATE operator instead of data
>>> phate.plot.scatter2d(phate_operator, c=tree_clusters)
>>> phate.plot.scatter3d(phate_operator, c=tree_clusters)
>>> ###
>>> # Using a cmap dictionary
>>> ###
>>> import numpy as np
>>> X = np.random.normal(0,1,[1000,2])
>>> c = np.random.choice(['a','b'], 1000, replace=True)
>>> X[c=='a'] += 10
>>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
"""
warnings.warn("`phate.plot.scatter2d` is deprecated. "
"Use `scprep.plot.scatter2d` instead.",
FutureWarning)
data = _get_plot_data(data, ndim=2)
return scprep.plot.scatter2d(data, **kwargs) | python | def scatter2d(data, **kwargs):
"""Create a 2D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, shape=[n_samples, n_features]
Input data. Only the first two components will be used.
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array of these of length n_samples, or a list of
discrete or continuous values of any data type. If `c` is not a single
or list of matplotlib colors, the values in `c` will be used to
populate the legend / colorbar with colors from `cmap`
cmap : `matplotlib` colormap, str, dict or None, optional (default: None)
matplotlib colormap. If None, uses `tab20` for discrete data and
`inferno` for continuous data. If a dictionary, expects one key
for every unique value in `c`, where values are valid matplotlib colors
(hsv, rbg, rgba, or named colors)
s : float, optional (default: 1)
Point size.
discrete : bool or None, optional (default: None)
If True, the legend is categorical. If False, the legend is a colorbar.
If None, discreteness is detected automatically. Data containing
non-numeric `c` is always discrete, and numeric data with 20 or less
unique values is discrete.
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
legend : bool, optional (default: True)
States whether or not to create a legend. If data is continuous,
the legend is a colorbar.
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
xticks : True, False, or list-like (default: False)
If True, keeps default x ticks. If False, removes x ticks.
If a list, sets custom x ticks
yticks : True, False, or list-like (default: False)
If True, keeps default y ticks. If False, removes y ticks.
If a list, sets custom y ticks
zticks : True, False, or list-like (default: False)
If True, keeps default z ticks. If False, removes z ticks.
If a list, sets custom z ticks. Only used for 3D plots.
xticklabels : True, False, or list-like (default: True)
If True, keeps default x tick labels. If False, removes x tick labels.
If a list, sets custom x tick labels
yticklabels : True, False, or list-like (default: True)
If True, keeps default y tick labels. If False, removes y tick labels.
If a list, sets custom y tick labels
zticklabels : True, False, or list-like (default: True)
If True, keeps default z tick labels. If False, removes z tick labels.
If a list, sets custom z tick labels. Only used for 3D plots.
label_prefix : str or None (default: "PHATE")
Prefix for all axis labels. Axes will be labelled `label_prefix`1,
`label_prefix`2, etc. Can be overriden by setting `xlabel`,
`ylabel`, and `zlabel`.
xlabel : str or None (default : None)
Label for the x axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
ylabel : str or None (default : None)
Label for the y axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. If None, no title is set.
legend_title : str (default: "")
title for the colorbar of legend
legend_loc : int or string or pair of floats, default: 'best'
Matplotlib legend location. Only used for discrete data.
See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html>
for details.
filename : str or None (default: None)
file to which the output is saved
dpi : int or None, optional (default: None)
The resolution in dots per inch. If None it will default to the value
savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi
to be the value of the figure. Only used if filename is not None.
**plot_kwargs : keyword arguments
Extra arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
ax : `matplotlib.Axes`
axis on which plot was drawn
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> ###
>>> # Running PHATE
>>> ###
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> ###
>>> # Plotting using phate.plot
>>> ###
>>> phate.plot.scatter2d(tree_phate, c=tree_clusters)
>>> # You can also pass the PHATE operator instead of data
>>> phate.plot.scatter2d(phate_operator, c=tree_clusters)
>>> phate.plot.scatter3d(phate_operator, c=tree_clusters)
>>> ###
>>> # Using a cmap dictionary
>>> ###
>>> import numpy as np
>>> X = np.random.normal(0,1,[1000,2])
>>> c = np.random.choice(['a','b'], 1000, replace=True)
>>> X[c=='a'] += 10
>>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'})
"""
warnings.warn("`phate.plot.scatter2d` is deprecated. "
"Use `scprep.plot.scatter2d` instead.",
FutureWarning)
data = _get_plot_data(data, ndim=2)
return scprep.plot.scatter2d(data, **kwargs) | [
"def",
"scatter2d",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`phate.plot.scatter2d` is deprecated. \"",
"\"Use `scprep.plot.scatter2d` instead.\"",
",",
"FutureWarning",
")",
"data",
"=",
"_get_plot_data",
"(",
"data",
",",
"n... | Create a 2D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, shape=[n_samples, n_features]
Input data. Only the first two components will be used.
c : list-like or None, optional (default: None)
Color vector. Can be a single color value (RGB, RGBA, or named
matplotlib colors), an array of these of length n_samples, or a list of
discrete or continuous values of any data type. If `c` is not a single
or list of matplotlib colors, the values in `c` will be used to
populate the legend / colorbar with colors from `cmap`
cmap : `matplotlib` colormap, str, dict or None, optional (default: None)
matplotlib colormap. If None, uses `tab20` for discrete data and
`inferno` for continuous data. If a dictionary, expects one key
for every unique value in `c`, where values are valid matplotlib colors
(hsv, rbg, rgba, or named colors)
s : float, optional (default: 1)
Point size.
discrete : bool or None, optional (default: None)
If True, the legend is categorical. If False, the legend is a colorbar.
If None, discreteness is detected automatically. Data containing
non-numeric `c` is always discrete, and numeric data with 20 or less
unique values is discrete.
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
legend : bool, optional (default: True)
States whether or not to create a legend. If data is continuous,
the legend is a colorbar.
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
xticks : True, False, or list-like (default: False)
If True, keeps default x ticks. If False, removes x ticks.
If a list, sets custom x ticks
yticks : True, False, or list-like (default: False)
If True, keeps default y ticks. If False, removes y ticks.
If a list, sets custom y ticks
zticks : True, False, or list-like (default: False)
If True, keeps default z ticks. If False, removes z ticks.
If a list, sets custom z ticks. Only used for 3D plots.
xticklabels : True, False, or list-like (default: True)
If True, keeps default x tick labels. If False, removes x tick labels.
If a list, sets custom x tick labels
yticklabels : True, False, or list-like (default: True)
If True, keeps default y tick labels. If False, removes y tick labels.
If a list, sets custom y tick labels
zticklabels : True, False, or list-like (default: True)
If True, keeps default z tick labels. If False, removes z tick labels.
If a list, sets custom z tick labels. Only used for 3D plots.
label_prefix : str or None (default: "PHATE")
Prefix for all axis labels. Axes will be labelled `label_prefix`1,
`label_prefix`2, etc. Can be overriden by setting `xlabel`,
`ylabel`, and `zlabel`.
xlabel : str or None (default : None)
Label for the x axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
ylabel : str or None (default : None)
Label for the y axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
zlabel : str or None (default : None)
Label for the z axis. Overrides the automatic label given by
label_prefix. If None and label_prefix is None, no label is set.
Only used for 3D plots.
title : str or None (default: None)
axis title. If None, no title is set.
legend_title : str (default: "")
title for the colorbar of legend
legend_loc : int or string or pair of floats, default: 'best'
Matplotlib legend location. Only used for discrete data.
See <https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html>
for details.
filename : str or None (default: None)
file to which the output is saved
dpi : int or None, optional (default: None)
The resolution in dots per inch. If None it will default to the value
savefig.dpi in the matplotlibrc file. If 'figure' it will set the dpi
to be the value of the figure. Only used if filename is not None.
**plot_kwargs : keyword arguments
Extra arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
ax : `matplotlib.Axes`
axis on which plot was drawn
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> ###
>>> # Running PHATE
>>> ###
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> ###
>>> # Plotting using phate.plot
>>> ###
>>> phate.plot.scatter2d(tree_phate, c=tree_clusters)
>>> # You can also pass the PHATE operator instead of data
>>> phate.plot.scatter2d(phate_operator, c=tree_clusters)
>>> phate.plot.scatter3d(phate_operator, c=tree_clusters)
>>> ###
>>> # Using a cmap dictionary
>>> ###
>>> import numpy as np
>>> X = np.random.normal(0,1,[1000,2])
>>> c = np.random.choice(['a','b'], 1000, replace=True)
>>> X[c=='a'] += 10
>>> phate.plot.scatter2d(X, c=c, cmap={'a' : [1,0,0,1], 'b' : 'xkcd:sky blue'}) | [
"Create",
"a",
"2D",
"scatter",
"plot"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/plot.py#L220-L345 | train | 209,919 |
KrishnaswamyLab/PHATE | Python/phate/plot.py | rotate_scatter3d | def rotate_scatter3d(data,
filename=None,
elev=30,
rotation_speed=30,
fps=10,
ax=None,
figsize=None,
dpi=None,
ipython_html="jshtml",
**kwargs):
"""Create a rotating 3D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, `phate.PHATE` or `scanpy.AnnData`
Input data. Only the first three dimensions are used.
filename : str, optional (default: None)
If not None, saves a .gif or .mp4 with the output
elev : float, optional (default: 30)
Elevation of viewpoint from horizontal, in degrees
rotation_speed : float, optional (default: 30)
Speed of axis rotation, in degrees per second
fps : int, optional (default: 10)
Frames per second. Increase this for a smoother animation
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
dpi : number, optional (default: None)
Controls the dots per inch for the movie frames. This combined with
the figure's size in inches controls the size of the movie.
If None, defaults to rcParams["savefig.dpi"]
ipython_html : {'html5', 'jshtml'}
which html writer to use if using a Jupyter Notebook
**kwargs : keyword arguments
See :~func:`phate.plot.scatter3d`.
Returns
-------
ani : `matplotlib.animation.FuncAnimation`
animation object
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(n_components=3, k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> phate.plot.rotate_scatter3d(tree_phate, c=tree_clusters)
"""
warnings.warn("`phate.plot.rotate_scatter3d` is deprecated. "
"Use `scprep.plot.rotate_scatter3d` instead.",
FutureWarning)
return scprep.plot.rotate_scatter3d(data,
filename=filename,
elev=elev,
rotation_speed=rotation_speed,
fps=fps,
ax=ax,
figsize=figsize,
dpi=dpi,
ipython_html=ipython_html,
**kwargs) | python | def rotate_scatter3d(data,
filename=None,
elev=30,
rotation_speed=30,
fps=10,
ax=None,
figsize=None,
dpi=None,
ipython_html="jshtml",
**kwargs):
"""Create a rotating 3D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, `phate.PHATE` or `scanpy.AnnData`
Input data. Only the first three dimensions are used.
filename : str, optional (default: None)
If not None, saves a .gif or .mp4 with the output
elev : float, optional (default: 30)
Elevation of viewpoint from horizontal, in degrees
rotation_speed : float, optional (default: 30)
Speed of axis rotation, in degrees per second
fps : int, optional (default: 10)
Frames per second. Increase this for a smoother animation
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
dpi : number, optional (default: None)
Controls the dots per inch for the movie frames. This combined with
the figure's size in inches controls the size of the movie.
If None, defaults to rcParams["savefig.dpi"]
ipython_html : {'html5', 'jshtml'}
which html writer to use if using a Jupyter Notebook
**kwargs : keyword arguments
See :~func:`phate.plot.scatter3d`.
Returns
-------
ani : `matplotlib.animation.FuncAnimation`
animation object
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(n_components=3, k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> phate.plot.rotate_scatter3d(tree_phate, c=tree_clusters)
"""
warnings.warn("`phate.plot.rotate_scatter3d` is deprecated. "
"Use `scprep.plot.rotate_scatter3d` instead.",
FutureWarning)
return scprep.plot.rotate_scatter3d(data,
filename=filename,
elev=elev,
rotation_speed=rotation_speed,
fps=fps,
ax=ax,
figsize=figsize,
dpi=dpi,
ipython_html=ipython_html,
**kwargs) | [
"def",
"rotate_scatter3d",
"(",
"data",
",",
"filename",
"=",
"None",
",",
"elev",
"=",
"30",
",",
"rotation_speed",
"=",
"30",
",",
"fps",
"=",
"10",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"dpi",
"=",
"None",
",",
"ipython_html",
... | Create a rotating 3D scatter plot
Builds upon `matplotlib.pyplot.scatter` with nice defaults
and handles categorical colors / legends better.
Parameters
----------
data : array-like, `phate.PHATE` or `scanpy.AnnData`
Input data. Only the first three dimensions are used.
filename : str, optional (default: None)
If not None, saves a .gif or .mp4 with the output
elev : float, optional (default: 30)
Elevation of viewpoint from horizontal, in degrees
rotation_speed : float, optional (default: 30)
Speed of axis rotation, in degrees per second
fps : int, optional (default: 10)
Frames per second. Increase this for a smoother animation
ax : `matplotlib.Axes` or None, optional (default: None)
axis on which to plot. If None, an axis is created
figsize : tuple, optional (default: None)
Tuple of floats for creation of new `matplotlib` figure. Only used if
`ax` is None.
dpi : number, optional (default: None)
Controls the dots per inch for the movie frames. This combined with
the figure's size in inches controls the size of the movie.
If None, defaults to rcParams["savefig.dpi"]
ipython_html : {'html5', 'jshtml'}
which html writer to use if using a Jupyter Notebook
**kwargs : keyword arguments
See :~func:`phate.plot.scatter3d`.
Returns
-------
ani : `matplotlib.animation.FuncAnimation`
animation object
Examples
--------
>>> import phate
>>> import matplotlib.pyplot as plt
>>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
... branch_length=100)
>>> tree_data.shape
(2000, 100)
>>> phate_operator = phate.PHATE(n_components=3, k=5, a=20, t=150)
>>> tree_phate = phate_operator.fit_transform(tree_data)
>>> tree_phate.shape
(2000, 2)
>>> phate.plot.rotate_scatter3d(tree_phate, c=tree_clusters) | [
"Create",
"a",
"rotating",
"3D",
"scatter",
"plot"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/plot.py#L477-L549 | train | 209,920 |
KrishnaswamyLab/PHATE | Python/phate/cluster.py | kmeans | def kmeans(phate_op, k=8, random_state=None):
"""KMeans on the PHATE potential
Clustering on the PHATE operator as introduced in Moon et al.
This is similar to spectral clustering.
Parameters
----------
phate_op : phate.PHATE
Fitted PHATE operator
k : int, optional (default: 8)
Number of clusters
random_state : int or None, optional (default: None)
Random seed for k-means
Returns
-------
clusters : np.ndarray
Integer array of cluster assignments
"""
if phate_op.graph is not None:
diff_potential = phate_op.calculate_potential()
if isinstance(phate_op.graph, graphtools.graphs.LandmarkGraph):
diff_potential = phate_op.graph.interpolate(diff_potential)
return cluster.KMeans(k, random_state=random_state).fit_predict(diff_potential)
else:
raise exceptions.NotFittedError(
"This PHATE instance is not fitted yet. Call "
"'fit' with appropriate arguments before "
"using this method.") | python | def kmeans(phate_op, k=8, random_state=None):
"""KMeans on the PHATE potential
Clustering on the PHATE operator as introduced in Moon et al.
This is similar to spectral clustering.
Parameters
----------
phate_op : phate.PHATE
Fitted PHATE operator
k : int, optional (default: 8)
Number of clusters
random_state : int or None, optional (default: None)
Random seed for k-means
Returns
-------
clusters : np.ndarray
Integer array of cluster assignments
"""
if phate_op.graph is not None:
diff_potential = phate_op.calculate_potential()
if isinstance(phate_op.graph, graphtools.graphs.LandmarkGraph):
diff_potential = phate_op.graph.interpolate(diff_potential)
return cluster.KMeans(k, random_state=random_state).fit_predict(diff_potential)
else:
raise exceptions.NotFittedError(
"This PHATE instance is not fitted yet. Call "
"'fit' with appropriate arguments before "
"using this method.") | [
"def",
"kmeans",
"(",
"phate_op",
",",
"k",
"=",
"8",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"phate_op",
".",
"graph",
"is",
"not",
"None",
":",
"diff_potential",
"=",
"phate_op",
".",
"calculate_potential",
"(",
")",
"if",
"isinstance",
"(",
... | KMeans on the PHATE potential
Clustering on the PHATE operator as introduced in Moon et al.
This is similar to spectral clustering.
Parameters
----------
phate_op : phate.PHATE
Fitted PHATE operator
k : int, optional (default: 8)
Number of clusters
random_state : int or None, optional (default: None)
Random seed for k-means
Returns
-------
clusters : np.ndarray
Integer array of cluster assignments | [
"KMeans",
"on",
"the",
"PHATE",
"potential"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/cluster.py#L5-L35 | train | 209,921 |
KrishnaswamyLab/PHATE | Python/phate/mds.py | cmdscale_fast | def cmdscale_fast(D, ndim):
"""Fast CMDS using random SVD
Parameters
----------
D : array-like, input data [n_samples, n_dimensions]
ndim : int, number of dimensions in which to embed `D`
Returns
-------
Y : array-like, embedded data [n_sample, ndim]
"""
tasklogger.log_debug("Performing classic MDS on {} of shape {}...".format(
type(D).__name__, D.shape))
D = D**2
D = D - D.mean(axis=0)[None, :]
D = D - D.mean(axis=1)[:, None]
pca = PCA(n_components=ndim, svd_solver='randomized')
Y = pca.fit_transform(D)
return Y | python | def cmdscale_fast(D, ndim):
"""Fast CMDS using random SVD
Parameters
----------
D : array-like, input data [n_samples, n_dimensions]
ndim : int, number of dimensions in which to embed `D`
Returns
-------
Y : array-like, embedded data [n_sample, ndim]
"""
tasklogger.log_debug("Performing classic MDS on {} of shape {}...".format(
type(D).__name__, D.shape))
D = D**2
D = D - D.mean(axis=0)[None, :]
D = D - D.mean(axis=1)[:, None]
pca = PCA(n_components=ndim, svd_solver='randomized')
Y = pca.fit_transform(D)
return Y | [
"def",
"cmdscale_fast",
"(",
"D",
",",
"ndim",
")",
":",
"tasklogger",
".",
"log_debug",
"(",
"\"Performing classic MDS on {} of shape {}...\"",
".",
"format",
"(",
"type",
"(",
"D",
")",
".",
"__name__",
",",
"D",
".",
"shape",
")",
")",
"D",
"=",
"D",
... | Fast CMDS using random SVD
Parameters
----------
D : array-like, input data [n_samples, n_dimensions]
ndim : int, number of dimensions in which to embed `D`
Returns
-------
Y : array-like, embedded data [n_sample, ndim] | [
"Fast",
"CMDS",
"using",
"random",
"SVD"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/mds.py#L13-L33 | train | 209,922 |
KrishnaswamyLab/PHATE | Python/phate/mds.py | embed_MDS | def embed_MDS(X, ndim=2, how='metric', distance_metric='euclidean',
n_jobs=1, seed=None, verbose=0):
"""Performs classic, metric, and non-metric MDS
Metric MDS is initialized using classic MDS,
non-metric MDS is initialized using metric MDS.
Parameters
----------
X: ndarray [n_samples, n_samples]
2 dimensional input data array with n_samples
embed_MDS does not check for matrix squareness,
but this is necessary for PHATE
n_dim : int, optional, default: 2
number of dimensions in which the data will be embedded
how : string, optional, default: 'classic'
choose from ['classic', 'metric', 'nonmetric']
which MDS algorithm is used for dimensionality reduction
distance_metric : string, optional, default: 'euclidean'
choose from ['cosine', 'euclidean']
distance metric for MDS
n_jobs : integer, optional, default: 1
The number of jobs to use for the computation.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging.
For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for
n_jobs = -2, all CPUs but one are used
seed: integer or numpy.RandomState, optional
The generator used to initialize SMACOF (metric, nonmetric) MDS
If an integer is given, it fixes the seed
Defaults to the global numpy random number generator
Returns
-------
Y : ndarray [n_samples, n_dim]
low dimensional embedding of X using MDS
"""
if how not in ['classic', 'metric', 'nonmetric']:
raise ValueError("Allowable 'how' values for MDS: 'classic', "
"'metric', or 'nonmetric'. "
"'{}' was passed.".format(how))
# MDS embeddings, each gives a different output.
X_dist = squareform(pdist(X, distance_metric))
# initialize all by CMDS
Y = cmdscale_fast(X_dist, ndim)
if how in ['metric', 'nonmetric']:
tasklogger.log_debug("Performing metric MDS on "
"{} of shape {}...".format(type(X_dist),
X_dist.shape))
# Metric MDS from sklearn
Y, _ = smacof(X_dist, n_components=ndim, metric=True, max_iter=3000,
eps=1e-6, random_state=seed, n_jobs=n_jobs,
n_init=1, init=Y, verbose=verbose)
if how == 'nonmetric':
tasklogger.log_debug(
"Performing non-metric MDS on "
"{} of shape {}...".format(type(X_dist),
X_dist.shape))
# Nonmetric MDS from sklearn using metric MDS as an initialization
Y, _ = smacof(X_dist, n_components=ndim, metric=True, max_iter=3000,
eps=1e-6, random_state=seed, n_jobs=n_jobs,
n_init=1, init=Y, verbose=verbose)
return Y | python | def embed_MDS(X, ndim=2, how='metric', distance_metric='euclidean',
n_jobs=1, seed=None, verbose=0):
"""Performs classic, metric, and non-metric MDS
Metric MDS is initialized using classic MDS,
non-metric MDS is initialized using metric MDS.
Parameters
----------
X: ndarray [n_samples, n_samples]
2 dimensional input data array with n_samples
embed_MDS does not check for matrix squareness,
but this is necessary for PHATE
n_dim : int, optional, default: 2
number of dimensions in which the data will be embedded
how : string, optional, default: 'classic'
choose from ['classic', 'metric', 'nonmetric']
which MDS algorithm is used for dimensionality reduction
distance_metric : string, optional, default: 'euclidean'
choose from ['cosine', 'euclidean']
distance metric for MDS
n_jobs : integer, optional, default: 1
The number of jobs to use for the computation.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging.
For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for
n_jobs = -2, all CPUs but one are used
seed: integer or numpy.RandomState, optional
The generator used to initialize SMACOF (metric, nonmetric) MDS
If an integer is given, it fixes the seed
Defaults to the global numpy random number generator
Returns
-------
Y : ndarray [n_samples, n_dim]
low dimensional embedding of X using MDS
"""
if how not in ['classic', 'metric', 'nonmetric']:
raise ValueError("Allowable 'how' values for MDS: 'classic', "
"'metric', or 'nonmetric'. "
"'{}' was passed.".format(how))
# MDS embeddings, each gives a different output.
X_dist = squareform(pdist(X, distance_metric))
# initialize all by CMDS
Y = cmdscale_fast(X_dist, ndim)
if how in ['metric', 'nonmetric']:
tasklogger.log_debug("Performing metric MDS on "
"{} of shape {}...".format(type(X_dist),
X_dist.shape))
# Metric MDS from sklearn
Y, _ = smacof(X_dist, n_components=ndim, metric=True, max_iter=3000,
eps=1e-6, random_state=seed, n_jobs=n_jobs,
n_init=1, init=Y, verbose=verbose)
if how == 'nonmetric':
tasklogger.log_debug(
"Performing non-metric MDS on "
"{} of shape {}...".format(type(X_dist),
X_dist.shape))
# Nonmetric MDS from sklearn using metric MDS as an initialization
Y, _ = smacof(X_dist, n_components=ndim, metric=True, max_iter=3000,
eps=1e-6, random_state=seed, n_jobs=n_jobs,
n_init=1, init=Y, verbose=verbose)
return Y | [
"def",
"embed_MDS",
"(",
"X",
",",
"ndim",
"=",
"2",
",",
"how",
"=",
"'metric'",
",",
"distance_metric",
"=",
"'euclidean'",
",",
"n_jobs",
"=",
"1",
",",
"seed",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"how",
"not",
"in",
"[",
"'... | Performs classic, metric, and non-metric MDS
Metric MDS is initialized using classic MDS,
non-metric MDS is initialized using metric MDS.
Parameters
----------
X: ndarray [n_samples, n_samples]
2 dimensional input data array with n_samples
embed_MDS does not check for matrix squareness,
but this is necessary for PHATE
n_dim : int, optional, default: 2
number of dimensions in which the data will be embedded
how : string, optional, default: 'classic'
choose from ['classic', 'metric', 'nonmetric']
which MDS algorithm is used for dimensionality reduction
distance_metric : string, optional, default: 'euclidean'
choose from ['cosine', 'euclidean']
distance metric for MDS
n_jobs : integer, optional, default: 1
The number of jobs to use for the computation.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging.
For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for
n_jobs = -2, all CPUs but one are used
seed: integer or numpy.RandomState, optional
The generator used to initialize SMACOF (metric, nonmetric) MDS
If an integer is given, it fixes the seed
Defaults to the global numpy random number generator
Returns
-------
Y : ndarray [n_samples, n_dim]
low dimensional embedding of X using MDS | [
"Performs",
"classic",
"metric",
"and",
"non",
"-",
"metric",
"MDS"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/mds.py#L36-L105 | train | 209,923 |
KrishnaswamyLab/PHATE | Python/phate/vne.py | compute_von_neumann_entropy | def compute_von_neumann_entropy(data, t_max=100):
"""
Determines the Von Neumann entropy of data
at varying matrix powers. The user should select a value of t
around the "knee" of the entropy curve.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
Returns
-------
entropy : array, shape=[t_max]
The entropy of the diffusion affinities for each value of t
Examples
--------
>>> import numpy as np
>>> import phate
>>> X = np.eye(10)
>>> X[0,0] = 5
>>> X[3,2] = 4
>>> h = phate.vne.compute_von_neumann_entropy(X)
>>> phate.vne.find_knee_point(h)
23
"""
_, eigenvalues, _ = svd(data)
entropy = []
eigenvalues_t = np.copy(eigenvalues)
for _ in range(t_max):
prob = eigenvalues_t / np.sum(eigenvalues_t)
prob = prob + np.finfo(float).eps
entropy.append(-np.sum(prob * np.log(prob)))
eigenvalues_t = eigenvalues_t * eigenvalues
entropy = np.array(entropy)
return np.array(entropy) | python | def compute_von_neumann_entropy(data, t_max=100):
"""
Determines the Von Neumann entropy of data
at varying matrix powers. The user should select a value of t
around the "knee" of the entropy curve.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
Returns
-------
entropy : array, shape=[t_max]
The entropy of the diffusion affinities for each value of t
Examples
--------
>>> import numpy as np
>>> import phate
>>> X = np.eye(10)
>>> X[0,0] = 5
>>> X[3,2] = 4
>>> h = phate.vne.compute_von_neumann_entropy(X)
>>> phate.vne.find_knee_point(h)
23
"""
_, eigenvalues, _ = svd(data)
entropy = []
eigenvalues_t = np.copy(eigenvalues)
for _ in range(t_max):
prob = eigenvalues_t / np.sum(eigenvalues_t)
prob = prob + np.finfo(float).eps
entropy.append(-np.sum(prob * np.log(prob)))
eigenvalues_t = eigenvalues_t * eigenvalues
entropy = np.array(entropy)
return np.array(entropy) | [
"def",
"compute_von_neumann_entropy",
"(",
"data",
",",
"t_max",
"=",
"100",
")",
":",
"_",
",",
"eigenvalues",
",",
"_",
"=",
"svd",
"(",
"data",
")",
"entropy",
"=",
"[",
"]",
"eigenvalues_t",
"=",
"np",
".",
"copy",
"(",
"eigenvalues",
")",
"for",
... | Determines the Von Neumann entropy of data
at varying matrix powers. The user should select a value of t
around the "knee" of the entropy curve.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
Returns
-------
entropy : array, shape=[t_max]
The entropy of the diffusion affinities for each value of t
Examples
--------
>>> import numpy as np
>>> import phate
>>> X = np.eye(10)
>>> X[0,0] = 5
>>> X[3,2] = 4
>>> h = phate.vne.compute_von_neumann_entropy(X)
>>> phate.vne.find_knee_point(h)
23 | [
"Determines",
"the",
"Von",
"Neumann",
"entropy",
"of",
"data",
"at",
"varying",
"matrix",
"powers",
".",
"The",
"user",
"should",
"select",
"a",
"value",
"of",
"t",
"around",
"the",
"knee",
"of",
"the",
"entropy",
"curve",
"."
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/vne.py#L11-L49 | train | 209,924 |
KrishnaswamyLab/PHATE | Python/phate/utils.py | check_positive | def check_positive(**params):
"""Check that parameters are positive as expected
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if not isinstance(params[p], numbers.Number) or params[p] <= 0:
raise ValueError(
"Expected {} > 0, got {}".format(p, params[p])) | python | def check_positive(**params):
"""Check that parameters are positive as expected
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if not isinstance(params[p], numbers.Number) or params[p] <= 0:
raise ValueError(
"Expected {} > 0, got {}".format(p, params[p])) | [
"def",
"check_positive",
"(",
"*",
"*",
"params",
")",
":",
"for",
"p",
"in",
"params",
":",
"if",
"not",
"isinstance",
"(",
"params",
"[",
"p",
"]",
",",
"numbers",
".",
"Number",
")",
"or",
"params",
"[",
"p",
"]",
"<=",
"0",
":",
"raise",
"Val... | Check that parameters are positive as expected
Raises
------
ValueError : unacceptable choice of parameters | [
"Check",
"that",
"parameters",
"are",
"positive",
"as",
"expected"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L5-L15 | train | 209,925 |
KrishnaswamyLab/PHATE | Python/phate/utils.py | check_int | def check_int(**params):
"""Check that parameters are integers as expected
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if not isinstance(params[p], numbers.Integral):
raise ValueError(
"Expected {} integer, got {}".format(p, params[p])) | python | def check_int(**params):
"""Check that parameters are integers as expected
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if not isinstance(params[p], numbers.Integral):
raise ValueError(
"Expected {} integer, got {}".format(p, params[p])) | [
"def",
"check_int",
"(",
"*",
"*",
"params",
")",
":",
"for",
"p",
"in",
"params",
":",
"if",
"not",
"isinstance",
"(",
"params",
"[",
"p",
"]",
",",
"numbers",
".",
"Integral",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected {} integer, got {}\"",
"."... | Check that parameters are integers as expected
Raises
------
ValueError : unacceptable choice of parameters | [
"Check",
"that",
"parameters",
"are",
"integers",
"as",
"expected"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L18-L28 | train | 209,926 |
KrishnaswamyLab/PHATE | Python/phate/utils.py | check_if_not | def check_if_not(x, *checks, **params):
"""Run checks only if parameters are not equal to a specified value
Parameters
----------
x : excepted value
Checks not run if parameters equal x
checks : function
Unnamed arguments, check functions to be run
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if params[p] is not x and params[p] != x:
[check(**{p: params[p]}) for check in checks] | python | def check_if_not(x, *checks, **params):
"""Run checks only if parameters are not equal to a specified value
Parameters
----------
x : excepted value
Checks not run if parameters equal x
checks : function
Unnamed arguments, check functions to be run
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if params[p] is not x and params[p] != x:
[check(**{p: params[p]}) for check in checks] | [
"def",
"check_if_not",
"(",
"x",
",",
"*",
"checks",
",",
"*",
"*",
"params",
")",
":",
"for",
"p",
"in",
"params",
":",
"if",
"params",
"[",
"p",
"]",
"is",
"not",
"x",
"and",
"params",
"[",
"p",
"]",
"!=",
"x",
":",
"[",
"check",
"(",
"*",
... | Run checks only if parameters are not equal to a specified value
Parameters
----------
x : excepted value
Checks not run if parameters equal x
checks : function
Unnamed arguments, check functions to be run
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters | [
"Run",
"checks",
"only",
"if",
"parameters",
"are",
"not",
"equal",
"to",
"a",
"specified",
"value"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L31-L52 | train | 209,927 |
KrishnaswamyLab/PHATE | Python/phate/utils.py | check_in | def check_in(choices, **params):
"""Checks parameters are in a list of allowed parameters
Parameters
----------
choices : array-like, accepted values
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if params[p] not in choices:
raise ValueError(
"{} value {} not recognized. Choose from {}".format(
p, params[p], choices)) | python | def check_in(choices, **params):
"""Checks parameters are in a list of allowed parameters
Parameters
----------
choices : array-like, accepted values
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if params[p] not in choices:
raise ValueError(
"{} value {} not recognized. Choose from {}".format(
p, params[p], choices)) | [
"def",
"check_in",
"(",
"choices",
",",
"*",
"*",
"params",
")",
":",
"for",
"p",
"in",
"params",
":",
"if",
"params",
"[",
"p",
"]",
"not",
"in",
"choices",
":",
"raise",
"ValueError",
"(",
"\"{} value {} not recognized. Choose from {}\"",
".",
"format",
... | Checks parameters are in a list of allowed parameters
Parameters
----------
choices : array-like, accepted values
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters | [
"Checks",
"parameters",
"are",
"in",
"a",
"list",
"of",
"allowed",
"parameters"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L55-L74 | train | 209,928 |
KrishnaswamyLab/PHATE | Python/phate/utils.py | check_between | def check_between(v_min, v_max, **params):
"""Checks parameters are in a specified range
Parameters
----------
v_min : float, minimum allowed value (inclusive)
v_max : float, maximum allowed value (inclusive)
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if params[p] < v_min or params[p] > v_max:
raise ValueError("Expected {} between {} and {}, "
"got {}".format(p, v_min, v_max, params[p])) | python | def check_between(v_min, v_max, **params):
"""Checks parameters are in a specified range
Parameters
----------
v_min : float, minimum allowed value (inclusive)
v_max : float, maximum allowed value (inclusive)
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if params[p] < v_min or params[p] > v_max:
raise ValueError("Expected {} between {} and {}, "
"got {}".format(p, v_min, v_max, params[p])) | [
"def",
"check_between",
"(",
"v_min",
",",
"v_max",
",",
"*",
"*",
"params",
")",
":",
"for",
"p",
"in",
"params",
":",
"if",
"params",
"[",
"p",
"]",
"<",
"v_min",
"or",
"params",
"[",
"p",
"]",
">",
"v_max",
":",
"raise",
"ValueError",
"(",
"\"... | Checks parameters are in a specified range
Parameters
----------
v_min : float, minimum allowed value (inclusive)
v_max : float, maximum allowed value (inclusive)
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters | [
"Checks",
"parameters",
"are",
"in",
"a",
"specified",
"range"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L77-L97 | train | 209,929 |
KrishnaswamyLab/PHATE | Python/phate/utils.py | matrix_is_equivalent | def matrix_is_equivalent(X, Y):
"""
Checks matrix equivalence with numpy, scipy and pandas
"""
return X is Y or (isinstance(X, Y.__class__) and X.shape == Y.shape and
np.sum((X != Y).sum()) == 0) | python | def matrix_is_equivalent(X, Y):
"""
Checks matrix equivalence with numpy, scipy and pandas
"""
return X is Y or (isinstance(X, Y.__class__) and X.shape == Y.shape and
np.sum((X != Y).sum()) == 0) | [
"def",
"matrix_is_equivalent",
"(",
"X",
",",
"Y",
")",
":",
"return",
"X",
"is",
"Y",
"or",
"(",
"isinstance",
"(",
"X",
",",
"Y",
".",
"__class__",
")",
"and",
"X",
".",
"shape",
"==",
"Y",
".",
"shape",
"and",
"np",
".",
"sum",
"(",
"(",
"X"... | Checks matrix equivalence with numpy, scipy and pandas | [
"Checks",
"matrix",
"equivalence",
"with",
"numpy",
"scipy",
"and",
"pandas"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L100-L105 | train | 209,930 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.diff_op | def diff_op(self):
"""The diffusion operator calculated from the data
"""
if self.graph is not None:
if isinstance(self.graph, graphtools.graphs.LandmarkGraph):
diff_op = self.graph.landmark_op
else:
diff_op = self.graph.diff_op
if sparse.issparse(diff_op):
diff_op = diff_op.toarray()
return diff_op
else:
raise NotFittedError("This PHATE instance is not fitted yet. Call "
"'fit' with appropriate arguments before "
"using this method.") | python | def diff_op(self):
"""The diffusion operator calculated from the data
"""
if self.graph is not None:
if isinstance(self.graph, graphtools.graphs.LandmarkGraph):
diff_op = self.graph.landmark_op
else:
diff_op = self.graph.diff_op
if sparse.issparse(diff_op):
diff_op = diff_op.toarray()
return diff_op
else:
raise NotFittedError("This PHATE instance is not fitted yet. Call "
"'fit' with appropriate arguments before "
"using this method.") | [
"def",
"diff_op",
"(",
"self",
")",
":",
"if",
"self",
".",
"graph",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"graph",
",",
"graphtools",
".",
"graphs",
".",
"LandmarkGraph",
")",
":",
"diff_op",
"=",
"self",
".",
"graph",
".",... | The diffusion operator calculated from the data | [
"The",
"diffusion",
"operator",
"calculated",
"from",
"the",
"data"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L233-L247 | train | 209,931 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE._check_params | def _check_params(self):
"""Check PHATE parameters
This allows us to fail early - otherwise certain unacceptable
parameter choices, such as mds='mmds', would only fail after
minutes of runtime.
Raises
------
ValueError : unacceptable choice of parameters
"""
utils.check_positive(n_components=self.n_components,
k=self.knn)
utils.check_int(n_components=self.n_components,
k=self.knn,
n_jobs=self.n_jobs)
utils.check_between(0, 1, gamma=self.gamma)
utils.check_if_not(None, utils.check_positive, a=self.decay)
utils.check_if_not(None, utils.check_positive, utils.check_int,
n_landmark=self.n_landmark,
n_pca=self.n_pca)
utils.check_if_not('auto', utils.check_positive, utils.check_int,
t=self.t)
if not callable(self.knn_dist):
utils.check_in(['euclidean', 'precomputed', 'cosine',
'correlation', 'cityblock', 'l1', 'l2',
'manhattan', 'braycurtis', 'canberra',
'chebyshev', 'dice', 'hamming', 'jaccard',
'kulsinski', 'mahalanobis', 'matching',
'minkowski', 'rogerstanimoto', 'russellrao',
'seuclidean', 'sokalmichener', 'sokalsneath',
'sqeuclidean', 'yule',
'precomputed_affinity', 'precomputed_distance'],
knn_dist=self.knn_dist)
if not callable(self.mds_dist):
utils.check_in(['euclidean', 'cosine', 'correlation', 'braycurtis',
'canberra', 'chebyshev', 'cityblock', 'dice',
'hamming', 'jaccard', 'kulsinski', 'mahalanobis',
'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener',
'sokalsneath', 'sqeuclidean', 'yule'],
mds_dist=self.mds_dist)
utils.check_in(['classic', 'metric', 'nonmetric'],
mds=self.mds) | python | def _check_params(self):
"""Check PHATE parameters
This allows us to fail early - otherwise certain unacceptable
parameter choices, such as mds='mmds', would only fail after
minutes of runtime.
Raises
------
ValueError : unacceptable choice of parameters
"""
utils.check_positive(n_components=self.n_components,
k=self.knn)
utils.check_int(n_components=self.n_components,
k=self.knn,
n_jobs=self.n_jobs)
utils.check_between(0, 1, gamma=self.gamma)
utils.check_if_not(None, utils.check_positive, a=self.decay)
utils.check_if_not(None, utils.check_positive, utils.check_int,
n_landmark=self.n_landmark,
n_pca=self.n_pca)
utils.check_if_not('auto', utils.check_positive, utils.check_int,
t=self.t)
if not callable(self.knn_dist):
utils.check_in(['euclidean', 'precomputed', 'cosine',
'correlation', 'cityblock', 'l1', 'l2',
'manhattan', 'braycurtis', 'canberra',
'chebyshev', 'dice', 'hamming', 'jaccard',
'kulsinski', 'mahalanobis', 'matching',
'minkowski', 'rogerstanimoto', 'russellrao',
'seuclidean', 'sokalmichener', 'sokalsneath',
'sqeuclidean', 'yule',
'precomputed_affinity', 'precomputed_distance'],
knn_dist=self.knn_dist)
if not callable(self.mds_dist):
utils.check_in(['euclidean', 'cosine', 'correlation', 'braycurtis',
'canberra', 'chebyshev', 'cityblock', 'dice',
'hamming', 'jaccard', 'kulsinski', 'mahalanobis',
'matching', 'minkowski', 'rogerstanimoto',
'russellrao', 'seuclidean', 'sokalmichener',
'sokalsneath', 'sqeuclidean', 'yule'],
mds_dist=self.mds_dist)
utils.check_in(['classic', 'metric', 'nonmetric'],
mds=self.mds) | [
"def",
"_check_params",
"(",
"self",
")",
":",
"utils",
".",
"check_positive",
"(",
"n_components",
"=",
"self",
".",
"n_components",
",",
"k",
"=",
"self",
".",
"knn",
")",
"utils",
".",
"check_int",
"(",
"n_components",
"=",
"self",
".",
"n_components",
... | Check PHATE parameters
This allows us to fail early - otherwise certain unacceptable
parameter choices, such as mds='mmds', would only fail after
minutes of runtime.
Raises
------
ValueError : unacceptable choice of parameters | [
"Check",
"PHATE",
"parameters"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L249-L292 | train | 209,932 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.fit | def fit(self, X):
"""Computes the diffusion operator
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
Returns
-------
phate_operator : PHATE
The estimator object
"""
X, n_pca, precomputed, update_graph = self._parse_input(X)
if precomputed is None:
tasklogger.log_info(
"Running PHATE on {} cells and {} genes.".format(
X.shape[0], X.shape[1]))
else:
tasklogger.log_info(
"Running PHATE on precomputed {} matrix with {} cells.".format(
precomputed, X.shape[0]))
if self.n_landmark is None or X.shape[0] <= self.n_landmark:
n_landmark = None
else:
n_landmark = self.n_landmark
if self.graph is not None and update_graph:
self._update_graph(X, precomputed, n_pca, n_landmark)
self.X = X
if self.graph is None:
tasklogger.log_start("graph and diffusion operator")
self.graph = graphtools.Graph(
X,
n_pca=n_pca,
n_landmark=n_landmark,
distance=self.knn_dist,
precomputed=precomputed,
knn=self.knn,
decay=self.decay,
thresh=1e-4,
n_jobs=self.n_jobs,
verbose=self.verbose,
random_state=self.random_state,
**(self.kwargs))
tasklogger.log_complete("graph and diffusion operator")
# landmark op doesn't build unless forced
self.diff_op
return self | python | def fit(self, X):
"""Computes the diffusion operator
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
Returns
-------
phate_operator : PHATE
The estimator object
"""
X, n_pca, precomputed, update_graph = self._parse_input(X)
if precomputed is None:
tasklogger.log_info(
"Running PHATE on {} cells and {} genes.".format(
X.shape[0], X.shape[1]))
else:
tasklogger.log_info(
"Running PHATE on precomputed {} matrix with {} cells.".format(
precomputed, X.shape[0]))
if self.n_landmark is None or X.shape[0] <= self.n_landmark:
n_landmark = None
else:
n_landmark = self.n_landmark
if self.graph is not None and update_graph:
self._update_graph(X, precomputed, n_pca, n_landmark)
self.X = X
if self.graph is None:
tasklogger.log_start("graph and diffusion operator")
self.graph = graphtools.Graph(
X,
n_pca=n_pca,
n_landmark=n_landmark,
distance=self.knn_dist,
precomputed=precomputed,
knn=self.knn,
decay=self.decay,
thresh=1e-4,
n_jobs=self.n_jobs,
verbose=self.verbose,
random_state=self.random_state,
**(self.kwargs))
tasklogger.log_complete("graph and diffusion operator")
# landmark op doesn't build unless forced
self.diff_op
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"X",
",",
"n_pca",
",",
"precomputed",
",",
"update_graph",
"=",
"self",
".",
"_parse_input",
"(",
"X",
")",
"if",
"precomputed",
"is",
"None",
":",
"tasklogger",
".",
"log_info",
"(",
"\"Running PHATE on {}... | Computes the diffusion operator
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
Returns
-------
phate_operator : PHATE
The estimator object | [
"Computes",
"the",
"diffusion",
"operator"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L663-L720 | train | 209,933 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.transform | def transform(self, X=None, t_max=100, plot_optimal_t=False, ax=None):
"""Computes the position of the cells in the embedding space
Parameters
----------
X : array, optional, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Not required, since PHATE does not currently embed
cells not given in the input matrix to `PHATE.fit()`.
Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
t_max : int, optional, default: 100
maximum t to test if `t` is set to 'auto'
plot_optimal_t : boolean, optional, default: False
If true and `t` is set to 'auto', plot the Von Neumann
entropy used to select t
ax : matplotlib.axes.Axes, optional
If given and `plot_optimal_t` is true, plot will be drawn
on the given axis.
Returns
-------
embedding : array, shape=[n_samples, n_dimensions]
The cells embedded in a lower dimensional space using PHATE
"""
if self.graph is None:
raise NotFittedError("This PHATE instance is not fitted yet. Call "
"'fit' with appropriate arguments before "
"using this method.")
elif X is not None and not utils.matrix_is_equivalent(X, self.X):
# fit to external data
warnings.warn("Pre-fit PHATE cannot be used to transform a "
"new data matrix. Please fit PHATE to the new"
" data by running 'fit' with the new data.",
RuntimeWarning)
if isinstance(self.graph, graphtools.graphs.TraditionalGraph) and \
self.graph.precomputed is not None:
raise ValueError("Cannot transform additional data using a "
"precomputed distance matrix.")
else:
transitions = self.graph.extend_to_data(X)
return self.graph.interpolate(self.embedding,
transitions)
else:
diff_potential = self.calculate_potential(
t_max=t_max, plot_optimal_t=plot_optimal_t, ax=ax)
if self.embedding is None:
tasklogger.log_start("{} MDS".format(self.mds))
self.embedding = mds.embed_MDS(
diff_potential, ndim=self.n_components, how=self.mds,
distance_metric=self.mds_dist, n_jobs=self.n_jobs,
seed=self.random_state, verbose=max(self.verbose - 1, 0))
tasklogger.log_complete("{} MDS".format(self.mds))
if isinstance(self.graph, graphtools.graphs.LandmarkGraph):
tasklogger.log_debug("Extending to original data...")
return self.graph.interpolate(self.embedding)
else:
return self.embedding | python | def transform(self, X=None, t_max=100, plot_optimal_t=False, ax=None):
"""Computes the position of the cells in the embedding space
Parameters
----------
X : array, optional, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Not required, since PHATE does not currently embed
cells not given in the input matrix to `PHATE.fit()`.
Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
t_max : int, optional, default: 100
maximum t to test if `t` is set to 'auto'
plot_optimal_t : boolean, optional, default: False
If true and `t` is set to 'auto', plot the Von Neumann
entropy used to select t
ax : matplotlib.axes.Axes, optional
If given and `plot_optimal_t` is true, plot will be drawn
on the given axis.
Returns
-------
embedding : array, shape=[n_samples, n_dimensions]
The cells embedded in a lower dimensional space using PHATE
"""
if self.graph is None:
raise NotFittedError("This PHATE instance is not fitted yet. Call "
"'fit' with appropriate arguments before "
"using this method.")
elif X is not None and not utils.matrix_is_equivalent(X, self.X):
# fit to external data
warnings.warn("Pre-fit PHATE cannot be used to transform a "
"new data matrix. Please fit PHATE to the new"
" data by running 'fit' with the new data.",
RuntimeWarning)
if isinstance(self.graph, graphtools.graphs.TraditionalGraph) and \
self.graph.precomputed is not None:
raise ValueError("Cannot transform additional data using a "
"precomputed distance matrix.")
else:
transitions = self.graph.extend_to_data(X)
return self.graph.interpolate(self.embedding,
transitions)
else:
diff_potential = self.calculate_potential(
t_max=t_max, plot_optimal_t=plot_optimal_t, ax=ax)
if self.embedding is None:
tasklogger.log_start("{} MDS".format(self.mds))
self.embedding = mds.embed_MDS(
diff_potential, ndim=self.n_components, how=self.mds,
distance_metric=self.mds_dist, n_jobs=self.n_jobs,
seed=self.random_state, verbose=max(self.verbose - 1, 0))
tasklogger.log_complete("{} MDS".format(self.mds))
if isinstance(self.graph, graphtools.graphs.LandmarkGraph):
tasklogger.log_debug("Extending to original data...")
return self.graph.interpolate(self.embedding)
else:
return self.embedding | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"t_max",
"=",
"100",
",",
"plot_optimal_t",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"if",
"self",
".",
"graph",
"is",
"None",
":",
"raise",
"NotFittedError",
"(",
"\"This PHATE instan... | Computes the position of the cells in the embedding space
Parameters
----------
X : array, optional, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Not required, since PHATE does not currently embed
cells not given in the input matrix to `PHATE.fit()`.
Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
t_max : int, optional, default: 100
maximum t to test if `t` is set to 'auto'
plot_optimal_t : boolean, optional, default: False
If true and `t` is set to 'auto', plot the Von Neumann
entropy used to select t
ax : matplotlib.axes.Axes, optional
If given and `plot_optimal_t` is true, plot will be drawn
on the given axis.
Returns
-------
embedding : array, shape=[n_samples, n_dimensions]
The cells embedded in a lower dimensional space using PHATE | [
"Computes",
"the",
"position",
"of",
"the",
"cells",
"in",
"the",
"embedding",
"space"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L722-L784 | train | 209,934 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.fit_transform | def fit_transform(self, X, **kwargs):
"""Computes the diffusion operator and the position of the cells in the
embedding space
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData` If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
kwargs : further arguments for `PHATE.transform()`
Keyword arguments as specified in :func:`~phate.PHATE.transform`
Returns
-------
embedding : array, shape=[n_samples, n_dimensions]
The cells embedded in a lower dimensional space using PHATE
"""
tasklogger.log_start('PHATE')
self.fit(X)
embedding = self.transform(**kwargs)
tasklogger.log_complete('PHATE')
return embedding | python | def fit_transform(self, X, **kwargs):
"""Computes the diffusion operator and the position of the cells in the
embedding space
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData` If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
kwargs : further arguments for `PHATE.transform()`
Keyword arguments as specified in :func:`~phate.PHATE.transform`
Returns
-------
embedding : array, shape=[n_samples, n_dimensions]
The cells embedded in a lower dimensional space using PHATE
"""
tasklogger.log_start('PHATE')
self.fit(X)
embedding = self.transform(**kwargs)
tasklogger.log_complete('PHATE')
return embedding | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"tasklogger",
".",
"log_start",
"(",
"'PHATE'",
")",
"self",
".",
"fit",
"(",
"X",
")",
"embedding",
"=",
"self",
".",
"transform",
"(",
"*",
"*",
"kwargs",
")",
"tas... | Computes the diffusion operator and the position of the cells in the
embedding space
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
`scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData` If
`knn_dist` is 'precomputed', `data` should be a n_samples x
n_samples distance or affinity matrix
kwargs : further arguments for `PHATE.transform()`
Keyword arguments as specified in :func:`~phate.PHATE.transform`
Returns
-------
embedding : array, shape=[n_samples, n_dimensions]
The cells embedded in a lower dimensional space using PHATE | [
"Computes",
"the",
"diffusion",
"operator",
"and",
"the",
"position",
"of",
"the",
"cells",
"in",
"the",
"embedding",
"space"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L786-L811 | train | 209,935 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.calculate_potential | def calculate_potential(self, t=None,
t_max=100, plot_optimal_t=False, ax=None):
"""Calculates the diffusion potential
Parameters
----------
t : int
power to which the diffusion operator is powered
sets the level of diffusion
t_max : int, default: 100
Maximum value of `t` to test
plot_optimal_t : boolean, default: False
If true, plots the Von Neumann Entropy and knee point
ax : matplotlib.Axes, default: None
If plot=True and ax is not None, plots the VNE on the given axis
Otherwise, creates a new axis and displays the plot
Returns
-------
diff_potential : array-like, shape=[n_samples, n_samples]
The diffusion potential fit on the input data
"""
if t is None:
t = self.t
if self.diff_potential is None:
if t == 'auto':
t = self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)
else:
t = self.t
tasklogger.log_start("diffusion potential")
# diffused diffusion operator
diff_op_t = np.linalg.matrix_power(self.diff_op, t)
if self.gamma == 1:
# handling small values
diff_op_t = diff_op_t + 1e-7
self.diff_potential = -1 * np.log(diff_op_t)
elif self.gamma == -1:
self.diff_potential = diff_op_t
else:
c = (1 - self.gamma) / 2
self.diff_potential = ((diff_op_t)**c) / c
tasklogger.log_complete("diffusion potential")
elif plot_optimal_t:
self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)
return self.diff_potential | python | def calculate_potential(self, t=None,
t_max=100, plot_optimal_t=False, ax=None):
"""Calculates the diffusion potential
Parameters
----------
t : int
power to which the diffusion operator is powered
sets the level of diffusion
t_max : int, default: 100
Maximum value of `t` to test
plot_optimal_t : boolean, default: False
If true, plots the Von Neumann Entropy and knee point
ax : matplotlib.Axes, default: None
If plot=True and ax is not None, plots the VNE on the given axis
Otherwise, creates a new axis and displays the plot
Returns
-------
diff_potential : array-like, shape=[n_samples, n_samples]
The diffusion potential fit on the input data
"""
if t is None:
t = self.t
if self.diff_potential is None:
if t == 'auto':
t = self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)
else:
t = self.t
tasklogger.log_start("diffusion potential")
# diffused diffusion operator
diff_op_t = np.linalg.matrix_power(self.diff_op, t)
if self.gamma == 1:
# handling small values
diff_op_t = diff_op_t + 1e-7
self.diff_potential = -1 * np.log(diff_op_t)
elif self.gamma == -1:
self.diff_potential = diff_op_t
else:
c = (1 - self.gamma) / 2
self.diff_potential = ((diff_op_t)**c) / c
tasklogger.log_complete("diffusion potential")
elif plot_optimal_t:
self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)
return self.diff_potential | [
"def",
"calculate_potential",
"(",
"self",
",",
"t",
"=",
"None",
",",
"t_max",
"=",
"100",
",",
"plot_optimal_t",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"if",
"t",
"is",
"None",
":",
"t",
"=",
"self",
".",
"t",
"if",
"self",
".",
"diff_... | Calculates the diffusion potential
Parameters
----------
t : int
power to which the diffusion operator is powered
sets the level of diffusion
t_max : int, default: 100
Maximum value of `t` to test
plot_optimal_t : boolean, default: False
If true, plots the Von Neumann Entropy and knee point
ax : matplotlib.Axes, default: None
If plot=True and ax is not None, plots the VNE on the given axis
Otherwise, creates a new axis and displays the plot
Returns
-------
diff_potential : array-like, shape=[n_samples, n_samples]
The diffusion potential fit on the input data | [
"Calculates",
"the",
"diffusion",
"potential"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L813-L863 | train | 209,936 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.von_neumann_entropy | def von_neumann_entropy(self, t_max=100):
"""Calculate Von Neumann Entropy
Determines the Von Neumann entropy of the diffusion affinities
at varying levels of `t`. The user should select a value of `t`
around the "knee" of the entropy curve.
We require that 'fit' stores the value of `PHATE.diff_op`
in order to calculate the Von Neumann entropy.
Parameters
----------
t_max : int, default: 100
Maximum value of `t` to test
Returns
-------
entropy : array, shape=[t_max]
The entropy of the diffusion affinities for each value of `t`
"""
t = np.arange(t_max)
return t, vne.compute_von_neumann_entropy(self.diff_op, t_max=t_max) | python | def von_neumann_entropy(self, t_max=100):
"""Calculate Von Neumann Entropy
Determines the Von Neumann entropy of the diffusion affinities
at varying levels of `t`. The user should select a value of `t`
around the "knee" of the entropy curve.
We require that 'fit' stores the value of `PHATE.diff_op`
in order to calculate the Von Neumann entropy.
Parameters
----------
t_max : int, default: 100
Maximum value of `t` to test
Returns
-------
entropy : array, shape=[t_max]
The entropy of the diffusion affinities for each value of `t`
"""
t = np.arange(t_max)
return t, vne.compute_von_neumann_entropy(self.diff_op, t_max=t_max) | [
"def",
"von_neumann_entropy",
"(",
"self",
",",
"t_max",
"=",
"100",
")",
":",
"t",
"=",
"np",
".",
"arange",
"(",
"t_max",
")",
"return",
"t",
",",
"vne",
".",
"compute_von_neumann_entropy",
"(",
"self",
".",
"diff_op",
",",
"t_max",
"=",
"t_max",
")"... | Calculate Von Neumann Entropy
Determines the Von Neumann entropy of the diffusion affinities
at varying levels of `t`. The user should select a value of `t`
around the "knee" of the entropy curve.
We require that 'fit' stores the value of `PHATE.diff_op`
in order to calculate the Von Neumann entropy.
Parameters
----------
t_max : int, default: 100
Maximum value of `t` to test
Returns
-------
entropy : array, shape=[t_max]
The entropy of the diffusion affinities for each value of `t` | [
"Calculate",
"Von",
"Neumann",
"Entropy"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L865-L886 | train | 209,937 |
KrishnaswamyLab/PHATE | Python/phate/phate.py | PHATE.optimal_t | def optimal_t(self, t_max=100, plot=False, ax=None):
"""Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
plot : boolean, default: False
If true, plots the Von Neumann Entropy and knee point
ax : matplotlib.Axes, default: None
If plot=True and ax is not None, plots the VNE on the given axis
Otherwise, creates a new axis and displays the plot
Returns
-------
t_opt : int
The optimal value of t
"""
tasklogger.log_start("optimal t")
t, h = self.von_neumann_entropy(t_max=t_max)
t_opt = vne.find_knee_point(y=h, x=t)
tasklogger.log_info("Automatically selected t = {}".format(t_opt))
tasklogger.log_complete("optimal t")
if plot:
if ax is None:
fig, ax = plt.subplots()
show = True
else:
show = False
ax.plot(t, h)
ax.scatter(t_opt, h[t == t_opt], marker='*', c='k', s=50)
ax.set_xlabel("t")
ax.set_ylabel("Von Neumann Entropy")
ax.set_title("Optimal t = {}".format(t_opt))
if show:
plt.show()
return t_opt | python | def optimal_t(self, t_max=100, plot=False, ax=None):
"""Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
plot : boolean, default: False
If true, plots the Von Neumann Entropy and knee point
ax : matplotlib.Axes, default: None
If plot=True and ax is not None, plots the VNE on the given axis
Otherwise, creates a new axis and displays the plot
Returns
-------
t_opt : int
The optimal value of t
"""
tasklogger.log_start("optimal t")
t, h = self.von_neumann_entropy(t_max=t_max)
t_opt = vne.find_knee_point(y=h, x=t)
tasklogger.log_info("Automatically selected t = {}".format(t_opt))
tasklogger.log_complete("optimal t")
if plot:
if ax is None:
fig, ax = plt.subplots()
show = True
else:
show = False
ax.plot(t, h)
ax.scatter(t_opt, h[t == t_opt], marker='*', c='k', s=50)
ax.set_xlabel("t")
ax.set_ylabel("Von Neumann Entropy")
ax.set_title("Optimal t = {}".format(t_opt))
if show:
plt.show()
return t_opt | [
"def",
"optimal_t",
"(",
"self",
",",
"t_max",
"=",
"100",
",",
"plot",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"tasklogger",
".",
"log_start",
"(",
"\"optimal t\"",
")",
"t",
",",
"h",
"=",
"self",
".",
"von_neumann_entropy",
"(",
"t_max",
"... | Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
plot : boolean, default: False
If true, plots the Von Neumann Entropy and knee point
ax : matplotlib.Axes, default: None
If plot=True and ax is not None, plots the VNE on the given axis
Otherwise, creates a new axis and displays the plot
Returns
-------
t_opt : int
The optimal value of t | [
"Find",
"the",
"optimal",
"value",
"of",
"t"
] | 346a4597dcfc523f8bef99bce482e677282b6719 | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/phate.py#L888-L931 | train | 209,938 |
cedricbonhomme/Stegano | stegano/tools.py | a2bits | def a2bits(chars: str) -> str:
"""Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return bin(reduce(lambda x, y: (x << 8) + y, (ord(c) for c in chars), 1))[
3:
] | python | def a2bits(chars: str) -> str:
"""Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return bin(reduce(lambda x, y: (x << 8) + y, (ord(c) for c in chars), 1))[
3:
] | [
"def",
"a2bits",
"(",
"chars",
":",
"str",
")",
"->",
"str",
":",
"return",
"bin",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"(",
"x",
"<<",
"8",
")",
"+",
"y",
",",
"(",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"chars",
")",
",",
... | Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001' | [
"Converts",
"a",
"string",
"to",
"its",
"bits",
"representation",
"as",
"a",
"string",
"of",
"0",
"s",
"and",
"1",
"s",
"."
] | 502e6303791d348e479290c22108551ba3be254f | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L38-L46 | train | 209,939 |
cedricbonhomme/Stegano | stegano/tools.py | a2bits_list | def a2bits_list(chars: str, encoding: str = "UTF-8") -> List[str]:
"""Convert a string to its bits representation as a list of 0's and 1's.
>>> a2bits_list("Hello World!")
['01001000',
'01100101',
'01101100',
'01101100',
'01101111',
'00100000',
'01010111',
'01101111',
'01110010',
'01101100',
'01100100',
'00100001']
>>> "".join(a2bits_list("Hello World!"))
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return [bin(ord(x))[2:].rjust(ENCODINGS[encoding], "0") for x in chars] | python | def a2bits_list(chars: str, encoding: str = "UTF-8") -> List[str]:
"""Convert a string to its bits representation as a list of 0's and 1's.
>>> a2bits_list("Hello World!")
['01001000',
'01100101',
'01101100',
'01101100',
'01101111',
'00100000',
'01010111',
'01101111',
'01110010',
'01101100',
'01100100',
'00100001']
>>> "".join(a2bits_list("Hello World!"))
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return [bin(ord(x))[2:].rjust(ENCODINGS[encoding], "0") for x in chars] | [
"def",
"a2bits_list",
"(",
"chars",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"\"UTF-8\"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"bin",
"(",
"ord",
"(",
"x",
")",
")",
"[",
"2",
":",
"]",
".",
"rjust",
"(",
"ENCODINGS",
"[... | Convert a string to its bits representation as a list of 0's and 1's.
>>> a2bits_list("Hello World!")
['01001000',
'01100101',
'01101100',
'01101100',
'01101111',
'00100000',
'01010111',
'01101111',
'01110010',
'01101100',
'01100100',
'00100001']
>>> "".join(a2bits_list("Hello World!"))
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001' | [
"Convert",
"a",
"string",
"to",
"its",
"bits",
"representation",
"as",
"a",
"list",
"of",
"0",
"s",
"and",
"1",
"s",
"."
] | 502e6303791d348e479290c22108551ba3be254f | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L49-L68 | train | 209,940 |
cedricbonhomme/Stegano | stegano/tools.py | bs | def bs(s: int) -> str:
"""Converts an int to its bits representation as a string of 0's and 1's.
"""
return str(s) if s <= 1 else bs(s >> 1) + str(s & 1) | python | def bs(s: int) -> str:
"""Converts an int to its bits representation as a string of 0's and 1's.
"""
return str(s) if s <= 1 else bs(s >> 1) + str(s & 1) | [
"def",
"bs",
"(",
"s",
":",
"int",
")",
"->",
"str",
":",
"return",
"str",
"(",
"s",
")",
"if",
"s",
"<=",
"1",
"else",
"bs",
"(",
"s",
">>",
"1",
")",
"+",
"str",
"(",
"s",
"&",
"1",
")"
] | Converts an int to its bits representation as a string of 0's and 1's. | [
"Converts",
"an",
"int",
"to",
"its",
"bits",
"representation",
"as",
"a",
"string",
"of",
"0",
"s",
"and",
"1",
"s",
"."
] | 502e6303791d348e479290c22108551ba3be254f | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L71-L74 | train | 209,941 |
cedricbonhomme/Stegano | stegano/tools.py | n_at_a_time | def n_at_a_time(
items: List[int], n: int, fillvalue: str
) -> Iterator[Tuple[Union[int, str]]]:
"""Returns an iterator which groups n items at a time.
Any final partial tuple will be padded with the fillvalue
>>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X'))
[(1, 2), (3, 4), (5, 'X')]
"""
it = iter(items)
return itertools.zip_longest(*[it] * n, fillvalue=fillvalue) | python | def n_at_a_time(
items: List[int], n: int, fillvalue: str
) -> Iterator[Tuple[Union[int, str]]]:
"""Returns an iterator which groups n items at a time.
Any final partial tuple will be padded with the fillvalue
>>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X'))
[(1, 2), (3, 4), (5, 'X')]
"""
it = iter(items)
return itertools.zip_longest(*[it] * n, fillvalue=fillvalue) | [
"def",
"n_at_a_time",
"(",
"items",
":",
"List",
"[",
"int",
"]",
",",
"n",
":",
"int",
",",
"fillvalue",
":",
"str",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"Union",
"[",
"int",
",",
"str",
"]",
"]",
"]",
":",
"it",
"=",
"iter",
"(",
"items"... | Returns an iterator which groups n items at a time.
Any final partial tuple will be padded with the fillvalue
>>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X'))
[(1, 2), (3, 4), (5, 'X')] | [
"Returns",
"an",
"iterator",
"which",
"groups",
"n",
"items",
"at",
"a",
"time",
".",
"Any",
"final",
"partial",
"tuple",
"will",
"be",
"padded",
"with",
"the",
"fillvalue"
] | 502e6303791d348e479290c22108551ba3be254f | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L83-L93 | train | 209,942 |
cedricbonhomme/Stegano | stegano/tools.py | open_image | def open_image(fname_or_instance: Union[str, IO[bytes]]):
"""Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself.
"""
if isinstance(fname_or_instance, Image.Image):
return fname_or_instance
return Image.open(fname_or_instance) | python | def open_image(fname_or_instance: Union[str, IO[bytes]]):
"""Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself.
"""
if isinstance(fname_or_instance, Image.Image):
return fname_or_instance
return Image.open(fname_or_instance) | [
"def",
"open_image",
"(",
"fname_or_instance",
":",
"Union",
"[",
"str",
",",
"IO",
"[",
"bytes",
"]",
"]",
")",
":",
"if",
"isinstance",
"(",
"fname_or_instance",
",",
"Image",
".",
"Image",
")",
":",
"return",
"fname_or_instance",
"return",
"Image",
".",... | Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself. | [
"Opens",
"a",
"Image",
"and",
"returns",
"it",
"."
] | 502e6303791d348e479290c22108551ba3be254f | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L113-L122 | train | 209,943 |
cedricbonhomme/Stegano | stegano/lsbset/generators.py | log_gen | def log_gen() -> Iterator[int]:
"""Logarithmic generator.
"""
y = 1
while True:
adder = max(1, math.pow(10, int(math.log10(y))))
yield int(y)
y = y + int(adder) | python | def log_gen() -> Iterator[int]:
"""Logarithmic generator.
"""
y = 1
while True:
adder = max(1, math.pow(10, int(math.log10(y))))
yield int(y)
y = y + int(adder) | [
"def",
"log_gen",
"(",
")",
"->",
"Iterator",
"[",
"int",
"]",
":",
"y",
"=",
"1",
"while",
"True",
":",
"adder",
"=",
"max",
"(",
"1",
",",
"math",
".",
"pow",
"(",
"10",
",",
"int",
"(",
"math",
".",
"log10",
"(",
"y",
")",
")",
")",
")",... | Logarithmic generator. | [
"Logarithmic",
"generator",
"."
] | 502e6303791d348e479290c22108551ba3be254f | https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/lsbset/generators.py#L150-L157 | train | 209,944 |
saxix/django-concurrency | src/concurrency/utils.py | deprecated | def deprecated(replacement=None, version=None):
"""A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.
>>> import pytest
>>> @deprecated()
... def foo1(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo1, 1)
1
>>> def newfun(x):
... return 0
...
>>> @deprecated(newfun, '1.1')
... def foo2(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo2, 1)
0
>>>
"""
def outer(oldfun):
def inner(*args, **kwargs):
msg = "%s is deprecated" % oldfun.__name__
if version is not None:
msg += "will be removed in version %s;" % version
if replacement is not None:
msg += "; use %s instead" % (replacement)
warnings.warn(msg, DeprecationWarning, stacklevel=2)
if callable(replacement):
return replacement(*args, **kwargs)
else:
return oldfun(*args, **kwargs)
return inner
return outer | python | def deprecated(replacement=None, version=None):
"""A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.
>>> import pytest
>>> @deprecated()
... def foo1(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo1, 1)
1
>>> def newfun(x):
... return 0
...
>>> @deprecated(newfun, '1.1')
... def foo2(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo2, 1)
0
>>>
"""
def outer(oldfun):
def inner(*args, **kwargs):
msg = "%s is deprecated" % oldfun.__name__
if version is not None:
msg += "will be removed in version %s;" % version
if replacement is not None:
msg += "; use %s instead" % (replacement)
warnings.warn(msg, DeprecationWarning, stacklevel=2)
if callable(replacement):
return replacement(*args, **kwargs)
else:
return oldfun(*args, **kwargs)
return inner
return outer | [
"def",
"deprecated",
"(",
"replacement",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"def",
"outer",
"(",
"oldfun",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"\"%s is deprecated\"",
"%",
"oldfu... | A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.
>>> import pytest
>>> @deprecated()
... def foo1(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo1, 1)
1
>>> def newfun(x):
... return 0
...
>>> @deprecated(newfun, '1.1')
... def foo2(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo2, 1)
0
>>> | [
"A",
"decorator",
"which",
"can",
"be",
"used",
"to",
"mark",
"functions",
"as",
"deprecated",
".",
"replacement",
"is",
"a",
"callable",
"that",
"will",
"be",
"called",
"with",
"the",
"same",
"args",
"as",
"the",
"decorated",
"function",
".",
">>>",
"impo... | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/utils.py#L13-L51 | train | 209,945 |
saxix/django-concurrency | src/concurrency/utils.py | get_classname | def get_classname(o):
""" Returns the classname of an object r a class
:param o:
:return:
"""
if inspect.isclass(o):
target = o
elif callable(o):
target = o
else:
target = o.__class__
try:
return target.__qualname__
except AttributeError: # pragma: no cover
return target.__name__ | python | def get_classname(o):
""" Returns the classname of an object r a class
:param o:
:return:
"""
if inspect.isclass(o):
target = o
elif callable(o):
target = o
else:
target = o.__class__
try:
return target.__qualname__
except AttributeError: # pragma: no cover
return target.__name__ | [
"def",
"get_classname",
"(",
"o",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"o",
")",
":",
"target",
"=",
"o",
"elif",
"callable",
"(",
"o",
")",
":",
"target",
"=",
"o",
"else",
":",
"target",
"=",
"o",
".",
"__class__",
"try",
":",
"retur... | Returns the classname of an object r a class
:param o:
:return: | [
"Returns",
"the",
"classname",
"of",
"an",
"object",
"r",
"a",
"class"
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/utils.py#L121-L136 | train | 209,946 |
saxix/django-concurrency | src/concurrency/config.py | AppSettings._handler | def _handler(self, sender, setting, value, **kwargs):
"""
handler for ``setting_changed`` signal.
@see :ref:`django:setting-changed`_
"""
if setting.startswith(self.prefix):
self._set_attr(setting, value) | python | def _handler(self, sender, setting, value, **kwargs):
"""
handler for ``setting_changed`` signal.
@see :ref:`django:setting-changed`_
"""
if setting.startswith(self.prefix):
self._set_attr(setting, value) | [
"def",
"_handler",
"(",
"self",
",",
"sender",
",",
"setting",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"setting",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"self",
".",
"_set_attr",
"(",
"setting",
",",
"value",
")"
] | handler for ``setting_changed`` signal.
@see :ref:`django:setting-changed`_ | [
"handler",
"for",
"setting_changed",
"signal",
"."
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/config.py#L67-L74 | train | 209,947 |
saxix/django-concurrency | src/concurrency/api.py | get_version | def get_version(model_instance, version):
"""
try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return:
"""
version_field = get_version_fieldname(model_instance)
kwargs = {'pk': model_instance.pk, version_field: version}
return model_instance.__class__.objects.get(**kwargs) | python | def get_version(model_instance, version):
"""
try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return:
"""
version_field = get_version_fieldname(model_instance)
kwargs = {'pk': model_instance.pk, version_field: version}
return model_instance.__class__.objects.get(**kwargs) | [
"def",
"get_version",
"(",
"model_instance",
",",
"version",
")",
":",
"version_field",
"=",
"get_version_fieldname",
"(",
"model_instance",
")",
"kwargs",
"=",
"{",
"'pk'",
":",
"model_instance",
".",
"pk",
",",
"version_field",
":",
"version",
"}",
"return",
... | try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return: | [
"try",
"go",
"load",
"from",
"the",
"database",
"one",
"object",
"with",
"specific",
"version"
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/api.py#L41-L51 | train | 209,948 |
saxix/django-concurrency | src/concurrency/views.py | conflict | def conflict(request, target=None, template_name='409.html'):
"""409 error handler.
:param request: Request
:param template_name: `409.html`
:param target: The model to save
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist: # pragma: no cover
template = Template(
'<h1>Conflict</h1>'
'<p>The request was unsuccessful due to a conflict. '
'The object changed during the transaction.</p>')
try:
saved = target.__class__._default_manager.get(pk=target.pk)
except target.__class__.DoesNotExist: # pragma: no cover
saved = None
ctx = {'target': target,
'saved': saved,
'request_path': request.path}
return ConflictResponse(template.render(ctx)) | python | def conflict(request, target=None, template_name='409.html'):
"""409 error handler.
:param request: Request
:param template_name: `409.html`
:param target: The model to save
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist: # pragma: no cover
template = Template(
'<h1>Conflict</h1>'
'<p>The request was unsuccessful due to a conflict. '
'The object changed during the transaction.</p>')
try:
saved = target.__class__._default_manager.get(pk=target.pk)
except target.__class__.DoesNotExist: # pragma: no cover
saved = None
ctx = {'target': target,
'saved': saved,
'request_path': request.path}
return ConflictResponse(template.render(ctx)) | [
"def",
"conflict",
"(",
"request",
",",
"target",
"=",
"None",
",",
"template_name",
"=",
"'409.html'",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"# pragma: no cover",
... | 409 error handler.
:param request: Request
:param template_name: `409.html`
:param target: The model to save | [
"409",
"error",
"handler",
"."
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/views.py#L21-L46 | train | 209,949 |
saxix/django-concurrency | src/concurrency/management/commands/triggers.py | Command.add_arguments | def add_arguments(self, parser):
"""
Entry point for subclassed commands to add custom arguments.
"""
subparsers = parser.add_subparsers(help='sub-command help',
dest='command')
add_parser = partial(_add_subparser, subparsers, parser)
add_parser('list', help="list concurrency triggers")
add_parser('drop', help="drop concurrency triggers")
add_parser('create', help="create concurrency triggers")
parser.add_argument('-d', '--database',
action='store',
dest='database',
default=None,
help='limit to this database')
parser.add_argument('-t', '--trigger',
action='store',
dest='trigger',
default=None,
help='limit to this trigger name') | python | def add_arguments(self, parser):
"""
Entry point for subclassed commands to add custom arguments.
"""
subparsers = parser.add_subparsers(help='sub-command help',
dest='command')
add_parser = partial(_add_subparser, subparsers, parser)
add_parser('list', help="list concurrency triggers")
add_parser('drop', help="drop concurrency triggers")
add_parser('create', help="create concurrency triggers")
parser.add_argument('-d', '--database',
action='store',
dest='database',
default=None,
help='limit to this database')
parser.add_argument('-t', '--trigger',
action='store',
dest='trigger',
default=None,
help='limit to this trigger name') | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=",
"'sub-command help'",
",",
"dest",
"=",
"'command'",
")",
"add_parser",
"=",
"partial",
"(",
"_add_subparser",
",",
"subparsers"... | Entry point for subclassed commands to add custom arguments. | [
"Entry",
"point",
"for",
"subclassed",
"commands",
"to",
"add",
"custom",
"arguments",
"."
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/management/commands/triggers.py#L29-L52 | train | 209,950 |
saxix/django-concurrency | src/concurrency/admin.py | ConcurrencyActionMixin.action_checkbox | def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
if self.check_concurrent_action:
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME,
force_text("%s,%s" % (obj.pk,
get_revision_of_object(obj))))
else: # pragma: no cover
return super(ConcurrencyActionMixin, self).action_checkbox(obj) | python | def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
if self.check_concurrent_action:
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME,
force_text("%s,%s" % (obj.pk,
get_revision_of_object(obj))))
else: # pragma: no cover
return super(ConcurrencyActionMixin, self).action_checkbox(obj) | [
"def",
"action_checkbox",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"check_concurrent_action",
":",
"return",
"helpers",
".",
"checkbox",
".",
"render",
"(",
"helpers",
".",
"ACTION_CHECKBOX_NAME",
",",
"force_text",
"(",
"\"%s,%s\"",
"%",
"(",
"... | A list_display column containing a checkbox widget. | [
"A",
"list_display",
"column",
"containing",
"a",
"checkbox",
"widget",
"."
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/admin.py#L35-L44 | train | 209,951 |
saxix/django-concurrency | src/concurrency/admin.py | ConcurrentBaseModelFormSet._management_form | def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.is_bound:
form = ConcurrentManagementForm(self.data, auto_id=self.auto_id,
prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ConcurrentManagementForm(auto_id=self.auto_id,
prefix=self.prefix,
initial={TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MAX_NUM_FORM_COUNT: self.max_num},
versions=[(form.instance.pk, get_revision_of_object(form.instance)) for form
in self.initial_forms])
return form | python | def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.is_bound:
form = ConcurrentManagementForm(self.data, auto_id=self.auto_id,
prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ConcurrentManagementForm(auto_id=self.auto_id,
prefix=self.prefix,
initial={TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MAX_NUM_FORM_COUNT: self.max_num},
versions=[(form.instance.pk, get_revision_of_object(form.instance)) for form
in self.initial_forms])
return form | [
"def",
"_management_form",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_bound",
":",
"form",
"=",
"ConcurrentManagementForm",
"(",
"self",
".",
"data",
",",
"auto_id",
"=",
"self",
".",
"auto_id",
",",
"prefix",
"=",
"self",
".",
"prefix",
")",
"if",
... | Returns the ManagementForm instance for this FormSet. | [
"Returns",
"the",
"ManagementForm",
"instance",
"for",
"this",
"FormSet",
"."
] | 9a289dc007b1cdf609b7dfb77a6d2868abc8097f | https://github.com/saxix/django-concurrency/blob/9a289dc007b1cdf609b7dfb77a6d2868abc8097f/src/concurrency/admin.py#L151-L166 | train | 209,952 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.cipherprefs | def cipherprefs(self):
"""
A ``list`` of preferred symmetric algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredSymmetricAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredSymmetricAlgorithms'])).flags
return [] | python | def cipherprefs(self):
"""
A ``list`` of preferred symmetric algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredSymmetricAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredSymmetricAlgorithms'])).flags
return [] | [
"def",
"cipherprefs",
"(",
"self",
")",
":",
"if",
"'PreferredSymmetricAlgorithms'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'h_PreferredSymmetricAlgorithms'",... | A ``list`` of preferred symmetric algorithms specified in this signature, if any. Otherwise, an empty ``list``. | [
"A",
"list",
"of",
"preferred",
"symmetric",
"algorithms",
"specified",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"list",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L93-L99 | train | 209,953 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.compprefs | def compprefs(self):
"""
A ``list`` of preferred compression algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredCompressionAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredCompressionAlgorithms'])).flags
return [] | python | def compprefs(self):
"""
A ``list`` of preferred compression algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredCompressionAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredCompressionAlgorithms'])).flags
return [] | [
"def",
"compprefs",
"(",
"self",
")",
":",
"if",
"'PreferredCompressionAlgorithms'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'h_PreferredCompressionAlgorithms'... | A ``list`` of preferred compression algorithms specified in this signature, if any. Otherwise, an empty ``list``. | [
"A",
"list",
"of",
"preferred",
"compression",
"algorithms",
"specified",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"list",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L102-L108 | train | 209,954 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.exportable | def exportable(self):
"""
``False`` if this signature is marked as being not exportable. Otherwise, ``True``.
"""
if 'ExportableCertification' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['ExportableCertification'])))
return True | python | def exportable(self):
"""
``False`` if this signature is marked as being not exportable. Otherwise, ``True``.
"""
if 'ExportableCertification' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['ExportableCertification'])))
return True | [
"def",
"exportable",
"(",
"self",
")",
":",
"if",
"'ExportableCertification'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"bool",
"(",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'ExportableCertificatio... | ``False`` if this signature is marked as being not exportable. Otherwise, ``True``. | [
"False",
"if",
"this",
"signature",
"is",
"marked",
"as",
"being",
"not",
"exportable",
".",
"Otherwise",
"True",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L133-L140 | train | 209,955 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.features | def features(self):
"""
A ``set`` of implementation features specified in this signature, if any. Otherwise, an empty ``set``.
"""
if 'Features' in self._signature.subpackets:
return next(iter(self._signature.subpackets['Features'])).flags
return set() | python | def features(self):
"""
A ``set`` of implementation features specified in this signature, if any. Otherwise, an empty ``set``.
"""
if 'Features' in self._signature.subpackets:
return next(iter(self._signature.subpackets['Features'])).flags
return set() | [
"def",
"features",
"(",
"self",
")",
":",
"if",
"'Features'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'Features'",
"]",
")",
")",
".",
"flags",
"re... | A ``set`` of implementation features specified in this signature, if any. Otherwise, an empty ``set``. | [
"A",
"set",
"of",
"implementation",
"features",
"specified",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"set",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L143-L149 | train | 209,956 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.hashprefs | def hashprefs(self):
"""
A ``list`` of preferred hash algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredHashAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredHashAlgorithms'])).flags
return [] | python | def hashprefs(self):
"""
A ``list`` of preferred hash algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredHashAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredHashAlgorithms'])).flags
return [] | [
"def",
"hashprefs",
"(",
"self",
")",
":",
"if",
"'PreferredHashAlgorithms'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'h_PreferredHashAlgorithms'",
"]",
")... | A ``list`` of preferred hash algorithms specified in this signature, if any. Otherwise, an empty ``list``. | [
"A",
"list",
"of",
"preferred",
"hash",
"algorithms",
"specified",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"list",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L156-L162 | train | 209,957 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.is_expired | def is_expired(self):
"""
``True`` if the signature has an expiration date, and is expired. Otherwise, ``False``
"""
expires_at = self.expires_at
if expires_at is not None and expires_at != self.created:
return expires_at < datetime.utcnow()
return False | python | def is_expired(self):
"""
``True`` if the signature has an expiration date, and is expired. Otherwise, ``False``
"""
expires_at = self.expires_at
if expires_at is not None and expires_at != self.created:
return expires_at < datetime.utcnow()
return False | [
"def",
"is_expired",
"(",
"self",
")",
":",
"expires_at",
"=",
"self",
".",
"expires_at",
"if",
"expires_at",
"is",
"not",
"None",
"and",
"expires_at",
"!=",
"self",
".",
"created",
":",
"return",
"expires_at",
"<",
"datetime",
".",
"utcnow",
"(",
")",
"... | ``True`` if the signature has an expiration date, and is expired. Otherwise, ``False`` | [
"True",
"if",
"the",
"signature",
"has",
"an",
"expiration",
"date",
"and",
"is",
"expired",
".",
"Otherwise",
"False"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L172-L180 | train | 209,958 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.keyserver | def keyserver(self):
"""
The preferred key server specified in this signature, if any. Otherwise, an empty ``str``.
"""
if 'PreferredKeyServer' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredKeyServer'])).uri
return '' | python | def keyserver(self):
"""
The preferred key server specified in this signature, if any. Otherwise, an empty ``str``.
"""
if 'PreferredKeyServer' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredKeyServer'])).uri
return '' | [
"def",
"keyserver",
"(",
"self",
")",
":",
"if",
"'PreferredKeyServer'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'h_PreferredKeyServer'",
"]",
")",
")",
... | The preferred key server specified in this signature, if any. Otherwise, an empty ``str``. | [
"The",
"preferred",
"key",
"server",
"specified",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"str",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L205-L211 | train | 209,959 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.notation | def notation(self):
"""
A ``dict`` of notation data in this signature, if any. Otherwise, an empty ``dict``.
"""
return dict((nd.name, nd.value) for nd in self._signature.subpackets['NotationData']) | python | def notation(self):
"""
A ``dict`` of notation data in this signature, if any. Otherwise, an empty ``dict``.
"""
return dict((nd.name, nd.value) for nd in self._signature.subpackets['NotationData']) | [
"def",
"notation",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"nd",
".",
"name",
",",
"nd",
".",
"value",
")",
"for",
"nd",
"in",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'NotationData'",
"]",
")"
] | A ``dict`` of notation data in this signature, if any. Otherwise, an empty ``dict``. | [
"A",
"dict",
"of",
"notation",
"data",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"dict",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L227-L231 | train | 209,960 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.policy_uri | def policy_uri(self):
"""
The policy URI specified in this signature, if any. Otherwise, an empty ``str``.
"""
if 'Policy' in self._signature.subpackets:
return next(iter(self._signature.subpackets['Policy'])).uri
return '' | python | def policy_uri(self):
"""
The policy URI specified in this signature, if any. Otherwise, an empty ``str``.
"""
if 'Policy' in self._signature.subpackets:
return next(iter(self._signature.subpackets['Policy'])).uri
return '' | [
"def",
"policy_uri",
"(",
"self",
")",
":",
"if",
"'Policy'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'Policy'",
"]",
")",
")",
".",
"uri",
"return... | The policy URI specified in this signature, if any. Otherwise, an empty ``str``. | [
"The",
"policy",
"URI",
"specified",
"in",
"this",
"signature",
"if",
"any",
".",
"Otherwise",
"an",
"empty",
"str",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L234-L240 | train | 209,961 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.revocable | def revocable(self):
"""
``False`` if this signature is marked as being not revocable. Otherwise, ``True``.
"""
if 'Revocable' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['Revocable'])))
return True | python | def revocable(self):
"""
``False`` if this signature is marked as being not revocable. Otherwise, ``True``.
"""
if 'Revocable' in self._signature.subpackets:
return bool(next(iter(self._signature.subpackets['Revocable'])))
return True | [
"def",
"revocable",
"(",
"self",
")",
":",
"if",
"'Revocable'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"bool",
"(",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'Revocable'",
"]",
")",
")",
"... | ``False`` if this signature is marked as being not revocable. Otherwise, ``True``. | [
"False",
"if",
"this",
"signature",
"is",
"marked",
"as",
"being",
"not",
"revocable",
".",
"Otherwise",
"True",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L243-L249 | train | 209,962 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPSignature.hashdata | def hashdata(self, subject):
_data = bytearray()
if isinstance(subject, six.string_types):
subject = subject.encode('charmap')
"""
All signatures are formed by producing a hash over the signature
data, and then using the resulting hash in the signature algorithm.
"""
if self.type == SignatureType.BinaryDocument:
"""
For binary document signatures (type 0x00), the document data is
hashed directly.
"""
if isinstance(subject, (SKEData, IntegrityProtectedSKEData)):
_data += subject.__bytearray__()
else:
_data += bytearray(subject)
if self.type == SignatureType.CanonicalDocument:
"""
For text document signatures (type 0x01), the
document is canonicalized by converting line endings to <CR><LF>,
and the resulting data is hashed.
"""
_data += re.subn(br'\r?\n', b'\r\n', subject)[0]
if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
SignatureType.Positive_Cert, SignatureType.CertRevocation, SignatureType.Subkey_Binding,
SignatureType.PrimaryKey_Binding}:
"""
When a signature is made over a key, the hash data starts with the
octet 0x99, followed by a two-octet length of the key, and then body
of the key packet. (Note that this is an old-style packet header for
a key packet with two-octet length.) ...
Key revocation signatures (types 0x20 and 0x28)
hash only the key being revoked.
"""
_s = b''
if isinstance(subject, PGPUID):
_s = subject._parent.hashdata
elif isinstance(subject, PGPKey) and not subject.is_primary:
_s = subject._parent.hashdata
elif isinstance(subject, PGPKey) and subject.is_primary:
_s = subject.hashdata
if len(_s) > 0:
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}:
"""
A subkey binding signature
(type 0x18) or primary key binding signature (type 0x19) then hashes
the subkey using the same format as the main key (also using 0x99 as
the first octet).
"""
if subject.is_primary:
_s = subject.subkeys[self.signer].hashdata
else:
_s = subject.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.KeyRevocation, SignatureType.SubkeyRevocation, SignatureType.DirectlyOnKey}:
"""
The signature is calculated directly on the key being revoked. A
revoked key is not to be used. Only revocation signatures by the
key being revoked, or by an authorized revocation key, should be
considered valid revocation signatures.
Subkey revocation signature
The signature is calculated directly on the subkey being revoked.
A revoked subkey is not to be used. Only revocation signatures
by the top-level signature key that is bound to this subkey, or
by an authorized revocation key, should be considered valid
revocation signatures.
- clarification from draft-ietf-openpgp-rfc4880bis-02:
Primary key revocation signatures (type 0x20) hash
only the key being revoked. Subkey revocation signature (type 0x28)
hash first the primary key and then the subkey being revoked
Signature directly on a key
This signature is calculated directly on a key. It binds the
information in the Signature subpackets to the key, and is
appropriate to be used for subpackets that provide information
about the key, such as the Revocation Key subpacket. It is also
appropriate for statements that non-self certifiers want to make
about the key itself, rather than the binding between a key and a
name.
"""
if self.type == SignatureType.SubkeyRevocation:
# hash the primary key first if this is a Subkey Revocation signature
_s = subject.parent.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
_s = subject.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
SignatureType.Positive_Cert, SignatureType.CertRevocation}:
"""
A certification signature (type 0x10 through 0x13) hashes the User
ID being bound to the key into the hash context after the above
data. ... A V4 certification
hashes the constant 0xB4 for User ID certifications or the constant
0xD1 for User Attribute certifications, followed by a four-octet
number giving the length of the User ID or User Attribute data, and
then the User ID or User Attribute data.
...
The [certificate revocation] signature
is computed over the same data as the certificate that it
revokes, and should have a later creation date than that
certificate.
"""
_s = subject.hashdata
if subject.is_uid:
_data += b'\xb4'
else:
_data += b'\xd1'
_data += self.int_to_bytes(len(_s), 4) + _s
# if this is a new signature, do update_hlen
if 0 in list(self._signature.signature):
self._signature.update_hlen()
"""
Once the data body is hashed, then a trailer is hashed. (...)
A V4 signature hashes the packet body
starting from its first field, the version number, through the end
of the hashed subpacket data. Thus, the fields hashed are the
signature version, the signature type, the public-key algorithm, the
hash algorithm, the hashed subpacket length, and the hashed
subpacket body.
V4 signatures also hash in a final trailer of six octets: the
version of the Signature packet, i.e., 0x04; 0xFF; and a four-octet,
big-endian number that is the length of the hashed data from the
Signature packet (note that this number does not include these final
six octets).
"""
hcontext = bytearray()
hcontext.append(self._signature.header.version if not self.embedded else self._signature._sig.header.version)
hcontext.append(self.type)
hcontext.append(self.key_algorithm)
hcontext.append(self.hash_algorithm)
hcontext += self._signature.subpackets.__hashbytearray__()
hlen = len(hcontext)
_data += hcontext
_data += b'\x04\xff'
_data += self.int_to_bytes(hlen, 4)
return bytes(_data) | python | def hashdata(self, subject):
_data = bytearray()
if isinstance(subject, six.string_types):
subject = subject.encode('charmap')
"""
All signatures are formed by producing a hash over the signature
data, and then using the resulting hash in the signature algorithm.
"""
if self.type == SignatureType.BinaryDocument:
"""
For binary document signatures (type 0x00), the document data is
hashed directly.
"""
if isinstance(subject, (SKEData, IntegrityProtectedSKEData)):
_data += subject.__bytearray__()
else:
_data += bytearray(subject)
if self.type == SignatureType.CanonicalDocument:
"""
For text document signatures (type 0x01), the
document is canonicalized by converting line endings to <CR><LF>,
and the resulting data is hashed.
"""
_data += re.subn(br'\r?\n', b'\r\n', subject)[0]
if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
SignatureType.Positive_Cert, SignatureType.CertRevocation, SignatureType.Subkey_Binding,
SignatureType.PrimaryKey_Binding}:
"""
When a signature is made over a key, the hash data starts with the
octet 0x99, followed by a two-octet length of the key, and then body
of the key packet. (Note that this is an old-style packet header for
a key packet with two-octet length.) ...
Key revocation signatures (types 0x20 and 0x28)
hash only the key being revoked.
"""
_s = b''
if isinstance(subject, PGPUID):
_s = subject._parent.hashdata
elif isinstance(subject, PGPKey) and not subject.is_primary:
_s = subject._parent.hashdata
elif isinstance(subject, PGPKey) and subject.is_primary:
_s = subject.hashdata
if len(_s) > 0:
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}:
"""
A subkey binding signature
(type 0x18) or primary key binding signature (type 0x19) then hashes
the subkey using the same format as the main key (also using 0x99 as
the first octet).
"""
if subject.is_primary:
_s = subject.subkeys[self.signer].hashdata
else:
_s = subject.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.KeyRevocation, SignatureType.SubkeyRevocation, SignatureType.DirectlyOnKey}:
"""
The signature is calculated directly on the key being revoked. A
revoked key is not to be used. Only revocation signatures by the
key being revoked, or by an authorized revocation key, should be
considered valid revocation signatures.
Subkey revocation signature
The signature is calculated directly on the subkey being revoked.
A revoked subkey is not to be used. Only revocation signatures
by the top-level signature key that is bound to this subkey, or
by an authorized revocation key, should be considered valid
revocation signatures.
- clarification from draft-ietf-openpgp-rfc4880bis-02:
Primary key revocation signatures (type 0x20) hash
only the key being revoked. Subkey revocation signature (type 0x28)
hash first the primary key and then the subkey being revoked
Signature directly on a key
This signature is calculated directly on a key. It binds the
information in the Signature subpackets to the key, and is
appropriate to be used for subpackets that provide information
about the key, such as the Revocation Key subpacket. It is also
appropriate for statements that non-self certifiers want to make
about the key itself, rather than the binding between a key and a
name.
"""
if self.type == SignatureType.SubkeyRevocation:
# hash the primary key first if this is a Subkey Revocation signature
_s = subject.parent.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
_s = subject.hashdata
_data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s
if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
SignatureType.Positive_Cert, SignatureType.CertRevocation}:
"""
A certification signature (type 0x10 through 0x13) hashes the User
ID being bound to the key into the hash context after the above
data. ... A V4 certification
hashes the constant 0xB4 for User ID certifications or the constant
0xD1 for User Attribute certifications, followed by a four-octet
number giving the length of the User ID or User Attribute data, and
then the User ID or User Attribute data.
...
The [certificate revocation] signature
is computed over the same data as the certificate that it
revokes, and should have a later creation date than that
certificate.
"""
_s = subject.hashdata
if subject.is_uid:
_data += b'\xb4'
else:
_data += b'\xd1'
_data += self.int_to_bytes(len(_s), 4) + _s
# if this is a new signature, do update_hlen
if 0 in list(self._signature.signature):
self._signature.update_hlen()
"""
Once the data body is hashed, then a trailer is hashed. (...)
A V4 signature hashes the packet body
starting from its first field, the version number, through the end
of the hashed subpacket data. Thus, the fields hashed are the
signature version, the signature type, the public-key algorithm, the
hash algorithm, the hashed subpacket length, and the hashed
subpacket body.
V4 signatures also hash in a final trailer of six octets: the
version of the Signature packet, i.e., 0x04; 0xFF; and a four-octet,
big-endian number that is the length of the hashed data from the
Signature packet (note that this number does not include these final
six octets).
"""
hcontext = bytearray()
hcontext.append(self._signature.header.version if not self.embedded else self._signature._sig.header.version)
hcontext.append(self.type)
hcontext.append(self.key_algorithm)
hcontext.append(self.hash_algorithm)
hcontext += self._signature.subpackets.__hashbytearray__()
hlen = len(hcontext)
_data += hcontext
_data += b'\x04\xff'
_data += self.int_to_bytes(hlen, 4)
return bytes(_data) | [
"def",
"hashdata",
"(",
"self",
",",
"subject",
")",
":",
"_data",
"=",
"bytearray",
"(",
")",
"if",
"isinstance",
"(",
"subject",
",",
"six",
".",
"string_types",
")",
":",
"subject",
"=",
"subject",
".",
"encode",
"(",
"'charmap'",
")",
"if",
"self",... | All signatures are formed by producing a hash over the signature
data, and then using the resulting hash in the signature algorithm. | [
"All",
"signatures",
"are",
"formed",
"by",
"producing",
"a",
"hash",
"over",
"the",
"signature",
"data",
"and",
"then",
"using",
"the",
"resulting",
"hash",
"in",
"the",
"signature",
"algorithm",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L338-L500 | train | 209,963 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPUID.image | def image(self):
"""
If this is a User Attribute, this will be the stored image. If this is not a User Attribute, this will be ``None``.
"""
return self._uid.image.image if isinstance(self._uid, UserAttribute) else None | python | def image(self):
"""
If this is a User Attribute, this will be the stored image. If this is not a User Attribute, this will be ``None``.
"""
return self._uid.image.image if isinstance(self._uid, UserAttribute) else None | [
"def",
"image",
"(",
"self",
")",
":",
"return",
"self",
".",
"_uid",
".",
"image",
".",
"image",
"if",
"isinstance",
"(",
"self",
".",
"_uid",
",",
"UserAttribute",
")",
"else",
"None"
] | If this is a User Attribute, this will be the stored image. If this is not a User Attribute, this will be ``None``. | [
"If",
"this",
"is",
"a",
"User",
"Attribute",
"this",
"will",
"be",
"the",
"stored",
"image",
".",
"If",
"this",
"is",
"not",
"a",
"User",
"Attribute",
"this",
"will",
"be",
"None",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L558-L562 | train | 209,964 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPUID.is_primary | def is_primary(self):
"""
If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, Faqlse.
"""
return bool(next(iter(self.selfsig._signature.subpackets['h_PrimaryUserID']), False)) | python | def is_primary(self):
"""
If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, Faqlse.
"""
return bool(next(iter(self.selfsig._signature.subpackets['h_PrimaryUserID']), False)) | [
"def",
"is_primary",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"next",
"(",
"iter",
"(",
"self",
".",
"selfsig",
".",
"_signature",
".",
"subpackets",
"[",
"'h_PrimaryUserID'",
"]",
")",
",",
"False",
")",
")"
] | If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, Faqlse. | [
"If",
"the",
"most",
"recent",
"valid",
"self",
"-",
"signature",
"specifies",
"this",
"as",
"being",
"primary",
"this",
"will",
"be",
"True",
".",
"Otherwise",
"Faqlse",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L565-L569 | train | 209,965 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPUID.selfsig | def selfsig(self):
"""
This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``.
"""
if self.parent is not None:
return next((sig for sig in reversed(self._signatures) if sig.signer == self.parent.fingerprint.keyid), None) | python | def selfsig(self):
"""
This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``.
"""
if self.parent is not None:
return next((sig for sig in reversed(self._signatures) if sig.signer == self.parent.fingerprint.keyid), None) | [
"def",
"selfsig",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"return",
"next",
"(",
"(",
"sig",
"for",
"sig",
"in",
"reversed",
"(",
"self",
".",
"_signatures",
")",
"if",
"sig",
".",
"signer",
"==",
"self",
".",
... | This will be the most recent, self-signature of this User ID or Attribute. If there isn't one, this will be ``None``. | [
"This",
"will",
"be",
"the",
"most",
"recent",
"self",
"-",
"signature",
"of",
"this",
"User",
"ID",
"or",
"Attribute",
".",
"If",
"there",
"isn",
"t",
"one",
"this",
"will",
"be",
"None",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L586-L591 | train | 209,966 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPUID.new | def new(cls, pn, comment="", email=""):
"""
Create a new User ID or photo.
:param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo.
Otherwise, it will be used as the name field for a User ID.
:type pn: ``bytearray``, ``str``, ``unicode``
:param comment: The comment field for a User ID. Ignored if this is a photo.
:type comment: ``str``, ``unicode``
:param email: The email address field for a User ID. Ignored if this is a photo.
:type email: ``str``, ``unicode``
:returns: :py:obj:`PGPUID`
"""
uid = PGPUID()
if isinstance(pn, bytearray):
uid._uid = UserAttribute()
uid._uid.image.image = pn
uid._uid.image.iencoding = ImageEncoding.encodingof(pn)
uid._uid.update_hlen()
else:
uid._uid = UserID()
uid._uid.name = pn
uid._uid.comment = comment
uid._uid.email = email
uid._uid.update_hlen()
return uid | python | def new(cls, pn, comment="", email=""):
"""
Create a new User ID or photo.
:param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo.
Otherwise, it will be used as the name field for a User ID.
:type pn: ``bytearray``, ``str``, ``unicode``
:param comment: The comment field for a User ID. Ignored if this is a photo.
:type comment: ``str``, ``unicode``
:param email: The email address field for a User ID. Ignored if this is a photo.
:type email: ``str``, ``unicode``
:returns: :py:obj:`PGPUID`
"""
uid = PGPUID()
if isinstance(pn, bytearray):
uid._uid = UserAttribute()
uid._uid.image.image = pn
uid._uid.image.iencoding = ImageEncoding.encodingof(pn)
uid._uid.update_hlen()
else:
uid._uid = UserID()
uid._uid.name = pn
uid._uid.comment = comment
uid._uid.email = email
uid._uid.update_hlen()
return uid | [
"def",
"new",
"(",
"cls",
",",
"pn",
",",
"comment",
"=",
"\"\"",
",",
"email",
"=",
"\"\"",
")",
":",
"uid",
"=",
"PGPUID",
"(",
")",
"if",
"isinstance",
"(",
"pn",
",",
"bytearray",
")",
":",
"uid",
".",
"_uid",
"=",
"UserAttribute",
"(",
")",
... | Create a new User ID or photo.
:param pn: User ID name, or photo. If this is a ``bytearray``, it will be loaded as a photo.
Otherwise, it will be used as the name field for a User ID.
:type pn: ``bytearray``, ``str``, ``unicode``
:param comment: The comment field for a User ID. Ignored if this is a photo.
:type comment: ``str``, ``unicode``
:param email: The email address field for a User ID. Ignored if this is a photo.
:type email: ``str``, ``unicode``
:returns: :py:obj:`PGPUID` | [
"Create",
"a",
"new",
"User",
"ID",
"or",
"photo",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L609-L636 | train | 209,967 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPMessage.message | def message(self):
"""The message contents"""
if self.type == 'cleartext':
return self.bytes_to_text(self._message)
if self.type == 'literal':
return self._message.contents
if self.type == 'encrypted':
return self._message | python | def message(self):
"""The message contents"""
if self.type == 'cleartext':
return self.bytes_to_text(self._message)
if self.type == 'literal':
return self._message.contents
if self.type == 'encrypted':
return self._message | [
"def",
"message",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"'cleartext'",
":",
"return",
"self",
".",
"bytes_to_text",
"(",
"self",
".",
"_message",
")",
"if",
"self",
".",
"type",
"==",
"'literal'",
":",
"return",
"self",
".",
"_message... | The message contents | [
"The",
"message",
"contents"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L763-L772 | train | 209,968 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPMessage.new | def new(cls, message, **kwargs):
"""
Create a new PGPMessage object.
:param message: The message to be stored.
:type message: ``str``, ``unicode``, ``bytes``, ``bytearray``
:returns: :py:obj:`PGPMessage`
The following optional keyword arguments can be used with :py:meth:`PGPMessage.new`:
:keyword file: if True, ``message`` should be a path to a file. The contents of that file will be read and used
as the contents of the message.
:type file: ``bool``
:keyword cleartext: if True, the message will be cleartext with inline signatures.
:type cleartext: ``bool``
:keyword sensitive: if True, the filename will be set to '_CONSOLE' to signal other OpenPGP clients to treat
this message as being 'for your eyes only'. Ignored if cleartext is True.
:type sensitive: ``bool``
:keyword format: Set the message format identifier. Ignored if cleartext is True.
:type format: ``str``
:keyword compression: Set the compression algorithm for the new message.
Defaults to :py:obj:`CompressionAlgorithm.ZIP`. Ignored if cleartext is True.
:keyword encoding: Set the Charset header for the message.
:type encoding: ``str`` representing a valid codec in codecs
"""
# TODO: have 'codecs' above (in :type encoding:) link to python documentation page on codecs
cleartext = kwargs.pop('cleartext', False)
format = kwargs.pop('format', None)
sensitive = kwargs.pop('sensitive', False)
compression = kwargs.pop('compression', CompressionAlgorithm.ZIP)
file = kwargs.pop('file', False)
charset = kwargs.pop('encoding', None)
filename = ''
mtime = datetime.utcnow()
msg = PGPMessage()
if charset:
msg.charset = charset
# if format in 'tu' and isinstance(message, (six.binary_type, bytearray)):
# # if message format is text or unicode and we got binary data, we'll need to transcode it to UTF-8
# message =
if file and os.path.isfile(message):
filename = message
message = bytearray(os.path.getsize(filename))
mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
with open(filename, 'rb') as mf:
mf.readinto(message)
# if format is None, we can try to detect it
if format is None:
if isinstance(message, six.text_type):
# message is definitely UTF-8 already
format = 'u'
elif cls.is_ascii(message):
# message is probably text
format = 't'
else:
# message is probably binary
format = 'b'
# if message is a binary type and we're building a textual message, we need to transcode the bytes to UTF-8
if isinstance(message, (six.binary_type, bytearray)) and (cleartext or format in 'tu'):
message = message.decode(charset or 'utf-8')
if cleartext:
msg |= message
else:
# load literal data
lit = LiteralData()
lit._contents = bytearray(msg.text_to_bytes(message))
lit.filename = '_CONSOLE' if sensitive else os.path.basename(filename)
lit.mtime = mtime
lit.format = format
# if cls.is_ascii(message):
# lit.format = 't'
lit.update_hlen()
msg |= lit
msg._compression = compression
return msg | python | def new(cls, message, **kwargs):
"""
Create a new PGPMessage object.
:param message: The message to be stored.
:type message: ``str``, ``unicode``, ``bytes``, ``bytearray``
:returns: :py:obj:`PGPMessage`
The following optional keyword arguments can be used with :py:meth:`PGPMessage.new`:
:keyword file: if True, ``message`` should be a path to a file. The contents of that file will be read and used
as the contents of the message.
:type file: ``bool``
:keyword cleartext: if True, the message will be cleartext with inline signatures.
:type cleartext: ``bool``
:keyword sensitive: if True, the filename will be set to '_CONSOLE' to signal other OpenPGP clients to treat
this message as being 'for your eyes only'. Ignored if cleartext is True.
:type sensitive: ``bool``
:keyword format: Set the message format identifier. Ignored if cleartext is True.
:type format: ``str``
:keyword compression: Set the compression algorithm for the new message.
Defaults to :py:obj:`CompressionAlgorithm.ZIP`. Ignored if cleartext is True.
:keyword encoding: Set the Charset header for the message.
:type encoding: ``str`` representing a valid codec in codecs
"""
# TODO: have 'codecs' above (in :type encoding:) link to python documentation page on codecs
cleartext = kwargs.pop('cleartext', False)
format = kwargs.pop('format', None)
sensitive = kwargs.pop('sensitive', False)
compression = kwargs.pop('compression', CompressionAlgorithm.ZIP)
file = kwargs.pop('file', False)
charset = kwargs.pop('encoding', None)
filename = ''
mtime = datetime.utcnow()
msg = PGPMessage()
if charset:
msg.charset = charset
# if format in 'tu' and isinstance(message, (six.binary_type, bytearray)):
# # if message format is text or unicode and we got binary data, we'll need to transcode it to UTF-8
# message =
if file and os.path.isfile(message):
filename = message
message = bytearray(os.path.getsize(filename))
mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
with open(filename, 'rb') as mf:
mf.readinto(message)
# if format is None, we can try to detect it
if format is None:
if isinstance(message, six.text_type):
# message is definitely UTF-8 already
format = 'u'
elif cls.is_ascii(message):
# message is probably text
format = 't'
else:
# message is probably binary
format = 'b'
# if message is a binary type and we're building a textual message, we need to transcode the bytes to UTF-8
if isinstance(message, (six.binary_type, bytearray)) and (cleartext or format in 'tu'):
message = message.decode(charset or 'utf-8')
if cleartext:
msg |= message
else:
# load literal data
lit = LiteralData()
lit._contents = bytearray(msg.text_to_bytes(message))
lit.filename = '_CONSOLE' if sensitive else os.path.basename(filename)
lit.mtime = mtime
lit.format = format
# if cls.is_ascii(message):
# lit.format = 't'
lit.update_hlen()
msg |= lit
msg._compression = compression
return msg | [
"def",
"new",
"(",
"cls",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: have 'codecs' above (in :type encoding:) link to python documentation page on codecs",
"cleartext",
"=",
"kwargs",
".",
"pop",
"(",
"'cleartext'",
",",
"False",
")",
"format",
"=",
... | Create a new PGPMessage object.
:param message: The message to be stored.
:type message: ``str``, ``unicode``, ``bytes``, ``bytearray``
:returns: :py:obj:`PGPMessage`
The following optional keyword arguments can be used with :py:meth:`PGPMessage.new`:
:keyword file: if True, ``message`` should be a path to a file. The contents of that file will be read and used
as the contents of the message.
:type file: ``bool``
:keyword cleartext: if True, the message will be cleartext with inline signatures.
:type cleartext: ``bool``
:keyword sensitive: if True, the filename will be set to '_CONSOLE' to signal other OpenPGP clients to treat
this message as being 'for your eyes only'. Ignored if cleartext is True.
:type sensitive: ``bool``
:keyword format: Set the message format identifier. Ignored if cleartext is True.
:type format: ``str``
:keyword compression: Set the compression algorithm for the new message.
Defaults to :py:obj:`CompressionAlgorithm.ZIP`. Ignored if cleartext is True.
:keyword encoding: Set the Charset header for the message.
:type encoding: ``str`` representing a valid codec in codecs | [
"Create",
"a",
"new",
"PGPMessage",
"object",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L940-L1030 | train | 209,969 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPMessage.decrypt | def decrypt(self, passphrase):
"""
Attempt to decrypt this message using a passphrase.
:param passphrase: The passphrase to use to attempt to decrypt this message.
:type passphrase: ``str``, ``unicode``, ``bytes``
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption failed for any reason.
:returns: A new :py:obj:`PGPMessage` containing the decrypted contents of this message
"""
if not self.is_encrypted:
raise PGPError("This message is not encrypted!")
for skesk in iter(sk for sk in self._sessionkeys if isinstance(sk, SKESessionKey)):
try:
symalg, key = skesk.decrypt_sk(passphrase)
decmsg = PGPMessage()
decmsg.parse(self.message.decrypt(key, symalg))
except (TypeError, ValueError, NotImplementedError, PGPDecryptionError):
continue
else:
del passphrase
break
else:
raise PGPDecryptionError("Decryption failed")
return decmsg | python | def decrypt(self, passphrase):
"""
Attempt to decrypt this message using a passphrase.
:param passphrase: The passphrase to use to attempt to decrypt this message.
:type passphrase: ``str``, ``unicode``, ``bytes``
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption failed for any reason.
:returns: A new :py:obj:`PGPMessage` containing the decrypted contents of this message
"""
if not self.is_encrypted:
raise PGPError("This message is not encrypted!")
for skesk in iter(sk for sk in self._sessionkeys if isinstance(sk, SKESessionKey)):
try:
symalg, key = skesk.decrypt_sk(passphrase)
decmsg = PGPMessage()
decmsg.parse(self.message.decrypt(key, symalg))
except (TypeError, ValueError, NotImplementedError, PGPDecryptionError):
continue
else:
del passphrase
break
else:
raise PGPDecryptionError("Decryption failed")
return decmsg | [
"def",
"decrypt",
"(",
"self",
",",
"passphrase",
")",
":",
"if",
"not",
"self",
".",
"is_encrypted",
":",
"raise",
"PGPError",
"(",
"\"This message is not encrypted!\"",
")",
"for",
"skesk",
"in",
"iter",
"(",
"sk",
"for",
"sk",
"in",
"self",
".",
"_sessi... | Attempt to decrypt this message using a passphrase.
:param passphrase: The passphrase to use to attempt to decrypt this message.
:type passphrase: ``str``, ``unicode``, ``bytes``
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption failed for any reason.
:returns: A new :py:obj:`PGPMessage` containing the decrypted contents of this message | [
"Attempt",
"to",
"decrypt",
"this",
"message",
"using",
"a",
"passphrase",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1079-L1107 | train | 209,970 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.is_expired | def is_expired(self):
"""``True`` if this key is expired, otherwise ``False``"""
expires = self.expires_at
if expires is not None:
return expires <= datetime.utcnow()
return False | python | def is_expired(self):
"""``True`` if this key is expired, otherwise ``False``"""
expires = self.expires_at
if expires is not None:
return expires <= datetime.utcnow()
return False | [
"def",
"is_expired",
"(",
"self",
")",
":",
"expires",
"=",
"self",
".",
"expires_at",
"if",
"expires",
"is",
"not",
"None",
":",
"return",
"expires",
"<=",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"False"
] | ``True`` if this key is expired, otherwise ``False`` | [
"True",
"if",
"this",
"key",
"is",
"expired",
"otherwise",
"False"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1260-L1266 | train | 209,971 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.is_primary | def is_primary(self):
"""``True`` if this is a primary key; ``False`` if this is a subkey"""
return isinstance(self._key, Primary) and not isinstance(self._key, Sub) | python | def is_primary(self):
"""``True`` if this is a primary key; ``False`` if this is a subkey"""
return isinstance(self._key, Primary) and not isinstance(self._key, Sub) | [
"def",
"is_primary",
"(",
"self",
")",
":",
"return",
"isinstance",
"(",
"self",
".",
"_key",
",",
"Primary",
")",
"and",
"not",
"isinstance",
"(",
"self",
".",
"_key",
",",
"Sub",
")"
] | ``True`` if this is a primary key; ``False`` if this is a subkey | [
"True",
"if",
"this",
"is",
"a",
"primary",
"key",
";",
"False",
"if",
"this",
"is",
"a",
"subkey"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1269-L1271 | train | 209,972 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.is_public | def is_public(self):
"""``True`` if this is a public key, otherwise ``False``"""
return isinstance(self._key, Public) and not isinstance(self._key, Private) | python | def is_public(self):
"""``True`` if this is a public key, otherwise ``False``"""
return isinstance(self._key, Public) and not isinstance(self._key, Private) | [
"def",
"is_public",
"(",
"self",
")",
":",
"return",
"isinstance",
"(",
"self",
".",
"_key",
",",
"Public",
")",
"and",
"not",
"isinstance",
"(",
"self",
".",
"_key",
",",
"Private",
")"
] | ``True`` if this is a public key, otherwise ``False`` | [
"True",
"if",
"this",
"is",
"a",
"public",
"key",
"otherwise",
"False"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1282-L1284 | train | 209,973 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.is_unlocked | def is_unlocked(self):
"""``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``"""
if self.is_public:
return True
if not self.is_protected:
return True
return self._key.unlocked | python | def is_unlocked(self):
"""``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``"""
if self.is_public:
return True
if not self.is_protected:
return True
return self._key.unlocked | [
"def",
"is_unlocked",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_public",
":",
"return",
"True",
"if",
"not",
"self",
".",
"is_protected",
":",
"return",
"True",
"return",
"self",
".",
"_key",
".",
"unlocked"
] | ``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True`` | [
"False",
"if",
"this",
"is",
"a",
"private",
"key",
"that",
"is",
"protected",
"with",
"a",
"passphrase",
"and",
"has",
"not",
"yet",
"been",
"unlocked",
"otherwise",
"True"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1287-L1295 | train | 209,974 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.new | def new(cls, key_algorithm, key_size):
"""
Generate a new PGP key
:param key_algorithm: Key algorithm to use.
:type key_algorithm: A :py:obj:`~constants.PubKeyAlgorithm`
:param key_size: Key size in bits, unless `key_algorithm` is :py:obj:`~constants.PubKeyAlgorithm.ECDSA` or
:py:obj:`~constants.PubKeyAlgorithm.ECDH`, in which case it should be the Curve OID to use.
:type key_size: ``int`` or :py:obj:`~constants.EllipticCurveOID`
:return: A newly generated :py:obj:`PGPKey`
"""
# new private key shell first
key = PGPKey()
if key_algorithm in {PubKeyAlgorithm.RSAEncrypt, PubKeyAlgorithm.RSASign}: # pragma: no cover
warnings.warn('{:s} is deprecated - generating key using RSAEncryptOrSign'.format(key_algorithm.name))
key_algorithm = PubKeyAlgorithm.RSAEncryptOrSign
# generate some key data to match key_algorithm and key_size
key._key = PrivKeyV4.new(key_algorithm, key_size)
return key | python | def new(cls, key_algorithm, key_size):
"""
Generate a new PGP key
:param key_algorithm: Key algorithm to use.
:type key_algorithm: A :py:obj:`~constants.PubKeyAlgorithm`
:param key_size: Key size in bits, unless `key_algorithm` is :py:obj:`~constants.PubKeyAlgorithm.ECDSA` or
:py:obj:`~constants.PubKeyAlgorithm.ECDH`, in which case it should be the Curve OID to use.
:type key_size: ``int`` or :py:obj:`~constants.EllipticCurveOID`
:return: A newly generated :py:obj:`PGPKey`
"""
# new private key shell first
key = PGPKey()
if key_algorithm in {PubKeyAlgorithm.RSAEncrypt, PubKeyAlgorithm.RSASign}: # pragma: no cover
warnings.warn('{:s} is deprecated - generating key using RSAEncryptOrSign'.format(key_algorithm.name))
key_algorithm = PubKeyAlgorithm.RSAEncryptOrSign
# generate some key data to match key_algorithm and key_size
key._key = PrivKeyV4.new(key_algorithm, key_size)
return key | [
"def",
"new",
"(",
"cls",
",",
"key_algorithm",
",",
"key_size",
")",
":",
"# new private key shell first",
"key",
"=",
"PGPKey",
"(",
")",
"if",
"key_algorithm",
"in",
"{",
"PubKeyAlgorithm",
".",
"RSAEncrypt",
",",
"PubKeyAlgorithm",
".",
"RSASign",
"}",
":"... | Generate a new PGP key
:param key_algorithm: Key algorithm to use.
:type key_algorithm: A :py:obj:`~constants.PubKeyAlgorithm`
:param key_size: Key size in bits, unless `key_algorithm` is :py:obj:`~constants.PubKeyAlgorithm.ECDSA` or
:py:obj:`~constants.PubKeyAlgorithm.ECDH`, in which case it should be the Curve OID to use.
:type key_size: ``int`` or :py:obj:`~constants.EllipticCurveOID`
:return: A newly generated :py:obj:`PGPKey` | [
"Generate",
"a",
"new",
"PGP",
"key"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1400-L1421 | train | 209,975 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.protect | def protect(self, passphrase, enc_alg, hash_alg):
"""
Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before
a new passphrase can be specified.
Has no effect on public keys.
:param passphrase: A passphrase to protect the key with
:type passphrase: ``str``, ``unicode``
:param enc_alg: Symmetric encryption algorithm to use to protect the key
:type enc_alg: :py:obj:`~constants.SymmetricKeyAlgorithm`
:param hash_alg: Hash algorithm to use in the String-to-Key specifier
:type hash_alg: :py:obj:`~constants.HashAlgorithm`
"""
##TODO: specify strong defaults for enc_alg and hash_alg
if self.is_public:
# we can't protect public keys because only private key material is ever protected
warnings.warn("Public keys cannot be passphrase-protected", stacklevel=2)
return
if self.is_protected and not self.is_unlocked:
# we can't protect a key that is already protected unless it is unlocked first
warnings.warn("This key is already protected with a passphrase - "
"please unlock it before attempting to specify a new passphrase", stacklevel=2)
return
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.protect(passphrase, enc_alg, hash_alg)
del passphrase | python | def protect(self, passphrase, enc_alg, hash_alg):
"""
Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before
a new passphrase can be specified.
Has no effect on public keys.
:param passphrase: A passphrase to protect the key with
:type passphrase: ``str``, ``unicode``
:param enc_alg: Symmetric encryption algorithm to use to protect the key
:type enc_alg: :py:obj:`~constants.SymmetricKeyAlgorithm`
:param hash_alg: Hash algorithm to use in the String-to-Key specifier
:type hash_alg: :py:obj:`~constants.HashAlgorithm`
"""
##TODO: specify strong defaults for enc_alg and hash_alg
if self.is_public:
# we can't protect public keys because only private key material is ever protected
warnings.warn("Public keys cannot be passphrase-protected", stacklevel=2)
return
if self.is_protected and not self.is_unlocked:
# we can't protect a key that is already protected unless it is unlocked first
warnings.warn("This key is already protected with a passphrase - "
"please unlock it before attempting to specify a new passphrase", stacklevel=2)
return
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.protect(passphrase, enc_alg, hash_alg)
del passphrase | [
"def",
"protect",
"(",
"self",
",",
"passphrase",
",",
"enc_alg",
",",
"hash_alg",
")",
":",
"##TODO: specify strong defaults for enc_alg and hash_alg",
"if",
"self",
".",
"is_public",
":",
"# we can't protect public keys because only private key material is ever protected",
"w... | Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before
a new passphrase can be specified.
Has no effect on public keys.
:param passphrase: A passphrase to protect the key with
:type passphrase: ``str``, ``unicode``
:param enc_alg: Symmetric encryption algorithm to use to protect the key
:type enc_alg: :py:obj:`~constants.SymmetricKeyAlgorithm`
:param hash_alg: Hash algorithm to use in the String-to-Key specifier
:type hash_alg: :py:obj:`~constants.HashAlgorithm` | [
"Add",
"a",
"passphrase",
"to",
"a",
"private",
"key",
".",
"If",
"the",
"key",
"is",
"already",
"passphrase",
"protected",
"it",
"should",
"be",
"unlocked",
"before",
"a",
"new",
"passphrase",
"can",
"be",
"specified",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1539-L1568 | train | 209,976 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.unlock | def unlock(self, passphrase):
"""
Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both
private and passphrase-protected.
When the context managed block is exited, the unprotected private key material is removed.
Example::
privkey = PGPKey()
privkey.parse(keytext)
assert privkey.is_protected
assert privkey.is_unlocked is False
# privkey.sign("some text") <- this would raise an exception
with privkey.unlock("TheCorrectPassphrase"):
# privkey is now unlocked
assert privkey.is_unlocked
# so you can do things with it
sig = privkey.sign("some text")
# privkey is no longer unlocked
assert privkey.is_unlocked is False
Emits a :py:obj:`~warnings.UserWarning` if the key is public or not passphrase protected.
:param str passphrase: The passphrase to be used to unlock this key.
:raises: :py:exc:`~pgpy.errors.PGPDecryptionError` if the passphrase is incorrect
"""
if self.is_public:
# we can't unprotect public keys because only private key material is ever protected
warnings.warn("Public keys cannot be passphrase-protected", stacklevel=3)
yield self
return
if not self.is_protected:
# we can't unprotect private keys that are not protected, because there is no ciphertext to decrypt
warnings.warn("This key is not protected with a passphrase", stacklevel=3)
yield self
return
try:
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.unprotect(passphrase)
del passphrase
yield self
finally:
# clean up here by deleting the previously decrypted secret key material
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.keymaterial.clear() | python | def unlock(self, passphrase):
"""
Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both
private and passphrase-protected.
When the context managed block is exited, the unprotected private key material is removed.
Example::
privkey = PGPKey()
privkey.parse(keytext)
assert privkey.is_protected
assert privkey.is_unlocked is False
# privkey.sign("some text") <- this would raise an exception
with privkey.unlock("TheCorrectPassphrase"):
# privkey is now unlocked
assert privkey.is_unlocked
# so you can do things with it
sig = privkey.sign("some text")
# privkey is no longer unlocked
assert privkey.is_unlocked is False
Emits a :py:obj:`~warnings.UserWarning` if the key is public or not passphrase protected.
:param str passphrase: The passphrase to be used to unlock this key.
:raises: :py:exc:`~pgpy.errors.PGPDecryptionError` if the passphrase is incorrect
"""
if self.is_public:
# we can't unprotect public keys because only private key material is ever protected
warnings.warn("Public keys cannot be passphrase-protected", stacklevel=3)
yield self
return
if not self.is_protected:
# we can't unprotect private keys that are not protected, because there is no ciphertext to decrypt
warnings.warn("This key is not protected with a passphrase", stacklevel=3)
yield self
return
try:
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.unprotect(passphrase)
del passphrase
yield self
finally:
# clean up here by deleting the previously decrypted secret key material
for sk in itertools.chain([self], self.subkeys.values()):
sk._key.keymaterial.clear() | [
"def",
"unlock",
"(",
"self",
",",
"passphrase",
")",
":",
"if",
"self",
".",
"is_public",
":",
"# we can't unprotect public keys because only private key material is ever protected",
"warnings",
".",
"warn",
"(",
"\"Public keys cannot be passphrase-protected\"",
",",
"stackl... | Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both
private and passphrase-protected.
When the context managed block is exited, the unprotected private key material is removed.
Example::
privkey = PGPKey()
privkey.parse(keytext)
assert privkey.is_protected
assert privkey.is_unlocked is False
# privkey.sign("some text") <- this would raise an exception
with privkey.unlock("TheCorrectPassphrase"):
# privkey is now unlocked
assert privkey.is_unlocked
# so you can do things with it
sig = privkey.sign("some text")
# privkey is no longer unlocked
assert privkey.is_unlocked is False
Emits a :py:obj:`~warnings.UserWarning` if the key is public or not passphrase protected.
:param str passphrase: The passphrase to be used to unlock this key.
:raises: :py:exc:`~pgpy.errors.PGPDecryptionError` if the passphrase is incorrect | [
"Context",
"manager",
"method",
"for",
"unlocking",
"passphrase",
"-",
"protected",
"private",
"keys",
".",
"Has",
"no",
"effect",
"if",
"the",
"key",
"is",
"not",
"both",
"private",
"and",
"passphrase",
"-",
"protected",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1571-L1622 | train | 209,977 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.add_uid | def add_uid(self, uid, selfsign=True, **prefs):
"""
Add a User ID to this key.
:param uid: The user id to add
:type uid: :py:obj:`~pgpy.PGPUID`
:param selfsign: Whether or not to self-sign the user id before adding it
:type selfsign: ``bool``
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`.
Any such keyword arguments are ignored if selfsign is ``False``
"""
uid._parent = self
if selfsign:
uid |= self.certify(uid, SignatureType.Positive_Cert, **prefs)
self |= uid | python | def add_uid(self, uid, selfsign=True, **prefs):
"""
Add a User ID to this key.
:param uid: The user id to add
:type uid: :py:obj:`~pgpy.PGPUID`
:param selfsign: Whether or not to self-sign the user id before adding it
:type selfsign: ``bool``
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`.
Any such keyword arguments are ignored if selfsign is ``False``
"""
uid._parent = self
if selfsign:
uid |= self.certify(uid, SignatureType.Positive_Cert, **prefs)
self |= uid | [
"def",
"add_uid",
"(",
"self",
",",
"uid",
",",
"selfsign",
"=",
"True",
",",
"*",
"*",
"prefs",
")",
":",
"uid",
".",
"_parent",
"=",
"self",
"if",
"selfsign",
":",
"uid",
"|=",
"self",
".",
"certify",
"(",
"uid",
",",
"SignatureType",
".",
"Posit... | Add a User ID to this key.
:param uid: The user id to add
:type uid: :py:obj:`~pgpy.PGPUID`
:param selfsign: Whether or not to self-sign the user id before adding it
:type selfsign: ``bool``
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`.
Any such keyword arguments are ignored if selfsign is ``False`` | [
"Add",
"a",
"User",
"ID",
"to",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1624-L1640 | train | 209,978 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.get_uid | def get_uid(self, search):
"""
Find and return a User ID that matches the search string given.
:param search: A text string to match name, comment, or email address against
:type search: ``str``, ``unicode``
:return: The first matching :py:obj:`~pgpy.PGPUID`, or ``None`` if no matches were found.
"""
if self.is_primary:
return next((u for u in self._uids if search in filter(lambda a: a is not None, (u.name, u.comment, u.email))), None)
return self.parent.get_uid(search) | python | def get_uid(self, search):
"""
Find and return a User ID that matches the search string given.
:param search: A text string to match name, comment, or email address against
:type search: ``str``, ``unicode``
:return: The first matching :py:obj:`~pgpy.PGPUID`, or ``None`` if no matches were found.
"""
if self.is_primary:
return next((u for u in self._uids if search in filter(lambda a: a is not None, (u.name, u.comment, u.email))), None)
return self.parent.get_uid(search) | [
"def",
"get_uid",
"(",
"self",
",",
"search",
")",
":",
"if",
"self",
".",
"is_primary",
":",
"return",
"next",
"(",
"(",
"u",
"for",
"u",
"in",
"self",
".",
"_uids",
"if",
"search",
"in",
"filter",
"(",
"lambda",
"a",
":",
"a",
"is",
"not",
"Non... | Find and return a User ID that matches the search string given.
:param search: A text string to match name, comment, or email address against
:type search: ``str``, ``unicode``
:return: The first matching :py:obj:`~pgpy.PGPUID`, or ``None`` if no matches were found. | [
"Find",
"and",
"return",
"a",
"User",
"ID",
"that",
"matches",
"the",
"search",
"string",
"given",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1642-L1652 | train | 209,979 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.sign | def sign(self, subject, **prefs):
"""
Sign text, a message, or a timestamp using this key.
:param subject: The text to be signed
:type subject: ``str``, :py:obj:`~pgpy.PGPMessage`, ``None``
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
The following optional keyword arguments can be used with :py:meth:`PGPKey.sign`, as well as
:py:meth:`PGPKey.certify`, :py:meth:`PGPKey.revoke`, and :py:meth:`PGPKey.bind`:
:keyword expires: Set an expiration date for this signature
:type expires: :py:obj:`~datetime.datetime`, :py:obj:`~datetime.timedelta`
:keyword notation: Add arbitrary notation data to this signature.
:type notation: ``dict``
:keyword policy_uri: Add a URI to the signature that should describe the policy under which the signature
was issued.
:type policy_uri: ``str``
:keyword revocable: If ``False``, this signature will be marked non-revocable
:type revocable: ``bool``
:keyword user: Specify which User ID to use when creating this signature. Also adds a "Signer's User ID"
to the signature.
:type user: ``str``
"""
sig_type = SignatureType.BinaryDocument
hash_algo = prefs.pop('hash', None)
if subject is None:
sig_type = SignatureType.Timestamp
if isinstance(subject, PGPMessage):
if subject.type == 'cleartext':
sig_type = SignatureType.CanonicalDocument
subject = subject.message
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
return self._sign(subject, sig, **prefs) | python | def sign(self, subject, **prefs):
"""
Sign text, a message, or a timestamp using this key.
:param subject: The text to be signed
:type subject: ``str``, :py:obj:`~pgpy.PGPMessage`, ``None``
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
The following optional keyword arguments can be used with :py:meth:`PGPKey.sign`, as well as
:py:meth:`PGPKey.certify`, :py:meth:`PGPKey.revoke`, and :py:meth:`PGPKey.bind`:
:keyword expires: Set an expiration date for this signature
:type expires: :py:obj:`~datetime.datetime`, :py:obj:`~datetime.timedelta`
:keyword notation: Add arbitrary notation data to this signature.
:type notation: ``dict``
:keyword policy_uri: Add a URI to the signature that should describe the policy under which the signature
was issued.
:type policy_uri: ``str``
:keyword revocable: If ``False``, this signature will be marked non-revocable
:type revocable: ``bool``
:keyword user: Specify which User ID to use when creating this signature. Also adds a "Signer's User ID"
to the signature.
:type user: ``str``
"""
sig_type = SignatureType.BinaryDocument
hash_algo = prefs.pop('hash', None)
if subject is None:
sig_type = SignatureType.Timestamp
if isinstance(subject, PGPMessage):
if subject.type == 'cleartext':
sig_type = SignatureType.CanonicalDocument
subject = subject.message
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
return self._sign(subject, sig, **prefs) | [
"def",
"sign",
"(",
"self",
",",
"subject",
",",
"*",
"*",
"prefs",
")",
":",
"sig_type",
"=",
"SignatureType",
".",
"BinaryDocument",
"hash_algo",
"=",
"prefs",
".",
"pop",
"(",
"'hash'",
",",
"None",
")",
"if",
"subject",
"is",
"None",
":",
"sig_type... | Sign text, a message, or a timestamp using this key.
:param subject: The text to be signed
:type subject: ``str``, :py:obj:`~pgpy.PGPMessage`, ``None``
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
The following optional keyword arguments can be used with :py:meth:`PGPKey.sign`, as well as
:py:meth:`PGPKey.certify`, :py:meth:`PGPKey.revoke`, and :py:meth:`PGPKey.bind`:
:keyword expires: Set an expiration date for this signature
:type expires: :py:obj:`~datetime.datetime`, :py:obj:`~datetime.timedelta`
:keyword notation: Add arbitrary notation data to this signature.
:type notation: ``dict``
:keyword policy_uri: Add a URI to the signature that should describe the policy under which the signature
was issued.
:type policy_uri: ``str``
:keyword revocable: If ``False``, this signature will be marked non-revocable
:type revocable: ``bool``
:keyword user: Specify which User ID to use when creating this signature. Also adds a "Signer's User ID"
to the signature.
:type user: ``str`` | [
"Sign",
"text",
"a",
"message",
"or",
"a",
"timestamp",
"using",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1795-L1835 | train | 209,980 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.revoke | def revoke(self, target, **prefs):
"""
Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far.
:param target: The key to revoke
:type target: :py:obj:`PGPKey`, :py:obj:`PGPUID`
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional
keyword arguments can be used with :py:meth:`PGPKey.revoke`.
:keyword reason: Defaults to :py:obj:`constants.RevocationReason.NotSpecified`
:type reason: One of :py:obj:`constants.RevocationReason`.
:keyword comment: Defaults to an empty string.
:type comment: ``str``
"""
hash_algo = prefs.pop('hash', None)
if isinstance(target, PGPUID):
sig_type = SignatureType.CertRevocation
elif isinstance(target, PGPKey):
##TODO: check to make sure that the key that is being revoked:
# - is this key
# - is one of this key's subkeys
# - specifies this key as its revocation key
if target.is_primary:
sig_type = SignatureType.KeyRevocation
else:
sig_type = SignatureType.SubkeyRevocation
else: # pragma: no cover
raise TypeError
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
# signature options that only make sense when revoking
reason = prefs.pop('reason', RevocationReason.NotSpecified)
comment = prefs.pop('comment', "")
sig._signature.subpackets.addnew('ReasonForRevocation', hashed=True, code=reason, string=comment)
return self._sign(target, sig, **prefs) | python | def revoke(self, target, **prefs):
"""
Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far.
:param target: The key to revoke
:type target: :py:obj:`PGPKey`, :py:obj:`PGPUID`
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional
keyword arguments can be used with :py:meth:`PGPKey.revoke`.
:keyword reason: Defaults to :py:obj:`constants.RevocationReason.NotSpecified`
:type reason: One of :py:obj:`constants.RevocationReason`.
:keyword comment: Defaults to an empty string.
:type comment: ``str``
"""
hash_algo = prefs.pop('hash', None)
if isinstance(target, PGPUID):
sig_type = SignatureType.CertRevocation
elif isinstance(target, PGPKey):
##TODO: check to make sure that the key that is being revoked:
# - is this key
# - is one of this key's subkeys
# - specifies this key as its revocation key
if target.is_primary:
sig_type = SignatureType.KeyRevocation
else:
sig_type = SignatureType.SubkeyRevocation
else: # pragma: no cover
raise TypeError
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
# signature options that only make sense when revoking
reason = prefs.pop('reason', RevocationReason.NotSpecified)
comment = prefs.pop('comment', "")
sig._signature.subpackets.addnew('ReasonForRevocation', hashed=True, code=reason, string=comment)
return self._sign(target, sig, **prefs) | [
"def",
"revoke",
"(",
"self",
",",
"target",
",",
"*",
"*",
"prefs",
")",
":",
"hash_algo",
"=",
"prefs",
".",
"pop",
"(",
"'hash'",
",",
"None",
")",
"if",
"isinstance",
"(",
"target",
",",
"PGPUID",
")",
":",
"sig_type",
"=",
"SignatureType",
".",
... | Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far.
:param target: The key to revoke
:type target: :py:obj:`PGPKey`, :py:obj:`PGPUID`
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional
keyword arguments can be used with :py:meth:`PGPKey.revoke`.
:keyword reason: Defaults to :py:obj:`constants.RevocationReason.NotSpecified`
:type reason: One of :py:obj:`constants.RevocationReason`.
:keyword comment: Defaults to an empty string.
:type comment: ``str`` | [
"Revoke",
"a",
"key",
"a",
"subkey",
"or",
"all",
"current",
"certification",
"signatures",
"of",
"a",
"User",
"ID",
"that",
"were",
"generated",
"by",
"this",
"key",
"so",
"far",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L1969-L2012 | train | 209,981 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.revoker | def revoker(self, revoker, **prefs):
"""
Generate a signature that specifies another key as being valid for revoking this key.
:param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key.
:type revoker: :py:obj:`PGPKey`
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional
keyword arguments can be used with :py:meth:`PGPKey.revoker`.
:keyword sensitive: If ``True``, this sets the sensitive flag on the RevocationKey subpacket. Currently,
this has no other effect.
:type sensitive: ``bool``
"""
hash_algo = prefs.pop('hash', None)
sig = PGPSignature.new(SignatureType.DirectlyOnKey, self.key_algorithm, hash_algo, self.fingerprint.keyid)
# signature options that only make sense when adding a revocation key
sensitive = prefs.pop('sensitive', False)
keyclass = RevocationKeyClass.Normal | (RevocationKeyClass.Sensitive if sensitive else 0x00)
sig._signature.subpackets.addnew('RevocationKey',
hashed=True,
algorithm=revoker.key_algorithm,
fingerprint=revoker.fingerprint,
keyclass=keyclass)
# revocation keys should really not be revocable themselves
prefs['revocable'] = False
return self._sign(self, sig, **prefs) | python | def revoker(self, revoker, **prefs):
"""
Generate a signature that specifies another key as being valid for revoking this key.
:param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key.
:type revoker: :py:obj:`PGPKey`
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional
keyword arguments can be used with :py:meth:`PGPKey.revoker`.
:keyword sensitive: If ``True``, this sets the sensitive flag on the RevocationKey subpacket. Currently,
this has no other effect.
:type sensitive: ``bool``
"""
hash_algo = prefs.pop('hash', None)
sig = PGPSignature.new(SignatureType.DirectlyOnKey, self.key_algorithm, hash_algo, self.fingerprint.keyid)
# signature options that only make sense when adding a revocation key
sensitive = prefs.pop('sensitive', False)
keyclass = RevocationKeyClass.Normal | (RevocationKeyClass.Sensitive if sensitive else 0x00)
sig._signature.subpackets.addnew('RevocationKey',
hashed=True,
algorithm=revoker.key_algorithm,
fingerprint=revoker.fingerprint,
keyclass=keyclass)
# revocation keys should really not be revocable themselves
prefs['revocable'] = False
return self._sign(self, sig, **prefs) | [
"def",
"revoker",
"(",
"self",
",",
"revoker",
",",
"*",
"*",
"prefs",
")",
":",
"hash_algo",
"=",
"prefs",
".",
"pop",
"(",
"'hash'",
",",
"None",
")",
"sig",
"=",
"PGPSignature",
".",
"new",
"(",
"SignatureType",
".",
"DirectlyOnKey",
",",
"self",
... | Generate a signature that specifies another key as being valid for revoking this key.
:param revoker: The :py:obj:`PGPKey` to specify as a valid revocation key.
:type revoker: :py:obj:`PGPKey`
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
:raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
:returns: :py:obj:`PGPSignature`
In addition to the optional keyword arguments accepted by :py:meth:`PGPKey.sign`, the following optional
keyword arguments can be used with :py:meth:`PGPKey.revoker`.
:keyword sensitive: If ``True``, this sets the sensitive flag on the RevocationKey subpacket. Currently,
this has no other effect.
:type sensitive: ``bool`` | [
"Generate",
"a",
"signature",
"that",
"specifies",
"another",
"key",
"as",
"being",
"valid",
"for",
"revoking",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2015-L2048 | train | 209,982 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.bind | def bind(self, key, **prefs):
"""
Bind a subkey to this key.
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPkey.certify`
"""
hash_algo = prefs.pop('hash', None)
if self.is_primary and not key.is_primary:
sig_type = SignatureType.Subkey_Binding
elif key.is_primary and not self.is_primary:
sig_type = SignatureType.PrimaryKey_Binding
else: # pragma: no cover
raise PGPError
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
if sig_type == SignatureType.Subkey_Binding:
# signature options that only make sense in subkey binding signatures
usage = prefs.pop('usage', None)
if usage is not None:
sig._signature.subpackets.addnew('KeyFlags', hashed=True, flags=usage)
# if possible, have the subkey create a primary key binding signature
if key.key_algorithm.can_sign:
subkeyid = key.fingerprint.keyid
esig = None
if not key.is_public:
esig = key.bind(self)
elif subkeyid in self.subkeys: # pragma: no cover
esig = self.subkeys[subkeyid].bind(self)
if esig is not None:
sig._signature.subpackets.addnew('EmbeddedSignature', hashed=False, _sig=esig._signature)
return self._sign(key, sig, **prefs) | python | def bind(self, key, **prefs):
"""
Bind a subkey to this key.
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPkey.certify`
"""
hash_algo = prefs.pop('hash', None)
if self.is_primary and not key.is_primary:
sig_type = SignatureType.Subkey_Binding
elif key.is_primary and not self.is_primary:
sig_type = SignatureType.PrimaryKey_Binding
else: # pragma: no cover
raise PGPError
sig = PGPSignature.new(sig_type, self.key_algorithm, hash_algo, self.fingerprint.keyid)
if sig_type == SignatureType.Subkey_Binding:
# signature options that only make sense in subkey binding signatures
usage = prefs.pop('usage', None)
if usage is not None:
sig._signature.subpackets.addnew('KeyFlags', hashed=True, flags=usage)
# if possible, have the subkey create a primary key binding signature
if key.key_algorithm.can_sign:
subkeyid = key.fingerprint.keyid
esig = None
if not key.is_public:
esig = key.bind(self)
elif subkeyid in self.subkeys: # pragma: no cover
esig = self.subkeys[subkeyid].bind(self)
if esig is not None:
sig._signature.subpackets.addnew('EmbeddedSignature', hashed=False, _sig=esig._signature)
return self._sign(key, sig, **prefs) | [
"def",
"bind",
"(",
"self",
",",
"key",
",",
"*",
"*",
"prefs",
")",
":",
"hash_algo",
"=",
"prefs",
".",
"pop",
"(",
"'hash'",
",",
"None",
")",
"if",
"self",
".",
"is_primary",
"and",
"not",
"key",
".",
"is_primary",
":",
"sig_type",
"=",
"Signat... | Bind a subkey to this key.
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPkey.certify` | [
"Bind",
"a",
"subkey",
"to",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2051-L2091 | train | 209,983 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.verify | def verify(self, subject, signature=None):
"""
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification`
"""
sspairs = []
# some type checking
if not isinstance(subject, (type(None), PGPMessage, PGPKey, PGPUID, PGPSignature, six.string_types, bytes, bytearray)):
raise TypeError("Unexpected subject value: {:s}".format(str(type(subject))))
if not isinstance(signature, (type(None), PGPSignature)):
raise TypeError("Unexpected signature value: {:s}".format(str(type(signature))))
def _filter_sigs(sigs):
_ids = {self.fingerprint.keyid} | set(self.subkeys)
return [ sig for sig in sigs if sig.signer in _ids ]
# collect signature(s)
if signature is None:
if isinstance(subject, PGPMessage):
sspairs += [ (sig, subject.message) for sig in _filter_sigs(subject.signatures) ]
if isinstance(subject, (PGPUID, PGPKey)):
sspairs += [ (sig, subject) for sig in _filter_sigs(subject.__sig__) ]
if isinstance(subject, PGPKey):
# user ids
sspairs += [ (sig, uid) for uid in subject.userids for sig in _filter_sigs(uid.__sig__) ]
# user attributes
sspairs += [ (sig, ua) for ua in subject.userattributes for sig in _filter_sigs(ua.__sig__) ]
# subkey binding signatures
sspairs += [ (sig, subkey) for subkey in subject.subkeys.values() for sig in _filter_sigs(subkey.__sig__) ]
elif signature.signer in {self.fingerprint.keyid} | set(self.subkeys):
sspairs += [(signature, subject)]
if len(sspairs) == 0:
raise PGPError("No signatures to verify")
# finally, start verifying signatures
sigv = SignatureVerification()
for sig, subj in sspairs:
if self.fingerprint.keyid != sig.signer and sig.signer in self.subkeys:
warnings.warn("Signature was signed with this key's subkey: {:s}. "
"Verifying with subkey...".format(sig.signer),
stacklevel=2)
sigv &= self.subkeys[sig.signer].verify(subj, sig)
else:
verified = self._key.verify(sig.hashdata(subj), sig.__sig__, getattr(hashes, sig.hash_algorithm.name)())
if verified is NotImplemented:
raise NotImplementedError(sig.key_algorithm)
sigv.add_sigsubj(sig, self.fingerprint.keyid, subj, verified)
return sigv | python | def verify(self, subject, signature=None):
"""
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification`
"""
sspairs = []
# some type checking
if not isinstance(subject, (type(None), PGPMessage, PGPKey, PGPUID, PGPSignature, six.string_types, bytes, bytearray)):
raise TypeError("Unexpected subject value: {:s}".format(str(type(subject))))
if not isinstance(signature, (type(None), PGPSignature)):
raise TypeError("Unexpected signature value: {:s}".format(str(type(signature))))
def _filter_sigs(sigs):
_ids = {self.fingerprint.keyid} | set(self.subkeys)
return [ sig for sig in sigs if sig.signer in _ids ]
# collect signature(s)
if signature is None:
if isinstance(subject, PGPMessage):
sspairs += [ (sig, subject.message) for sig in _filter_sigs(subject.signatures) ]
if isinstance(subject, (PGPUID, PGPKey)):
sspairs += [ (sig, subject) for sig in _filter_sigs(subject.__sig__) ]
if isinstance(subject, PGPKey):
# user ids
sspairs += [ (sig, uid) for uid in subject.userids for sig in _filter_sigs(uid.__sig__) ]
# user attributes
sspairs += [ (sig, ua) for ua in subject.userattributes for sig in _filter_sigs(ua.__sig__) ]
# subkey binding signatures
sspairs += [ (sig, subkey) for subkey in subject.subkeys.values() for sig in _filter_sigs(subkey.__sig__) ]
elif signature.signer in {self.fingerprint.keyid} | set(self.subkeys):
sspairs += [(signature, subject)]
if len(sspairs) == 0:
raise PGPError("No signatures to verify")
# finally, start verifying signatures
sigv = SignatureVerification()
for sig, subj in sspairs:
if self.fingerprint.keyid != sig.signer and sig.signer in self.subkeys:
warnings.warn("Signature was signed with this key's subkey: {:s}. "
"Verifying with subkey...".format(sig.signer),
stacklevel=2)
sigv &= self.subkeys[sig.signer].verify(subj, sig)
else:
verified = self._key.verify(sig.hashdata(subj), sig.__sig__, getattr(hashes, sig.hash_algorithm.name)())
if verified is NotImplemented:
raise NotImplementedError(sig.key_algorithm)
sigv.add_sigsubj(sig, self.fingerprint.keyid, subj, verified)
return sigv | [
"def",
"verify",
"(",
"self",
",",
"subject",
",",
"signature",
"=",
"None",
")",
":",
"sspairs",
"=",
"[",
"]",
"# some type checking",
"if",
"not",
"isinstance",
"(",
"subject",
",",
"(",
"type",
"(",
"None",
")",
",",
"PGPMessage",
",",
"PGPKey",
",... | Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is detached, it should be specified here.
:type signature: :py:obj:`PGPSignature`
:returns: :py:obj:`~pgpy.types.SignatureVerification` | [
"Verify",
"a",
"subject",
"with",
"a",
"signature",
"using",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2093-L2153 | train | 209,984 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.encrypt | def encrypt(self, message, sessionkey=None, **prefs):
"""
Encrypt a PGPMessage using this key.
:param message: The message to encrypt.
:type message: :py:obj:`PGPMessage`
:optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``.
If ``None``, a session key of the appropriate length will be generated randomly.
.. warning::
Care should be taken when making use of this option! Session keys *absolutely need*
to be unpredictable! Use the ``gen_key()`` method on the desired
:py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key!
:type sessionkey: ``bytes``, ``str``
:raises: :py:exc:`~errors.PGPEncryptionError` if encryption failed for any reason.
:returns: A new :py:obj:`PGPMessage` with the encrypted contents of ``message``
The following optional keyword arguments can be used with :py:meth:`PGPKey.encrypt`:
:keyword cipher: Specifies the symmetric block cipher to use when encrypting the message.
:type cipher: :py:obj:`~constants.SymmetricKeyAlgorithm`
:keyword user: Specifies the User ID to use as the recipient for this encryption operation, for the purposes of
preference defaults and selection validation.
:type user: ``str``, ``unicode``
"""
user = prefs.pop('user', None)
uid = None
if user is not None:
uid = self.get_uid(user)
else:
uid = next(iter(self.userids), None)
if uid is None and self.parent is not None:
uid = next(iter(self.parent.userids), None)
cipher_algo = prefs.pop('cipher', uid.selfsig.cipherprefs[0])
if cipher_algo not in uid.selfsig.cipherprefs:
warnings.warn("Selected symmetric algorithm not in key preferences", stacklevel=3)
if message.is_compressed and message._compression not in uid.selfsig.compprefs:
warnings.warn("Selected compression algorithm not in key preferences", stacklevel=3)
if sessionkey is None:
sessionkey = cipher_algo.gen_key()
# set up a new PKESessionKeyV3
pkesk = PKESessionKeyV3()
pkesk.encrypter = bytearray(binascii.unhexlify(self.fingerprint.keyid.encode('latin-1')))
pkesk.pkalg = self.key_algorithm
# pkesk.encrypt_sk(self.__key__, cipher_algo, sessionkey)
pkesk.encrypt_sk(self._key, cipher_algo, sessionkey)
if message.is_encrypted: # pragma: no cover
_m = message
else:
_m = PGPMessage()
skedata = IntegrityProtectedSKEDataV1()
skedata.encrypt(sessionkey, cipher_algo, message.__bytes__())
_m |= skedata
_m |= pkesk
return _m | python | def encrypt(self, message, sessionkey=None, **prefs):
"""
Encrypt a PGPMessage using this key.
:param message: The message to encrypt.
:type message: :py:obj:`PGPMessage`
:optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``.
If ``None``, a session key of the appropriate length will be generated randomly.
.. warning::
Care should be taken when making use of this option! Session keys *absolutely need*
to be unpredictable! Use the ``gen_key()`` method on the desired
:py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key!
:type sessionkey: ``bytes``, ``str``
:raises: :py:exc:`~errors.PGPEncryptionError` if encryption failed for any reason.
:returns: A new :py:obj:`PGPMessage` with the encrypted contents of ``message``
The following optional keyword arguments can be used with :py:meth:`PGPKey.encrypt`:
:keyword cipher: Specifies the symmetric block cipher to use when encrypting the message.
:type cipher: :py:obj:`~constants.SymmetricKeyAlgorithm`
:keyword user: Specifies the User ID to use as the recipient for this encryption operation, for the purposes of
preference defaults and selection validation.
:type user: ``str``, ``unicode``
"""
user = prefs.pop('user', None)
uid = None
if user is not None:
uid = self.get_uid(user)
else:
uid = next(iter(self.userids), None)
if uid is None and self.parent is not None:
uid = next(iter(self.parent.userids), None)
cipher_algo = prefs.pop('cipher', uid.selfsig.cipherprefs[0])
if cipher_algo not in uid.selfsig.cipherprefs:
warnings.warn("Selected symmetric algorithm not in key preferences", stacklevel=3)
if message.is_compressed and message._compression not in uid.selfsig.compprefs:
warnings.warn("Selected compression algorithm not in key preferences", stacklevel=3)
if sessionkey is None:
sessionkey = cipher_algo.gen_key()
# set up a new PKESessionKeyV3
pkesk = PKESessionKeyV3()
pkesk.encrypter = bytearray(binascii.unhexlify(self.fingerprint.keyid.encode('latin-1')))
pkesk.pkalg = self.key_algorithm
# pkesk.encrypt_sk(self.__key__, cipher_algo, sessionkey)
pkesk.encrypt_sk(self._key, cipher_algo, sessionkey)
if message.is_encrypted: # pragma: no cover
_m = message
else:
_m = PGPMessage()
skedata = IntegrityProtectedSKEDataV1()
skedata.encrypt(sessionkey, cipher_algo, message.__bytes__())
_m |= skedata
_m |= pkesk
return _m | [
"def",
"encrypt",
"(",
"self",
",",
"message",
",",
"sessionkey",
"=",
"None",
",",
"*",
"*",
"prefs",
")",
":",
"user",
"=",
"prefs",
".",
"pop",
"(",
"'user'",
",",
"None",
")",
"uid",
"=",
"None",
"if",
"user",
"is",
"not",
"None",
":",
"uid",... | Encrypt a PGPMessage using this key.
:param message: The message to encrypt.
:type message: :py:obj:`PGPMessage`
:optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``.
If ``None``, a session key of the appropriate length will be generated randomly.
.. warning::
Care should be taken when making use of this option! Session keys *absolutely need*
to be unpredictable! Use the ``gen_key()`` method on the desired
:py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key!
:type sessionkey: ``bytes``, ``str``
:raises: :py:exc:`~errors.PGPEncryptionError` if encryption failed for any reason.
:returns: A new :py:obj:`PGPMessage` with the encrypted contents of ``message``
The following optional keyword arguments can be used with :py:meth:`PGPKey.encrypt`:
:keyword cipher: Specifies the symmetric block cipher to use when encrypting the message.
:type cipher: :py:obj:`~constants.SymmetricKeyAlgorithm`
:keyword user: Specifies the User ID to use as the recipient for this encryption operation, for the purposes of
preference defaults and selection validation.
:type user: ``str``, ``unicode`` | [
"Encrypt",
"a",
"PGPMessage",
"using",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2156-L2220 | train | 209,985 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKey.decrypt | def decrypt(self, message):
"""
Decrypt a PGPMessage using this key.
:param message: An encrypted :py:obj:`PGPMessage`
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason.
:returns: A new :py:obj:`PGPMessage` with the decrypted contents of ``message``.
"""
if not message.is_encrypted:
warnings.warn("This message is not encrypted", stacklevel=3)
return message
if self.fingerprint.keyid not in message.encrypters:
sks = set(self.subkeys)
mis = set(message.encrypters)
if sks & mis:
skid = list(sks & mis)[0]
warnings.warn("Message was encrypted with this key's subkey: {:s}. "
"Decrypting with that...".format(skid),
stacklevel=2)
return self.subkeys[skid].decrypt(message)
raise PGPError("Cannot decrypt the provided message with this key")
pkesk = next(pk for pk in message._sessionkeys if pk.pkalg == self.key_algorithm and pk.encrypter == self.fingerprint.keyid)
alg, key = pkesk.decrypt_sk(self._key)
# now that we have the symmetric cipher used and the key, we can decrypt the actual message
decmsg = PGPMessage()
decmsg.parse(message.message.decrypt(key, alg))
return decmsg | python | def decrypt(self, message):
"""
Decrypt a PGPMessage using this key.
:param message: An encrypted :py:obj:`PGPMessage`
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason.
:returns: A new :py:obj:`PGPMessage` with the decrypted contents of ``message``.
"""
if not message.is_encrypted:
warnings.warn("This message is not encrypted", stacklevel=3)
return message
if self.fingerprint.keyid not in message.encrypters:
sks = set(self.subkeys)
mis = set(message.encrypters)
if sks & mis:
skid = list(sks & mis)[0]
warnings.warn("Message was encrypted with this key's subkey: {:s}. "
"Decrypting with that...".format(skid),
stacklevel=2)
return self.subkeys[skid].decrypt(message)
raise PGPError("Cannot decrypt the provided message with this key")
pkesk = next(pk for pk in message._sessionkeys if pk.pkalg == self.key_algorithm and pk.encrypter == self.fingerprint.keyid)
alg, key = pkesk.decrypt_sk(self._key)
# now that we have the symmetric cipher used and the key, we can decrypt the actual message
decmsg = PGPMessage()
decmsg.parse(message.message.decrypt(key, alg))
return decmsg | [
"def",
"decrypt",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"message",
".",
"is_encrypted",
":",
"warnings",
".",
"warn",
"(",
"\"This message is not encrypted\"",
",",
"stacklevel",
"=",
"3",
")",
"return",
"message",
"if",
"self",
".",
"fingerpri... | Decrypt a PGPMessage using this key.
:param message: An encrypted :py:obj:`PGPMessage`
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason.
:returns: A new :py:obj:`PGPMessage` with the decrypted contents of ``message``. | [
"Decrypt",
"a",
"PGPMessage",
"using",
"this",
"key",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2223-L2255 | train | 209,986 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKeyring.load | def load(self, *args):
"""
Load all keys provided into this keyring object.
:param \*args: Each arg in ``args`` can be any of the formats supported by :py:meth:`PGPKey.from_path` and
:py:meth:`PGPKey.from_blob`, or a ``list`` or ``tuple`` of these.
:type \*args: ``list``, ``tuple``, ``str``, ``unicode``, ``bytes``, ``bytearray``
:returns: a ``set`` containing the unique fingerprints of all of the keys that were loaded during this operation.
"""
def _preiter(first, iterable):
yield first
for item in iterable:
yield item
loaded = set()
for key in iter(item for ilist in iter(ilist if isinstance(ilist, (tuple, list)) else [ilist] for ilist in args)
for item in ilist):
if os.path.isfile(key):
_key, keys = PGPKey.from_file(key)
else:
_key, keys = PGPKey.from_blob(key)
for ik in _preiter(_key, keys.values()):
self._add_key(ik)
loaded |= {ik.fingerprint} | {isk.fingerprint for isk in ik.subkeys.values()}
return list(loaded) | python | def load(self, *args):
"""
Load all keys provided into this keyring object.
:param \*args: Each arg in ``args`` can be any of the formats supported by :py:meth:`PGPKey.from_path` and
:py:meth:`PGPKey.from_blob`, or a ``list`` or ``tuple`` of these.
:type \*args: ``list``, ``tuple``, ``str``, ``unicode``, ``bytes``, ``bytearray``
:returns: a ``set`` containing the unique fingerprints of all of the keys that were loaded during this operation.
"""
def _preiter(first, iterable):
yield first
for item in iterable:
yield item
loaded = set()
for key in iter(item for ilist in iter(ilist if isinstance(ilist, (tuple, list)) else [ilist] for ilist in args)
for item in ilist):
if os.path.isfile(key):
_key, keys = PGPKey.from_file(key)
else:
_key, keys = PGPKey.from_blob(key)
for ik in _preiter(_key, keys.values()):
self._add_key(ik)
loaded |= {ik.fingerprint} | {isk.fingerprint for isk in ik.subkeys.values()}
return list(loaded) | [
"def",
"load",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"_preiter",
"(",
"first",
",",
"iterable",
")",
":",
"yield",
"first",
"for",
"item",
"in",
"iterable",
":",
"yield",
"item",
"loaded",
"=",
"set",
"(",
")",
"for",
"key",
"in",
"iter",... | Load all keys provided into this keyring object.
:param \*args: Each arg in ``args`` can be any of the formats supported by :py:meth:`PGPKey.from_path` and
:py:meth:`PGPKey.from_blob`, or a ``list`` or ``tuple`` of these.
:type \*args: ``list``, ``tuple``, ``str``, ``unicode``, ``bytes``, ``bytearray``
:returns: a ``set`` containing the unique fingerprints of all of the keys that were loaded during this operation. | [
"Load",
"all",
"keys",
"provided",
"into",
"this",
"keyring",
"object",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2446-L2473 | train | 209,987 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKeyring.fingerprints | def fingerprints(self, keyhalf='any', keytype='any'):
"""
List loaded fingerprints with some optional filtering.
:param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the
the other type will not be included in the results.
:param str keytype: Can be 'any', 'primary', or 'sub'. If 'primary' or 'sub', the fingerprints of keys of the
the other type will not be included in the results.
:returns: a ``set`` of fingerprints of keys matching the filters specified.
"""
return {pk.fingerprint for pk in self._keys.values()
if pk.is_primary in [True if keytype in ['primary', 'any'] else None,
False if keytype in ['sub', 'any'] else None]
if pk.is_public in [True if keyhalf in ['public', 'any'] else None,
False if keyhalf in ['private', 'any'] else None]} | python | def fingerprints(self, keyhalf='any', keytype='any'):
"""
List loaded fingerprints with some optional filtering.
:param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the
the other type will not be included in the results.
:param str keytype: Can be 'any', 'primary', or 'sub'. If 'primary' or 'sub', the fingerprints of keys of the
the other type will not be included in the results.
:returns: a ``set`` of fingerprints of keys matching the filters specified.
"""
return {pk.fingerprint for pk in self._keys.values()
if pk.is_primary in [True if keytype in ['primary', 'any'] else None,
False if keytype in ['sub', 'any'] else None]
if pk.is_public in [True if keyhalf in ['public', 'any'] else None,
False if keyhalf in ['private', 'any'] else None]} | [
"def",
"fingerprints",
"(",
"self",
",",
"keyhalf",
"=",
"'any'",
",",
"keytype",
"=",
"'any'",
")",
":",
"return",
"{",
"pk",
".",
"fingerprint",
"for",
"pk",
"in",
"self",
".",
"_keys",
".",
"values",
"(",
")",
"if",
"pk",
".",
"is_primary",
"in",
... | List loaded fingerprints with some optional filtering.
:param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the
the other type will not be included in the results.
:param str keytype: Can be 'any', 'primary', or 'sub'. If 'primary' or 'sub', the fingerprints of keys of the
the other type will not be included in the results.
:returns: a ``set`` of fingerprints of keys matching the filters specified. | [
"List",
"loaded",
"fingerprints",
"with",
"some",
"optional",
"filtering",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2495-L2509 | train | 209,988 |
SecurityInnovation/PGPy | pgpy/pgp.py | PGPKeyring.unload | def unload(self, key):
"""
Unload a loaded key and its subkeys.
The easiest way to do this is to select a key using :py:meth:`PGPKeyring.key` first::
with keyring.key("DSA von TestKey") as key:
keyring.unload(key)
:param key: The key to unload.
:type key: :py:obj:`PGPKey`
"""
assert isinstance(key, PGPKey)
pkid = id(key)
if pkid in self._keys:
# remove references
[ kd.remove(pkid) for kd in [self._pubkeys, self._privkeys] if pkid in kd ]
# remove the key
self._keys.pop(pkid)
# remove aliases
for m, a in [ (m, a) for m in self._aliases for a, p in m.items() if p == pkid ]:
m.pop(a)
# do a re-sort of this alias if it was not unique
if a in self:
self._sort_alias(a)
# if key is a primary key, unload its subkeys as well
if key.is_primary:
[ self.unload(sk) for sk in key.subkeys.values() ] | python | def unload(self, key):
"""
Unload a loaded key and its subkeys.
The easiest way to do this is to select a key using :py:meth:`PGPKeyring.key` first::
with keyring.key("DSA von TestKey") as key:
keyring.unload(key)
:param key: The key to unload.
:type key: :py:obj:`PGPKey`
"""
assert isinstance(key, PGPKey)
pkid = id(key)
if pkid in self._keys:
# remove references
[ kd.remove(pkid) for kd in [self._pubkeys, self._privkeys] if pkid in kd ]
# remove the key
self._keys.pop(pkid)
# remove aliases
for m, a in [ (m, a) for m in self._aliases for a, p in m.items() if p == pkid ]:
m.pop(a)
# do a re-sort of this alias if it was not unique
if a in self:
self._sort_alias(a)
# if key is a primary key, unload its subkeys as well
if key.is_primary:
[ self.unload(sk) for sk in key.subkeys.values() ] | [
"def",
"unload",
"(",
"self",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"PGPKey",
")",
"pkid",
"=",
"id",
"(",
"key",
")",
"if",
"pkid",
"in",
"self",
".",
"_keys",
":",
"# remove references",
"[",
"kd",
".",
"remove",
"(",
"pk... | Unload a loaded key and its subkeys.
The easiest way to do this is to select a key using :py:meth:`PGPKeyring.key` first::
with keyring.key("DSA von TestKey") as key:
keyring.unload(key)
:param key: The key to unload.
:type key: :py:obj:`PGPKey` | [
"Unload",
"a",
"loaded",
"key",
"and",
"its",
"subkeys",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/pgp.py#L2511-L2540 | train | 209,989 |
SecurityInnovation/PGPy | pgpy/packet/types.py | Header.parse | def parse(self, packet):
"""
There are two formats for headers
old style
---------
Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length.
If the header length is 1 octet (length_type == 3), then there is no Length field.
new style
---------
New style headers can be 2, 3, or 6 octets long and are also composed of a Tag and a Length.
Packet Tag
----------
The packet tag is the first byte, comprising the following fields:
+-------------+----------+---------------+---+---+---+---+----------+----------+
| byte | 1 |
+-------------+----------+---------------+---+---+---+---+----------+----------+
| bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+-------------+----------+---------------+---+---+---+---+----------+----------+
| old-style | always 1 | packet format | packet tag | length type |
| description | | 0 = old-style | | 0 = 1 octet |
| | | 1 = new-style | | 1 = 2 octets |
| | | | | 2 = 5 octets |
| | | | | 3 = no length field |
+-------------+ + +---------------+---------------------+
| new-style | | | packet tag |
| description | | | |
+-------------+----------+---------------+-------------------------------------+
:param packet: raw packet bytes
"""
self._lenfmt = ((packet[0] & 0x40) >> 6)
self.tag = packet[0]
if self._lenfmt == 0:
self.llen = (packet[0] & 0x03)
del packet[0]
if (self._lenfmt == 0 and self.llen > 0) or self._lenfmt == 1:
self.length = packet
else:
# indeterminate packet length
self.length = len(packet) | python | def parse(self, packet):
"""
There are two formats for headers
old style
---------
Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length.
If the header length is 1 octet (length_type == 3), then there is no Length field.
new style
---------
New style headers can be 2, 3, or 6 octets long and are also composed of a Tag and a Length.
Packet Tag
----------
The packet tag is the first byte, comprising the following fields:
+-------------+----------+---------------+---+---+---+---+----------+----------+
| byte | 1 |
+-------------+----------+---------------+---+---+---+---+----------+----------+
| bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+-------------+----------+---------------+---+---+---+---+----------+----------+
| old-style | always 1 | packet format | packet tag | length type |
| description | | 0 = old-style | | 0 = 1 octet |
| | | 1 = new-style | | 1 = 2 octets |
| | | | | 2 = 5 octets |
| | | | | 3 = no length field |
+-------------+ + +---------------+---------------------+
| new-style | | | packet tag |
| description | | | |
+-------------+----------+---------------+-------------------------------------+
:param packet: raw packet bytes
"""
self._lenfmt = ((packet[0] & 0x40) >> 6)
self.tag = packet[0]
if self._lenfmt == 0:
self.llen = (packet[0] & 0x03)
del packet[0]
if (self._lenfmt == 0 and self.llen > 0) or self._lenfmt == 1:
self.length = packet
else:
# indeterminate packet length
self.length = len(packet) | [
"def",
"parse",
"(",
"self",
",",
"packet",
")",
":",
"self",
".",
"_lenfmt",
"=",
"(",
"(",
"packet",
"[",
"0",
"]",
"&",
"0x40",
")",
">>",
"6",
")",
"self",
".",
"tag",
"=",
"packet",
"[",
"0",
"]",
"if",
"self",
".",
"_lenfmt",
"==",
"0",... | There are two formats for headers
old style
---------
Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length.
If the header length is 1 octet (length_type == 3), then there is no Length field.
new style
---------
New style headers can be 2, 3, or 6 octets long and are also composed of a Tag and a Length.
Packet Tag
----------
The packet tag is the first byte, comprising the following fields:
+-------------+----------+---------------+---+---+---+---+----------+----------+
| byte | 1 |
+-------------+----------+---------------+---+---+---+---+----------+----------+
| bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
+-------------+----------+---------------+---+---+---+---+----------+----------+
| old-style | always 1 | packet format | packet tag | length type |
| description | | 0 = old-style | | 0 = 1 octet |
| | | 1 = new-style | | 1 = 2 octets |
| | | | | 2 = 5 octets |
| | | | | 3 = no length field |
+-------------+ + +---------------+---------------------+
| new-style | | | packet tag |
| description | | | |
+-------------+----------+---------------+-------------------------------------+
:param packet: raw packet bytes | [
"There",
"are",
"two",
"formats",
"for",
"headers"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/packet/types.py#L66-L115 | train | 209,990 |
SecurityInnovation/PGPy | pgpy/packet/fields.py | PrivKey.clear | def clear(self):
"""delete and re-initialize all private components to zero"""
for field in self.__privfields__:
delattr(self, field)
setattr(self, field, MPI(0)) | python | def clear(self):
"""delete and re-initialize all private components to zero"""
for field in self.__privfields__:
delattr(self, field)
setattr(self, field, MPI(0)) | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"field",
"in",
"self",
".",
"__privfields__",
":",
"delattr",
"(",
"self",
",",
"field",
")",
"setattr",
"(",
"self",
",",
"field",
",",
"MPI",
"(",
"0",
")",
")"
] | delete and re-initialize all private components to zero | [
"delete",
"and",
"re",
"-",
"initialize",
"all",
"private",
"components",
"to",
"zero"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/packet/fields.py#L1106-L1110 | train | 209,991 |
SecurityInnovation/PGPy | pgpy/types.py | Armorable.ascii_unarmor | def ascii_unarmor(text):
"""
Takes an ASCII-armored PGP block and returns the decoded byte value.
:param text: An ASCII-armored PGP block, to un-armor.
:raises: :py:exc:`ValueError` if ``text`` did not contain an ASCII-armored PGP block.
:raises: :py:exc:`TypeError` if ``text`` is not a ``str``, ``bytes``, or ``bytearray``
:returns: A ``dict`` containing information from ``text``, including the de-armored data.
It can contain the following keys: ``magic``, ``headers``, ``hashes``, ``cleartext``, ``body``, ``crc``.
"""
m = {'magic': None, 'headers': None, 'body': bytearray(), 'crc': None}
if not Armorable.is_ascii(text):
m['body'] = bytearray(text)
return m
if isinstance(text, (bytes, bytearray)): # pragma: no cover
text = text.decode('latin-1')
m = Armorable.__armor_regex.search(text)
if m is None: # pragma: no cover
raise ValueError("Expected: ASCII-armored PGP data")
m = m.groupdict()
if m['hashes'] is not None:
m['hashes'] = m['hashes'].split(',')
if m['headers'] is not None:
m['headers'] = collections.OrderedDict(re.findall('^(?P<key>.+): (?P<value>.+)$\n?', m['headers'], flags=re.MULTILINE))
if m['body'] is not None:
try:
m['body'] = bytearray(base64.b64decode(m['body'].encode()))
except (binascii.Error, TypeError) as ex:
six.raise_from(PGPError, ex)
six.raise_from(PGPError(str(ex)), ex)
if m['crc'] is not None:
m['crc'] = Header.bytes_to_int(base64.b64decode(m['crc'].encode()))
if Armorable.crc24(m['body']) != m['crc']:
warnings.warn('Incorrect crc24', stacklevel=3)
return m | python | def ascii_unarmor(text):
"""
Takes an ASCII-armored PGP block and returns the decoded byte value.
:param text: An ASCII-armored PGP block, to un-armor.
:raises: :py:exc:`ValueError` if ``text`` did not contain an ASCII-armored PGP block.
:raises: :py:exc:`TypeError` if ``text`` is not a ``str``, ``bytes``, or ``bytearray``
:returns: A ``dict`` containing information from ``text``, including the de-armored data.
It can contain the following keys: ``magic``, ``headers``, ``hashes``, ``cleartext``, ``body``, ``crc``.
"""
m = {'magic': None, 'headers': None, 'body': bytearray(), 'crc': None}
if not Armorable.is_ascii(text):
m['body'] = bytearray(text)
return m
if isinstance(text, (bytes, bytearray)): # pragma: no cover
text = text.decode('latin-1')
m = Armorable.__armor_regex.search(text)
if m is None: # pragma: no cover
raise ValueError("Expected: ASCII-armored PGP data")
m = m.groupdict()
if m['hashes'] is not None:
m['hashes'] = m['hashes'].split(',')
if m['headers'] is not None:
m['headers'] = collections.OrderedDict(re.findall('^(?P<key>.+): (?P<value>.+)$\n?', m['headers'], flags=re.MULTILINE))
if m['body'] is not None:
try:
m['body'] = bytearray(base64.b64decode(m['body'].encode()))
except (binascii.Error, TypeError) as ex:
six.raise_from(PGPError, ex)
six.raise_from(PGPError(str(ex)), ex)
if m['crc'] is not None:
m['crc'] = Header.bytes_to_int(base64.b64decode(m['crc'].encode()))
if Armorable.crc24(m['body']) != m['crc']:
warnings.warn('Incorrect crc24', stacklevel=3)
return m | [
"def",
"ascii_unarmor",
"(",
"text",
")",
":",
"m",
"=",
"{",
"'magic'",
":",
"None",
",",
"'headers'",
":",
"None",
",",
"'body'",
":",
"bytearray",
"(",
")",
",",
"'crc'",
":",
"None",
"}",
"if",
"not",
"Armorable",
".",
"is_ascii",
"(",
"text",
... | Takes an ASCII-armored PGP block and returns the decoded byte value.
:param text: An ASCII-armored PGP block, to un-armor.
:raises: :py:exc:`ValueError` if ``text`` did not contain an ASCII-armored PGP block.
:raises: :py:exc:`TypeError` if ``text`` is not a ``str``, ``bytes``, or ``bytearray``
:returns: A ``dict`` containing information from ``text``, including the de-armored data.
It can contain the following keys: ``magic``, ``headers``, ``hashes``, ``cleartext``, ``body``, ``crc``. | [
"Takes",
"an",
"ASCII",
"-",
"armored",
"PGP",
"block",
"and",
"returns",
"the",
"decoded",
"byte",
"value",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/types.py#L108-L152 | train | 209,992 |
SecurityInnovation/PGPy | pgpy/types.py | PGPObject.bytes_to_int | def bytes_to_int(b, order='big'): # pragma: no cover
"""convert bytes to integer"""
if six.PY2:
# save the original type of b without having to copy any data
_b = b.__class__()
if order != 'little':
b = reversed(b)
if not isinstance(_b, bytearray):
b = six.iterbytes(b)
return sum(c << (i * 8) for i, c in enumerate(b))
return int.from_bytes(b, order) | python | def bytes_to_int(b, order='big'): # pragma: no cover
"""convert bytes to integer"""
if six.PY2:
# save the original type of b without having to copy any data
_b = b.__class__()
if order != 'little':
b = reversed(b)
if not isinstance(_b, bytearray):
b = six.iterbytes(b)
return sum(c << (i * 8) for i, c in enumerate(b))
return int.from_bytes(b, order) | [
"def",
"bytes_to_int",
"(",
"b",
",",
"order",
"=",
"'big'",
")",
":",
"# pragma: no cover",
"if",
"six",
".",
"PY2",
":",
"# save the original type of b without having to copy any data",
"_b",
"=",
"b",
".",
"__class__",
"(",
")",
"if",
"order",
"!=",
"'little'... | convert bytes to integer | [
"convert",
"bytes",
"to",
"integer"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/types.py#L265-L278 | train | 209,993 |
SecurityInnovation/PGPy | pgpy/types.py | PGPObject.int_to_bytes | def int_to_bytes(i, minlen=1, order='big'): # pragma: no cover
"""convert integer to bytes"""
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))
return bytes(bytearray((i >> c) & 0xff for c in r))
return i.to_bytes(blen, order) | python | def int_to_bytes(i, minlen=1, order='big'): # pragma: no cover
"""convert integer to bytes"""
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))
return bytes(bytearray((i >> c) & 0xff for c in r))
return i.to_bytes(blen, order) | [
"def",
"int_to_bytes",
"(",
"i",
",",
"minlen",
"=",
"1",
",",
"order",
"=",
"'big'",
")",
":",
"# pragma: no cover",
"blen",
"=",
"max",
"(",
"minlen",
",",
"PGPObject",
".",
"int_byte_len",
"(",
"i",
")",
",",
"1",
")",
"if",
"six",
".",
"PY2",
"... | convert integer to bytes | [
"convert",
"integer",
"to",
"bytes"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/types.py#L281-L289 | train | 209,994 |
SecurityInnovation/PGPy | pgpy/types.py | SorteDeque.check | def check(self): # pragma: no cover
"""re-sort any items in self that are not sorted"""
for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1])):
self.resort(unsorted) | python | def check(self): # pragma: no cover
"""re-sort any items in self that are not sorted"""
for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1])):
self.resort(unsorted) | [
"def",
"check",
"(",
"self",
")",
":",
"# pragma: no cover",
"for",
"unsorted",
"in",
"iter",
"(",
"self",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
"-",
"2",
")",
"if",
"not",
"operator",
".",
"le",
"(",
"self",
"["... | re-sort any items in self that are not sorted | [
"re",
"-",
"sort",
"any",
"items",
"in",
"self",
"that",
"are",
"not",
"sorted"
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/types.py#L747-L750 | train | 209,995 |
SecurityInnovation/PGPy | pgpy/decorators.py | sdmethod | def sdmethod(meth):
"""
This is a hack to monkey patch sdproperty to work as expected with instance methods.
"""
sd = singledispatch(meth)
def wrapper(obj, *args, **kwargs):
return sd.dispatch(args[0].__class__)(obj, *args, **kwargs)
wrapper.register = sd.register
wrapper.dispatch = sd.dispatch
wrapper.registry = sd.registry
wrapper._clear_cache = sd._clear_cache
functools.update_wrapper(wrapper, meth)
return wrapper | python | def sdmethod(meth):
"""
This is a hack to monkey patch sdproperty to work as expected with instance methods.
"""
sd = singledispatch(meth)
def wrapper(obj, *args, **kwargs):
return sd.dispatch(args[0].__class__)(obj, *args, **kwargs)
wrapper.register = sd.register
wrapper.dispatch = sd.dispatch
wrapper.registry = sd.registry
wrapper._clear_cache = sd._clear_cache
functools.update_wrapper(wrapper, meth)
return wrapper | [
"def",
"sdmethod",
"(",
"meth",
")",
":",
"sd",
"=",
"singledispatch",
"(",
"meth",
")",
"def",
"wrapper",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"sd",
".",
"dispatch",
"(",
"args",
"[",
"0",
"]",
".",
"__class... | This is a hack to monkey patch sdproperty to work as expected with instance methods. | [
"This",
"is",
"a",
"hack",
"to",
"monkey",
"patch",
"sdproperty",
"to",
"work",
"as",
"expected",
"with",
"instance",
"methods",
"."
] | f1c3d68e32c334f5aa14c34580925e97f17f4fde | https://github.com/SecurityInnovation/PGPy/blob/f1c3d68e32c334f5aa14c34580925e97f17f4fde/pgpy/decorators.py#L41-L55 | train | 209,996 |
tortilla/tortilla | tortilla/formatters.py | mixedcase | def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) | python | def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) | [
"def",
"mixedcase",
"(",
"path",
")",
":",
"words",
"=",
"path",
".",
"split",
"(",
"'_'",
")",
"return",
"words",
"[",
"0",
"]",
"+",
"''",
".",
"join",
"(",
"word",
".",
"title",
"(",
")",
"for",
"word",
"in",
"words",
"[",
"1",
":",
"]",
"... | Removes underscores and capitalizes the neighbouring character | [
"Removes",
"underscores",
"and",
"capitalizes",
"the",
"neighbouring",
"character"
] | eccc8a268307e9bea98f12f958f48bb03ff115b7 | https://github.com/tortilla/tortilla/blob/eccc8a268307e9bea98f12f958f48bb03ff115b7/tortilla/formatters.py#L9-L12 | train | 209,997 |
tortilla/tortilla | tortilla/wrappers.py | Client._log | def _log(self, message, debug=None, **kwargs):
"""Outputs a formatted message in the console if the
debug mode is activated.
:param message: The message that will be printed
:param debug: (optional) Overwrite of `Client.debug`
:param kwargs: (optional) Arguments that will be passed
to the `str.format()` method
"""
display_log = self.debug
if debug is not None:
display_log = debug
if display_log:
print(message.format(**kwargs)) | python | def _log(self, message, debug=None, **kwargs):
"""Outputs a formatted message in the console if the
debug mode is activated.
:param message: The message that will be printed
:param debug: (optional) Overwrite of `Client.debug`
:param kwargs: (optional) Arguments that will be passed
to the `str.format()` method
"""
display_log = self.debug
if debug is not None:
display_log = debug
if display_log:
print(message.format(**kwargs)) | [
"def",
"_log",
"(",
"self",
",",
"message",
",",
"debug",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"display_log",
"=",
"self",
".",
"debug",
"if",
"debug",
"is",
"not",
"None",
":",
"display_log",
"=",
"debug",
"if",
"display_log",
":",
"print... | Outputs a formatted message in the console if the
debug mode is activated.
:param message: The message that will be printed
:param debug: (optional) Overwrite of `Client.debug`
:param kwargs: (optional) Arguments that will be passed
to the `str.format()` method | [
"Outputs",
"a",
"formatted",
"message",
"in",
"the",
"console",
"if",
"the",
"debug",
"mode",
"is",
"activated",
"."
] | eccc8a268307e9bea98f12f958f48bb03ff115b7 | https://github.com/tortilla/tortilla/blob/eccc8a268307e9bea98f12f958f48bb03ff115b7/tortilla/wrappers.py#L87-L100 | train | 209,998 |
tortilla/tortilla | tortilla/wrappers.py | Client.send_request | def send_request(self, *args, **kwargs):
"""Wrapper for session.request
Handle connection reset error even from pyopenssl
"""
try:
return self.session.request(*args, **kwargs)
except ConnectionError:
self.session.close()
return self.session.request(*args, **kwargs) | python | def send_request(self, *args, **kwargs):
"""Wrapper for session.request
Handle connection reset error even from pyopenssl
"""
try:
return self.session.request(*args, **kwargs)
except ConnectionError:
self.session.close()
return self.session.request(*args, **kwargs) | [
"def",
"send_request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"session",
".",
"request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"ConnectionError",
":",
"self",
".",
"s... | Wrapper for session.request
Handle connection reset error even from pyopenssl | [
"Wrapper",
"for",
"session",
".",
"request",
"Handle",
"connection",
"reset",
"error",
"even",
"from",
"pyopenssl"
] | eccc8a268307e9bea98f12f958f48bb03ff115b7 | https://github.com/tortilla/tortilla/blob/eccc8a268307e9bea98f12f958f48bb03ff115b7/tortilla/wrappers.py#L102-L110 | train | 209,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.