repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Feneric/doxypypy | doxypypy/doxypypy.py | AstWalker.visit_Module | def visit_Module(self, node, **kwargs):
"""
Handles the module-level docstring.
Process the module-level docstring and create appropriate Doxygen tags
if autobrief option is set.
"""
containingNodes=kwargs.get('containingNodes', [])
if self.options.debug:
... | python | def visit_Module(self, node, **kwargs):
"""
Handles the module-level docstring.
Process the module-level docstring and create appropriate Doxygen tags
if autobrief option is set.
"""
containingNodes=kwargs.get('containingNodes', [])
if self.options.debug:
... | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
",",
"**",
"kwargs",
")",
":",
"containingNodes",
"=",
"kwargs",
".",
"get",
"(",
"'containingNodes'",
",",
"[",
"]",
")",
"if",
"self",
".",
"options",
".",
"debug",
":",
"stderr",
".",
"write",
"(",
... | Handles the module-level docstring.
Process the module-level docstring and create appropriate Doxygen tags
if autobrief option is set. | [
"Handles",
"the",
"module",
"-",
"level",
"docstring",
"."
] | a8555b15fa2a758ea8392372de31c0f635cc0d93 | https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L594-L614 | train |
Feneric/doxypypy | doxypypy/doxypypy.py | AstWalker.visit_Assign | def visit_Assign(self, node, **kwargs):
"""
Handles assignments within code.
Variable assignments in Python are used to represent interface
attributes in addition to basic variables. If an assignment appears
to be an attribute, it gets labeled as such for Doxygen. If a variabl... | python | def visit_Assign(self, node, **kwargs):
"""
Handles assignments within code.
Variable assignments in Python are used to represent interface
attributes in addition to basic variables. If an assignment appears
to be an attribute, it gets labeled as such for Doxygen. If a variabl... | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
",",
"**",
"kwargs",
")",
":",
"lineNum",
"=",
"node",
".",
"lineno",
"-",
"1",
"match",
"=",
"AstWalker",
".",
"__attributeRE",
".",
"match",
"(",
"self",
".",
"lines",
"[",
"lineNum",
"]",
")",
"if",... | Handles assignments within code.
Variable assignments in Python are used to represent interface
attributes in addition to basic variables. If an assignment appears
to be an attribute, it gets labeled as such for Doxygen. If a variable
name uses Python mangling or is just a bed lump, i... | [
"Handles",
"assignments",
"within",
"code",
"."
] | a8555b15fa2a758ea8392372de31c0f635cc0d93 | https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L616-L656 | train |
Feneric/doxypypy | doxypypy/doxypypy.py | AstWalker.visit_Call | def visit_Call(self, node, **kwargs):
"""
Handles function calls within code.
Function calls in Python are used to represent interface implementations
in addition to their normal use. If a call appears to mark an
implementation, it gets labeled as such for Doxygen.
"""
... | python | def visit_Call(self, node, **kwargs):
"""
Handles function calls within code.
Function calls in Python are used to represent interface implementations
in addition to their normal use. If a call appears to mark an
implementation, it gets labeled as such for Doxygen.
"""
... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
",",
"**",
"kwargs",
")",
":",
"lineNum",
"=",
"node",
".",
"lineno",
"-",
"1",
"match",
"=",
"AstWalker",
".",
"__implementsRE",
".",
"match",
"(",
"self",
".",
"lines",
"[",
"lineNum",
"]",
")",
"if",
... | Handles function calls within code.
Function calls in Python are used to represent interface implementations
in addition to their normal use. If a call appears to mark an
implementation, it gets labeled as such for Doxygen. | [
"Handles",
"function",
"calls",
"within",
"code",
"."
] | a8555b15fa2a758ea8392372de31c0f635cc0d93 | https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L658-L678 | train |
Feneric/doxypypy | doxypypy/doxypypy.py | AstWalker.visit_FunctionDef | def visit_FunctionDef(self, node, **kwargs):
"""
Handles function definitions within code.
Process a function's docstring, keeping well aware of the function's
context and whether or not it's part of an interface definition.
"""
if self.options.debug:
stderr.... | python | def visit_FunctionDef(self, node, **kwargs):
"""
Handles function definitions within code.
Process a function's docstring, keeping well aware of the function's
context and whether or not it's part of an interface definition.
"""
if self.options.debug:
stderr.... | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
",",
"**",
"kwargs",
")",
":",
"if",
"self",
".",
"options",
".",
"debug",
":",
"stderr",
".",
"write",
"(",
"\"# Function {0.name}{1}\"",
".",
"format",
"(",
"node",
",",
"linesep",
")",
")",
"contai... | Handles function definitions within code.
Process a function's docstring, keeping well aware of the function's
context and whether or not it's part of an interface definition. | [
"Handles",
"function",
"definitions",
"within",
"code",
"."
] | a8555b15fa2a758ea8392372de31c0f635cc0d93 | https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L680-L708 | train |
Feneric/doxypypy | doxypypy/doxypypy.py | AstWalker.visit_ClassDef | def visit_ClassDef(self, node, **kwargs):
"""
Handles class definitions within code.
Process the docstring. Note though that in Python Class definitions
are used to define interfaces in addition to classes.
If a class definition appears to be an interface definition tag it as a... | python | def visit_ClassDef(self, node, **kwargs):
"""
Handles class definitions within code.
Process the docstring. Note though that in Python Class definitions
are used to define interfaces in addition to classes.
If a class definition appears to be an interface definition tag it as a... | [
"def",
"visit_ClassDef",
"(",
"self",
",",
"node",
",",
"**",
"kwargs",
")",
":",
"lineNum",
"=",
"node",
".",
"lineno",
"-",
"1",
"containingNodes",
"=",
"kwargs",
".",
"get",
"(",
"'containingNodes'",
")",
"or",
"[",
"]",
"if",
"not",
"self",
".",
... | Handles class definitions within code.
Process the docstring. Note though that in Python Class definitions
are used to define interfaces in addition to classes.
If a class definition appears to be an interface definition tag it as an
interface definition for Doxygen. Otherwise tag it ... | [
"Handles",
"class",
"definitions",
"within",
"code",
"."
] | a8555b15fa2a758ea8392372de31c0f635cc0d93 | https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L710-L766 | train |
Feneric/doxypypy | doxypypy/doxypypy.py | AstWalker.parseLines | def parseLines(self):
"""Form an AST for the code and produce a new version of the source."""
inAst = parse(''.join(self.lines), self.inFilename)
# Visit all the nodes in our tree and apply Doxygen tags to the source.
self.visit(inAst) | python | def parseLines(self):
"""Form an AST for the code and produce a new version of the source."""
inAst = parse(''.join(self.lines), self.inFilename)
# Visit all the nodes in our tree and apply Doxygen tags to the source.
self.visit(inAst) | [
"def",
"parseLines",
"(",
"self",
")",
":",
"inAst",
"=",
"parse",
"(",
"''",
".",
"join",
"(",
"self",
".",
"lines",
")",
",",
"self",
".",
"inFilename",
")",
"self",
".",
"visit",
"(",
"inAst",
")"
] | Form an AST for the code and produce a new version of the source. | [
"Form",
"an",
"AST",
"for",
"the",
"code",
"and",
"produce",
"a",
"new",
"version",
"of",
"the",
"source",
"."
] | a8555b15fa2a758ea8392372de31c0f635cc0d93 | https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L768-L772 | train |
Miserlou/django-zappa | django_zappa/handler.py | lambda_handler | def lambda_handler(event, context=None, settings_name="zappa_settings"): # NoQA
"""
An AWS Lambda function which parses specific API Gateway input into a WSGI request.
The request get fed it to Django, processes the Django response, and returns that
back to the API Gateway.
"""
time_start = da... | python | def lambda_handler(event, context=None, settings_name="zappa_settings"): # NoQA
"""
An AWS Lambda function which parses specific API Gateway input into a WSGI request.
The request get fed it to Django, processes the Django response, and returns that
back to the API Gateway.
"""
time_start = da... | [
"def",
"lambda_handler",
"(",
"event",
",",
"context",
"=",
"None",
",",
"settings_name",
"=",
"\"zappa_settings\"",
")",
":",
"time_start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"settings",
".",
"DEBUG",
":",
"logger",
".",
"info",... | An AWS Lambda function which parses specific API Gateway input into a WSGI request.
The request get fed it to Django, processes the Django response, and returns that
back to the API Gateway. | [
"An",
"AWS",
"Lambda",
"function",
"which",
"parses",
"specific",
"API",
"Gateway",
"input",
"into",
"a",
"WSGI",
"request",
"."
] | 7a8083ab6257a0bf0f5c9ae460afabd4de4e2215 | https://github.com/Miserlou/django-zappa/blob/7a8083ab6257a0bf0f5c9ae460afabd4de4e2215/django_zappa/handler.py#L41-L126 | train |
Miserlou/django-zappa | django_zappa/management/commands/zappa_command.py | ZappaCommand.require_settings | def require_settings(self, args, options):
"""
Load the ZAPPA_SETTINGS as we expect it.
"""
if not options.has_key('environment'):
print(
"You must call deploy with an environment name. \n python manage.py deploy <environment>")
raise ImproperlyC... | python | def require_settings(self, args, options):
"""
Load the ZAPPA_SETTINGS as we expect it.
"""
if not options.has_key('environment'):
print(
"You must call deploy with an environment name. \n python manage.py deploy <environment>")
raise ImproperlyC... | [
"def",
"require_settings",
"(",
"self",
",",
"args",
",",
"options",
")",
":",
"if",
"not",
"options",
".",
"has_key",
"(",
"'environment'",
")",
":",
"print",
"(",
"\"You must call deploy with an environment name. \\n python manage.py deploy <environment>\"",
")",
"rai... | Load the ZAPPA_SETTINGS as we expect it. | [
"Load",
"the",
"ZAPPA_SETTINGS",
"as",
"we",
"expect",
"it",
"."
] | 7a8083ab6257a0bf0f5c9ae460afabd4de4e2215 | https://github.com/Miserlou/django-zappa/blob/7a8083ab6257a0bf0f5c9ae460afabd4de4e2215/django_zappa/management/commands/zappa_command.py#L43-L98 | train |
adamcharnock/swiftwind | swiftwind/housemates/forms.py | HousemateCreateForm.clean_account | def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES.income:
raise ValidationError('Account must be an income account')
try:
account.hou... | python | def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES.income:
raise ValidationError('Account must be an income account')
try:
account.hou... | [
"def",
"clean_account",
"(",
"self",
")",
":",
"account",
"=",
"self",
".",
"cleaned_data",
"[",
"'account'",
"]",
"if",
"not",
"account",
":",
"return",
"if",
"account",
".",
"type",
"!=",
"Account",
".",
"TYPES",
".",
"income",
":",
"raise",
"Validatio... | Ensure this is an income account | [
"Ensure",
"this",
"is",
"an",
"income",
"account"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/housemates/forms.py#L28-L44 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.get_amount_normal | def get_amount_normal(self, billing_cycle):
"""Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle.
"""
if self.is_one_off():
... | python | def get_amount_normal(self, billing_cycle):
"""Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle.
"""
if self.is_one_off():
... | [
"def",
"get_amount_normal",
"(",
"self",
",",
"billing_cycle",
")",
":",
"if",
"self",
".",
"is_one_off",
"(",
")",
":",
"billing_cycle_number",
"=",
"self",
".",
"_get_billing_cycle_number",
"(",
"billing_cycle",
")",
"if",
"billing_cycle_number",
">",
"self",
... | Get the amount due on the given billing cycle
For regular recurring costs this is simply `fixed_amount`. For
one-off costs this is the portion of `fixed_amount` for the given
billing_cycle. | [
"Get",
"the",
"amount",
"due",
"on",
"the",
"given",
"billing",
"cycle"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L121-L144 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.get_amount_arrears_balance | def get_amount_arrears_balance(self, billing_cycle):
"""Get the balance of to_account at the end of billing_cycle"""
return self.to_account.balance(
transaction__date__lt=billing_cycle.date_range.lower,
) | python | def get_amount_arrears_balance(self, billing_cycle):
"""Get the balance of to_account at the end of billing_cycle"""
return self.to_account.balance(
transaction__date__lt=billing_cycle.date_range.lower,
) | [
"def",
"get_amount_arrears_balance",
"(",
"self",
",",
"billing_cycle",
")",
":",
"return",
"self",
".",
"to_account",
".",
"balance",
"(",
"transaction__date__lt",
"=",
"billing_cycle",
".",
"date_range",
".",
"lower",
",",
")"
] | Get the balance of to_account at the end of billing_cycle | [
"Get",
"the",
"balance",
"of",
"to_account",
"at",
"the",
"end",
"of",
"billing_cycle"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L146-L150 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.get_amount_arrears_transactions | def get_amount_arrears_transactions(self, billing_cycle):
"""Get the sum of all transaction legs in to_account during given billing cycle"""
previous_billing_cycle = billing_cycle.get_previous()
if not previous_billing_cycle:
return Decimal(0)
return self.to_account.balance(
... | python | def get_amount_arrears_transactions(self, billing_cycle):
"""Get the sum of all transaction legs in to_account during given billing cycle"""
previous_billing_cycle = billing_cycle.get_previous()
if not previous_billing_cycle:
return Decimal(0)
return self.to_account.balance(
... | [
"def",
"get_amount_arrears_transactions",
"(",
"self",
",",
"billing_cycle",
")",
":",
"previous_billing_cycle",
"=",
"billing_cycle",
".",
"get_previous",
"(",
")",
"if",
"not",
"previous_billing_cycle",
":",
"return",
"Decimal",
"(",
"0",
")",
"return",
"self",
... | Get the sum of all transaction legs in to_account during given billing cycle | [
"Get",
"the",
"sum",
"of",
"all",
"transaction",
"legs",
"in",
"to_account",
"during",
"given",
"billing",
"cycle"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L152-L160 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.enact | def enact(self, billing_cycle, disable_if_done=True):
"""Enact this RecurringCost for the given billing cycle
This will:
- Create a RecurredCost and the relevant Transactions & Transaction Legs
- Mark this RecurringCost as disabled if this is its final billing cycle
"""
... | python | def enact(self, billing_cycle, disable_if_done=True):
"""Enact this RecurringCost for the given billing cycle
This will:
- Create a RecurredCost and the relevant Transactions & Transaction Legs
- Mark this RecurringCost as disabled if this is its final billing cycle
"""
... | [
"def",
"enact",
"(",
"self",
",",
"billing_cycle",
",",
"disable_if_done",
"=",
"True",
")",
":",
"as_of",
"=",
"billing_cycle",
".",
"date_range",
".",
"lower",
"if",
"not",
"self",
".",
"is_enactable",
"(",
"as_of",
")",
":",
"raise",
"CannotEnactUnenactab... | Enact this RecurringCost for the given billing cycle
This will:
- Create a RecurredCost and the relevant Transactions & Transaction Legs
- Mark this RecurringCost as disabled if this is its final billing cycle | [
"Enact",
"this",
"RecurringCost",
"for",
"the",
"given",
"billing",
"cycle"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L166-L194 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.disable_if_done | def disable_if_done(self, commit=True):
"""Set disabled=True if we have billed all we need to
Will only have an effect on one-off costs.
"""
if self._is_billing_complete() and not self.disabled:
self.disabled = True
if commit:
self.save() | python | def disable_if_done(self, commit=True):
"""Set disabled=True if we have billed all we need to
Will only have an effect on one-off costs.
"""
if self._is_billing_complete() and not self.disabled:
self.disabled = True
if commit:
self.save() | [
"def",
"disable_if_done",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"if",
"self",
".",
"_is_billing_complete",
"(",
")",
"and",
"not",
"self",
".",
"disabled",
":",
"self",
".",
"disabled",
"=",
"True",
"if",
"commit",
":",
"self",
".",
"save"... | Set disabled=True if we have billed all we need to
Will only have an effect on one-off costs. | [
"Set",
"disabled",
"=",
"True",
"if",
"we",
"have",
"billed",
"all",
"we",
"need",
"to"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L196-L205 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.is_enactable | def is_enactable(self, as_of):
"""Can this RecurringCost be enacted"""
return \
not self.disabled and \
not self.archived and \
not self._is_finished(as_of) and \
self._is_ready(as_of) and \
not self._is_billing_complete() | python | def is_enactable(self, as_of):
"""Can this RecurringCost be enacted"""
return \
not self.disabled and \
not self.archived and \
not self._is_finished(as_of) and \
self._is_ready(as_of) and \
not self._is_billing_complete() | [
"def",
"is_enactable",
"(",
"self",
",",
"as_of",
")",
":",
"return",
"not",
"self",
".",
"disabled",
"and",
"not",
"self",
".",
"archived",
"and",
"not",
"self",
".",
"_is_finished",
"(",
"as_of",
")",
"and",
"self",
".",
"_is_ready",
"(",
"as_of",
")... | Can this RecurringCost be enacted | [
"Can",
"this",
"RecurringCost",
"be",
"enacted"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L217-L224 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost.has_enacted | def has_enacted(self, billing_cycle):
"""Has this recurring cost already enacted transactions for given billing cycle?"""
return RecurredCost.objects.filter(
recurring_cost=self,
billing_cycle=billing_cycle,
).exists() | python | def has_enacted(self, billing_cycle):
"""Has this recurring cost already enacted transactions for given billing cycle?"""
return RecurredCost.objects.filter(
recurring_cost=self,
billing_cycle=billing_cycle,
).exists() | [
"def",
"has_enacted",
"(",
"self",
",",
"billing_cycle",
")",
":",
"return",
"RecurredCost",
".",
"objects",
".",
"filter",
"(",
"recurring_cost",
"=",
"self",
",",
"billing_cycle",
"=",
"billing_cycle",
",",
")",
".",
"exists",
"(",
")"
] | Has this recurring cost already enacted transactions for given billing cycle? | [
"Has",
"this",
"recurring",
"cost",
"already",
"enacted",
"transactions",
"for",
"given",
"billing",
"cycle?"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L226-L231 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost._is_ready | def _is_ready(self, as_of):
"""Is the RecurringCost ready to be enacted as of the date `as_of`
This determines if `as_of` precedes the start of `initial_billing_cycle`. If so,
we should not be enacting this RecurringCost yet.
Args:
as_of (Date):
"""
if self.... | python | def _is_ready(self, as_of):
"""Is the RecurringCost ready to be enacted as of the date `as_of`
This determines if `as_of` precedes the start of `initial_billing_cycle`. If so,
we should not be enacting this RecurringCost yet.
Args:
as_of (Date):
"""
if self.... | [
"def",
"_is_ready",
"(",
"self",
",",
"as_of",
")",
":",
"if",
"self",
".",
"is_one_off",
"(",
")",
":",
"return",
"self",
".",
"initial_billing_cycle",
".",
"date_range",
".",
"lower",
"<=",
"as_of",
"else",
":",
"return",
"True"
] | Is the RecurringCost ready to be enacted as of the date `as_of`
This determines if `as_of` precedes the start of `initial_billing_cycle`. If so,
we should not be enacting this RecurringCost yet.
Args:
as_of (Date): | [
"Is",
"the",
"RecurringCost",
"ready",
"to",
"be",
"enacted",
"as",
"of",
"the",
"date",
"as_of"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L236-L248 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost._is_finished | def _is_finished(self, as_of):
"""Have the specified number of billing cycles been completed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
last_billing_cycle = self.get_billing_cycles()[self.total_billing_cycles - 1]
return last_... | python | def _is_finished(self, as_of):
"""Have the specified number of billing cycles been completed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
last_billing_cycle = self.get_billing_cycles()[self.total_billing_cycles - 1]
return last_... | [
"def",
"_is_finished",
"(",
"self",
",",
"as_of",
")",
":",
"if",
"self",
".",
"is_one_off",
"(",
")",
":",
"last_billing_cycle",
"=",
"self",
".",
"get_billing_cycles",
"(",
")",
"[",
"self",
".",
"total_billing_cycles",
"-",
"1",
"]",
"return",
"last_bil... | Have the specified number of billing cycles been completed?
If so, we should not be enacting this RecurringCost. | [
"Have",
"the",
"specified",
"number",
"of",
"billing",
"cycles",
"been",
"completed?"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L250-L259 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost._is_billing_complete | def _is_billing_complete(self):
"""Has the specified `fixed_amount` been billed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
return self.get_billed_amount() >= Balance(self.fixed_amount, self.currency)
else:
return False | python | def _is_billing_complete(self):
"""Has the specified `fixed_amount` been billed?
If so, we should not be enacting this RecurringCost.
"""
if self.is_one_off():
return self.get_billed_amount() >= Balance(self.fixed_amount, self.currency)
else:
return False | [
"def",
"_is_billing_complete",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_one_off",
"(",
")",
":",
"return",
"self",
".",
"get_billed_amount",
"(",
")",
">=",
"Balance",
"(",
"self",
".",
"fixed_amount",
",",
"self",
".",
"currency",
")",
"else",
":",... | Has the specified `fixed_amount` been billed?
If so, we should not be enacting this RecurringCost. | [
"Has",
"the",
"specified",
"fixed_amount",
"been",
"billed?"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L261-L269 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCost._get_billing_cycle_number | def _get_billing_cycle_number(self, billing_cycle):
"""Gets the 1-indexed number of the billing cycle relative to the provided billing cycle"""
begins_before_initial_date = billing_cycle.date_range.lower < self.initial_billing_cycle.date_range.lower
if begins_before_initial_date:
rai... | python | def _get_billing_cycle_number(self, billing_cycle):
"""Gets the 1-indexed number of the billing cycle relative to the provided billing cycle"""
begins_before_initial_date = billing_cycle.date_range.lower < self.initial_billing_cycle.date_range.lower
if begins_before_initial_date:
rai... | [
"def",
"_get_billing_cycle_number",
"(",
"self",
",",
"billing_cycle",
")",
":",
"begins_before_initial_date",
"=",
"billing_cycle",
".",
"date_range",
".",
"lower",
"<",
"self",
".",
"initial_billing_cycle",
".",
"date_range",
".",
"lower",
"if",
"begins_before_initi... | Gets the 1-indexed number of the billing cycle relative to the provided billing cycle | [
"Gets",
"the",
"1",
"-",
"indexed",
"number",
"of",
"the",
"billing",
"cycle",
"relative",
"to",
"the",
"provided",
"billing",
"cycle"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L271-L287 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurringCostSplitQuerySet.split | def split(self, amount):
"""Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal)
"""
split_objs... | python | def split(self, amount):
"""Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal)
"""
split_objs... | [
"def",
"split",
"(",
"self",
",",
"amount",
")",
":",
"split_objs",
"=",
"list",
"(",
"self",
".",
"all",
"(",
")",
")",
"if",
"not",
"split_objs",
":",
"raise",
"NoSplitsFoundForRecurringCost",
"(",
")",
"portions",
"=",
"[",
"split_obj",
".",
"portion"... | Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal) | [
"Split",
"the",
"value",
"given",
"by",
"amount",
"according",
"to",
"the",
"RecurringCostSplit",
"s",
"portions"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L300-L320 | train |
adamcharnock/swiftwind | swiftwind/costs/models.py | RecurredCost.make_transaction | def make_transaction(self):
"""Create the transaction for this RecurredCost
May only be used to create the RecurredCost's initial transaction.
Returns:
Transaction: The created transaction, also assigned to self.transaction. None if the amount is zero.
"""
if self.p... | python | def make_transaction(self):
"""Create the transaction for this RecurredCost
May only be used to create the RecurredCost's initial transaction.
Returns:
Transaction: The created transaction, also assigned to self.transaction. None if the amount is zero.
"""
if self.p... | [
"def",
"make_transaction",
"(",
"self",
")",
":",
"if",
"self",
".",
"pk",
":",
"raise",
"CannotRecreateTransactionOnRecurredCost",
"(",
"'The transaction for this recurred cost has already been created. You cannot create it again.'",
")",
"amount",
"=",
"self",
".",
"recurri... | Create the transaction for this RecurredCost
May only be used to create the RecurredCost's initial transaction.
Returns:
Transaction: The created transaction, also assigned to self.transaction. None if the amount is zero. | [
"Create",
"the",
"transaction",
"for",
"this",
"RecurredCost"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L357-L405 | train |
adamcharnock/swiftwind | swiftwind/billing_cycle/models.py | BillingCycle.populate | def populate(cls, as_of=None):
"""Ensure the next X years of billing cycles exist
"""
return cls._populate(as_of=as_of or date.today(), delete=True) | python | def populate(cls, as_of=None):
"""Ensure the next X years of billing cycles exist
"""
return cls._populate(as_of=as_of or date.today(), delete=True) | [
"def",
"populate",
"(",
"cls",
",",
"as_of",
"=",
"None",
")",
":",
"return",
"cls",
".",
"_populate",
"(",
"as_of",
"=",
"as_of",
"or",
"date",
".",
"today",
"(",
")",
",",
"delete",
"=",
"True",
")"
] | Ensure the next X years of billing cycles exist | [
"Ensure",
"the",
"next",
"X",
"years",
"of",
"billing",
"cycles",
"exist"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/billing_cycle/models.py#L78-L81 | train |
adamcharnock/swiftwind | swiftwind/billing_cycle/models.py | BillingCycle._populate | def _populate(cls, as_of=None, delete=False):
"""Populate the table with billing cycles starting from `as_of`
Args:
as_of (date): The date at which to begin the populating
delete (bool): Should future billing cycles be deleted?
"""
billing_cycle_helper = get_bi... | python | def _populate(cls, as_of=None, delete=False):
"""Populate the table with billing cycles starting from `as_of`
Args:
as_of (date): The date at which to begin the populating
delete (bool): Should future billing cycles be deleted?
"""
billing_cycle_helper = get_bi... | [
"def",
"_populate",
"(",
"cls",
",",
"as_of",
"=",
"None",
",",
"delete",
"=",
"False",
")",
":",
"billing_cycle_helper",
"=",
"get_billing_cycle",
"(",
")",
"billing_cycles_exist",
"=",
"BillingCycle",
".",
"objects",
".",
"exists",
"(",
")",
"try",
":",
... | Populate the table with billing cycles starting from `as_of`
Args:
as_of (date): The date at which to begin the populating
delete (bool): Should future billing cycles be deleted? | [
"Populate",
"the",
"table",
"with",
"billing",
"cycles",
"starting",
"from",
"as_of"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/billing_cycle/models.py#L92-L146 | train |
adamcharnock/swiftwind | swiftwind/billing_cycle/models.py | BillingCycle.get_next | def get_next(self):
"""Get the billing cycle after this one. May return None"""
return BillingCycle.objects.filter(date_range__gt=self.date_range).order_by('date_range').first() | python | def get_next(self):
"""Get the billing cycle after this one. May return None"""
return BillingCycle.objects.filter(date_range__gt=self.date_range).order_by('date_range').first() | [
"def",
"get_next",
"(",
"self",
")",
":",
"return",
"BillingCycle",
".",
"objects",
".",
"filter",
"(",
"date_range__gt",
"=",
"self",
".",
"date_range",
")",
".",
"order_by",
"(",
"'date_range'",
")",
".",
"first",
"(",
")"
] | Get the billing cycle after this one. May return None | [
"Get",
"the",
"billing",
"cycle",
"after",
"this",
"one",
".",
"May",
"return",
"None"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/billing_cycle/models.py#L148-L150 | train |
adamcharnock/swiftwind | swiftwind/billing_cycle/models.py | BillingCycle.get_previous | def get_previous(self):
"""Get the billing cycle prior to this one. May return None"""
return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last() | python | def get_previous(self):
"""Get the billing cycle prior to this one. May return None"""
return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last() | [
"def",
"get_previous",
"(",
"self",
")",
":",
"return",
"BillingCycle",
".",
"objects",
".",
"filter",
"(",
"date_range__lt",
"=",
"self",
".",
"date_range",
")",
".",
"order_by",
"(",
"'date_range'",
")",
".",
"last",
"(",
")"
] | Get the billing cycle prior to this one. May return None | [
"Get",
"the",
"billing",
"cycle",
"prior",
"to",
"this",
"one",
".",
"May",
"return",
"None"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/billing_cycle/models.py#L152-L154 | train |
adamcharnock/swiftwind | swiftwind/billing_cycle/models.py | BillingCycle.is_reconciled | def is_reconciled(self):
"""Have transactions been imported and reconciled for this billing cycle?"""
from hordak.models import StatementImport, StatementLine
since = datetime(
self.date_range.lower.year,
self.date_range.lower.month,
self.date_range.lower.day,... | python | def is_reconciled(self):
"""Have transactions been imported and reconciled for this billing cycle?"""
from hordak.models import StatementImport, StatementLine
since = datetime(
self.date_range.lower.year,
self.date_range.lower.month,
self.date_range.lower.day,... | [
"def",
"is_reconciled",
"(",
"self",
")",
":",
"from",
"hordak",
".",
"models",
"import",
"StatementImport",
",",
"StatementLine",
"since",
"=",
"datetime",
"(",
"self",
".",
"date_range",
".",
"lower",
".",
"year",
",",
"self",
".",
"date_range",
".",
"lo... | Have transactions been imported and reconciled for this billing cycle? | [
"Have",
"transactions",
"been",
"imported",
"and",
"reconciled",
"for",
"this",
"billing",
"cycle?"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/billing_cycle/models.py#L156-L178 | train |
di/pip-api | pip_api/_hash.py | hash | def hash(filename, algorithm='sha256'):
"""
Hash the given filename. Unavailable in `pip<8.0.0`
"""
if incompatible:
raise Incompatible
if algorithm not in ['sha256', 'sha384', 'sha512']:
raise InvalidArguments('Algorithm {} not supported'.format(algorithm))
result = call('hash... | python | def hash(filename, algorithm='sha256'):
"""
Hash the given filename. Unavailable in `pip<8.0.0`
"""
if incompatible:
raise Incompatible
if algorithm not in ['sha256', 'sha384', 'sha512']:
raise InvalidArguments('Algorithm {} not supported'.format(algorithm))
result = call('hash... | [
"def",
"hash",
"(",
"filename",
",",
"algorithm",
"=",
"'sha256'",
")",
":",
"if",
"incompatible",
":",
"raise",
"Incompatible",
"if",
"algorithm",
"not",
"in",
"[",
"'sha256'",
",",
"'sha384'",
",",
"'sha512'",
"]",
":",
"raise",
"InvalidArguments",
"(",
... | Hash the given filename. Unavailable in `pip<8.0.0` | [
"Hash",
"the",
"given",
"filename",
".",
"Unavailable",
"in",
"pip<8",
".",
"0",
".",
"0"
] | 6824afa634484eca258b2f757a35b7df8ebf56d7 | https://github.com/di/pip-api/blob/6824afa634484eca258b2f757a35b7df8ebf56d7/pip_api/_hash.py#L10-L24 | train |
adamcharnock/swiftwind | swiftwind/core/templatetags/swiftwind_utilities.py | partition | def partition(list_, columns=2):
"""
Break a list into ``columns`` number of columns.
"""
iter_ = iter(list_)
columns = int(columns)
rows = []
while True:
row = []
for column_number in range(1, columns + 1):
try:
value = six.next(iter_)
... | python | def partition(list_, columns=2):
"""
Break a list into ``columns`` number of columns.
"""
iter_ = iter(list_)
columns = int(columns)
rows = []
while True:
row = []
for column_number in range(1, columns + 1):
try:
value = six.next(iter_)
... | [
"def",
"partition",
"(",
"list_",
",",
"columns",
"=",
"2",
")",
":",
"iter_",
"=",
"iter",
"(",
"list_",
")",
"columns",
"=",
"int",
"(",
"columns",
")",
"rows",
"=",
"[",
"]",
"while",
"True",
":",
"row",
"=",
"[",
"]",
"for",
"column_number",
... | Break a list into ``columns`` number of columns. | [
"Break",
"a",
"list",
"into",
"columns",
"number",
"of",
"columns",
"."
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/core/templatetags/swiftwind_utilities.py#L8-L29 | train |
adamcharnock/swiftwind | swiftwind/dashboard/views.py | DashboardView.get_balance_context | def get_balance_context(self):
"""Get the high level balances"""
bank_account = Account.objects.get(name='Bank')
return dict(
bank=bank_account,
retained_earnings_accounts=Account.objects.filter(parent__name='Retained Earnings'),
) | python | def get_balance_context(self):
"""Get the high level balances"""
bank_account = Account.objects.get(name='Bank')
return dict(
bank=bank_account,
retained_earnings_accounts=Account.objects.filter(parent__name='Retained Earnings'),
) | [
"def",
"get_balance_context",
"(",
"self",
")",
":",
"bank_account",
"=",
"Account",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"'Bank'",
")",
"return",
"dict",
"(",
"bank",
"=",
"bank_account",
",",
"retained_earnings_accounts",
"=",
"Account",
".",
"obj... | Get the high level balances | [
"Get",
"the",
"high",
"level",
"balances"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/dashboard/views.py#L15-L22 | train |
adamcharnock/swiftwind | swiftwind/dashboard/views.py | DashboardView.get_accounts_context | def get_accounts_context(self):
"""Get the accounts we may want to display"""
income_parent = Account.objects.get(name='Income')
housemate_parent = Account.objects.get(name='Housemate Income')
expense_parent = Account.objects.get(name='Expenses')
current_liabilities_parent = Acco... | python | def get_accounts_context(self):
"""Get the accounts we may want to display"""
income_parent = Account.objects.get(name='Income')
housemate_parent = Account.objects.get(name='Housemate Income')
expense_parent = Account.objects.get(name='Expenses')
current_liabilities_parent = Acco... | [
"def",
"get_accounts_context",
"(",
"self",
")",
":",
"income_parent",
"=",
"Account",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"'Income'",
")",
"housemate_parent",
"=",
"Account",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"'Housemate Income'",
")",... | Get the accounts we may want to display | [
"Get",
"the",
"accounts",
"we",
"may",
"want",
"to",
"display"
] | 72c715800841c3b2feabded3f3b65b76388b4cea | https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/dashboard/views.py#L24-L38 | train |
tsroten/zhon | zhon/pinyin.py | _build_syl | def _build_syl(vowels, tone_numbers=False):
"""Builds a Pinyin syllable re pattern.
Syllables can be preceded by a middle dot (tone mark). Syllables that end
in a consonant are only valid if they aren't followed directly by a vowel
with no apostrophe in between.
The rough approach used to validate... | python | def _build_syl(vowels, tone_numbers=False):
"""Builds a Pinyin syllable re pattern.
Syllables can be preceded by a middle dot (tone mark). Syllables that end
in a consonant are only valid if they aren't followed directly by a vowel
with no apostrophe in between.
The rough approach used to validate... | [
"def",
"_build_syl",
"(",
"vowels",
",",
"tone_numbers",
"=",
"False",
")",
":",
"consonant_end",
"=",
"'(?![{a}{e}{i}{o}{u}{v}]|u:)'",
".",
"format",
"(",
"a",
"=",
"_a",
",",
"e",
"=",
"_e",
",",
"i",
"=",
"_i",
",",
"o",
"=",
"_o",
",",
"u",
"=",
... | Builds a Pinyin syllable re pattern.
Syllables can be preceded by a middle dot (tone mark). Syllables that end
in a consonant are only valid if they aren't followed directly by a vowel
with no apostrophe in between.
The rough approach used to validate a Pinyin syllable is:
1. Get the longest v... | [
"Builds",
"a",
"Pinyin",
"syllable",
"re",
"pattern",
"."
] | 09bf543696277f71de502506984661a60d24494c | https://github.com/tsroten/zhon/blob/09bf543696277f71de502506984661a60d24494c/zhon/pinyin.py#L56-L125 | train |
tsroten/zhon | zhon/pinyin.py | _build_word | def _build_word(syl, vowels):
"""Builds a Pinyin word re pattern from a Pinyin syllable re pattern.
A word is defined as a series of consecutive valid Pinyin syllables
with optional hyphens and apostrophes interspersed. Hyphens must be
followed immediately by another valid Pinyin syllable. Apostrophes ... | python | def _build_word(syl, vowels):
"""Builds a Pinyin word re pattern from a Pinyin syllable re pattern.
A word is defined as a series of consecutive valid Pinyin syllables
with optional hyphens and apostrophes interspersed. Hyphens must be
followed immediately by another valid Pinyin syllable. Apostrophes ... | [
"def",
"_build_word",
"(",
"syl",
",",
"vowels",
")",
":",
"return",
"\"(?:{syl}(?:-(?={syl})|'(?=[{a}{e}{o}])(?={syl}))?)+\"",
".",
"format",
"(",
"syl",
"=",
"syl",
",",
"a",
"=",
"vowels",
"[",
"'a'",
"]",
",",
"e",
"=",
"vowels",
"[",
"'e'",
"]",
",",
... | Builds a Pinyin word re pattern from a Pinyin syllable re pattern.
A word is defined as a series of consecutive valid Pinyin syllables
with optional hyphens and apostrophes interspersed. Hyphens must be
followed immediately by another valid Pinyin syllable. Apostrophes must be
followed by another valid... | [
"Builds",
"a",
"Pinyin",
"word",
"re",
"pattern",
"from",
"a",
"Pinyin",
"syllable",
"re",
"pattern",
"."
] | 09bf543696277f71de502506984661a60d24494c | https://github.com/tsroten/zhon/blob/09bf543696277f71de502506984661a60d24494c/zhon/pinyin.py#L128-L139 | train |
tsroten/zhon | zhon/pinyin.py | _build_sentence | def _build_sentence(word):
"""Builds a Pinyin sentence re pattern from a Pinyin word re pattern.
A sentence is defined as a series of valid Pinyin words, punctuation
(non-stops), and spaces followed by a single stop and zero or more
container-closing punctuation marks (e.g. apostrophe and brackets).
... | python | def _build_sentence(word):
"""Builds a Pinyin sentence re pattern from a Pinyin word re pattern.
A sentence is defined as a series of valid Pinyin words, punctuation
(non-stops), and spaces followed by a single stop and zero or more
container-closing punctuation marks (e.g. apostrophe and brackets).
... | [
"def",
"_build_sentence",
"(",
"word",
")",
":",
"return",
"(",
"\"(?:{word}|[{non_stops}]|(?<![{stops} ]) )+\"",
"\"[{stops}]['\\\"\\]\\}}\\)]*\"",
")",
".",
"format",
"(",
"word",
"=",
"word",
",",
"non_stops",
"=",
"non_stops",
".",
"replace",
"(",
"'-'",
",",
... | Builds a Pinyin sentence re pattern from a Pinyin word re pattern.
A sentence is defined as a series of valid Pinyin words, punctuation
(non-stops), and spaces followed by a single stop and zero or more
container-closing punctuation marks (e.g. apostrophe and brackets). | [
"Builds",
"a",
"Pinyin",
"sentence",
"re",
"pattern",
"from",
"a",
"Pinyin",
"word",
"re",
"pattern",
"."
] | 09bf543696277f71de502506984661a60d24494c | https://github.com/tsroten/zhon/blob/09bf543696277f71de502506984661a60d24494c/zhon/pinyin.py#L142-L154 | train |
choderalab/pymbar | examples/parallel-tempering-2dpmf/parallel-tempering-2dpmf.py | read_file | def read_file(filename):
"""Read contents of the specified file.
Parameters:
-----------
filename : str
The name of the file to be read
Returns:
lines : list of str
The contents of the file, split by line
"""
infile = open(filename, 'r')
lines = infile.readlines()
infile.cl... | python | def read_file(filename):
"""Read contents of the specified file.
Parameters:
-----------
filename : str
The name of the file to be read
Returns:
lines : list of str
The contents of the file, split by line
"""
infile = open(filename, 'r')
lines = infile.readlines()
infile.cl... | [
"def",
"read_file",
"(",
"filename",
")",
":",
"infile",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"lines",
"=",
"infile",
".",
"readlines",
"(",
")",
"infile",
".",
"close",
"(",
")",
"return",
"lines"
] | Read contents of the specified file.
Parameters:
-----------
filename : str
The name of the file to be read
Returns:
lines : list of str
The contents of the file, split by line | [
"Read",
"contents",
"of",
"the",
"specified",
"file",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/examples/parallel-tempering-2dpmf/parallel-tempering-2dpmf.py#L58-L76 | train |
choderalab/pymbar | pymbar/old_mbar.py | MBAR._computeWeights | def _computeWeights(self, logform=False, include_nonzero=False, recalc_denom=True, return_f_k=False):
"""Compute the normalized weights corresponding to samples for the given reduced potential.
Compute the normalized weights corresponding to samples for the given reduced potential.
Also stores ... | python | def _computeWeights(self, logform=False, include_nonzero=False, recalc_denom=True, return_f_k=False):
"""Compute the normalized weights corresponding to samples for the given reduced potential.
Compute the normalized weights corresponding to samples for the given reduced potential.
Also stores ... | [
"def",
"_computeWeights",
"(",
"self",
",",
"logform",
"=",
"False",
",",
"include_nonzero",
"=",
"False",
",",
"recalc_denom",
"=",
"True",
",",
"return_f_k",
"=",
"False",
")",
":",
"if",
"(",
"include_nonzero",
")",
":",
"f_k",
"=",
"self",
".",
"f_k"... | Compute the normalized weights corresponding to samples for the given reduced potential.
Compute the normalized weights corresponding to samples for the given reduced potential.
Also stores the all_log_denom array for reuse.
Parameters
----------
logform : bool, optional
... | [
"Compute",
"the",
"normalized",
"weights",
"corresponding",
"to",
"samples",
"for",
"the",
"given",
"reduced",
"potential",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L1654-L1725 | train |
choderalab/pymbar | pymbar/old_mbar.py | MBAR._pseudoinverse | def _pseudoinverse(self, A, tol=1.0e-10):
"""
Compute the Moore-Penrose pseudoinverse.
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
... | python | def _pseudoinverse(self, A, tol=1.0e-10):
"""
Compute the Moore-Penrose pseudoinverse.
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
... | [
"def",
"_pseudoinverse",
"(",
"self",
",",
"A",
",",
"tol",
"=",
"1.0e-10",
")",
":",
"[",
"M",
",",
"N",
"]",
"=",
"A",
".",
"shape",
"if",
"N",
"!=",
"M",
":",
"raise",
"DataError",
"(",
"\"pseudoinverse can only be computed for square matrices: dimensions... | Compute the Moore-Penrose pseudoinverse.
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
tol - the tolerance (relative to largest magnitude singl... | [
"Compute",
"the",
"Moore",
"-",
"Penrose",
"pseudoinverse",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L1729-L1789 | train |
choderalab/pymbar | pymbar/old_mbar.py | MBAR._zerosamestates | def _zerosamestates(self, A):
"""
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
"""
for pair in self.samestates:
A[pair[0], pair[1]] = 0
A[pair[1], pair[0]] = 0 | python | def _zerosamestates(self, A):
"""
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
"""
for pair in self.samestates:
A[pair[0], pair[1]] = 0
A[pair[1], pair[0]] = 0 | [
"def",
"_zerosamestates",
"(",
"self",
",",
"A",
")",
":",
"for",
"pair",
"in",
"self",
".",
"samestates",
":",
"A",
"[",
"pair",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
"]",
"=",
"0",
"A",
"[",
"pair",
"[",
"1",
"]",
",",
"pair",
"[",
"... | zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed. | [
"zeros",
"out",
"states",
"that",
"should",
"be",
"identical"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L1792-L1804 | train |
choderalab/pymbar | pymbar/old_mbar.py | MBAR._initializeFreeEnergies | def _initializeFreeEnergies(self, verbose=False, method='zeros'):
"""
Compute an initial guess at the relative free energies.
OPTIONAL ARGUMENTS
verbose (boolean) - If True, will print debug information (default: False)
method (string) - Method for initializing guess at free ene... | python | def _initializeFreeEnergies(self, verbose=False, method='zeros'):
"""
Compute an initial guess at the relative free energies.
OPTIONAL ARGUMENTS
verbose (boolean) - If True, will print debug information (default: False)
method (string) - Method for initializing guess at free ene... | [
"def",
"_initializeFreeEnergies",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"method",
"=",
"'zeros'",
")",
":",
"if",
"(",
"method",
"==",
"'zeros'",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Initializing free energies to zero.\"",
")",
"self",
... | Compute an initial guess at the relative free energies.
OPTIONAL ARGUMENTS
verbose (boolean) - If True, will print debug information (default: False)
method (string) - Method for initializing guess at free energies.
'zeros' - all free energies are initially set to zero
'mean-red... | [
"Compute",
"an",
"initial",
"guess",
"at",
"the",
"relative",
"free",
"energies",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L2009-L2074 | train |
choderalab/pymbar | pymbar/old_mbar.py | MBAR._amIdoneIterating | def _amIdoneIterating(self, f_k_new, relative_tolerance, iteration, maximum_iterations, print_warning, verbose):
"""
Convenience function to test whether we are done iterating, same for all iteration types
REQUIRED ARGUMENTS
f_k_new (array): new free energies
f_k (array) : o... | python | def _amIdoneIterating(self, f_k_new, relative_tolerance, iteration, maximum_iterations, print_warning, verbose):
"""
Convenience function to test whether we are done iterating, same for all iteration types
REQUIRED ARGUMENTS
f_k_new (array): new free energies
f_k (array) : o... | [
"def",
"_amIdoneIterating",
"(",
"self",
",",
"f_k_new",
",",
"relative_tolerance",
",",
"iteration",
",",
"maximum_iterations",
",",
"print_warning",
",",
"verbose",
")",
":",
"yesIam",
"=",
"False",
"Delta_f_k",
"=",
"f_k_new",
"-",
"self",
".",
"f_k",
"[",
... | Convenience function to test whether we are done iterating, same for all iteration types
REQUIRED ARGUMENTS
f_k_new (array): new free energies
f_k (array) : older free energies
relative_tolerance (float): the relative tolerance for terminating
verbose (bool): verbose res... | [
"Convenience",
"function",
"to",
"test",
"whether",
"we",
"are",
"done",
"iterating",
"same",
"for",
"all",
"iteration",
"types"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L2152-L2212 | train |
choderalab/pymbar | pymbar/old_mbar.py | MBAR._selfConsistentIteration | def _selfConsistentIteration(self, relative_tolerance=1.0e-6, maximum_iterations=1000, verbose=True, print_warning=False):
"""
Determine free energies by self-consistent iteration.
OPTIONAL ARGUMENTS
relative_tolerance (float between 0 and 1) - relative tolerance for convergence (def... | python | def _selfConsistentIteration(self, relative_tolerance=1.0e-6, maximum_iterations=1000, verbose=True, print_warning=False):
"""
Determine free energies by self-consistent iteration.
OPTIONAL ARGUMENTS
relative_tolerance (float between 0 and 1) - relative tolerance for convergence (def... | [
"def",
"_selfConsistentIteration",
"(",
"self",
",",
"relative_tolerance",
"=",
"1.0e-6",
",",
"maximum_iterations",
"=",
"1000",
",",
"verbose",
"=",
"True",
",",
"print_warning",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"MBAR: Computing di... | Determine free energies by self-consistent iteration.
OPTIONAL ARGUMENTS
relative_tolerance (float between 0 and 1) - relative tolerance for convergence (default 1.0e-5)
maximum_iterations (int) - maximum number of self-consistent iterations (default 1000)
verbose (boolean) - ver... | [
"Determine",
"free",
"energies",
"by",
"self",
"-",
"consistent",
"iteration",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/old_mbar.py#L2215-L2251 | train |
choderalab/pymbar | pymbar/mbar.py | MBAR._pseudoinverse | def _pseudoinverse(self, A, tol=1.0e-10):
"""Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL... | python | def _pseudoinverse(self, A, tol=1.0e-10):
"""Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL... | [
"def",
"_pseudoinverse",
"(",
"self",
",",
"A",
",",
"tol",
"=",
"1.0e-10",
")",
":",
"return",
"np",
".",
"linalg",
".",
"pinv",
"(",
"A",
",",
"rcond",
"=",
"tol",
")"
] | Compute the Moore-Penrose pseudoinverse, wraps np.linalg.pinv
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
tol - the tolerance (relative to la... | [
"Compute",
"the",
"Moore",
"-",
"Penrose",
"pseudoinverse",
"wraps",
"np",
".",
"linalg",
".",
"pinv"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar.py#L1546-L1564 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | validate_inputs | def validate_inputs(u_kn, N_k, f_k):
"""Check types and return inputs for MBAR calculations.
Parameters
----------
u_kn or q_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies or unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='in... | python | def validate_inputs(u_kn, N_k, f_k):
"""Check types and return inputs for MBAR calculations.
Parameters
----------
u_kn or q_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies or unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='in... | [
"def",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"n_states",
",",
"n_samples",
"=",
"u_kn",
".",
"shape",
"u_kn",
"=",
"ensure_type",
"(",
"u_kn",
",",
"'float'",
",",
"2",
",",
"\"u_kn or Q_kn\"",
",",
"shape",
"=",
"(",
"n_sta... | Check types and return inputs for MBAR calculations.
Parameters
----------
u_kn or q_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies or unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in each sta... | [
"Check",
"types",
"and",
"return",
"inputs",
"for",
"MBAR",
"calculations",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L17-L44 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | self_consistent_update | def self_consistent_update(u_kn, N_k, f_k):
"""Return an improved guess for the dimensionless free energies
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_sta... | python | def self_consistent_update(u_kn, N_k, f_k):
"""Return an improved guess for the dimensionless free energies
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_sta... | [
"def",
"self_consistent_update",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"u_kn",
",",
"N_k",
",",
"f_k",
"=",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"states_with_samples",
"=",
"(",
"N_k",
">",
"0",
")",
"log_denominator_n",
... | Return an improved guess for the dimensionless free energies
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in ... | [
"Return",
"an",
"improved",
"guess",
"for",
"the",
"dimensionless",
"free",
"energies"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L47-L77 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | mbar_gradient | def mbar_gradient(u_kn, N_k, f_k):
"""Gradient of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The num... | python | def mbar_gradient(u_kn, N_k, f_k):
"""Gradient of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The num... | [
"def",
"mbar_gradient",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"u_kn",
",",
"N_k",
",",
"f_k",
"=",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"log_denominator_n",
"=",
"logsumexp",
"(",
"f_k",
"-",
"u_kn",
".",
"T",
",",
... | Gradient of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in each state
f_k : np.... | [
"Gradient",
"of",
"MBAR",
"objective",
"function",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L80-L105 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | mbar_objective_and_gradient | def mbar_objective_and_gradient(u_kn, N_k, f_k):
"""Calculates both objective function and gradient for MBAR.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_s... | python | def mbar_objective_and_gradient(u_kn, N_k, f_k):
"""Calculates both objective function and gradient for MBAR.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_s... | [
"def",
"mbar_objective_and_gradient",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"u_kn",
",",
"N_k",
",",
"f_k",
"=",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"log_denominator_n",
"=",
"logsumexp",
"(",
"f_k",
"-",
"u_kn",
".",
... | Calculates both objective function and gradient for MBAR.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in eac... | [
"Calculates",
"both",
"objective",
"function",
"and",
"gradient",
"for",
"MBAR",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L108-L149 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | mbar_hessian | def mbar_hessian(u_kn, N_k, f_k):
"""Hessian of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The numbe... | python | def mbar_hessian(u_kn, N_k, f_k):
"""Hessian of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The numbe... | [
"def",
"mbar_hessian",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"u_kn",
",",
"N_k",
",",
"f_k",
"=",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"W",
"=",
"mbar_W_nk",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"H",
"=",
"... | Hessian of MBAR objective function.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in each state
f_k : np.n... | [
"Hessian",
"of",
"MBAR",
"objective",
"function",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L152-L182 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | mbar_log_W_nk | def mbar_log_W_nk(u_kn, N_k, f_k):
"""Calculate the log weight matrix.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number ... | python | def mbar_log_W_nk(u_kn, N_k, f_k):
"""Calculate the log weight matrix.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number ... | [
"def",
"mbar_log_W_nk",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"u_kn",
",",
"N_k",
",",
"f_k",
"=",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"log_denominator_n",
"=",
"logsumexp",
"(",
"f_k",
"-",
"u_kn",
".",
"T",
",",
... | Calculate the log weight matrix.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in each state
f_k : np.ndar... | [
"Calculate",
"the",
"log",
"weight",
"matrix",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L185-L210 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | mbar_W_nk | def mbar_W_nk(u_kn, N_k, f_k):
"""Calculate the weight matrix.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of sampl... | python | def mbar_W_nk(u_kn, N_k, f_k):
"""Calculate the weight matrix.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of sampl... | [
"def",
"mbar_W_nk",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"return",
"np",
".",
"exp",
"(",
"mbar_log_W_nk",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
")"
] | Calculate the weight matrix.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samples in each state
f_k : np.ndarray,... | [
"Calculate",
"the",
"weight",
"matrix",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L213-L234 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | precondition_u_kn | def precondition_u_kn(u_kn, N_k, f_k):
"""Subtract a sample-dependent constant from u_kn to improve precision
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_s... | python | def precondition_u_kn(u_kn, N_k, f_k):
"""Subtract a sample-dependent constant from u_kn to improve precision
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_s... | [
"def",
"precondition_u_kn",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
":",
"u_kn",
",",
"N_k",
",",
"f_k",
"=",
"validate_inputs",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
")",
"u_kn",
"=",
"u_kn",
"-",
"u_kn",
".",
"min",
"(",
"0",
")",
"u_kn",
"+="... | Subtract a sample-dependent constant from u_kn to improve precision
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
The number of samp... | [
"Subtract",
"a",
"sample",
"-",
"dependent",
"constant",
"from",
"u_kn",
"to",
"improve",
"precision"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L352-L380 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | solve_mbar_once | def solve_mbar_once(u_kn_nonzero, N_k_nonzero, f_k_nonzero, method="hybr", tol=1E-12, options=None):
"""Solve MBAR self-consistent equations using some form of equation solver.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential ener... | python | def solve_mbar_once(u_kn_nonzero, N_k_nonzero, f_k_nonzero, method="hybr", tol=1E-12, options=None):
"""Solve MBAR self-consistent equations using some form of equation solver.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential ener... | [
"def",
"solve_mbar_once",
"(",
"u_kn_nonzero",
",",
"N_k_nonzero",
",",
"f_k_nonzero",
",",
"method",
"=",
"\"hybr\"",
",",
"tol",
"=",
"1E-12",
",",
"options",
"=",
"None",
")",
":",
"u_kn_nonzero",
",",
"N_k_nonzero",
",",
"f_k_nonzero",
"=",
"validate_input... | Solve MBAR self-consistent equations using some form of equation solver.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
for the nonempty states
N_k_nonzero : np.ndarray, sha... | [
"Solve",
"MBAR",
"self",
"-",
"consistent",
"equations",
"using",
"some",
"form",
"of",
"equation",
"solver",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L383-L465 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | solve_mbar | def solve_mbar(u_kn_nonzero, N_k_nonzero, f_k_nonzero, solver_protocol=None):
"""Solve MBAR self-consistent equations using some sequence of equation solvers.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log un... | python | def solve_mbar(u_kn_nonzero, N_k_nonzero, f_k_nonzero, solver_protocol=None):
"""Solve MBAR self-consistent equations using some sequence of equation solvers.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log un... | [
"def",
"solve_mbar",
"(",
"u_kn_nonzero",
",",
"N_k_nonzero",
",",
"f_k_nonzero",
",",
"solver_protocol",
"=",
"None",
")",
":",
"if",
"solver_protocol",
"is",
"None",
":",
"solver_protocol",
"=",
"DEFAULT_SOLVER_PROTOCOL",
"for",
"protocol",
"in",
"solver_protocol"... | Solve MBAR self-consistent equations using some sequence of equation solvers.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
for the nonempty states
N_k_nonzero : np.ndarray... | [
"Solve",
"MBAR",
"self",
"-",
"consistent",
"equations",
"using",
"some",
"sequence",
"of",
"equation",
"solvers",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L468-L518 | train |
choderalab/pymbar | pymbar/mbar_solvers.py | solve_mbar_for_all_states | def solve_mbar_for_all_states(u_kn, N_k, f_k, solver_protocol):
"""Solve for free energies of states with samples, then calculate for
empty states.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized prob... | python | def solve_mbar_for_all_states(u_kn, N_k, f_k, solver_protocol):
"""Solve for free energies of states with samples, then calculate for
empty states.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized prob... | [
"def",
"solve_mbar_for_all_states",
"(",
"u_kn",
",",
"N_k",
",",
"f_k",
",",
"solver_protocol",
")",
":",
"states_with_samples",
"=",
"np",
".",
"where",
"(",
"N_k",
">",
"0",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"states_with_samples",
")",
"==",
"1",
... | Solve for free energies of states with samples, then calculate for
empty states.
Parameters
----------
u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
N_k : np.ndarray, shape=(n_states), dtype='int'
T... | [
"Solve",
"for",
"free",
"energies",
"of",
"states",
"with",
"samples",
"then",
"calculate",
"for",
"empty",
"states",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/mbar_solvers.py#L521-L558 | train |
choderalab/pymbar | examples/constant-force-optical-trap/force-bias-optical-trap.py | construct_nonuniform_bins | def construct_nonuniform_bins(x_n, nbins):
"""Construct histogram using bins of unequal size to ensure approximately equal population in each bin.
ARGUMENTS
x_n (1D numpy array of floats) - x_n[n] is data point n
RETURN VALUES
bin_left_boundary_i (1D numpy array of floats) - data in bin i will... | python | def construct_nonuniform_bins(x_n, nbins):
"""Construct histogram using bins of unequal size to ensure approximately equal population in each bin.
ARGUMENTS
x_n (1D numpy array of floats) - x_n[n] is data point n
RETURN VALUES
bin_left_boundary_i (1D numpy array of floats) - data in bin i will... | [
"def",
"construct_nonuniform_bins",
"(",
"x_n",
",",
"nbins",
")",
":",
"N",
"=",
"x_n",
".",
"size",
"sorted_indices",
"=",
"x_n",
".",
"argsort",
"(",
")",
"bin_left_boundary_i",
"=",
"zeros",
"(",
"[",
"nbins",
"+",
"1",
"]",
",",
"float64",
")",
"b... | Construct histogram using bins of unequal size to ensure approximately equal population in each bin.
ARGUMENTS
x_n (1D numpy array of floats) - x_n[n] is data point n
RETURN VALUES
bin_left_boundary_i (1D numpy array of floats) - data in bin i will satisfy bin_left_boundary_i[i] <= x < bin_left_bo... | [
"Construct",
"histogram",
"using",
"bins",
"of",
"unequal",
"size",
"to",
"ensure",
"approximately",
"equal",
"population",
"in",
"each",
"bin",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/examples/constant-force-optical-trap/force-bias-optical-trap.py#L47-L104 | train |
choderalab/pymbar | pymbar/timeseries.py | integratedAutocorrelationTime | def integratedAutocorrelationTime(A_n, B_n=None, fast=False, mintime=3):
"""Estimate the integrated autocorrelation time.
See Also
--------
statisticalInefficiency
"""
g = statisticalInefficiency(A_n, B_n, fast, mintime)
tau = (g - 1.0) / 2.0
return tau | python | def integratedAutocorrelationTime(A_n, B_n=None, fast=False, mintime=3):
"""Estimate the integrated autocorrelation time.
See Also
--------
statisticalInefficiency
"""
g = statisticalInefficiency(A_n, B_n, fast, mintime)
tau = (g - 1.0) / 2.0
return tau | [
"def",
"integratedAutocorrelationTime",
"(",
"A_n",
",",
"B_n",
"=",
"None",
",",
"fast",
"=",
"False",
",",
"mintime",
"=",
"3",
")",
":",
"g",
"=",
"statisticalInefficiency",
"(",
"A_n",
",",
"B_n",
",",
"fast",
",",
"mintime",
")",
"tau",
"=",
"(",
... | Estimate the integrated autocorrelation time.
See Also
--------
statisticalInefficiency | [
"Estimate",
"the",
"integrated",
"autocorrelation",
"time",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/timeseries.py#L357-L368 | train |
choderalab/pymbar | pymbar/timeseries.py | integratedAutocorrelationTimeMultiple | def integratedAutocorrelationTimeMultiple(A_kn, fast=False):
"""Estimate the integrated autocorrelation time from multiple timeseries.
See Also
--------
statisticalInefficiencyMultiple
"""
g = statisticalInefficiencyMultiple(A_kn, fast, False)
tau = (g - 1.0) / 2.0
return tau | python | def integratedAutocorrelationTimeMultiple(A_kn, fast=False):
"""Estimate the integrated autocorrelation time from multiple timeseries.
See Also
--------
statisticalInefficiencyMultiple
"""
g = statisticalInefficiencyMultiple(A_kn, fast, False)
tau = (g - 1.0) / 2.0
return tau | [
"def",
"integratedAutocorrelationTimeMultiple",
"(",
"A_kn",
",",
"fast",
"=",
"False",
")",
":",
"g",
"=",
"statisticalInefficiencyMultiple",
"(",
"A_kn",
",",
"fast",
",",
"False",
")",
"tau",
"=",
"(",
"g",
"-",
"1.0",
")",
"/",
"2.0",
"return",
"tau"
] | Estimate the integrated autocorrelation time from multiple timeseries.
See Also
--------
statisticalInefficiencyMultiple | [
"Estimate",
"the",
"integrated",
"autocorrelation",
"time",
"from",
"multiple",
"timeseries",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/timeseries.py#L372-L383 | train |
choderalab/pymbar | pymbar/timeseries.py | subsampleCorrelatedData | def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False):
"""Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional... | python | def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False):
"""Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional... | [
"def",
"subsampleCorrelatedData",
"(",
"A_t",
",",
"g",
"=",
"None",
",",
"fast",
"=",
"False",
",",
"conservative",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"A_t",
"=",
"np",
".",
"array",
"(",
"A_t",
")",
"T",
"=",
"A_t",
".",
"size"... | Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional
if provided, the statistical inefficiency g is used to subsample the timeseries -- othe... | [
"Determine",
"the",
"indices",
"of",
"an",
"uncorrelated",
"subsample",
"of",
"the",
"data",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/timeseries.py#L632-L736 | train |
choderalab/pymbar | pymbar/bar.py | BARzero | def BARzero(w_F, w_R, DeltaF):
"""A function that when zeroed is equivalent to the solution of
the Bennett acceptance ratio.
from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601
D_F = M + w_F - Delta F
D_R = M + w_R - Delta F
we want:
\sum_N_F (1+exp(D_F))^-1 = \sum N_R N_R <... | python | def BARzero(w_F, w_R, DeltaF):
"""A function that when zeroed is equivalent to the solution of
the Bennett acceptance ratio.
from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601
D_F = M + w_F - Delta F
D_R = M + w_R - Delta F
we want:
\sum_N_F (1+exp(D_F))^-1 = \sum N_R N_R <... | [
"def",
"BARzero",
"(",
"w_F",
",",
"w_R",
",",
"DeltaF",
")",
":",
"np",
".",
"seterr",
"(",
"over",
"=",
"'raise'",
")",
"w_F",
"=",
"np",
".",
"array",
"(",
"w_F",
",",
"np",
".",
"float64",
")",
"w_R",
"=",
"np",
".",
"array",
"(",
"w_R",
... | A function that when zeroed is equivalent to the solution of
the Bennett acceptance ratio.
from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601
D_F = M + w_F - Delta F
D_R = M + w_R - Delta F
we want:
\sum_N_F (1+exp(D_F))^-1 = \sum N_R N_R <(1+exp(-D_R))^-1>
ln \sum N_F (1+e... | [
"A",
"function",
"that",
"when",
"zeroed",
"is",
"equivalent",
"to",
"the",
"solution",
"of",
"the",
"Bennett",
"acceptance",
"ratio",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/bar.py#L54-L147 | train |
choderalab/pymbar | pymbar/utils.py | kln_to_kn | def kln_to_kn(kln, N_k = None, cleanup = False):
""" Convert KxKxN_max array to KxN max array
if self.N is not initialized, it will be here.
Parameters
----------
u_kln : np.ndarray, float, shape=(KxLxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
... | python | def kln_to_kn(kln, N_k = None, cleanup = False):
""" Convert KxKxN_max array to KxN max array
if self.N is not initialized, it will be here.
Parameters
----------
u_kln : np.ndarray, float, shape=(KxLxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
... | [
"def",
"kln_to_kn",
"(",
"kln",
",",
"N_k",
"=",
"None",
",",
"cleanup",
"=",
"False",
")",
":",
"[",
"K",
",",
"L",
",",
"N_max",
"]",
"=",
"np",
".",
"shape",
"(",
"kln",
")",
"if",
"N_k",
"is",
"None",
":",
"N_k",
"=",
"N_max",
"*",
"np",
... | Convert KxKxN_max array to KxN max array
if self.N is not initialized, it will be here.
Parameters
----------
u_kln : np.ndarray, float, shape=(KxLxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
cleanup (optional) : bool
optional command to cl... | [
"Convert",
"KxKxN_max",
"array",
"to",
"KxN",
"max",
"array"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L46-L85 | train |
choderalab/pymbar | pymbar/utils.py | kn_to_n | def kn_to_n(kn, N_k = None, cleanup = False):
""" Convert KxN_max array to N array
Parameters
----------
u_kn: np.ndarray, float, shape=(KxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
cleanup (optional) : bool
optional command to clean up, s... | python | def kn_to_n(kn, N_k = None, cleanup = False):
""" Convert KxN_max array to N array
Parameters
----------
u_kn: np.ndarray, float, shape=(KxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
cleanup (optional) : bool
optional command to clean up, s... | [
"def",
"kn_to_n",
"(",
"kn",
",",
"N_k",
"=",
"None",
",",
"cleanup",
"=",
"False",
")",
":",
"[",
"K",
",",
"N_max",
"]",
"=",
"np",
".",
"shape",
"(",
"kn",
")",
"if",
"N_k",
"is",
"None",
":",
"N_k",
"=",
"N_max",
"*",
"np",
".",
"ones",
... | Convert KxN_max array to N array
Parameters
----------
u_kn: np.ndarray, float, shape=(KxN_max)
N_k (optional) : np.array
the N_k matrix from the previous formatting form
cleanup (optional) : bool
optional command to clean up, since u_kln can get very large
Outputs
-------
... | [
"Convert",
"KxN_max",
"array",
"to",
"N",
"array"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L88-L125 | train |
choderalab/pymbar | pymbar/utils.py | ensure_type | def ensure_type(val, dtype, ndim, name, length=None, can_be_none=False, shape=None,
warn_on_cast=True, add_newaxis_on_deficient_ndim=False):
"""Typecheck the size, shape and dtype of a numpy array, with optional
casting.
Parameters
----------
val : {np.ndaraay, None}
The arr... | python | def ensure_type(val, dtype, ndim, name, length=None, can_be_none=False, shape=None,
warn_on_cast=True, add_newaxis_on_deficient_ndim=False):
"""Typecheck the size, shape and dtype of a numpy array, with optional
casting.
Parameters
----------
val : {np.ndaraay, None}
The arr... | [
"def",
"ensure_type",
"(",
"val",
",",
"dtype",
",",
"ndim",
",",
"name",
",",
"length",
"=",
"None",
",",
"can_be_none",
"=",
"False",
",",
"shape",
"=",
"None",
",",
"warn_on_cast",
"=",
"True",
",",
"add_newaxis_on_deficient_ndim",
"=",
"False",
")",
... | Typecheck the size, shape and dtype of a numpy array, with optional
casting.
Parameters
----------
val : {np.ndaraay, None}
The array to check
dtype : {nd.dtype, str}
The dtype you'd like the array to have
ndim : int
The number of dimensions you'd like the array to have
... | [
"Typecheck",
"the",
"size",
"shape",
"and",
"dtype",
"of",
"a",
"numpy",
"array",
"with",
"optional",
"casting",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L128-L226 | train |
choderalab/pymbar | pymbar/utils.py | logsumexp | def logsumexp(a, axis=None, b=None, use_numexpr=True):
"""Compute the log of the sum of exponentials of input elements.
Parameters
----------
a : array_like
Input array.
axis : None or int, optional, default=None
Axis or axes over which the sum is taken. By default `axis` is None,
... | python | def logsumexp(a, axis=None, b=None, use_numexpr=True):
"""Compute the log of the sum of exponentials of input elements.
Parameters
----------
a : array_like
Input array.
axis : None or int, optional, default=None
Axis or axes over which the sum is taken. By default `axis` is None,
... | [
"def",
"logsumexp",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"b",
"=",
"None",
",",
"use_numexpr",
"=",
"True",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"a_max",
"=",
"np",
".",
"amax",
"(",
"a",
",",
"axis",
"=",
"axis",
",",... | Compute the log of the sum of exponentials of input elements.
Parameters
----------
a : array_like
Input array.
axis : None or int, optional, default=None
Axis or axes over which the sum is taken. By default `axis` is None,
and all elements are summed.
b : array-like, option... | [
"Compute",
"the",
"log",
"of",
"the",
"sum",
"of",
"exponentials",
"of",
"input",
"elements",
"."
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L271-L329 | train |
choderalab/pymbar | pymbar/utils.py | check_w_normalized | def check_w_normalized(W, N_k, tolerance = 1.0e-4):
"""Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1
Parameters
----------
W : np.ndarray, shape=(N, K), dtype='float'
The normalized weight matrix for snapshots and states... | python | def check_w_normalized(W, N_k, tolerance = 1.0e-4):
"""Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1
Parameters
----------
W : np.ndarray, shape=(N, K), dtype='float'
The normalized weight matrix for snapshots and states... | [
"def",
"check_w_normalized",
"(",
"W",
",",
"N_k",
",",
"tolerance",
"=",
"1.0e-4",
")",
":",
"[",
"N",
",",
"K",
"]",
"=",
"W",
".",
"shape",
"column_sums",
"=",
"np",
".",
"sum",
"(",
"W",
",",
"axis",
"=",
"0",
")",
"badcolumns",
"=",
"(",
"... | Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1
Parameters
----------
W : np.ndarray, shape=(N, K), dtype='float'
The normalized weight matrix for snapshots and states.
W[n, k] is the weight of snapshot n in state k.
... | [
"Check",
"the",
"weight",
"matrix",
"W",
"is",
"properly",
"normalized",
".",
"The",
"sum",
"over",
"N",
"should",
"be",
"1",
"and",
"the",
"sum",
"over",
"k",
"by",
"N_k",
"should",
"aslo",
"be",
"1"
] | 69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740 | https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L332-L371 | train |
phha/click_config_file | click_config_file.py | configuration_callback | def configuration_callback(cmd_name, option_name, config_file_name,
saved_callback, provider, implicit, ctx,
param, value):
"""
Callback for reading the config file.
Also takes care of calling user specified custom callback afterwards.
cmd_name : s... | python | def configuration_callback(cmd_name, option_name, config_file_name,
saved_callback, provider, implicit, ctx,
param, value):
"""
Callback for reading the config file.
Also takes care of calling user specified custom callback afterwards.
cmd_name : s... | [
"def",
"configuration_callback",
"(",
"cmd_name",
",",
"option_name",
",",
"config_file_name",
",",
"saved_callback",
",",
"provider",
",",
"implicit",
",",
"ctx",
",",
"param",
",",
"value",
")",
":",
"ctx",
".",
"default_map",
"=",
"ctx",
".",
"default_map",... | Callback for reading the config file.
Also takes care of calling user specified custom callback afterwards.
cmd_name : str
The command name. This is used to determine the configuration directory.
option_name : str
The name of the option. This is used for error messages.
config_file_nam... | [
"Callback",
"for",
"reading",
"the",
"config",
"file",
"."
] | 1c3b3ec13b41d94683bbb9467d184df6ca3b6fe1 | https://github.com/phha/click_config_file/blob/1c3b3ec13b41d94683bbb9467d184df6ca3b6fe1/click_config_file.py#L51-L95 | train |
phha/click_config_file | click_config_file.py | configuration_option | def configuration_option(*param_decls, **attrs):
"""
Adds configuration file support to a click application.
This will create an option of type `click.File` expecting the path to a
configuration file. When specified, it overwrites the default values for
all other click arguments or options with the... | python | def configuration_option(*param_decls, **attrs):
"""
Adds configuration file support to a click application.
This will create an option of type `click.File` expecting the path to a
configuration file. When specified, it overwrites the default values for
all other click arguments or options with the... | [
"def",
"configuration_option",
"(",
"*",
"param_decls",
",",
"**",
"attrs",
")",
":",
"param_decls",
"=",
"param_decls",
"or",
"(",
"'--config'",
",",
")",
"option_name",
"=",
"param_decls",
"[",
"0",
"]",
"def",
"decorator",
"(",
"f",
")",
":",
"attrs",
... | Adds configuration file support to a click application.
This will create an option of type `click.File` expecting the path to a
configuration file. When specified, it overwrites the default values for
all other click arguments or options with the corresponding value from the
configuration file.
Th... | [
"Adds",
"configuration",
"file",
"support",
"to",
"a",
"click",
"application",
"."
] | 1c3b3ec13b41d94683bbb9467d184df6ca3b6fe1 | https://github.com/phha/click_config_file/blob/1c3b3ec13b41d94683bbb9467d184df6ca3b6fe1/click_config_file.py#L98-L164 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/formatting/deserialize/__init__.py | decode_value | def decode_value(stream):
"""Decode the contents of a value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded value
:rtype: bytes
"""
length = decode_length(stream)
(value,) = unpack_value(">{:d}s".format(length), stream)
return v... | python | def decode_value(stream):
"""Decode the contents of a value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded value
:rtype: bytes
"""
length = decode_length(stream)
(value,) = unpack_value(">{:d}s".format(length), stream)
return v... | [
"def",
"decode_value",
"(",
"stream",
")",
":",
"length",
"=",
"decode_length",
"(",
"stream",
")",
"(",
"value",
",",
")",
"=",
"unpack_value",
"(",
"\">{:d}s\"",
".",
"format",
"(",
"length",
")",
",",
"stream",
")",
"return",
"value"
] | Decode the contents of a value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded value
:rtype: bytes | [
"Decode",
"the",
"contents",
"of",
"a",
"value",
"from",
"a",
"serialized",
"stream",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/formatting/deserialize/__init__.py#L51-L61 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/formatting/deserialize/__init__.py | decode_tag | def decode_tag(stream):
"""Decode a tag value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded tag
:rtype: bytes
"""
(reserved, tag) = unpack_value(">cc", stream)
if reserved != b"\x00":
raise DeserializationError("Invalid t... | python | def decode_tag(stream):
"""Decode a tag value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded tag
:rtype: bytes
"""
(reserved, tag) = unpack_value(">cc", stream)
if reserved != b"\x00":
raise DeserializationError("Invalid t... | [
"def",
"decode_tag",
"(",
"stream",
")",
":",
"(",
"reserved",
",",
"tag",
")",
"=",
"unpack_value",
"(",
"\">cc\"",
",",
"stream",
")",
"if",
"reserved",
"!=",
"b\"\\x00\"",
":",
"raise",
"DeserializationError",
"(",
"\"Invalid tag: reserved byte is not null\"",
... | Decode a tag value from a serialized stream.
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Decoded tag
:rtype: bytes | [
"Decode",
"a",
"tag",
"value",
"from",
"a",
"serialized",
"stream",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/formatting/deserialize/__init__.py#L76-L89 | train |
aws/aws-dynamodb-encryption-python | setup.py | read | def read(*args):
"""Reads complete file contents."""
return io.open(os.path.join(HERE, *args), encoding="utf-8").read() | python | def read(*args):
"""Reads complete file contents."""
return io.open(os.path.join(HERE, *args), encoding="utf-8").read() | [
"def",
"read",
"(",
"*",
"args",
")",
":",
"return",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"HERE",
",",
"*",
"args",
")",
",",
"encoding",
"=",
"\"utf-8\"",
")",
".",
"read",
"(",
")"
] | Reads complete file contents. | [
"Reads",
"complete",
"file",
"contents",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/setup.py#L12-L14 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/authentication.py | sign_item | def sign_item(encrypted_item, signing_key, crypto_config):
# type: (dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> dynamodb_types.BINARY_ATTRIBUTE
"""Generate the signature DynamoDB atttribute.
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey signing_key: DelegatedKey to use... | python | def sign_item(encrypted_item, signing_key, crypto_config):
# type: (dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> dynamodb_types.BINARY_ATTRIBUTE
"""Generate the signature DynamoDB atttribute.
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey signing_key: DelegatedKey to use... | [
"def",
"sign_item",
"(",
"encrypted_item",
",",
"signing_key",
",",
"crypto_config",
")",
":",
"signature",
"=",
"signing_key",
".",
"sign",
"(",
"algorithm",
"=",
"signing_key",
".",
"algorithm",
",",
"data",
"=",
"_string_to_sign",
"(",
"item",
"=",
"encrypt... | Generate the signature DynamoDB atttribute.
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey signing_key: DelegatedKey to use to calculate the signature
:param CryptoConfig crypto_config: Cryptographic configuration
:returns: Item signature DynamoDB attribute value
:rtype: di... | [
"Generate",
"the",
"signature",
"DynamoDB",
"atttribute",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/authentication.py#L40-L58 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/authentication.py | verify_item_signature | def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config):
# type: (dynamodb_types.BINARY_ATTRIBUTE, dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> None
"""Verify the item signature.
:param dict signature_attribute: Item signature DynamoDB attribute value
:par... | python | def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config):
# type: (dynamodb_types.BINARY_ATTRIBUTE, dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> None
"""Verify the item signature.
:param dict signature_attribute: Item signature DynamoDB attribute value
:par... | [
"def",
"verify_item_signature",
"(",
"signature_attribute",
",",
"encrypted_item",
",",
"verification_key",
",",
"crypto_config",
")",
":",
"signature",
"=",
"signature_attribute",
"[",
"Tag",
".",
"BINARY",
".",
"dynamodb_tag",
"]",
"verification_key",
".",
"verify",... | Verify the item signature.
:param dict signature_attribute: Item signature DynamoDB attribute value
:param dict encrypted_item: Encrypted DynamoDB item
:param DelegatedKey verification_key: DelegatedKey to use to calculate the signature
:param CryptoConfig crypto_config: Cryptographic configuration | [
"Verify",
"the",
"item",
"signature",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/authentication.py#L61-L79 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/authentication.py | _string_to_sign | def _string_to_sign(item, table_name, attribute_actions):
# type: (dynamodb_types.ITEM, Text, AttributeActions) -> bytes
"""Generate the string to sign from an encrypted item and configuration.
:param dict item: Encrypted DynamoDB item
:param str table_name: Table name to use when generating the string... | python | def _string_to_sign(item, table_name, attribute_actions):
# type: (dynamodb_types.ITEM, Text, AttributeActions) -> bytes
"""Generate the string to sign from an encrypted item and configuration.
:param dict item: Encrypted DynamoDB item
:param str table_name: Table name to use when generating the string... | [
"def",
"_string_to_sign",
"(",
"item",
",",
"table_name",
",",
"attribute_actions",
")",
":",
"hasher",
"=",
"hashes",
".",
"Hash",
"(",
"hashes",
".",
"SHA256",
"(",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"data_to_sign",
"=",
"bytearr... | Generate the string to sign from an encrypted item and configuration.
:param dict item: Encrypted DynamoDB item
:param str table_name: Table name to use when generating the string to sign
:param AttributeActions attribute_actions: Actions to take for item | [
"Generate",
"the",
"string",
"to",
"sign",
"from",
"an",
"encrypted",
"item",
"and",
"configuration",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/authentication.py#L82-L106 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/authentication.py | _hash_data | def _hash_data(hasher, data):
"""Generate hash of data using provided hash type.
:param hasher: Hasher instance to use as a base for calculating hash
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param bytes data: Data to sign
:returns: Hash of data
:rtype: bytes
"""
_hasher... | python | def _hash_data(hasher, data):
"""Generate hash of data using provided hash type.
:param hasher: Hasher instance to use as a base for calculating hash
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param bytes data: Data to sign
:returns: Hash of data
:rtype: bytes
"""
_hasher... | [
"def",
"_hash_data",
"(",
"hasher",
",",
"data",
")",
":",
"_hasher",
"=",
"hasher",
".",
"copy",
"(",
")",
"_hasher",
".",
"update",
"(",
"data",
")",
"return",
"_hasher",
".",
"finalize",
"(",
")"
] | Generate hash of data using provided hash type.
:param hasher: Hasher instance to use as a base for calculating hash
:type hasher: cryptography.hazmat.primitives.hashes.Hash
:param bytes data: Data to sign
:returns: Hash of data
:rtype: bytes | [
"Generate",
"hash",
"of",
"data",
"using",
"provided",
"hash",
"type",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/authentication.py#L109-L120 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/formatting/material_description.py | serialize | def serialize(material_description):
# type: (Dict[Text, Text]) -> dynamodb_types.BINARY_ATTRIBUTE
"""Serialize a material description dictionary into a DynamodDB attribute.
:param dict material_description: Material description dictionary
:returns: Serialized material description as a DynamoDB binary ... | python | def serialize(material_description):
# type: (Dict[Text, Text]) -> dynamodb_types.BINARY_ATTRIBUTE
"""Serialize a material description dictionary into a DynamodDB attribute.
:param dict material_description: Material description dictionary
:returns: Serialized material description as a DynamoDB binary ... | [
"def",
"serialize",
"(",
"material_description",
")",
":",
"material_description_bytes",
"=",
"bytearray",
"(",
"_MATERIAL_DESCRIPTION_VERSION",
")",
"for",
"name",
",",
"value",
"in",
"sorted",
"(",
"material_description",
".",
"items",
"(",
")",
",",
"key",
"=",... | Serialize a material description dictionary into a DynamodDB attribute.
:param dict material_description: Material description dictionary
:returns: Serialized material description as a DynamoDB binary attribute value
:rtype: dict
:raises InvalidMaterialDescriptionError: if invalid name or value found i... | [
"Serialize",
"a",
"material",
"description",
"dictionary",
"into",
"a",
"DynamodDB",
"attribute",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/formatting/material_description.py#L44-L65 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/formatting/material_description.py | deserialize | def deserialize(serialized_material_description):
# type: (dynamodb_types.BINARY_ATTRIBUTE) -> Dict[Text, Text]
"""Deserialize a serialized material description attribute into a material description dictionary.
:param dict serialized_material_description: DynamoDB attribute value containing serialized mate... | python | def deserialize(serialized_material_description):
# type: (dynamodb_types.BINARY_ATTRIBUTE) -> Dict[Text, Text]
"""Deserialize a serialized material description attribute into a material description dictionary.
:param dict serialized_material_description: DynamoDB attribute value containing serialized mate... | [
"def",
"deserialize",
"(",
"serialized_material_description",
")",
":",
"try",
":",
"_raw_material_description",
"=",
"serialized_material_description",
"[",
"Tag",
".",
"BINARY",
".",
"dynamodb_tag",
"]",
"material_description_bytes",
"=",
"io",
".",
"BytesIO",
"(",
... | Deserialize a serialized material description attribute into a material description dictionary.
:param dict serialized_material_description: DynamoDB attribute value containing serialized material description.
:returns: Material description dictionary
:rtype: dict
:raises InvalidMaterialDescriptionErro... | [
"Deserialize",
"a",
"serialized",
"material",
"description",
"attribute",
"into",
"a",
"material",
"description",
"dictionary",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/formatting/material_description.py#L68-L100 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/formatting/material_description.py | _read_version | def _read_version(material_description_bytes):
# type: (io.BytesIO) -> None
"""Read the version from the serialized material description and raise an error if it is unknown.
:param material_description_bytes: serializezd material description
:type material_description_bytes: io.BytesIO
:raises Inva... | python | def _read_version(material_description_bytes):
# type: (io.BytesIO) -> None
"""Read the version from the serialized material description and raise an error if it is unknown.
:param material_description_bytes: serializezd material description
:type material_description_bytes: io.BytesIO
:raises Inva... | [
"def",
"_read_version",
"(",
"material_description_bytes",
")",
":",
"try",
":",
"(",
"version",
",",
")",
"=",
"unpack_value",
"(",
"\">4s\"",
",",
"material_description_bytes",
")",
"except",
"struct",
".",
"error",
":",
"message",
"=",
"\"Malformed material des... | Read the version from the serialized material description and raise an error if it is unknown.
:param material_description_bytes: serializezd material description
:type material_description_bytes: io.BytesIO
:raises InvalidMaterialDescriptionError: if malformed version
:raises InvalidMaterialDescriptio... | [
"Read",
"the",
"version",
"from",
"the",
"serialized",
"material",
"description",
"and",
"raise",
"an",
"error",
"if",
"it",
"is",
"unknown",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/formatting/material_description.py#L103-L119 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/encrypted/item.py | encrypt_dynamodb_item | def encrypt_dynamodb_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Encrypt a DynamoDB item.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item
>>> plaintext_item = {
... 'some': {'S': 'data'},
... 'more': {'N':... | python | def encrypt_dynamodb_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Encrypt a DynamoDB item.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item
>>> plaintext_item = {
... 'some': {'S': 'data'},
... 'more': {'N':... | [
"def",
"encrypt_dynamodb_item",
"(",
"item",
",",
"crypto_config",
")",
":",
"if",
"crypto_config",
".",
"attribute_actions",
".",
"take_no_actions",
":",
"return",
"item",
".",
"copy",
"(",
")",
"for",
"reserved_name",
"in",
"ReservedAttributes",
":",
"if",
"re... | Encrypt a DynamoDB item.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item
>>> plaintext_item = {
... 'some': {'S': 'data'},
... 'more': {'N': '5'}
... }
>>> encrypted_item = encrypt_dynamodb_item(
... item=plaintext_item,
... crypto_config=my_... | [
"Encrypt",
"a",
"DynamoDB",
"item",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/encrypted/item.py#L40-L119 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/encrypted/item.py | encrypt_python_item | def encrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... | python | def encrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... | [
"def",
"encrypt_python_item",
"(",
"item",
",",
"crypto_config",
")",
":",
"ddb_item",
"=",
"dict_to_ddb",
"(",
"item",
")",
"encrypted_ddb_item",
"=",
"encrypt_dynamodb_item",
"(",
"ddb_item",
",",
"crypto_config",
")",
"return",
"ddb_to_dict",
"(",
"encrypted_ddb_... | Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... }
>>> encrypted_item = encrypt_python_item(
... item=plaintext_item,
... crypto_config=my_crypto_con... | [
"Encrypt",
"a",
"dictionary",
"for",
"DynamoDB",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/encrypted/item.py#L122-L147 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/encrypted/item.py | decrypt_dynamodb_item | def decrypt_dynamodb_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Decrypt a DynamoDB item.
>>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item
>>> encrypted_item = {
... 'some': {'B': b'ENCRYPTED_DATA'},
... 'mor... | python | def decrypt_dynamodb_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Decrypt a DynamoDB item.
>>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item
>>> encrypted_item = {
... 'some': {'B': b'ENCRYPTED_DATA'},
... 'mor... | [
"def",
"decrypt_dynamodb_item",
"(",
"item",
",",
"crypto_config",
")",
":",
"unique_actions",
"=",
"set",
"(",
"[",
"crypto_config",
".",
"attribute_actions",
".",
"default_action",
".",
"name",
"]",
")",
"unique_actions",
".",
"update",
"(",
"set",
"(",
"[",... | Decrypt a DynamoDB item.
>>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item
>>> encrypted_item = {
... 'some': {'B': b'ENCRYPTED_DATA'},
... 'more': {'B': b'ENCRYPTED_DATA'}
... }
>>> decrypted_item = decrypt_python_item(
... item=encrypted_item,
... ... | [
"Decrypt",
"a",
"DynamoDB",
"item",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/encrypted/item.py#L150-L228 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/encrypted/item.py | decrypt_python_item | def decrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Decrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item
>>> encrypted_item = {
... 'some': Binary(b'ENCRYPTED_DATA'),
...... | python | def decrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Decrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item
>>> encrypted_item = {
... 'some': Binary(b'ENCRYPTED_DATA'),
...... | [
"def",
"decrypt_python_item",
"(",
"item",
",",
"crypto_config",
")",
":",
"ddb_item",
"=",
"dict_to_ddb",
"(",
"item",
")",
"decrypted_ddb_item",
"=",
"decrypt_dynamodb_item",
"(",
"ddb_item",
",",
"crypto_config",
")",
"return",
"ddb_to_dict",
"(",
"decrypted_ddb_... | Decrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import decrypt_python_item
>>> encrypted_item = {
... 'some': Binary(b'ENCRYPTED_DATA'),
... 'more': Binary(b'ENCRYPTED_DATA')
... }
>>> decrypted_item = decrypt_python_item(
... item=encrypted_it... | [
"Decrypt",
"a",
"dictionary",
"for",
"DynamoDB",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/encrypted/item.py#L231-L256 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/transform.py | dict_to_ddb | def dict_to_ddb(item):
# type: (Dict[str, Any]) -> Dict[str, Any]
# TODO: narrow these types down
"""Converts a native Python dictionary to a raw DynamoDB item.
:param dict item: Native item
:returns: DynamoDB item
:rtype: dict
"""
serializer = TypeSerializer()
return {key: serializ... | python | def dict_to_ddb(item):
# type: (Dict[str, Any]) -> Dict[str, Any]
# TODO: narrow these types down
"""Converts a native Python dictionary to a raw DynamoDB item.
:param dict item: Native item
:returns: DynamoDB item
:rtype: dict
"""
serializer = TypeSerializer()
return {key: serializ... | [
"def",
"dict_to_ddb",
"(",
"item",
")",
":",
"serializer",
"=",
"TypeSerializer",
"(",
")",
"return",
"{",
"key",
":",
"serializer",
".",
"serialize",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"item",
".",
"items",
"(",
")",
"}"
] | Converts a native Python dictionary to a raw DynamoDB item.
:param dict item: Native item
:returns: DynamoDB item
:rtype: dict | [
"Converts",
"a",
"native",
"Python",
"dictionary",
"to",
"a",
"raw",
"DynamoDB",
"item",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/transform.py#L25-L35 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/transform.py | ddb_to_dict | def ddb_to_dict(item):
# type: (Dict[str, Any]) -> Dict[str, Any]
# TODO: narrow these types down
"""Converts a raw DynamoDB item to a native Python dictionary.
:param dict item: DynamoDB item
:returns: Native item
:rtype: dict
"""
deserializer = TypeDeserializer()
return {key: dese... | python | def ddb_to_dict(item):
# type: (Dict[str, Any]) -> Dict[str, Any]
# TODO: narrow these types down
"""Converts a raw DynamoDB item to a native Python dictionary.
:param dict item: DynamoDB item
:returns: Native item
:rtype: dict
"""
deserializer = TypeDeserializer()
return {key: dese... | [
"def",
"ddb_to_dict",
"(",
"item",
")",
":",
"deserializer",
"=",
"TypeDeserializer",
"(",
")",
"return",
"{",
"key",
":",
"deserializer",
".",
"deserialize",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"item",
".",
"items",
"(",
")",
"}"
] | Converts a raw DynamoDB item to a native Python dictionary.
:param dict item: DynamoDB item
:returns: Native item
:rtype: dict | [
"Converts",
"a",
"raw",
"DynamoDB",
"item",
"to",
"a",
"native",
"Python",
"dictionary",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/transform.py#L38-L48 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/validators.py | dictionary_validator | def dictionary_validator(key_type, value_type):
"""Validator for ``attrs`` that performs deep type checking of dictionaries."""
def _validate_dictionary(instance, attribute, value):
# pylint: disable=unused-argument
"""Validate that a dictionary is structured as expected.
:raises TypeE... | python | def dictionary_validator(key_type, value_type):
"""Validator for ``attrs`` that performs deep type checking of dictionaries."""
def _validate_dictionary(instance, attribute, value):
# pylint: disable=unused-argument
"""Validate that a dictionary is structured as expected.
:raises TypeE... | [
"def",
"dictionary_validator",
"(",
"key_type",
",",
"value_type",
")",
":",
"def",
"_validate_dictionary",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
... | Validator for ``attrs`` that performs deep type checking of dictionaries. | [
"Validator",
"for",
"attrs",
"that",
"performs",
"deep",
"type",
"checking",
"of",
"dictionaries",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/validators.py#L23-L48 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/validators.py | iterable_validator | def iterable_validator(iterable_type, member_type):
"""Validator for ``attrs`` that performs deep type checking of iterables."""
def _validate_tuple(instance, attribute, value):
# pylint: disable=unused-argument
"""Validate that a dictionary is structured as expected.
:raises TypeError... | python | def iterable_validator(iterable_type, member_type):
"""Validator for ``attrs`` that performs deep type checking of iterables."""
def _validate_tuple(instance, attribute, value):
# pylint: disable=unused-argument
"""Validate that a dictionary is structured as expected.
:raises TypeError... | [
"def",
"iterable_validator",
"(",
"iterable_type",
",",
"member_type",
")",
":",
"def",
"_validate_tuple",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"iterable_type",
")",
":",
"raise",
"TypeError",... | Validator for ``attrs`` that performs deep type checking of iterables. | [
"Validator",
"for",
"attrs",
"that",
"performs",
"deep",
"type",
"checking",
"of",
"iterables",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/validators.py#L51-L70 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/validators.py | callable_validator | def callable_validator(instance, attribute, value):
# pylint: disable=unused-argument
"""Validate that an attribute value is callable.
:raises TypeError: if ``value`` is not callable
"""
if not callable(value):
raise TypeError('"{name}" value "{value}" must be callable'.format(name=attribut... | python | def callable_validator(instance, attribute, value):
# pylint: disable=unused-argument
"""Validate that an attribute value is callable.
:raises TypeError: if ``value`` is not callable
"""
if not callable(value):
raise TypeError('"{name}" value "{value}" must be callable'.format(name=attribut... | [
"def",
"callable_validator",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"if",
"not",
"callable",
"(",
"value",
")",
":",
"raise",
"TypeError",
"(",
"'\"{name}\" value \"{value}\" must be callable'",
".",
"format",
"(",
"name",
"=",
"attribute",
"... | Validate that an attribute value is callable.
:raises TypeError: if ``value`` is not callable | [
"Validate",
"that",
"an",
"attribute",
"value",
"is",
"callable",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/validators.py#L73-L80 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/encryption.py | encrypt_attribute | def encrypt_attribute(attribute_name, attribute, encryption_key, algorithm):
# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.BINARY_ATTRIBUTE
"""Encrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Plaintext Dy... | python | def encrypt_attribute(attribute_name, attribute, encryption_key, algorithm):
# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.BINARY_ATTRIBUTE
"""Encrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Plaintext Dy... | [
"def",
"encrypt_attribute",
"(",
"attribute_name",
",",
"attribute",
",",
"encryption_key",
",",
"algorithm",
")",
":",
"serialized_attribute",
"=",
"serialize_attribute",
"(",
"attribute",
")",
"encrypted_attribute",
"=",
"encryption_key",
".",
"encrypt",
"(",
"algor... | Encrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Plaintext DynamoDB attribute
:param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute
:param str algorithm: Encryption algorithm descriptor (passed to encryption_key as... | [
"Encrypt",
"a",
"single",
"DynamoDB",
"attribute",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/encryption.py#L34-L49 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/encryption.py | decrypt_attribute | def decrypt_attribute(attribute_name, attribute, decryption_key, algorithm):
# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE
"""Decrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Encrypted Dynam... | python | def decrypt_attribute(attribute_name, attribute, decryption_key, algorithm):
# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE
"""Decrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Encrypted Dynam... | [
"def",
"decrypt_attribute",
"(",
"attribute_name",
",",
"attribute",
",",
"decryption_key",
",",
"algorithm",
")",
":",
"encrypted_attribute",
"=",
"attribute",
"[",
"Tag",
".",
"BINARY",
".",
"dynamodb_tag",
"]",
"decrypted_attribute",
"=",
"decryption_key",
".",
... | Decrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Encrypted DynamoDB attribute
:param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute
:param str algorithm: Decryption algorithm descriptor (passed to encryption_key as... | [
"Decrypt",
"a",
"single",
"DynamoDB",
"attribute",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/encryption.py#L52-L67 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/delegated_keys/jce.py | _generate_rsa_key | def _generate_rsa_key(key_length):
"""Generate a new RSA private key.
:param int key_length: Required key length in bits
:returns: DER-encoded private key, private key identifier, and DER encoding identifier
:rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`)
"""
private_... | python | def _generate_rsa_key(key_length):
"""Generate a new RSA private key.
:param int key_length: Required key length in bits
:returns: DER-encoded private key, private key identifier, and DER encoding identifier
:rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`)
"""
private_... | [
"def",
"_generate_rsa_key",
"(",
"key_length",
")",
":",
"private_key",
"=",
"rsa",
".",
"generate_private_key",
"(",
"public_exponent",
"=",
"65537",
",",
"key_size",
"=",
"key_length",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"key_bytes",
"=",
... | Generate a new RSA private key.
:param int key_length: Required key length in bits
:returns: DER-encoded private key, private key identifier, and DER encoding identifier
:rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`) | [
"Generate",
"a",
"new",
"RSA",
"private",
"key",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/delegated_keys/jce.py#L52-L65 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/formatting/serialize/__init__.py | encode_value | def encode_value(value):
# type: (bytes) -> bytes
"""Encodes the value in Length-Value format.
:param value: Value to encode
:type value: six.string_types or :class:`boto3.dynamodb_encryption_sdk.types.Binary`
:returns: Length-Value encoded value
:rtype: bytes
"""
return struct.pack(">I... | python | def encode_value(value):
# type: (bytes) -> bytes
"""Encodes the value in Length-Value format.
:param value: Value to encode
:type value: six.string_types or :class:`boto3.dynamodb_encryption_sdk.types.Binary`
:returns: Length-Value encoded value
:rtype: bytes
"""
return struct.pack(">I... | [
"def",
"encode_value",
"(",
"value",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"\">I{attr_len:d}s\"",
".",
"format",
"(",
"attr_len",
"=",
"len",
"(",
"value",
")",
")",
",",
"len",
"(",
"value",
")",
",",
"value",
")"
] | Encodes the value in Length-Value format.
:param value: Value to encode
:type value: six.string_types or :class:`boto3.dynamodb_encryption_sdk.types.Binary`
:returns: Length-Value encoded value
:rtype: bytes | [
"Encodes",
"the",
"value",
"in",
"Length",
"-",
"Value",
"format",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/formatting/serialize/__init__.py#L41-L50 | train |
aws/aws-dynamodb-encryption-python | examples/src/aws_kms_encrypted_client.py | encrypt_item | def encrypt_item(table_name, aws_cmk_id):
"""Demonstrate use of EncryptedClient to transparently encrypt an item."""
index_key = {"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}}
plaintext_item = {
"example": {"S": "data"},
"some numbers": {"N": "99"},
"and som... | python | def encrypt_item(table_name, aws_cmk_id):
"""Demonstrate use of EncryptedClient to transparently encrypt an item."""
index_key = {"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}}
plaintext_item = {
"example": {"S": "data"},
"some numbers": {"N": "99"},
"and som... | [
"def",
"encrypt_item",
"(",
"table_name",
",",
"aws_cmk_id",
")",
":",
"index_key",
"=",
"{",
"\"partition_attribute\"",
":",
"{",
"\"S\"",
":",
"\"is this\"",
"}",
",",
"\"sort_attribute\"",
":",
"{",
"\"N\"",
":",
"\"55\"",
"}",
"}",
"plaintext_item",
"=",
... | Demonstrate use of EncryptedClient to transparently encrypt an item. | [
"Demonstrate",
"use",
"of",
"EncryptedClient",
"to",
"transparently",
"encrypt",
"an",
"item",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/examples/src/aws_kms_encrypted_client.py#L22-L70 | train |
aws/aws-dynamodb-encryption-python | examples/src/aws_kms_encrypted_client.py | encrypt_batch_items | def encrypt_batch_items(table_name, aws_cmk_id):
"""Demonstrate use of EncryptedClient to transparently encrypt multiple items in a batch request."""
index_keys = [
{"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}},
{"partition_attribute": {"S": "is this"}, "sort_attribute... | python | def encrypt_batch_items(table_name, aws_cmk_id):
"""Demonstrate use of EncryptedClient to transparently encrypt multiple items in a batch request."""
index_keys = [
{"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}},
{"partition_attribute": {"S": "is this"}, "sort_attribute... | [
"def",
"encrypt_batch_items",
"(",
"table_name",
",",
"aws_cmk_id",
")",
":",
"index_keys",
"=",
"[",
"{",
"\"partition_attribute\"",
":",
"{",
"\"S\"",
":",
"\"is this\"",
"}",
",",
"\"sort_attribute\"",
":",
"{",
"\"N\"",
":",
"\"55\"",
"}",
"}",
",",
"{",... | Demonstrate use of EncryptedClient to transparently encrypt multiple items in a batch request. | [
"Demonstrate",
"use",
"of",
"EncryptedClient",
"to",
"transparently",
"encrypt",
"multiple",
"items",
"in",
"a",
"batch",
"request",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/examples/src/aws_kms_encrypted_client.py#L73-L157 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py | load_rsa_key | def load_rsa_key(key, key_type, key_encoding):
# (bytes, EncryptionKeyType, KeyEncodingType) -> Any
# TODO: narrow down the output type
"""Load an RSA key object from the provided raw key bytes.
:param bytes key: Raw key bytes to load
:param EncryptionKeyType key_type: Type of key to load
:para... | python | def load_rsa_key(key, key_type, key_encoding):
# (bytes, EncryptionKeyType, KeyEncodingType) -> Any
# TODO: narrow down the output type
"""Load an RSA key object from the provided raw key bytes.
:param bytes key: Raw key bytes to load
:param EncryptionKeyType key_type: Type of key to load
:para... | [
"def",
"load_rsa_key",
"(",
"key",
",",
"key_type",
",",
"key_encoding",
")",
":",
"try",
":",
"loader",
"=",
"_RSA_KEY_LOADING",
"[",
"key_type",
"]",
"[",
"key_encoding",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Invalid key type and encod... | Load an RSA key object from the provided raw key bytes.
:param bytes key: Raw key bytes to load
:param EncryptionKeyType key_type: Type of key to load
:param KeyEncodingType key_encoding: Encoding used to serialize ``key``
:returns: Loaded key
:rtype: TODO:
:raises ValueError: if ``key_type`` a... | [
"Load",
"an",
"RSA",
"key",
"object",
"from",
"the",
"provided",
"raw",
"key",
"bytes",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L434-L460 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py | JavaSymmetricEncryptionAlgorithm._disable_encryption | def _disable_encryption(self):
# () -> None
"""Enable encryption methods for ciphers that support them."""
self.encrypt = self._disabled_encrypt
self.decrypt = self._disabled_decrypt | python | def _disable_encryption(self):
# () -> None
"""Enable encryption methods for ciphers that support them."""
self.encrypt = self._disabled_encrypt
self.decrypt = self._disabled_decrypt | [
"def",
"_disable_encryption",
"(",
"self",
")",
":",
"self",
".",
"encrypt",
"=",
"self",
".",
"_disabled_encrypt",
"self",
".",
"decrypt",
"=",
"self",
".",
"_disabled_decrypt"
] | Enable encryption methods for ciphers that support them. | [
"Enable",
"encryption",
"methods",
"for",
"ciphers",
"that",
"support",
"them",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L296-L300 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py | JavaSymmetricEncryptionAlgorithm.wrap | def wrap(self, wrapping_key, key_to_wrap):
# type: (bytes, bytes) -> bytes
"""Wrap key using AES keywrap.
:param bytes wrapping_key: Loaded key with which to wrap
:param bytes key_to_wrap: Raw key to wrap
:returns: Wrapped key
:rtype: bytes
"""
if self.ja... | python | def wrap(self, wrapping_key, key_to_wrap):
# type: (bytes, bytes) -> bytes
"""Wrap key using AES keywrap.
:param bytes wrapping_key: Loaded key with which to wrap
:param bytes key_to_wrap: Raw key to wrap
:returns: Wrapped key
:rtype: bytes
"""
if self.ja... | [
"def",
"wrap",
"(",
"self",
",",
"wrapping_key",
",",
"key_to_wrap",
")",
":",
"if",
"self",
".",
"java_name",
"not",
"in",
"(",
"\"AES\"",
",",
"\"AESWrap\"",
")",
":",
"raise",
"NotImplementedError",
"(",
"'\"wrap\" is not supported by the \"{}\" cipher'",
".",
... | Wrap key using AES keywrap.
:param bytes wrapping_key: Loaded key with which to wrap
:param bytes key_to_wrap: Raw key to wrap
:returns: Wrapped key
:rtype: bytes | [
"Wrap",
"key",
"using",
"AES",
"keywrap",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L330-L347 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py | JavaSymmetricEncryptionAlgorithm.unwrap | def unwrap(self, wrapping_key, wrapped_key):
# type: (bytes, bytes) -> bytes
"""Unwrap key using AES keywrap.
:param bytes wrapping_key: Loaded key with which to unwrap
:param bytes wrapped_key: Wrapped key to unwrap
:returns: Unwrapped key
:rtype: bytes
"""
... | python | def unwrap(self, wrapping_key, wrapped_key):
# type: (bytes, bytes) -> bytes
"""Unwrap key using AES keywrap.
:param bytes wrapping_key: Loaded key with which to unwrap
:param bytes wrapped_key: Wrapped key to unwrap
:returns: Unwrapped key
:rtype: bytes
"""
... | [
"def",
"unwrap",
"(",
"self",
",",
"wrapping_key",
",",
"wrapped_key",
")",
":",
"if",
"self",
".",
"java_name",
"not",
"in",
"(",
"\"AES\"",
",",
"\"AESWrap\"",
")",
":",
"raise",
"NotImplementedError",
"(",
"'\"unwrap\" is not supported by this cipher'",
")",
... | Unwrap key using AES keywrap.
:param bytes wrapping_key: Loaded key with which to unwrap
:param bytes wrapped_key: Wrapped key to unwrap
:returns: Unwrapped key
:rtype: bytes | [
"Unwrap",
"key",
"using",
"AES",
"keywrap",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L349-L366 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/structures.py | _validate_attribute_values_are_ddb_items | def _validate_attribute_values_are_ddb_items(instance, attribute, value): # pylint: disable=unused-argument
"""Validate that dictionary values in ``value`` match the structure of DynamoDB JSON
items.
.. note::
We are not trying to validate the full structure of the item with this validator.
... | python | def _validate_attribute_values_are_ddb_items(instance, attribute, value): # pylint: disable=unused-argument
"""Validate that dictionary values in ``value`` match the structure of DynamoDB JSON
items.
.. note::
We are not trying to validate the full structure of the item with this validator.
... | [
"def",
"_validate_attribute_values_are_ddb_items",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"for",
"data",
"in",
"value",
".",
"values",
"(",
")",
":",
"if",
"len",
"(",
"list",
"(",
"data",
".",
"values",
"(",
")",
")",
")",
"!=",
"1... | Validate that dictionary values in ``value`` match the structure of DynamoDB JSON
items.
.. note::
We are not trying to validate the full structure of the item with this validator.
This is just meant to verify that the values roughly match the correct format. | [
"Validate",
"that",
"dictionary",
"values",
"in",
"value",
"match",
"the",
"structure",
"of",
"DynamoDB",
"JSON",
"items",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/structures.py#L35-L46 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | validate_get_arguments | def validate_get_arguments(kwargs):
# type: (Dict[Text, Any]) -> None
"""Verify that attribute filtering parameters are not found in the request.
:raises InvalidArgumentError: if banned parameters are found
"""
for arg in ("AttributesToGet", "ProjectionExpression"):
if arg in kwargs:
... | python | def validate_get_arguments(kwargs):
# type: (Dict[Text, Any]) -> None
"""Verify that attribute filtering parameters are not found in the request.
:raises InvalidArgumentError: if banned parameters are found
"""
for arg in ("AttributesToGet", "ProjectionExpression"):
if arg in kwargs:
... | [
"def",
"validate_get_arguments",
"(",
"kwargs",
")",
":",
"for",
"arg",
"in",
"(",
"\"AttributesToGet\"",
",",
"\"ProjectionExpression\"",
")",
":",
"if",
"arg",
"in",
"kwargs",
":",
"raise",
"InvalidArgumentError",
"(",
"'\"{}\" is not supported for this operation'",
... | Verify that attribute filtering parameters are not found in the request.
:raises InvalidArgumentError: if banned parameters are found | [
"Verify",
"that",
"attribute",
"filtering",
"parameters",
"are",
"not",
"found",
"in",
"the",
"request",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L97-L108 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | crypto_config_from_kwargs | def crypto_config_from_kwargs(fallback, **kwargs):
"""Pull all encryption-specific parameters from the request and use them to build a crypto config.
:returns: crypto config and updated kwargs
:rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict
"""
try:
crypto_config = kwargs.po... | python | def crypto_config_from_kwargs(fallback, **kwargs):
"""Pull all encryption-specific parameters from the request and use them to build a crypto config.
:returns: crypto config and updated kwargs
:rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict
"""
try:
crypto_config = kwargs.po... | [
"def",
"crypto_config_from_kwargs",
"(",
"fallback",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"crypto_config",
"=",
"kwargs",
".",
"pop",
"(",
"\"crypto_config\"",
")",
"except",
"KeyError",
":",
"try",
":",
"fallback_kwargs",
"=",
"{",
"\"table_name\"",
":"... | Pull all encryption-specific parameters from the request and use them to build a crypto config.
:returns: crypto config and updated kwargs
:rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict | [
"Pull",
"all",
"encryption",
"-",
"specific",
"parameters",
"from",
"the",
"request",
"and",
"use",
"them",
"to",
"build",
"a",
"crypto",
"config",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L111-L125 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | crypto_config_from_table_info | def crypto_config_from_table_info(materials_provider, attribute_actions, table_info):
"""Build a crypto config from the provided values and table info.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
ec_kwargs = table_info.encryption_context_values
if table_info... | python | def crypto_config_from_table_info(materials_provider, attribute_actions, table_info):
"""Build a crypto config from the provided values and table info.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
ec_kwargs = table_info.encryption_context_values
if table_info... | [
"def",
"crypto_config_from_table_info",
"(",
"materials_provider",
",",
"attribute_actions",
",",
"table_info",
")",
":",
"ec_kwargs",
"=",
"table_info",
".",
"encryption_context_values",
"if",
"table_info",
".",
"primary_index",
"is",
"not",
"None",
":",
"ec_kwargs",
... | Build a crypto config from the provided values and table info.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict) | [
"Build",
"a",
"crypto",
"config",
"from",
"the",
"provided",
"values",
"and",
"table",
"info",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L128-L144 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | crypto_config_from_cache | def crypto_config_from_cache(materials_provider, attribute_actions, table_info_cache, table_name):
"""Build a crypto config from the provided values, loading the table info from the provided cache.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
table_info = table_i... | python | def crypto_config_from_cache(materials_provider, attribute_actions, table_info_cache, table_name):
"""Build a crypto config from the provided values, loading the table info from the provided cache.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
table_info = table_i... | [
"def",
"crypto_config_from_cache",
"(",
"materials_provider",
",",
"attribute_actions",
",",
"table_info_cache",
",",
"table_name",
")",
":",
"table_info",
"=",
"table_info_cache",
".",
"table_info",
"(",
"table_name",
")",
"attribute_actions",
"=",
"attribute_actions",
... | Build a crypto config from the provided values, loading the table info from the provided cache.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict) | [
"Build",
"a",
"crypto",
"config",
"from",
"the",
"provided",
"values",
"loading",
"the",
"table",
"info",
"from",
"the",
"provided",
"cache",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L147-L158 | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | decrypt_multi_get | def decrypt_multi_get(decrypt_method, crypto_config_method, read_method, **kwargs):
# type: (Callable, Callable, Callable, **Any) -> Dict
# TODO: narrow this down
"""Transparently decrypt multiple items after getting them from the table with a scan or query method.
:param callable decrypt_method: Metho... | python | def decrypt_multi_get(decrypt_method, crypto_config_method, read_method, **kwargs):
# type: (Callable, Callable, Callable, **Any) -> Dict
# TODO: narrow this down
"""Transparently decrypt multiple items after getting them from the table with a scan or query method.
:param callable decrypt_method: Metho... | [
"def",
"decrypt_multi_get",
"(",
"decrypt_method",
",",
"crypto_config_method",
",",
"read_method",
",",
"**",
"kwargs",
")",
":",
"validate_get_arguments",
"(",
"kwargs",
")",
"crypto_config",
",",
"ddb_kwargs",
"=",
"crypto_config_method",
"(",
"**",
"kwargs",
")"... | Transparently decrypt multiple items after getting them from the table with a scan or query method.
:param callable decrypt_method: Method to use to decrypt items
:param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig`
:param callable read_method: Method th... | [
"Transparently",
"decrypt",
"multiple",
"items",
"after",
"getting",
"them",
"from",
"the",
"table",
"with",
"a",
"scan",
"or",
"query",
"method",
"."
] | 8de3bbe13df39c59b21bf431010f7acfcf629a2f | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L174-L194 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.