repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_string | def scramble_string(self, length):
"""Return random string"""
return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)]) | python | def scramble_string(self, length):
"""Return random string"""
return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)]) | [
"def",
"scramble_string",
"(",
"self",
",",
"length",
")",
":",
"return",
"fake",
".",
"text",
"(",
"length",
")",
"if",
"length",
">",
"5",
"else",
"''",
".",
"join",
"(",
"[",
"fake",
".",
"random_letter",
"(",
")",
"for",
"n",
"in",
"range",
"("... | Return random string | [
"Return",
"random",
"string"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L102-L104 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_value | def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
i, f = value.split('.')
return self.scramble_float(len(value) - 1, len(f))
elif type == 'i... | python | def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
i, f = value.split('.')
return self.scramble_float(len(value) - 1, len(f))
elif type == 'i... | [
"def",
"scramble_value",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"type",
",",
"format",
"=",
"typeof_rave_data",
"(",
"value",
")",
"if",
"type",
"==",
"'float'",
":",
"i",
",",
"f",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
"return",
"... | Duck-type value and scramble appropriately | [
"Duck",
"-",
"type",
"value",
"and",
"scramble",
"appropriately"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L106-L124 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_codelist | def scramble_codelist(self, codelist):
"""Return random element from code list"""
# TODO: External code lists
path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist)
elem = self.metadata.find(path)
codes = []
for c in elem.iter(E_ODM.CODELIST_... | python | def scramble_codelist(self, codelist):
"""Return random element from code list"""
# TODO: External code lists
path = ".//{0}[@{1}='{2}']".format(E_ODM.CODELIST.value, A_ODM.OID.value, codelist)
elem = self.metadata.find(path)
codes = []
for c in elem.iter(E_ODM.CODELIST_... | [
"def",
"scramble_codelist",
"(",
"self",
",",
"codelist",
")",
":",
"# TODO: External code lists",
"path",
"=",
"\".//{0}[@{1}='{2}']\"",
".",
"format",
"(",
"E_ODM",
".",
"CODELIST",
".",
"value",
",",
"A_ODM",
".",
"OID",
".",
"value",
",",
"codelist",
")",... | Return random element from code list | [
"Return",
"random",
"element",
"from",
"code",
"list"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L134-L145 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.scramble_itemdata | def scramble_itemdata(self, oid, value):
"""If metadata provided, use it to scramble the value based on data type"""
if self.metadata is not None:
path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid)
elem = self.metadata.find(path)
# for elem... | python | def scramble_itemdata(self, oid, value):
"""If metadata provided, use it to scramble the value based on data type"""
if self.metadata is not None:
path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid)
elem = self.metadata.find(path)
# for elem... | [
"def",
"scramble_itemdata",
"(",
"self",
",",
"oid",
",",
"value",
")",
":",
"if",
"self",
".",
"metadata",
"is",
"not",
"None",
":",
"path",
"=",
"\".//{0}[@{1}='{2}']\"",
".",
"format",
"(",
"E_ODM",
".",
"ITEM_DEF",
".",
"value",
",",
"A_ODM",
".",
... | If metadata provided, use it to scramble the value based on data type | [
"If",
"metadata",
"provided",
"use",
"it",
"to",
"scramble",
"the",
"value",
"based",
"on",
"data",
"type"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L147-L194 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | Scramble.fill_empty | def fill_empty(self, fixed_values, input):
"""Fill in random values for all empty-valued ItemData elements in an ODM document"""
odm_elements = etree.fromstring(input)
for v in odm_elements.iter(E_ODM.ITEM_DATA.value):
if v.get(A_ODM.VALUE.value) == "":
oid = v.get(A... | python | def fill_empty(self, fixed_values, input):
"""Fill in random values for all empty-valued ItemData elements in an ODM document"""
odm_elements = etree.fromstring(input)
for v in odm_elements.iter(E_ODM.ITEM_DATA.value):
if v.get(A_ODM.VALUE.value) == "":
oid = v.get(A... | [
"def",
"fill_empty",
"(",
"self",
",",
"fixed_values",
",",
"input",
")",
":",
"odm_elements",
"=",
"etree",
".",
"fromstring",
"(",
"input",
")",
"for",
"v",
"in",
"odm_elements",
".",
"iter",
"(",
"E_ODM",
".",
"ITEM_DATA",
".",
"value",
")",
":",
"i... | Fill in random values for all empty-valued ItemData elements in an ODM document | [
"Fill",
"in",
"random",
"values",
"for",
"all",
"empty",
"-",
"valued",
"ItemData",
"elements",
"in",
"an",
"ODM",
"document"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L200-L233 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | make_int | def make_int(value, missing=-1):
"""Convert string value to long, '' to missing"""
if isinstance(value, six.string_types):
if not value.strip():
return missing
elif value is None:
return missing
return int(value) | python | def make_int(value, missing=-1):
"""Convert string value to long, '' to missing"""
if isinstance(value, six.string_types):
if not value.strip():
return missing
elif value is None:
return missing
return int(value) | [
"def",
"make_int",
"(",
"value",
",",
"missing",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"value",
".",
"strip",
"(",
")",
":",
"return",
"missing",
"elif",
"value",
"is",
"N... | Convert string value to long, '' to missing | [
"Convert",
"string",
"value",
"to",
"long",
"to",
"missing"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L38-L45 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | parse | def parse(data, eventer):
"""Parse the XML data, firing events from the eventer"""
parser = etree.XMLParser(target=ODMTargetParser(eventer))
return etree.XML(data, parser) | python | def parse(data, eventer):
"""Parse the XML data, firing events from the eventer"""
parser = etree.XMLParser(target=ODMTargetParser(eventer))
return etree.XML(data, parser) | [
"def",
"parse",
"(",
"data",
",",
"eventer",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"target",
"=",
"ODMTargetParser",
"(",
"eventer",
")",
")",
"return",
"etree",
".",
"XML",
"(",
"data",
",",
"parser",
")"
] | Parse the XML data, firing events from the eventer | [
"Parse",
"the",
"XML",
"data",
"firing",
"events",
"from",
"the",
"eventer"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L284-L287 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.emit | def emit(self):
"""We are finished processing one element. Emit it"""
self.count += 1
# event_name = 'on_{0}'.format(self.context.subcategory.lower())
event_name = self.context.subcategory
if hasattr(self.handler, event_name):
getattr(self.handler, event_name)(self.... | python | def emit(self):
"""We are finished processing one element. Emit it"""
self.count += 1
# event_name = 'on_{0}'.format(self.context.subcategory.lower())
event_name = self.context.subcategory
if hasattr(self.handler, event_name):
getattr(self.handler, event_name)(self.... | [
"def",
"emit",
"(",
"self",
")",
":",
"self",
".",
"count",
"+=",
"1",
"# event_name = 'on_{0}'.format(self.context.subcategory.lower())",
"event_name",
"=",
"self",
".",
"context",
".",
"subcategory",
"if",
"hasattr",
"(",
"self",
".",
"handler",
",",
"event_name... | We are finished processing one element. Emit it | [
"We",
"are",
"finished",
"processing",
"one",
"element",
".",
"Emit",
"it"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L139-L149 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.start | def start(self, tag, attrib):
"""On start of element tag"""
if tag == E_CLINICAL_DATA:
self.ref_state = AUDIT_REF_STATE
self.context = Context(attrib[A_STUDY_OID],
attrib[A_AUDIT_SUBCATEGORY_NAME],
int(attrib[A... | python | def start(self, tag, attrib):
"""On start of element tag"""
if tag == E_CLINICAL_DATA:
self.ref_state = AUDIT_REF_STATE
self.context = Context(attrib[A_STUDY_OID],
attrib[A_AUDIT_SUBCATEGORY_NAME],
int(attrib[A... | [
"def",
"start",
"(",
"self",
",",
"tag",
",",
"attrib",
")",
":",
"if",
"tag",
"==",
"E_CLINICAL_DATA",
":",
"self",
".",
"ref_state",
"=",
"AUDIT_REF_STATE",
"self",
".",
"context",
"=",
"Context",
"(",
"attrib",
"[",
"A_STUDY_OID",
"]",
",",
"attrib",
... | On start of element tag | [
"On",
"start",
"of",
"element",
"tag"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L151-L255 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.get_parent_element | def get_parent_element(self):
"""Signatures and Audit elements share sub-elements, we need to know which to set attributes on"""
return {AUDIT_REF_STATE: self.context.audit_record,
SIGNATURE_REF_STATE: self.context.signature}[self.ref_state] | python | def get_parent_element(self):
"""Signatures and Audit elements share sub-elements, we need to know which to set attributes on"""
return {AUDIT_REF_STATE: self.context.audit_record,
SIGNATURE_REF_STATE: self.context.signature}[self.ref_state] | [
"def",
"get_parent_element",
"(",
"self",
")",
":",
"return",
"{",
"AUDIT_REF_STATE",
":",
"self",
".",
"context",
".",
"audit_record",
",",
"SIGNATURE_REF_STATE",
":",
"self",
".",
"context",
".",
"signature",
"}",
"[",
"self",
".",
"ref_state",
"]"
] | Signatures and Audit elements share sub-elements, we need to know which to set attributes on | [
"Signatures",
"and",
"Audit",
"elements",
"share",
"sub",
"-",
"elements",
"we",
"need",
"to",
"know",
"which",
"to",
"set",
"attributes",
"on"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L263-L266 |
mdsol/rwslib | rwslib/extras/audit_event/parser.py | ODMTargetParser.data | def data(self, data):
"""Called for text between tags"""
if self.state == STATE_SOURCE_ID:
self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits
elif self.state == STATE_DATETIME:
dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
... | python | def data(self, data):
"""Called for text between tags"""
if self.state == STATE_SOURCE_ID:
self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits
elif self.state == STATE_DATETIME:
dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
... | [
"def",
"data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_SOURCE_ID",
":",
"self",
".",
"context",
".",
"audit_record",
".",
"source_id",
"=",
"int",
"(",
"data",
")",
"# Audit ids can be 64 bits",
"elif",
"self",
".",
"... | Called for text between tags | [
"Called",
"for",
"text",
"between",
"tags"
] | train | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/audit_event/parser.py#L268-L277 |
timster/peewee-validates | peewee_validates.py | validate_not_empty | def validate_not_empty():
"""
Validate that a field is not empty (blank string).
:raises: ``ValidationError('empty')``
"""
def empty_validator(field, data):
if isinstance(field.value, str) and not field.value.strip():
raise ValidationError('empty')
return empty_validator | python | def validate_not_empty():
"""
Validate that a field is not empty (blank string).
:raises: ``ValidationError('empty')``
"""
def empty_validator(field, data):
if isinstance(field.value, str) and not field.value.strip():
raise ValidationError('empty')
return empty_validator | [
"def",
"validate_not_empty",
"(",
")",
":",
"def",
"empty_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"field",
".",
"value",
",",
"str",
")",
"and",
"not",
"field",
".",
"value",
".",
"strip",
"(",
")",
":",
"raise",
"Va... | Validate that a field is not empty (blank string).
:raises: ``ValidationError('empty')`` | [
"Validate",
"that",
"a",
"field",
"is",
"not",
"empty",
"(",
"blank",
"string",
")",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L78-L87 |
timster/peewee-validates | peewee_validates.py | validate_length | def validate_length(low=None, high=None, equal=None):
"""
Validate the length of a field with either low, high, or equal.
Should work with anything that supports len().
:param low: Smallest length required.
:param high: Longest length required.
:param equal: Exact length required.
:raises: ... | python | def validate_length(low=None, high=None, equal=None):
"""
Validate the length of a field with either low, high, or equal.
Should work with anything that supports len().
:param low: Smallest length required.
:param high: Longest length required.
:param equal: Exact length required.
:raises: ... | [
"def",
"validate_length",
"(",
"low",
"=",
"None",
",",
"high",
"=",
"None",
",",
"equal",
"=",
"None",
")",
":",
"def",
"length_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"equal",... | Validate the length of a field with either low, high, or equal.
Should work with anything that supports len().
:param low: Smallest length required.
:param high: Longest length required.
:param equal: Exact length required.
:raises: ``ValidationError('length_low')``
:raises: ``ValidationError('... | [
"Validate",
"the",
"length",
"of",
"a",
"field",
"with",
"either",
"low",
"high",
"or",
"equal",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"len",
"()",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L90-L114 |
timster/peewee-validates | peewee_validates.py | validate_one_of | def validate_one_of(values):
"""
Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')``
"""
def one_of_validator(field, data):
if field.value is None:
return
options = values
if cal... | python | def validate_one_of(values):
"""
Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')``
"""
def one_of_validator(field, data):
if field.value is None:
return
options = values
if cal... | [
"def",
"validate_one_of",
"(",
"values",
")",
":",
"def",
"one_of_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"options",
"=",
"values",
"if",
"callable",
"(",
"options",
")",
":",
"options",
... | Validate that a field is in one of the given values.
:param values: Iterable of valid values.
:raises: ``ValidationError('one_of')`` | [
"Validate",
"that",
"a",
"field",
"is",
"in",
"one",
"of",
"the",
"given",
"values",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L117-L132 |
timster/peewee-validates | peewee_validates.py | validate_none_of | def validate_none_of(values):
"""
Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')``
"""
def none_of_validator(field, data):
options = values
if callable(options):
options = opti... | python | def validate_none_of(values):
"""
Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')``
"""
def none_of_validator(field, data):
options = values
if callable(options):
options = opti... | [
"def",
"validate_none_of",
"(",
"values",
")",
":",
"def",
"none_of_validator",
"(",
"field",
",",
"data",
")",
":",
"options",
"=",
"values",
"if",
"callable",
"(",
"options",
")",
":",
"options",
"=",
"options",
"(",
")",
"if",
"field",
".",
"value",
... | Validate that a field is not in one of the given values.
:param values: Iterable of invalid values.
:raises: ``ValidationError('none_of')`` | [
"Validate",
"that",
"a",
"field",
"is",
"not",
"in",
"one",
"of",
"the",
"given",
"values",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L135-L148 |
timster/peewee-validates | peewee_validates.py | validate_range | def validate_range(low=None, high=None):
"""
Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_low')``
:rai... | python | def validate_range(low=None, high=None):
"""
Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_low')``
:rai... | [
"def",
"validate_range",
"(",
"low",
"=",
"None",
",",
"high",
"=",
"None",
")",
":",
"def",
"range_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"low",
"is",
"not",
"None",
"and",
... | Validate the range of a field with either low, high, or equal.
Should work with anything that supports '>' and '<' operators.
:param low: Smallest value required.
:param high: Longest value required.
:raises: ``ValidationError('range_low')``
:raises: ``ValidationError('range_high')``
:raises: `... | [
"Validate",
"the",
"range",
"of",
"a",
"field",
"with",
"either",
"low",
"high",
"or",
"equal",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
">",
"and",
"<",
"operators",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L151-L171 |
timster/peewee-validates | peewee_validates.py | validate_equal | def validate_equal(value):
"""
Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')``
"""
def equal_validator(field, data):
if field.value is None:
... | python | def validate_equal(value):
"""
Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')``
"""
def equal_validator(field, data):
if field.value is None:
... | [
"def",
"validate_equal",
"(",
"value",
")",
":",
"def",
"equal_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"(",
"field",
".",
"value",
"==",
"value",
")",
":",
"raise",
"Vali... | Validate the field value is equal to the given value.
Should work with anything that supports '==' operator.
:param value: Value to compare.
:raises: ``ValidationError('equal')`` | [
"Validate",
"the",
"field",
"value",
"is",
"equal",
"to",
"the",
"given",
"value",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"==",
"operator",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L174-L187 |
timster/peewee-validates | peewee_validates.py | validate_matches | def validate_matches(other):
"""
Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')``
"""
def matches_validator(field, data):
if field.value ... | python | def validate_matches(other):
"""
Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')``
"""
def matches_validator(field, data):
if field.value ... | [
"def",
"validate_matches",
"(",
"other",
")",
":",
"def",
"matches_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"(",
"field",
".",
"value",
"==",
"data",
".",
"get",
"(",
"oth... | Validate the field value is equal to another field in the data.
Should work with anything that supports '==' operator.
:param value: Field key to compare.
:raises: ``ValidationError('matches')`` | [
"Validate",
"the",
"field",
"value",
"is",
"equal",
"to",
"another",
"field",
"in",
"the",
"data",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"==",
"operator",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L190-L203 |
timster/peewee-validates | peewee_validates.py | validate_regexp | def validate_regexp(pattern, flags=0):
"""
Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises... | python | def validate_regexp(pattern, flags=0):
"""
Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises... | [
"def",
"validate_regexp",
"(",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"flags",
")",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
"else",
"pattern",
"def",
"regexp_validator",
"(",
"... | Validate the field matches the given regular expression.
Should work with anything that supports '==' operator.
:param pattern: Regular expresion to match. String or regular expression instance.
:param pattern: Flags for the regular expression.
:raises: ``ValidationError('equal')`` | [
"Validate",
"the",
"field",
"matches",
"the",
"given",
"regular",
"expression",
".",
"Should",
"work",
"with",
"anything",
"that",
"supports",
"==",
"operator",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L206-L222 |
timster/peewee-validates | peewee_validates.py | validate_function | def validate_function(method, **kwargs):
"""
Validate the field matches the result of calling the given method. Example::
def myfunc(value, name):
return value == name
validator = validate_function(myfunc, name='tim')
Essentially creates a validator that only accepts the name ... | python | def validate_function(method, **kwargs):
"""
Validate the field matches the result of calling the given method. Example::
def myfunc(value, name):
return value == name
validator = validate_function(myfunc, name='tim')
Essentially creates a validator that only accepts the name ... | [
"def",
"validate_function",
"(",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"function_validator",
"(",
"field",
",",
"data",
")",
":",
"if",
"field",
".",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"method",
"(",
"field",
".",
"value",... | Validate the field matches the result of calling the given method. Example::
def myfunc(value, name):
return value == name
validator = validate_function(myfunc, name='tim')
Essentially creates a validator that only accepts the name 'tim'.
:param method: Method to call.
:param... | [
"Validate",
"the",
"field",
"matches",
"the",
"result",
"of",
"calling",
"the",
"given",
"method",
".",
"Example",
"::"
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L225-L245 |
timster/peewee-validates | peewee_validates.py | validate_email | def validate_email():
"""
Validate the field is a valid email address.
:raises: ``ValidationError('email')``
"""
user_regex = re.compile(
r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\17... | python | def validate_email():
"""
Validate the field is a valid email address.
:raises: ``ValidationError('email')``
"""
user_regex = re.compile(
r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\17... | [
"def",
"validate_email",
"(",
")",
":",
"user_regex",
"=",
"re",
".",
"compile",
"(",
"r\"(^[-!#$%&'*+/=?^`{}|~\\w]+(\\.[-!#$%&'*+/=?^`{}|~\\w]+)*$\"",
"r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]'",
"r'|\\\\[\\001-\\011\\013\\014\\016-\\177])*\"$)'",
",",
"re",
".",
"... | Validate the field is a valid email address.
:raises: ``ValidationError('email')`` | [
"Validate",
"the",
"field",
"is",
"a",
"valid",
"email",
"address",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L248-L287 |
timster/peewee-validates | peewee_validates.py | validate_model_unique | def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None):
"""
Validate the field is a unique, given a queryset and lookup_field. Example::
validator = validate_model_unique(User.email, User.select())
Creates a validator that can validate the uniqueness of an email address.
... | python | def validate_model_unique(lookup_field, queryset, pk_field=None, pk_value=None):
"""
Validate the field is a unique, given a queryset and lookup_field. Example::
validator = validate_model_unique(User.email, User.select())
Creates a validator that can validate the uniqueness of an email address.
... | [
"def",
"validate_model_unique",
"(",
"lookup_field",
",",
"queryset",
",",
"pk_field",
"=",
"None",
",",
"pk_value",
"=",
"None",
")",
":",
"def",
"unique_validator",
"(",
"field",
",",
"data",
")",
":",
"# If we have a PK, ignore it because it represents the current ... | Validate the field is a unique, given a queryset and lookup_field. Example::
validator = validate_model_unique(User.email, User.select())
Creates a validator that can validate the uniqueness of an email address.
:param lookup_field: Peewee model field that should be used for checking existing values.... | [
"Validate",
"the",
"field",
"is",
"a",
"unique",
"given",
"a",
"queryset",
"and",
"lookup_field",
".",
"Example",
"::"
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L290-L311 |
timster/peewee-validates | peewee_validates.py | coerce_single_instance | def coerce_single_instance(lookup_field, value):
"""
Convert from whatever value is given to a scalar value for lookup_field.
If value is a dict, then lookup_field.name is used to get the value from the dict. Example:
lookup_field.name = 'id'
value = {'id': 123, 'name': 'tim'}
return... | python | def coerce_single_instance(lookup_field, value):
"""
Convert from whatever value is given to a scalar value for lookup_field.
If value is a dict, then lookup_field.name is used to get the value from the dict. Example:
lookup_field.name = 'id'
value = {'id': 123, 'name': 'tim'}
return... | [
"def",
"coerce_single_instance",
"(",
"lookup_field",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"value",
".",
"get",
"(",
"lookup_field",
".",
"name",
")",
"if",
"isinstance",
"(",
"value",
",",
"peewee",
... | Convert from whatever value is given to a scalar value for lookup_field.
If value is a dict, then lookup_field.name is used to get the value from the dict. Example:
lookup_field.name = 'id'
value = {'id': 123, 'name': 'tim'}
returns = 123
If value is a model, then lookup_field.name is ex... | [
"Convert",
"from",
"whatever",
"value",
"is",
"given",
"to",
"a",
"scalar",
"value",
"for",
"lookup_field",
".",
"If",
"value",
"is",
"a",
"dict",
"then",
"lookup_field",
".",
"name",
"is",
"used",
"to",
"get",
"the",
"value",
"from",
"the",
"dict",
".",... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L314-L334 |
timster/peewee-validates | peewee_validates.py | isiterable_notstring | def isiterable_notstring(value):
"""
Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check.
"""
if isinstance(value, str):
return False
return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value) | python | def isiterable_notstring(value):
"""
Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check.
"""
if isinstance(value, str):
return False
return isinstance(value, Iterable) or isgeneratorfunction(value) or isgenerator(value) | [
"def",
"isiterable_notstring",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"False",
"return",
"isinstance",
"(",
"value",
",",
"Iterable",
")",
"or",
"isgeneratorfunction",
"(",
"value",
")",
"or",
"isgenerator",... | Returns True if the value is iterable but not a string. Otherwise returns False.
:param value: Value to check. | [
"Returns",
"True",
"if",
"the",
"value",
"is",
"iterable",
"but",
"not",
"a",
"string",
".",
"Otherwise",
"returns",
"False",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L337-L345 |
timster/peewee-validates | peewee_validates.py | Field.get_value | def get_value(self, name, data):
"""
Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
... | python | def get_value(self, name, data):
"""
Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
... | [
"def",
"get_value",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"if",
"name",
"in",
"data",
":",
"return",
"data",
".",
"get",
"(",
"name",
")",
"if",
"self",
".",
"default",
":",
"if",
"callable",
"(",
"self",
".",
"default",
")",
":",
"ret... | Get the value of this field from the data.
If there is a problem with the data, raise ValidationError.
:param name: Name of this field (to retrieve from data).
:param data: Dictionary of data for all fields.
:raises: ValidationError
:return: The value of this field.
:rty... | [
"Get",
"the",
"value",
"of",
"this",
"field",
"from",
"the",
"data",
".",
"If",
"there",
"is",
"a",
"problem",
"with",
"the",
"data",
"raise",
"ValidationError",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L379-L396 |
timster/peewee-validates | peewee_validates.py | Field.validate | def validate(self, name, data):
"""
Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data ... | python | def validate(self, name, data):
"""
Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data ... | [
"def",
"validate",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"self",
".",
"value",
"=",
"self",
".",
"get_value",
"(",
"name",
",",
"data",
")",
"if",
"self",
".",
"value",
"is",
"not",
"None",
":",
"self",
".",
"value",
"=",
"self",
".",
... | Check to make sure ths data for this field is valid.
Usually runs all validators in self.validators list.
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError | [
"Check",
"to",
"make",
"sure",
"ths",
"data",
"for",
"this",
"field",
"is",
"valid",
".",
"Usually",
"runs",
"all",
"validators",
"in",
"self",
".",
"validators",
"list",
".",
"If",
"there",
"is",
"a",
"problem",
"with",
"the",
"data",
"raise",
"Validati... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L398-L412 |
timster/peewee-validates | peewee_validates.py | ModelChoiceField.validate | def validate(self, name, data):
"""
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
super().validate(name, data)
if self.value is... | python | def validate(self, name, data):
"""
If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError
"""
super().validate(name, data)
if self.value is... | [
"def",
"validate",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"super",
"(",
")",
".",
"validate",
"(",
"name",
",",
"data",
")",
"if",
"self",
".",
"value",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"value",
"=",
"self",
".",
"qu... | If there is a problem with the data, raise ValidationError.
:param name: The name of this field.
:param data: Dictionary of data for all fields.
:raises: ValidationError | [
"If",
"there",
"is",
"a",
"problem",
"with",
"the",
"data",
"raise",
"ValidationError",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L641-L654 |
timster/peewee-validates | peewee_validates.py | ManyModelChoiceField.coerce | def coerce(self, value):
"""Convert from whatever is given to a list of scalars for the lookup_field."""
if isinstance(value, dict):
value = [value]
if not isiterable_notstring(value):
value = [value]
return [coerce_single_instance(self.lookup_field, v) for v in v... | python | def coerce(self, value):
"""Convert from whatever is given to a list of scalars for the lookup_field."""
if isinstance(value, dict):
value = [value]
if not isiterable_notstring(value):
value = [value]
return [coerce_single_instance(self.lookup_field, v) for v in v... | [
"def",
"coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"[",
"value",
"]",
"if",
"not",
"isiterable_notstring",
"(",
"value",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
... | Convert from whatever is given to a list of scalars for the lookup_field. | [
"Convert",
"from",
"whatever",
"is",
"given",
"to",
"a",
"list",
"of",
"scalars",
"for",
"the",
"lookup_field",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L672-L678 |
timster/peewee-validates | peewee_validates.py | Validator.initialize_fields | def initialize_fields(self):
"""
The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None
"""
for field in dir(self):
... | python | def initialize_fields(self):
"""
The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None
"""
for field in dir(self):
... | [
"def",
"initialize_fields",
"(",
"self",
")",
":",
"for",
"field",
"in",
"dir",
"(",
"self",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Field",
")",
":",
"self",
".",
"_meta",
".",
"fields... | The dict self.base_fields is a model instance at this point.
Turn it into an instance attribute on this meta class.
Also intitialize any other special fields if needed in sub-classes.
:return: None | [
"The",
"dict",
"self",
".",
"base_fields",
"is",
"a",
"model",
"instance",
"at",
"this",
"point",
".",
"Turn",
"it",
"into",
"an",
"instance",
"attribute",
"on",
"this",
"meta",
"class",
".",
"Also",
"intitialize",
"any",
"other",
"special",
"fields",
"if"... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L742-L753 |
timster/peewee-validates | peewee_validates.py | Validator.validate | def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
This is usually the method you want to call after... | python | def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
This is usually the method you want to call after... | [
"def",
"validate",
"(",
"self",
",",
"data",
"=",
"None",
",",
"only",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"only",
"=",
"only",
"or",
"[",
"]",
"exclude",
"=",
"exclude",
"or",
"[",
"]",
"data",
"=",
"data",
"or",
"{",
"}",
"sel... | Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
This is usually the method you want to call after creating the validator instance.
:param data: Dictionary of data t... | [
"Validate",
"the",
"data",
"for",
"all",
"fields",
"and",
"return",
"whether",
"the",
"validation",
"was",
"successful",
".",
"This",
"method",
"also",
"retains",
"the",
"validated",
"data",
"in",
"self",
".",
"data",
"so",
"that",
"it",
"can",
"be",
"acce... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L755-L795 |
timster/peewee-validates | peewee_validates.py | Validator.clean_fields | def clean_fields(self, data):
"""
For each field, check to see if there is a clean_<name> method.
If so, run that method and set the returned value on the self.data dict.
This happens after all validations so that each field can act on the
cleaned data of other fields if needed.
... | python | def clean_fields(self, data):
"""
For each field, check to see if there is a clean_<name> method.
If so, run that method and set the returned value on the self.data dict.
This happens after all validations so that each field can act on the
cleaned data of other fields if needed.
... | [
"def",
"clean_fields",
"(",
"self",
",",
"data",
")",
":",
"for",
"name",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"try",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'clean_{}'",
".",
"format",
"(",
"name",
")",
",",
"None",
... | For each field, check to see if there is a clean_<name> method.
If so, run that method and set the returned value on the self.data dict.
This happens after all validations so that each field can act on the
cleaned data of other fields if needed.
:param data: Dictionary of data to clean.... | [
"For",
"each",
"field",
"check",
"to",
"see",
"if",
"there",
"is",
"a",
"clean_<name",
">",
"method",
".",
"If",
"so",
"run",
"that",
"method",
"and",
"set",
"the",
"returned",
"value",
"on",
"the",
"self",
".",
"data",
"dict",
".",
"This",
"happens",
... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L797-L814 |
timster/peewee-validates | peewee_validates.py | ModelValidator.initialize_fields | def initialize_fields(self):
"""
Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None
"""
# # Pull all the "normal" fields off the model instance meta.
for name, f... | python | def initialize_fields(self):
"""
Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None
"""
# # Pull all the "normal" fields off the model instance meta.
for name, f... | [
"def",
"initialize_fields",
"(",
"self",
")",
":",
"# # Pull all the \"normal\" fields off the model instance meta.",
"for",
"name",
",",
"field",
"in",
"self",
".",
"instance",
".",
"_meta",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"fie... | Convert all model fields to validator fields.
Then call the parent so that overwrites can happen if necessary for manually defined fields.
:return: None | [
"Convert",
"all",
"model",
"fields",
"to",
"validator",
"fields",
".",
"Then",
"call",
"the",
"parent",
"so",
"that",
"overwrites",
"can",
"happen",
"if",
"necessary",
"for",
"manually",
"defined",
"fields",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L864-L884 |
timster/peewee-validates | peewee_validates.py | ModelValidator.convert_field | def convert_field(self, name, field):
"""
Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field.
"""
if PEEWEE3:
... | python | def convert_field(self, name, field):
"""
Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field.
"""
if PEEWEE3:
... | [
"def",
"convert_field",
"(",
"self",
",",
"name",
",",
"field",
")",
":",
"if",
"PEEWEE3",
":",
"field_type",
"=",
"field",
".",
"field_type",
".",
"lower",
"(",
")",
"else",
":",
"field_type",
"=",
"field",
".",
"db_field",
"pwv_field",
"=",
"ModelValid... | Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field. | [
"Convert",
"a",
"single",
"field",
"from",
"a",
"Peewee",
"model",
"field",
"to",
"a",
"validator",
"field",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L886-L935 |
timster/peewee-validates | peewee_validates.py | ModelValidator.validate | def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
If data for a field is not provided in ``data`` t... | python | def validate(self, data=None, only=None, exclude=None):
"""
Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
If data for a field is not provided in ``data`` t... | [
"def",
"validate",
"(",
"self",
",",
"data",
"=",
"None",
",",
"only",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"only",
"=",
"only",
"or",
"self",
".",
"_meta",
".",
"only",
"exclude",
"=",
"exclude... | Validate the data for all fields and return whether the validation was successful.
This method also retains the validated data in ``self.data`` so that it can be accessed later.
If data for a field is not provided in ``data`` then this validator will check against the
provided model instance.
... | [
"Validate",
"the",
"data",
"for",
"all",
"fields",
"and",
"return",
"whether",
"the",
"validation",
"was",
"successful",
".",
"This",
"method",
"also",
"retains",
"the",
"validated",
"data",
"in",
"self",
".",
"data",
"so",
"that",
"it",
"can",
"be",
"acce... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L937-L974 |
timster/peewee-validates | peewee_validates.py | ModelValidator.perform_index_validation | def perform_index_validation(self, data):
"""
Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None
"""
# Build a list of dict containi... | python | def perform_index_validation(self, data):
"""
Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None
"""
# Build a list of dict containi... | [
"def",
"perform_index_validation",
"(",
"self",
",",
"data",
")",
":",
"# Build a list of dict containing query values for each unique index.",
"index_data",
"=",
"[",
"]",
"for",
"columns",
",",
"unique",
"in",
"self",
".",
"instance",
".",
"_meta",
".",
"indexes",
... | Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None | [
"Validate",
"any",
"unique",
"indexes",
"specified",
"on",
"the",
"model",
".",
"This",
"should",
"happen",
"after",
"all",
"the",
"normal",
"fields",
"have",
"been",
"validated",
".",
"This",
"can",
"add",
"error",
"messages",
"to",
"multiple",
"fields",
".... | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L976-L1000 |
timster/peewee-validates | peewee_validates.py | ModelValidator.save | def save(self, force_insert=False):
"""
Save the model and any related many-to-many fields.
:param force_insert: Should the save force an insert?
:return: Number of rows impacted, or False.
"""
delayed = {}
for field, value in self.data.items():
model... | python | def save(self, force_insert=False):
"""
Save the model and any related many-to-many fields.
:param force_insert: Should the save force an insert?
:return: Number of rows impacted, or False.
"""
delayed = {}
for field, value in self.data.items():
model... | [
"def",
"save",
"(",
"self",
",",
"force_insert",
"=",
"False",
")",
":",
"delayed",
"=",
"{",
"}",
"for",
"field",
",",
"value",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"model_field",
"=",
"getattr",
"(",
"type",
"(",
"self",
".",
... | Save the model and any related many-to-many fields.
:param force_insert: Should the save force an insert?
:return: Number of rows impacted, or False. | [
"Save",
"the",
"model",
"and",
"any",
"related",
"many",
"-",
"to",
"-",
"many",
"fields",
"."
] | train | https://github.com/timster/peewee-validates/blob/417f0fafb87fe9209439d65bc279d86a3d9e8028/peewee_validates.py#L1002-L1028 |
kpdyer/libfte | fte/bit_ops.py | long_to_bytes | def long_to_bytes(N, blocksize=1):
"""Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blo... | python | def long_to_bytes(N, blocksize=1):
"""Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blo... | [
"def",
"long_to_bytes",
"(",
"N",
",",
"blocksize",
"=",
"1",
")",
":",
"bytestring",
"=",
"hex",
"(",
"N",
")",
"bytestring",
"=",
"bytestring",
"[",
"2",
":",
"]",
"if",
"bytestring",
".",
"startswith",
"(",
"'0x'",
")",
"else",
"bytestring",
"bytest... | Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
such that the return values length is a multiple of ``blocksize``. | [
"Given",
"an",
"input",
"integer",
"N",
"long_to_bytes",
"returns",
"the",
"representation",
"of",
"N",
"in",
"bytes",
".",
"If",
"blocksize",
"is",
"greater",
"than",
"1",
"then",
"the",
"output",
"string",
"will",
"be",
"right",
"justified",
"and",
"then",... | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/bit_ops.py#L17-L33 |
kpdyer/libfte | fte/encrypter.py | Encrypter.encrypt | def encrypt(self, plaintext, iv_bytes=None):
"""Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``.
Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``.
... | python | def encrypt(self, plaintext, iv_bytes=None):
"""Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``.
Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``.
... | [
"def",
"encrypt",
"(",
"self",
",",
"plaintext",
",",
"iv_bytes",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"plaintext",
",",
"str",
")",
":",
"raise",
"PlaintextTypeError",
"(",
"\"Input plaintext is not of type string\"",
")",
"if",
"iv_bytes",
... | Given ``plaintext``, returns a ``ciphertext`` encrypted with an authenticated-encryption scheme, using the keys specified in ``__init__``.
Ciphertext expansion is deterministic, the output ciphertext is always 42 bytes longer than the input ``plaintext``.
The input ``plaintext`` can be ``''``.
... | [
"Given",
"plaintext",
"returns",
"a",
"ciphertext",
"encrypted",
"with",
"an",
"authenticated",
"-",
"encryption",
"scheme",
"using",
"the",
"keys",
"specified",
"in",
"__init__",
".",
"Ciphertext",
"expansion",
"is",
"deterministic",
"the",
"output",
"ciphertext",
... | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L84-L122 |
kpdyer/libfte | fte/encrypter.py | Encrypter.decrypt | def decrypt(self, ciphertext):
"""Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``.
Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string.
Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative mes... | python | def decrypt(self, ciphertext):
"""Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``.
Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string.
Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative mes... | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
")",
":",
"if",
"not",
"isinstance",
"(",
"ciphertext",
",",
"str",
")",
":",
"raise",
"CiphertextTypeError",
"(",
"\"Input ciphertext is not of type string\"",
")",
"plaintext_length",
"=",
"self",
".",
"getPlaint... | Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``.
Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string.
Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext le... | [
"Given",
"ciphertext",
"returns",
"a",
"plaintext",
"decrypted",
"using",
"the",
"keys",
"specified",
"in",
"__init__",
"."
] | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L124-L171 |
kpdyer/libfte | fte/encrypter.py | Encrypter.getCiphertextLen | def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
... | python | def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
... | [
"def",
"getCiphertextLen",
"(",
"self",
",",
"ciphertext",
")",
":",
"plaintext_length",
"=",
"self",
".",
"getPlaintextLen",
"(",
"ciphertext",
")",
"ciphertext_length",
"=",
"plaintext_length",
"+",
"Encrypter",
".",
"_CTXT_EXPANSION",
"return",
"ciphertext_length"
... | Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion. | [
"Given",
"a",
"ciphertext",
"with",
"a",
"valid",
"header",
"returns",
"the",
"length",
"of",
"the",
"ciphertext",
"inclusive",
"of",
"ciphertext",
"expansion",
"."
] | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L173-L179 |
kpdyer/libfte | fte/encrypter.py | Encrypter.getPlaintextLen | def getPlaintextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
"""
completeCiphertextHeader = (len(ciphertext) >= 16)
if completeCiphertextHeader is False:
raise RecoverableDecryptionError('Incomplete cipher... | python | def getPlaintextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
"""
completeCiphertextHeader = (len(ciphertext) >= 16)
if completeCiphertextHeader is False:
raise RecoverableDecryptionError('Incomplete cipher... | [
"def",
"getPlaintextLen",
"(",
"self",
",",
"ciphertext",
")",
":",
"completeCiphertextHeader",
"=",
"(",
"len",
"(",
"ciphertext",
")",
">=",
"16",
")",
"if",
"completeCiphertextHeader",
"is",
"False",
":",
"raise",
"RecoverableDecryptionError",
"(",
"'Incomplete... | Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload. | [
"Given",
"a",
"ciphertext",
"with",
"a",
"valid",
"header",
"returns",
"the",
"length",
"of",
"the",
"plaintext",
"payload",
"."
] | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encrypter.py#L181-L205 |
hammerlab/stancache | stancache/stancache.py | _make_digest | def _make_digest(k, **kwargs):
"""
Creates a digest suitable for use within an :class:`phyles.FSCache`
object from the key object `k`.
>>> adict = {'a' : {'b':1}, 'f': []}
>>> make_digest(adict)
'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A'
"""
result = list()
result_dict = _make_dig... | python | def _make_digest(k, **kwargs):
"""
Creates a digest suitable for use within an :class:`phyles.FSCache`
object from the key object `k`.
>>> adict = {'a' : {'b':1}, 'f': []}
>>> make_digest(adict)
'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A'
"""
result = list()
result_dict = _make_dig... | [
"def",
"_make_digest",
"(",
"k",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"list",
"(",
")",
"result_dict",
"=",
"_make_digest_dict",
"(",
"k",
",",
"*",
"*",
"kwargs",
")",
"if",
"result_dict",
"is",
"None",
":",
"return",
"'default'",
"else",... | Creates a digest suitable for use within an :class:`phyles.FSCache`
object from the key object `k`.
>>> adict = {'a' : {'b':1}, 'f': []}
>>> make_digest(adict)
'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A' | [
"Creates",
"a",
"digest",
"suitable",
"for",
"use",
"within",
"an",
":",
"class",
":",
"phyles",
".",
"FSCache",
"object",
"from",
"the",
"key",
"object",
"k",
"."
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L106-L122 |
hammerlab/stancache | stancache/stancache.py | cached_model_file | def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None,
fit_cachefile=None, include_prefix=False):
''' Given model name & stan model code/file, compute path to cached stan fit
if include_prefix, returns (model_prefix, model_cachefile)
'''... | python | def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None,
fit_cachefile=None, include_prefix=False):
''' Given model name & stan model code/file, compute path to cached stan fit
if include_prefix, returns (model_prefix, model_cachefile)
'''... | [
"def",
"cached_model_file",
"(",
"model_name",
"=",
"'anon_model'",
",",
"file",
"=",
"None",
",",
"model_code",
"=",
"None",
",",
"cache_dir",
"=",
"None",
",",
"fit_cachefile",
"=",
"None",
",",
"include_prefix",
"=",
"False",
")",
":",
"cache_dir",
"=",
... | Given model name & stan model code/file, compute path to cached stan fit
if include_prefix, returns (model_prefix, model_cachefile) | [
"Given",
"model",
"name",
"&",
"stan",
"model",
"code",
"/",
"file",
"compute",
"path",
"to",
"cached",
"stan",
"fit",
"if",
"include_prefix",
"returns",
"(",
"model_prefix",
"model_cachefile",
")"
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L132-L167 |
hammerlab/stancache | stancache/stancache.py | cached_stan_file | def cached_stan_file(model_name='anon_model', file=None, model_code=None,
cache_dir=None, fit_cachefile=None, cache_only=None, force=False,
include_modelfile=False, prefix_only=False,
**kwargs
):
''' Given inputs to cached_stan_fit, compute pic... | python | def cached_stan_file(model_name='anon_model', file=None, model_code=None,
cache_dir=None, fit_cachefile=None, cache_only=None, force=False,
include_modelfile=False, prefix_only=False,
**kwargs
):
''' Given inputs to cached_stan_fit, compute pic... | [
"def",
"cached_stan_file",
"(",
"model_name",
"=",
"'anon_model'",
",",
"file",
"=",
"None",
",",
"model_code",
"=",
"None",
",",
"cache_dir",
"=",
"None",
",",
"fit_cachefile",
"=",
"None",
",",
"cache_only",
"=",
"None",
",",
"force",
"=",
"False",
",",
... | Given inputs to cached_stan_fit, compute pickle file containing cached fit | [
"Given",
"inputs",
"to",
"cached_stan_fit",
"compute",
"pickle",
"file",
"containing",
"cached",
"fit"
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L170-L185 |
hammerlab/stancache | stancache/stancache.py | _cached_stan_fit | def _cached_stan_fit(model_name='anon_model', file=None, model_code=None,
force=False, cache_dir=None, cache_only=None,
fit_cachefile=None, **kwargs):
''' Cache fit stan model, by storing pickled objects in filesystem
per following warning:
07: UserWarning: P... | python | def _cached_stan_fit(model_name='anon_model', file=None, model_code=None,
force=False, cache_dir=None, cache_only=None,
fit_cachefile=None, **kwargs):
''' Cache fit stan model, by storing pickled objects in filesystem
per following warning:
07: UserWarning: P... | [
"def",
"_cached_stan_fit",
"(",
"model_name",
"=",
"'anon_model'",
",",
"file",
"=",
"None",
",",
"model_code",
"=",
"None",
",",
"force",
"=",
"False",
",",
"cache_dir",
"=",
"None",
",",
"cache_only",
"=",
"None",
",",
"fit_cachefile",
"=",
"None",
",",
... | Cache fit stan model, by storing pickled objects in filesystem
per following warning:
07: UserWarning: Pickling fit objects is an experimental feature!
The relevant StanModel instance must be pickled along with this fit object.
When unpickling the StanModel must be unpickled first.
... | [
"Cache",
"fit",
"stan",
"model",
"by",
"storing",
"pickled",
"objects",
"in",
"filesystem",
"per",
"following",
"warning",
":",
"07",
":",
"UserWarning",
":",
"Pickling",
"fit",
"objects",
"is",
"an",
"experimental",
"feature!",
"The",
"relevant",
"StanModel",
... | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/stancache.py#L204-L240 |
oscarlazoarjona/fast | build/lib/fast/graphic.py | fit_lorentizan | def fit_lorentizan(curve,p0=None,N_points=1000):
'''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess.
It returns a curve with N_points.'''
def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2)
N=len(curve)
x=[curve[i][0] for i in range(N)]
y=[curve[i][1] for i in range(N)]
... | python | def fit_lorentizan(curve,p0=None,N_points=1000):
'''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess.
It returns a curve with N_points.'''
def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2)
N=len(curve)
x=[curve[i][0] for i in range(N)]
y=[curve[i][1] for i in range(N)]
... | [
"def",
"fit_lorentizan",
"(",
"curve",
",",
"p0",
"=",
"None",
",",
"N_points",
"=",
"1000",
")",
":",
"def",
"lorentzian",
"(",
"x",
",",
"x0",
",",
"A",
",",
"gamma",
")",
":",
"return",
"A",
"*",
"gamma",
"**",
"2",
"/",
"(",
"(",
"x",
"-",
... | Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess.
It returns a curve with N_points. | [
"Fits",
"a",
"lorentzian",
"curve",
"using",
"p0",
"=",
"[",
"x0",
"A",
"gamma",
"]",
"as",
"an",
"initial",
"guess",
".",
"It",
"returns",
"a",
"curve",
"with",
"N_points",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/graphic.py#L406-L422 |
oscarlazoarjona/fast | fast/electric_field.py | electric_field_amplitude_gaussian | def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6,
units="ad-hoc"):
"""Return the amplitude of the electric field for a Gaussian beam.
This the amplitude at the center of a laser beam of power P (in Watts) and\
a Gaussian intensity distributio... | python | def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6,
units="ad-hoc"):
"""Return the amplitude of the electric field for a Gaussian beam.
This the amplitude at the center of a laser beam of power P (in Watts) and\
a Gaussian intensity distributio... | [
"def",
"electric_field_amplitude_gaussian",
"(",
"P",
",",
"sigmax",
",",
"sigmay",
"=",
"None",
",",
"Omega",
"=",
"1.0e6",
",",
"units",
"=",
"\"ad-hoc\"",
")",
":",
"e0",
"=",
"hbar",
"*",
"Omega",
"/",
"(",
"e",
"*",
"a0",
")",
"# This is the electri... | Return the amplitude of the electric field for a Gaussian beam.
This the amplitude at the center of a laser beam of power P (in Watts) and\
a Gaussian intensity distribution of standard deviations sigmax, sigmay\
(in meters). The value of E0 is given in rescaled units according to the\
frequency scale Ome... | [
"Return",
"the",
"amplitude",
"of",
"the",
"electric",
"field",
"for",
"a",
"Gaussian",
"beam",
".",
"This",
"the",
"amplitude",
"at",
"the",
"center",
"of",
"a",
"laser",
"beam",
"of",
"power",
"P",
"(",
"in",
"Watts",
")",
"and",
"\\",
"a",
"Gaussian... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L318-L338 |
oscarlazoarjona/fast | fast/electric_field.py | electric_field_amplitude_top | def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"):
"""Return the amplitude of the electric field for a top hat beam.
This is the amplitude of a laser beam of power P (in Watts) and a top-hat\
intensity distribution of radius a (in meters). The value of E0 is given in\
rescaled units acco... | python | def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"):
"""Return the amplitude of the electric field for a top hat beam.
This is the amplitude of a laser beam of power P (in Watts) and a top-hat\
intensity distribution of radius a (in meters). The value of E0 is given in\
rescaled units acco... | [
"def",
"electric_field_amplitude_top",
"(",
"P",
",",
"a",
",",
"Omega",
"=",
"1e6",
",",
"units",
"=",
"\"ad-hoc\"",
")",
":",
"e0",
"=",
"hbar",
"*",
"Omega",
"/",
"(",
"e",
"*",
"a0",
")",
"# This is the electric field scale.\r",
"E0",
"=",
"sqrt",
"(... | Return the amplitude of the electric field for a top hat beam.
This is the amplitude of a laser beam of power P (in Watts) and a top-hat\
intensity distribution of radius a (in meters). The value of E0 is given in\
rescaled units according to the frequency scale Omega (in Hertz)\
understood as absolute fr... | [
"Return",
"the",
"amplitude",
"of",
"the",
"electric",
"field",
"for",
"a",
"top",
"hat",
"beam",
".",
"This",
"is",
"the",
"amplitude",
"of",
"a",
"laser",
"beam",
"of",
"power",
"P",
"(",
"in",
"Watts",
")",
"and",
"a",
"top",
"-",
"hat",
"\\",
"... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L341-L357 |
oscarlazoarjona/fast | fast/electric_field.py | electric_field_amplitude_intensity | def electric_field_amplitude_intensity(s0, Isat=16.6889462814,
Omega=1e6, units="ad-hoc"):
"""Return the amplitude of the electric field for saturation parameter.
This is at a given saturation parameter s0=I/Isat, where I0 is by default \
Isat=16.6889462814 m/m^2 is ... | python | def electric_field_amplitude_intensity(s0, Isat=16.6889462814,
Omega=1e6, units="ad-hoc"):
"""Return the amplitude of the electric field for saturation parameter.
This is at a given saturation parameter s0=I/Isat, where I0 is by default \
Isat=16.6889462814 m/m^2 is ... | [
"def",
"electric_field_amplitude_intensity",
"(",
"s0",
",",
"Isat",
"=",
"16.6889462814",
",",
"Omega",
"=",
"1e6",
",",
"units",
"=",
"\"ad-hoc\"",
")",
":",
"E0_sat",
"=",
"sqrt",
"(",
"2",
"*",
"mu0",
"*",
"c",
"*",
"Isat",
")",
"/",
"Omega",
"if",... | Return the amplitude of the electric field for saturation parameter.
This is at a given saturation parameter s0=I/Isat, where I0 is by default \
Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \
rubidium for circularly polarized light. Optionally, a frequency scale \
`Omega` can be prov... | [
"Return",
"the",
"amplitude",
"of",
"the",
"electric",
"field",
"for",
"saturation",
"parameter",
".",
"This",
"is",
"at",
"a",
"given",
"saturation",
"parameter",
"s0",
"=",
"I",
"/",
"Isat",
"where",
"I0",
"is",
"by",
"default",
"\\",
"Isat",
"=",
"16"... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L360-L383 |
oscarlazoarjona/fast | fast/electric_field.py | MotField.plot | def plot(self, **kwds):
r"""The plotting function for MOT fields."""
plo = self.lx.plot(dist_to_center=3, **kwds)
plo += self.ly.plot(dist_to_center=3, **kwds)
plo += self.lz.plot(dist_to_center=3, **kwds)
plo += self.lx_r.plot(dist_to_center=3, **kwds)
plo += self.... | python | def plot(self, **kwds):
r"""The plotting function for MOT fields."""
plo = self.lx.plot(dist_to_center=3, **kwds)
plo += self.ly.plot(dist_to_center=3, **kwds)
plo += self.lz.plot(dist_to_center=3, **kwds)
plo += self.lx_r.plot(dist_to_center=3, **kwds)
plo += self.... | [
"def",
"plot",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"plo",
"=",
"self",
".",
"lx",
".",
"plot",
"(",
"dist_to_center",
"=",
"3",
",",
"*",
"*",
"kwds",
")",
"plo",
"+=",
"self",
".",
"ly",
".",
"plot",
"(",
"dist_to_center",
"=",
"3",
... | r"""The plotting function for MOT fields. | [
"r",
"The",
"plotting",
"function",
"for",
"MOT",
"fields",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L307-L315 |
oscarlazoarjona/fast | fast/misc.py | fprint | def fprint(expr, print_ascii=False):
r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega)
"""
if pri... | python | def fprint(expr, print_ascii=False):
r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega)
"""
if pri... | [
"def",
"fprint",
"(",
"expr",
",",
"print_ascii",
"=",
"False",
")",
":",
"if",
"print_ascii",
":",
"pprint",
"(",
"expr",
",",
"use_unicode",
"=",
"False",
",",
"num_columns",
"=",
"120",
")",
"else",
":",
"return",
"expr"
] | r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega) | [
"r",
"This",
"function",
"chooses",
"whether",
"to",
"use",
"ascii",
"characters",
"to",
"represent",
"a",
"symbolic",
"expression",
"in",
"the",
"notebook",
"or",
"to",
"use",
"sympy",
"s",
"pprint",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L45-L59 |
oscarlazoarjona/fast | fast/misc.py | Mu | def Mu(i, j, s, N, excluded_mu=[]):
"""This function calculates the global index mu for the element i, j.
It returns the index for the real part if s=0 and the one for the
imaginary part if s=1.
"""
if i == j:
if s == -1:
if i == 1:
return 0
else:
... | python | def Mu(i, j, s, N, excluded_mu=[]):
"""This function calculates the global index mu for the element i, j.
It returns the index for the real part if s=0 and the one for the
imaginary part if s=1.
"""
if i == j:
if s == -1:
if i == 1:
return 0
else:
... | [
"def",
"Mu",
"(",
"i",
",",
"j",
",",
"s",
",",
"N",
",",
"excluded_mu",
"=",
"[",
"]",
")",
":",
"if",
"i",
"==",
"j",
":",
"if",
"s",
"==",
"-",
"1",
":",
"if",
"i",
"==",
"1",
":",
"return",
"0",
"else",
":",
"mes",
"=",
"'There is no ... | This function calculates the global index mu for the element i, j.
It returns the index for the real part if s=0 and the one for the
imaginary part if s=1. | [
"This",
"function",
"calculates",
"the",
"global",
"index",
"mu",
"for",
"the",
"element",
"i",
"j",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L71-L96 |
oscarlazoarjona/fast | fast/misc.py | IJ | def IJ(mu, N):
"""Return i, j, s for any given mu."""
if mu == 0: return 1, 1, 1
if mu not in range(0, N**2):
raise ValueError('mu has an invalid value mu='+str(mu)+'.')
if 1 <= mu <= N-1:
return mu+1, mu+1, 1
else:
m = N-1
M = N*(N-1)/2
for jj in range(1, N... | python | def IJ(mu, N):
"""Return i, j, s for any given mu."""
if mu == 0: return 1, 1, 1
if mu not in range(0, N**2):
raise ValueError('mu has an invalid value mu='+str(mu)+'.')
if 1 <= mu <= N-1:
return mu+1, mu+1, 1
else:
m = N-1
M = N*(N-1)/2
for jj in range(1, N... | [
"def",
"IJ",
"(",
"mu",
",",
"N",
")",
":",
"if",
"mu",
"==",
"0",
":",
"return",
"1",
",",
"1",
",",
"1",
"if",
"mu",
"not",
"in",
"range",
"(",
"0",
",",
"N",
"**",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'mu has an invalid value mu='",
"... | Return i, j, s for any given mu. | [
"Return",
"i",
"j",
"s",
"for",
"any",
"given",
"mu",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L99-L118 |
oscarlazoarjona/fast | fast/misc.py | read_result | def read_result(path, name, i=None, j=None, s=0, N=None,
excluded_mu=[], use_netcdf=True, clone=None):
r"""This function reads the results stored in path under file name.dat
returning them as a list of N^2 lists of the form
[frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can retur... | python | def read_result(path, name, i=None, j=None, s=0, N=None,
excluded_mu=[], use_netcdf=True, clone=None):
r"""This function reads the results stored in path under file name.dat
returning them as a list of N^2 lists of the form
[frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can retur... | [
"def",
"read_result",
"(",
"path",
",",
"name",
",",
"i",
"=",
"None",
",",
"j",
"=",
"None",
",",
"s",
"=",
"0",
",",
"N",
"=",
"None",
",",
"excluded_mu",
"=",
"[",
"]",
",",
"use_netcdf",
"=",
"True",
",",
"clone",
"=",
"None",
")",
":",
"... | r"""This function reads the results stored in path under file name.dat
returning them as a list of N^2 lists of the form
[frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can return only
two lists [frequency, rho_i,j,s] where s must be 1 for the real part and
-1 for the imaginary part. | [
"r",
"This",
"function",
"reads",
"the",
"results",
"stored",
"in",
"path",
"under",
"file",
"name",
".",
"dat",
"returning",
"them",
"as",
"a",
"list",
"of",
"N^2",
"lists",
"of",
"the",
"form",
"[",
"frequency",
"rho22",
"rho33",
"...",
"rho_N",
"N",
... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L121-L176 |
oscarlazoarjona/fast | fast/misc.py | find_phase_transformation | def find_phase_transformation(Ne, Nl, r, Lij, verbose=0,
return_equations=False, **kwds):
"""This function returns a phase transformation specified as a list of
lenght Ne whose elements correspond to each theta_i. Each element is a
list of length Nl which specifies the coeffici... | python | def find_phase_transformation(Ne, Nl, r, Lij, verbose=0,
return_equations=False, **kwds):
"""This function returns a phase transformation specified as a list of
lenght Ne whose elements correspond to each theta_i. Each element is a
list of length Nl which specifies the coeffici... | [
"def",
"find_phase_transformation",
"(",
"Ne",
",",
"Nl",
",",
"r",
",",
"Lij",
",",
"verbose",
"=",
"0",
",",
"return_equations",
"=",
"False",
",",
"*",
"*",
"kwds",
")",
":",
"# We first define the needed variables",
"_omega_laser",
"=",
"[",
"Symbol",
"(... | This function returns a phase transformation specified as a list of
lenght Ne whose elements correspond to each theta_i. Each element is a
list of length Nl which specifies the coefficients multiplying each
optical frequency omega^l. So for instance [[1,1],[1,0],[0,0]] means
theta_1=omega^1+omega^2
... | [
"This",
"function",
"returns",
"a",
"phase",
"transformation",
"specified",
"as",
"a",
"list",
"of",
"lenght",
"Ne",
"whose",
"elements",
"correspond",
"to",
"each",
"theta_i",
".",
"Each",
"element",
"is",
"a",
"list",
"of",
"length",
"Nl",
"which",
"specif... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L228-L275 |
oscarlazoarjona/fast | fast/misc.py | calculate_iI_correspondence | def calculate_iI_correspondence(omega):
r"""Get the correspondance between degenerate and nondegenerate schemes."""
Ne = len(omega[0])
om = omega[0][0]
correspondence = []
I = 0
for i in range(Ne):
if omega[i][0] != om:
om = omega[i][0]
I += 1
corresponden... | python | def calculate_iI_correspondence(omega):
r"""Get the correspondance between degenerate and nondegenerate schemes."""
Ne = len(omega[0])
om = omega[0][0]
correspondence = []
I = 0
for i in range(Ne):
if omega[i][0] != om:
om = omega[i][0]
I += 1
corresponden... | [
"def",
"calculate_iI_correspondence",
"(",
"omega",
")",
":",
"Ne",
"=",
"len",
"(",
"omega",
"[",
"0",
"]",
")",
"om",
"=",
"omega",
"[",
"0",
"]",
"[",
"0",
"]",
"correspondence",
"=",
"[",
"]",
"I",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
... | r"""Get the correspondance between degenerate and nondegenerate schemes. | [
"r",
"Get",
"the",
"correspondance",
"between",
"degenerate",
"and",
"nondegenerate",
"schemes",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L278-L299 |
oscarlazoarjona/fast | fast/misc.py | part | def part(z, s):
r"""Get the real or imaginary part of a complex number."""
if sage_included:
if s == 1: return np.real(z)
elif s == -1: return np.imag(z)
elif s == 0:
return z
else:
if s == 1: return z.real
elif s == -1: return z.imag
elif s == 0: ... | python | def part(z, s):
r"""Get the real or imaginary part of a complex number."""
if sage_included:
if s == 1: return np.real(z)
elif s == -1: return np.imag(z)
elif s == 0:
return z
else:
if s == 1: return z.real
elif s == -1: return z.imag
elif s == 0: ... | [
"def",
"part",
"(",
"z",
",",
"s",
")",
":",
"if",
"sage_included",
":",
"if",
"s",
"==",
"1",
":",
"return",
"np",
".",
"real",
"(",
"z",
")",
"elif",
"s",
"==",
"-",
"1",
":",
"return",
"np",
".",
"imag",
"(",
"z",
")",
"elif",
"s",
"==",... | r"""Get the real or imaginary part of a complex number. | [
"r",
"Get",
"the",
"real",
"or",
"imaginary",
"part",
"of",
"a",
"complex",
"number",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L302-L312 |
oscarlazoarjona/fast | fast/misc.py | symbolic_part | def symbolic_part(z, s):
r"""Get the real or imaginary part of a complex symbol."""
if s == 1: return symre(z)
elif s == -1: return symim(z)
elif s == 0: return z | python | def symbolic_part(z, s):
r"""Get the real or imaginary part of a complex symbol."""
if s == 1: return symre(z)
elif s == -1: return symim(z)
elif s == 0: return z | [
"def",
"symbolic_part",
"(",
"z",
",",
"s",
")",
":",
"if",
"s",
"==",
"1",
":",
"return",
"symre",
"(",
"z",
")",
"elif",
"s",
"==",
"-",
"1",
":",
"return",
"symim",
"(",
"z",
")",
"elif",
"s",
"==",
"0",
":",
"return",
"z"
] | r"""Get the real or imaginary part of a complex symbol. | [
"r",
"Get",
"the",
"real",
"or",
"imaginary",
"part",
"of",
"a",
"complex",
"symbol",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L315-L319 |
oscarlazoarjona/fast | fast/misc.py | detuning_combinations | def detuning_combinations(lists):
r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
"""
Nl = len(lists)
comb = [[i] for i in range(lists[0])]
for... | python | def detuning_combinations(lists):
r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
"""
Nl = len(lists)
comb = [[i] for i in range(lists[0])]
for... | [
"def",
"detuning_combinations",
"(",
"lists",
")",
":",
"Nl",
"=",
"len",
"(",
"lists",
")",
"comb",
"=",
"[",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"lists",
"[",
"0",
"]",
")",
"]",
"for",
"l",
"in",
"range",
"(",
"1",
",",
"Nl",
")... | r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations. | [
"r",
"This",
"function",
"recieves",
"a",
"list",
"of",
"length",
"Nl",
"with",
"the",
"number",
"of",
"transitions",
"each",
"laser",
"induces",
".",
"It",
"returns",
"the",
"cartesian",
"product",
"of",
"all",
"these",
"posibilities",
"as",
"a",
"list",
... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L322-L335 |
oscarlazoarjona/fast | fast/misc.py | laser_detunings | def laser_detunings(Lij, Nl, i_d, I_nd, Nnd):
r"""This function returns the list of transitions i,j that each laser
produces as lists of length Ne, whose elements are all zero except for the
ith element =1 and the jth element = -1.
Also, it returns detuningsij, which contains the same information
b... | python | def laser_detunings(Lij, Nl, i_d, I_nd, Nnd):
r"""This function returns the list of transitions i,j that each laser
produces as lists of length Ne, whose elements are all zero except for the
ith element =1 and the jth element = -1.
Also, it returns detuningsij, which contains the same information
b... | [
"def",
"laser_detunings",
"(",
"Lij",
",",
"Nl",
",",
"i_d",
",",
"I_nd",
",",
"Nnd",
")",
":",
"Ne",
"=",
"len",
"(",
"Lij",
")",
"detunings",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Nl",
")",
"]",
"detuningsij",
"=",
"[",
"[",
... | r"""This function returns the list of transitions i,j that each laser
produces as lists of length Ne, whose elements are all zero except for the
ith element =1 and the jth element = -1.
Also, it returns detuningsij, which contains the same information
but as pairs if ij. The indices in it start from 0. | [
"r",
"This",
"function",
"returns",
"the",
"list",
"of",
"transitions",
"i",
"j",
"that",
"each",
"laser",
"produces",
"as",
"lists",
"of",
"length",
"Ne",
"whose",
"elements",
"are",
"all",
"zero",
"except",
"for",
"the",
"ith",
"element",
"=",
"1",
"an... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L338-L359 |
oscarlazoarjona/fast | fast/misc.py | find_omega_min | def find_omega_min(omega, Nl, detuningsij, i_d, I_nd):
r"""This function returns a list of length Nl containing the mininmal frequency
that each laser excites.
"""
omega_min = []
omega_min_indices = []
for l in range(Nl):
omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p)
... | python | def find_omega_min(omega, Nl, detuningsij, i_d, I_nd):
r"""This function returns a list of length Nl containing the mininmal frequency
that each laser excites.
"""
omega_min = []
omega_min_indices = []
for l in range(Nl):
omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p)
... | [
"def",
"find_omega_min",
"(",
"omega",
",",
"Nl",
",",
"detuningsij",
",",
"i_d",
",",
"I_nd",
")",
":",
"omega_min",
"=",
"[",
"]",
"omega_min_indices",
"=",
"[",
"]",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"omegas",
"=",
"sorted",
"(",
"... | r"""This function returns a list of length Nl containing the mininmal frequency
that each laser excites. | [
"r",
"This",
"function",
"returns",
"a",
"list",
"of",
"length",
"Nl",
"containing",
"the",
"mininmal",
"frequency",
"that",
"each",
"laser",
"excites",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L602-L613 |
oscarlazoarjona/fast | fast/misc.py | write_equations_code | def write_equations_code(path, name, laser, omega, gamma, r, Lij, states=None,
excluded_mu=[], verbose=1):
r"""Write code for the equations."""
Ne = len(omega[0])
Nl = len(laser)
N_excluded_mu = len(excluded_mu)
if states is None: states = range(1, Ne+1)
omega_rescaled... | python | def write_equations_code(path, name, laser, omega, gamma, r, Lij, states=None,
excluded_mu=[], verbose=1):
r"""Write code for the equations."""
Ne = len(omega[0])
Nl = len(laser)
N_excluded_mu = len(excluded_mu)
if states is None: states = range(1, Ne+1)
omega_rescaled... | [
"def",
"write_equations_code",
"(",
"path",
",",
"name",
",",
"laser",
",",
"omega",
",",
"gamma",
",",
"r",
",",
"Lij",
",",
"states",
"=",
"None",
",",
"excluded_mu",
"=",
"[",
"]",
",",
"verbose",
"=",
"1",
")",
":",
"Ne",
"=",
"len",
"(",
"om... | r"""Write code for the equations. | [
"r",
"Write",
"code",
"for",
"the",
"equations",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L616-L1012 |
oscarlazoarjona/fast | fast/misc.py | block_diagonal_matrix | def block_diagonal_matrix(matrices, type=None):
ur"""Build a block-diagonal matrix out of a given list of matrices.
The type of matrix is chosen according to the input matrices.
>>> import numpy as np
>>> import sympy as sy
>>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)]
>>> sy.pprint(block... | python | def block_diagonal_matrix(matrices, type=None):
ur"""Build a block-diagonal matrix out of a given list of matrices.
The type of matrix is chosen according to the input matrices.
>>> import numpy as np
>>> import sympy as sy
>>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)]
>>> sy.pprint(block... | [
"def",
"block_diagonal_matrix",
"(",
"matrices",
",",
"type",
"=",
"None",
")",
":",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"np",
".",
"float64",
"sizes",
"=",
"[",
"Ai",
".",
"shape",
"[",
"0",
"]",
"for",
"Ai",
"in",
"matrices",
"]",
"size... | ur"""Build a block-diagonal matrix out of a given list of matrices.
The type of matrix is chosen according to the input matrices.
>>> import numpy as np
>>> import sympy as sy
>>> lis = [sy.ones(2), 2*sy.ones(3), 3*sy.ones(4)]
>>> sy.pprint(block_diagonal_matrix(lis))
⎡1 1 0 0 0 0 0 0 ... | [
"ur",
"Build",
"a",
"block",
"-",
"diagonal",
"matrix",
"out",
"of",
"a",
"given",
"list",
"of",
"matrices",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/misc.py#L1088-L1143 |
abn/cafeteria | cafeteria/datastructs/dict.py | MergingDict.replace | def replace(self, key, value):
"""
Convenience method provided as a way to replace a value mapped by a
key.This is required since a MergingDict always merges via assignment
of item/attribute.
:param key: Attribute name or item key to replace rvalue for.
:type key: object... | python | def replace(self, key, value):
"""
Convenience method provided as a way to replace a value mapped by a
key.This is required since a MergingDict always merges via assignment
of item/attribute.
:param key: Attribute name or item key to replace rvalue for.
:type key: object... | [
"def",
"replace",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"super",
"(",
"MergingDict",
",",
"self",
")",
".",
"__setitem__",
"(",
"key",
",",
"value",
")"
] | Convenience method provided as a way to replace a value mapped by a
key.This is required since a MergingDict always merges via assignment
of item/attribute.
:param key: Attribute name or item key to replace rvalue for.
:type key: object
:param value: The new value to assign.
... | [
"Convenience",
"method",
"provided",
"as",
"a",
"way",
"to",
"replace",
"a",
"value",
"mapped",
"by",
"a",
"key",
".",
"This",
"is",
"required",
"since",
"a",
"MergingDict",
"always",
"merges",
"via",
"assignment",
"of",
"item",
"/",
"attribute",
"."
] | train | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L51-L63 |
abn/cafeteria | cafeteria/datastructs/dict.py | MergingDict.update | def update(self, other=None, **kwargs):
"""
A special update method to handle merging of dict objects. For all
other iterable objects, we use the parent class update method. For
other objects, we simply make use of the internal merging logic.
:param other: An iterable object.
... | python | def update(self, other=None, **kwargs):
"""
A special update method to handle merging of dict objects. For all
other iterable objects, we use the parent class update method. For
other objects, we simply make use of the internal merging logic.
:param other: An iterable object.
... | [
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"other",
",",
"dict",
")",
":",
"for",
"key",
"in",
"other",
":",
"self",
"[",
"key",
... | A special update method to handle merging of dict objects. For all
other iterable objects, we use the parent class update method. For
other objects, we simply make use of the internal merging logic.
:param other: An iterable object.
:type other: dict or object
:param kwargs: key... | [
"A",
"special",
"update",
"method",
"to",
"handle",
"merging",
"of",
"dict",
"objects",
".",
"For",
"all",
"other",
"iterable",
"objects",
"we",
"use",
"the",
"parent",
"class",
"update",
"method",
".",
"For",
"other",
"objects",
"we",
"simply",
"make",
"u... | train | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L65-L85 |
abn/cafeteria | cafeteria/datastructs/dict.py | MergingDict._merge_method | def _merge_method(self, key):
"""
Identify a merge compatible method available in self[key]. Currently we
support 'update' and 'append'.
:param key: Attribute name or item key
:return: Method name usable to merge a value into the instance mapped
by key
:r... | python | def _merge_method(self, key):
"""
Identify a merge compatible method available in self[key]. Currently we
support 'update' and 'append'.
:param key: Attribute name or item key
:return: Method name usable to merge a value into the instance mapped
by key
:r... | [
"def",
"_merge_method",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
":",
"for",
"method",
"in",
"[",
"\"update\"",
",",
"\"append\"",
"]",
":",
"if",
"hasattr",
"(",
"self",
"[",
"key",
"]",
",",
"method",
")",
":",
"return",
"met... | Identify a merge compatible method available in self[key]. Currently we
support 'update' and 'append'.
:param key: Attribute name or item key
:return: Method name usable to merge a value into the instance mapped
by key
:rtype: str | [
"Identify",
"a",
"merge",
"compatible",
"method",
"available",
"in",
"self",
"[",
"key",
"]",
".",
"Currently",
"we",
"support",
"update",
"and",
"append",
"."
] | train | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L87-L101 |
abn/cafeteria | cafeteria/datastructs/dict.py | MergingDict._merge | def _merge(self, key, value):
"""
Internal merge logic implementation to allow merging of values when
setting attributes/items.
:param key: Attribute name or item key
:type key: str
:param value: Value to set attribute/item as.
:type value: object
:rtype:... | python | def _merge(self, key, value):
"""
Internal merge logic implementation to allow merging of values when
setting attributes/items.
:param key: Attribute name or item key
:type key: str
:param value: Value to set attribute/item as.
:type value: object
:rtype:... | [
"def",
"_merge",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"method",
"=",
"self",
".",
"_merge_method",
"(",
"key",
")",
"if",
"method",
"is",
"not",
"None",
":",
"# strings are special, update methods like set.update looks for",
"# iterables",
"if",
"met... | Internal merge logic implementation to allow merging of values when
setting attributes/items.
:param key: Attribute name or item key
:type key: str
:param value: Value to set attribute/item as.
:type value: object
:rtype: None | [
"Internal",
"merge",
"logic",
"implementation",
"to",
"allow",
"merging",
"of",
"values",
"when",
"setting",
"attributes",
"/",
"items",
"."
] | train | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/datastructs/dict.py#L103-L130 |
FrancoisConstant/django-twitter-feed | twitter_feed/import_tweets.py | ImportTweets._tweepy_status_to_tweet | def _tweepy_status_to_tweet(self, status):
"""
Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
"""
tweet = Tweet()
tweet.published_at = status.created_at
tweet.content = status.text
return tweet | python | def _tweepy_status_to_tweet(self, status):
"""
Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
"""
tweet = Tweet()
tweet.published_at = status.created_at
tweet.content = status.text
return tweet | [
"def",
"_tweepy_status_to_tweet",
"(",
"self",
",",
"status",
")",
":",
"tweet",
"=",
"Tweet",
"(",
")",
"tweet",
".",
"published_at",
"=",
"status",
".",
"created_at",
"tweet",
".",
"content",
"=",
"status",
".",
"text",
"return",
"tweet"
] | Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline | [
"Fields",
"documentation",
":",
"https",
":",
"//",
"dev",
".",
"twitter",
".",
"com",
"/",
"docs",
"/",
"api",
"/",
"1",
".",
"1",
"/",
"get",
"/",
"statuses",
"/",
"home_timeline"
] | train | https://github.com/FrancoisConstant/django-twitter-feed/blob/4ef90cdc2a3e12852380f07ebf224834ce510396/twitter_feed/import_tweets.py#L31-L39 |
oscarlazoarjona/fast | build/lib/fast/misc.py | formatLij | def formatLij(Lij0,Ne):
"""This function transforms a list of laser conections of the form
[i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a
Ne x Ne matrix whose elements are the lasers connecting the corresponding
indices."""
#We create Lij as a matrix of lists of laser indices
global Lij
Lij=... | python | def formatLij(Lij0,Ne):
"""This function transforms a list of laser conections of the form
[i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a
Ne x Ne matrix whose elements are the lasers connecting the corresponding
indices."""
#We create Lij as a matrix of lists of laser indices
global Lij
Lij=... | [
"def",
"formatLij",
"(",
"Lij0",
",",
"Ne",
")",
":",
"#We create Lij as a matrix of lists of laser indices",
"global",
"Lij",
"Lij",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"fila",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
... | This function transforms a list of laser conections of the form
[i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a
Ne x Ne matrix whose elements are the lasers connecting the corresponding
indices. | [
"This",
"function",
"transforms",
"a",
"list",
"of",
"laser",
"conections",
"of",
"the",
"form",
"[",
"i",
"j",
"[",
"l1",
"l2",
"...",
"]]",
"between",
"states",
"i",
"and",
"j",
"by",
"lasers",
"l1",
"l2",
"...",
"into",
"a",
"Ne",
"x",
"Ne",
"ma... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/misc.py#L183-L207 |
oscarlazoarjona/fast | build/lib/fast/misc.py | Theta | def Theta(i,j,theta,omega_rescaled,omega_min,
detunings,detuningsij,combinations,detuning_indices,
Lij,i_d,I_nd,Nnd,
states=None,verbose=1,other_the=None):
"""This function returns code for Theta_i j as defined in the equation labeled Theta. in terms
of detunings. It recieves indexes i,j starting from 1."""
... | python | def Theta(i,j,theta,omega_rescaled,omega_min,
detunings,detuningsij,combinations,detuning_indices,
Lij,i_d,I_nd,Nnd,
states=None,verbose=1,other_the=None):
"""This function returns code for Theta_i j as defined in the equation labeled Theta. in terms
of detunings. It recieves indexes i,j starting from 1."""
... | [
"def",
"Theta",
"(",
"i",
",",
"j",
",",
"theta",
",",
"omega_rescaled",
",",
"omega_min",
",",
"detunings",
",",
"detuningsij",
",",
"combinations",
",",
"detuning_indices",
",",
"Lij",
",",
"i_d",
",",
"I_nd",
",",
"Nnd",
",",
"states",
"=",
"None",
... | This function returns code for Theta_i j as defined in the equation labeled Theta. in terms
of detunings. It recieves indexes i,j starting from 1. | [
"This",
"function",
"returns",
"code",
"for",
"Theta_i",
"j",
"as",
"defined",
"in",
"the",
"equation",
"labeled",
"Theta",
".",
"in",
"terms",
"of",
"detunings",
".",
"It",
"recieves",
"indexes",
"i",
"j",
"starting",
"from",
"1",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/misc.py#L329-L527 |
oscarlazoarjona/fast | build/lib/fast/misc.py | dot_product | def dot_product(laserl,sign,r,i,j):
"This function calculates the dot product epsilon^(l(+-)) . vec(r_ij)."
if sign==1:
dp=sum([laserl.Yp[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)])
elif sign==-1:
dp=sum([laserl.Ym[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)])
#~ if i==2 and j==9 and sign==-1:
... | python | def dot_product(laserl,sign,r,i,j):
"This function calculates the dot product epsilon^(l(+-)) . vec(r_ij)."
if sign==1:
dp=sum([laserl.Yp[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)])
elif sign==-1:
dp=sum([laserl.Ym[1-p]*r[p+1][i-1][j-1]*(-1)**p for p in range(-1,2)])
#~ if i==2 and j==9 and sign==-1:
... | [
"def",
"dot_product",
"(",
"laserl",
",",
"sign",
",",
"r",
",",
"i",
",",
"j",
")",
":",
"if",
"sign",
"==",
"1",
":",
"dp",
"=",
"sum",
"(",
"[",
"laserl",
".",
"Yp",
"[",
"1",
"-",
"p",
"]",
"*",
"r",
"[",
"p",
"+",
"1",
"]",
"[",
"i... | This function calculates the dot product epsilon^(l(+-)) . vec(r_ij). | [
"This",
"function",
"calculates",
"the",
"dot",
"product",
"epsilon^",
"(",
"l",
"(",
"+",
"-",
"))",
".",
"vec",
"(",
"r_ij",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/misc.py#L529-L545 |
tilde-lab/tilde | tilde/berlinium/categs.py | wrap_cell | def wrap_cell(entity, json_obj, mapping, table_view=False):
'''
Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this!
'''
html_class = '' # for GUI javascript
out = ''
#if 'cell_wrapper' in entity: # TODO : this bound type was d... | python | def wrap_cell(entity, json_obj, mapping, table_view=False):
'''
Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this!
'''
html_class = '' # for GUI javascript
out = ''
#if 'cell_wrapper' in entity: # TODO : this bound type was d... | [
"def",
"wrap_cell",
"(",
"entity",
",",
"json_obj",
",",
"mapping",
",",
"table_view",
"=",
"False",
")",
":",
"html_class",
"=",
"''",
"# for GUI javascript",
"out",
"=",
"''",
"#if 'cell_wrapper' in entity: # TODO : this bound type was defined by apps only",
"# out =... | Cell wrappers
for customizing the GUI data table
TODO : must coincide with hierarchy!
TODO : simplify this! | [
"Cell",
"wrappers",
"for",
"customizing",
"the",
"GUI",
"data",
"table"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/categs.py#L4-L46 |
tilde-lab/tilde | utils/syshwinfo.py | meminfo | def meminfo():
"""Get the amount of memory and swap, Mebibytes"""
f = open("/proc/meminfo")
hwinfo = {}
for line in f.readlines():
meml = line.split()
if (meml[0] == "MemTotal:"):
mem = int(meml[1])
hwinfo["Mem_MiB"] = mem/1024
elif (meml[0] == "SwapTotal:... | python | def meminfo():
"""Get the amount of memory and swap, Mebibytes"""
f = open("/proc/meminfo")
hwinfo = {}
for line in f.readlines():
meml = line.split()
if (meml[0] == "MemTotal:"):
mem = int(meml[1])
hwinfo["Mem_MiB"] = mem/1024
elif (meml[0] == "SwapTotal:... | [
"def",
"meminfo",
"(",
")",
":",
"f",
"=",
"open",
"(",
"\"/proc/meminfo\"",
")",
"hwinfo",
"=",
"{",
"}",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"meml",
"=",
"line",
".",
"split",
"(",
")",
"if",
"(",
"meml",
"[",
"0",
"]",... | Get the amount of memory and swap, Mebibytes | [
"Get",
"the",
"amount",
"of",
"memory",
"and",
"swap",
"Mebibytes"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L34-L47 |
tilde-lab/tilde | utils/syshwinfo.py | cpuinfo | def cpuinfo():
"""Get the cpu info"""
f = open("/proc/cpuinfo")
hwinfo = {}
for line in f.readlines():
cpul = line.split(":")
name = cpul[0].strip()
if (len(cpul) > 1):
val = cpul[1].strip()
if (name == "model name"):
hwinfo["CPU"] = val
el... | python | def cpuinfo():
"""Get the cpu info"""
f = open("/proc/cpuinfo")
hwinfo = {}
for line in f.readlines():
cpul = line.split(":")
name = cpul[0].strip()
if (len(cpul) > 1):
val = cpul[1].strip()
if (name == "model name"):
hwinfo["CPU"] = val
el... | [
"def",
"cpuinfo",
"(",
")",
":",
"f",
"=",
"open",
"(",
"\"/proc/cpuinfo\"",
")",
"hwinfo",
"=",
"{",
"}",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"cpul",
"=",
"line",
".",
"split",
"(",
"\":\"",
")",
"name",
"=",
"cpul",
"[",
... | Get the cpu info | [
"Get",
"the",
"cpu",
"info"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L49-L63 |
tilde-lab/tilde | utils/syshwinfo.py | vgadata | def vgadata():
"""Get data about the graphics card."""
if os.path.isfile('/sbin/lspci'):
lspci = '/sbin/lspci'
else:
lspci = '/usr/bin/lspci'
f = os.popen (lspci + ' -m')
pdata = {}
for line in f.readlines():
p = line.split("\"")
name = p[1].strip()
if (na... | python | def vgadata():
"""Get data about the graphics card."""
if os.path.isfile('/sbin/lspci'):
lspci = '/sbin/lspci'
else:
lspci = '/usr/bin/lspci'
f = os.popen (lspci + ' -m')
pdata = {}
for line in f.readlines():
p = line.split("\"")
name = p[1].strip()
if (na... | [
"def",
"vgadata",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'/sbin/lspci'",
")",
":",
"lspci",
"=",
"'/sbin/lspci'",
"else",
":",
"lspci",
"=",
"'/usr/bin/lspci'",
"f",
"=",
"os",
".",
"popen",
"(",
"lspci",
"+",
"' -m'",
")",
"pda... | Get data about the graphics card. | [
"Get",
"data",
"about",
"the",
"graphics",
"card",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L70-L84 |
tilde-lab/tilde | utils/syshwinfo.py | serial_number | def serial_number():
"""Get the serial number. Requires root access"""
sdata = {}
if os.getuid() == 0:
try:
sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \
.read().strip()
except:
for line in os.popen('/usr/sbin/dmidecode -s system-serial-... | python | def serial_number():
"""Get the serial number. Requires root access"""
sdata = {}
if os.getuid() == 0:
try:
sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \
.read().strip()
except:
for line in os.popen('/usr/sbin/dmidecode -s system-serial-... | [
"def",
"serial_number",
"(",
")",
":",
"sdata",
"=",
"{",
"}",
"if",
"os",
".",
"getuid",
"(",
")",
"==",
"0",
":",
"try",
":",
"sdata",
"[",
"'Serial'",
"]",
"=",
"open",
"(",
"'/sys/class/dmi/id/product_serial'",
")",
".",
"read",
"(",
")",
".",
... | Get the serial number. Requires root access | [
"Get",
"the",
"serial",
"number",
".",
"Requires",
"root",
"access"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L86-L96 |
tilde-lab/tilde | utils/syshwinfo.py | system_model | def system_model():
"""Get manufacturer and model number.
On older Linux kernel versions without /sys/class/dmi/id this
requires root access.
"""
mdata = {}
man = None
pn = None
try:
# This might be
# sys_vendor, bios_vendor, board_vendor, or chassis_vendor
man =... | python | def system_model():
"""Get manufacturer and model number.
On older Linux kernel versions without /sys/class/dmi/id this
requires root access.
"""
mdata = {}
man = None
pn = None
try:
# This might be
# sys_vendor, bios_vendor, board_vendor, or chassis_vendor
man =... | [
"def",
"system_model",
"(",
")",
":",
"mdata",
"=",
"{",
"}",
"man",
"=",
"None",
"pn",
"=",
"None",
"try",
":",
"# This might be",
"# sys_vendor, bios_vendor, board_vendor, or chassis_vendor",
"man",
"=",
"open",
"(",
"'/sys/class/dmi/id/sys_vendor'",
")",
".",
"... | Get manufacturer and model number.
On older Linux kernel versions without /sys/class/dmi/id this
requires root access. | [
"Get",
"manufacturer",
"and",
"model",
"number",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L98-L125 |
tilde-lab/tilde | utils/syshwinfo.py | diskdata | def diskdata():
"""Get total disk size in GB."""
p = os.popen("/bin/df -l -P")
ddata = {}
tsize = 0
for line in p.readlines():
d = line.split()
if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]):
tsize = tsize + int(d[1])
ddata["Disk_GB"] = int(tsize... | python | def diskdata():
"""Get total disk size in GB."""
p = os.popen("/bin/df -l -P")
ddata = {}
tsize = 0
for line in p.readlines():
d = line.split()
if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]):
tsize = tsize + int(d[1])
ddata["Disk_GB"] = int(tsize... | [
"def",
"diskdata",
"(",
")",
":",
"p",
"=",
"os",
".",
"popen",
"(",
"\"/bin/df -l -P\"",
")",
"ddata",
"=",
"{",
"}",
"tsize",
"=",
"0",
"for",
"line",
"in",
"p",
".",
"readlines",
"(",
")",
":",
"d",
"=",
"line",
".",
"split",
"(",
")",
"if",... | Get total disk size in GB. | [
"Get",
"total",
"disk",
"size",
"in",
"GB",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L127-L138 |
tilde-lab/tilde | utils/syshwinfo.py | ip_address | def ip_address():
"""Get the IP address used for public connections."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 8.8.8.8 is the google public DNS
s.connect(("8.8.8.8", 53))
ip = s.getsockname()[0]
s.close()
return ip | python | def ip_address():
"""Get the IP address used for public connections."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 8.8.8.8 is the google public DNS
s.connect(("8.8.8.8", 53))
ip = s.getsockname()[0]
s.close()
return ip | [
"def",
"ip_address",
"(",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"# 8.8.8.8 is the google public DNS",
"s",
".",
"connect",
"(",
"(",
"\"8.8.8.8\"",
",",
"53",
")",
")",
"ip",
"=... | Get the IP address used for public connections. | [
"Get",
"the",
"IP",
"address",
"used",
"for",
"public",
"connections",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L155-L162 |
tilde-lab/tilde | utils/syshwinfo.py | mac_address | def mac_address(ip):
"""Get the MAC address"""
mac = ''
for line in os.popen('/sbin/ifconfig'):
s = line.split()
if len(s) > 3:
if s[3] == 'HWaddr':
mac = s[4]
elif s[2] == ip:
break
return {'MAC': mac} | python | def mac_address(ip):
"""Get the MAC address"""
mac = ''
for line in os.popen('/sbin/ifconfig'):
s = line.split()
if len(s) > 3:
if s[3] == 'HWaddr':
mac = s[4]
elif s[2] == ip:
break
return {'MAC': mac} | [
"def",
"mac_address",
"(",
"ip",
")",
":",
"mac",
"=",
"''",
"for",
"line",
"in",
"os",
".",
"popen",
"(",
"'/sbin/ifconfig'",
")",
":",
"s",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"s",
")",
">",
"3",
":",
"if",
"s",
"[",
"3",... | Get the MAC address | [
"Get",
"the",
"MAC",
"address"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L164-L174 |
tilde-lab/tilde | utils/syshwinfo.py | getallhwinfo | def getallhwinfo():
"""Get all the hw info."""
hwinfo = meminfo()
hwinfo.update(cpuinfo())
hwinfo.update(uname())
hwinfo.update(vgadata())
hwinfo.update(distro())
hwinfo.update(diskdata())
hwinfo.update(hostname())
hwinfo.update(serial_number())
ip = ip_address()
hwinfo.updat... | python | def getallhwinfo():
"""Get all the hw info."""
hwinfo = meminfo()
hwinfo.update(cpuinfo())
hwinfo.update(uname())
hwinfo.update(vgadata())
hwinfo.update(distro())
hwinfo.update(diskdata())
hwinfo.update(hostname())
hwinfo.update(serial_number())
ip = ip_address()
hwinfo.updat... | [
"def",
"getallhwinfo",
"(",
")",
":",
"hwinfo",
"=",
"meminfo",
"(",
")",
"hwinfo",
".",
"update",
"(",
"cpuinfo",
"(",
")",
")",
"hwinfo",
".",
"update",
"(",
"uname",
"(",
")",
")",
"hwinfo",
".",
"update",
"(",
"vgadata",
"(",
")",
")",
"hwinfo"... | Get all the hw info. | [
"Get",
"all",
"the",
"hw",
"info",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L176-L190 |
tilde-lab/tilde | utils/syshwinfo.py | printheader | def printheader(h=None):
"""Print the header for the CSV table."""
writer = csv.writer(sys.stdout)
writer.writerow(header_fields(h)) | python | def printheader(h=None):
"""Print the header for the CSV table."""
writer = csv.writer(sys.stdout)
writer.writerow(header_fields(h)) | [
"def",
"printheader",
"(",
"h",
"=",
"None",
")",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"sys",
".",
"stdout",
")",
"writer",
".",
"writerow",
"(",
"header_fields",
"(",
"h",
")",
")"
] | Print the header for the CSV table. | [
"Print",
"the",
"header",
"for",
"the",
"CSV",
"table",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L200-L203 |
tilde-lab/tilde | utils/syshwinfo.py | printtable | def printtable(h, header):
"""Print as a table."""
hk = header_fields(h)
if (header):
printheader()
writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore')
writer.writerow(h) | python | def printtable(h, header):
"""Print as a table."""
hk = header_fields(h)
if (header):
printheader()
writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore')
writer.writerow(h) | [
"def",
"printtable",
"(",
"h",
",",
"header",
")",
":",
"hk",
"=",
"header_fields",
"(",
"h",
")",
"if",
"(",
"header",
")",
":",
"printheader",
"(",
")",
"writer",
"=",
"csv",
".",
"DictWriter",
"(",
"sys",
".",
"stdout",
",",
"hk",
",",
"extrasac... | Print as a table. | [
"Print",
"as",
"a",
"table",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L205-L211 |
tilde-lab/tilde | utils/syshwinfo.py | agent | def agent(server="http://localhost:8000"):
"""Run in agent mode.
This gathers data, and sends it to a server given by the server argument.
"""
import xmlrpc.client
sp = xmlrpc.client.ServerProxy(server)
hw = getallhwinfo()
fields = header_fields()
for f in fields:
if not f in h... | python | def agent(server="http://localhost:8000"):
"""Run in agent mode.
This gathers data, and sends it to a server given by the server argument.
"""
import xmlrpc.client
sp = xmlrpc.client.ServerProxy(server)
hw = getallhwinfo()
fields = header_fields()
for f in fields:
if not f in h... | [
"def",
"agent",
"(",
"server",
"=",
"\"http://localhost:8000\"",
")",
":",
"import",
"xmlrpc",
".",
"client",
"sp",
"=",
"xmlrpc",
".",
"client",
".",
"ServerProxy",
"(",
"server",
")",
"hw",
"=",
"getallhwinfo",
"(",
")",
"fields",
"=",
"header_fields",
"... | Run in agent mode.
This gathers data, and sends it to a server given by the server argument. | [
"Run",
"in",
"agent",
"mode",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L213-L229 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_omega_matrix | def calculate_omega_matrix(states, Omega=1):
"""Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies).
"""
... | python | def calculate_omega_matrix(states, Omega=1):
"""Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies).
"""
... | [
"def",
"calculate_omega_matrix",
"(",
"states",
",",
"Omega",
"=",
"1",
")",
":",
"N",
"=",
"len",
"(",
"states",
")",
"omega",
"=",
"[",
"[",
"2",
"*",
"Pi",
"*",
"(",
"states",
"[",
"i",
"]",
".",
"nu",
"-",
"states",
"[",
"j",
"]",
".",
"n... | Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies). | [
"Calculate",
"the",
"matrix",
"of",
"transition",
"frequencies",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1279-L1290 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_gamma_matrix | def calculate_gamma_matrix(magnetic_states, Omega=1):
r"""Calculate the matrix of decay between states.
This function calculates the matrix $\gamma_{ij}$ of decay rates between
states |i> and |j> (in the units specified by the Omega argument).
>>> g=State("Rb",87,5,0,1/Integer(2))
>>> e=State("Rb"... | python | def calculate_gamma_matrix(magnetic_states, Omega=1):
r"""Calculate the matrix of decay between states.
This function calculates the matrix $\gamma_{ij}$ of decay rates between
states |i> and |j> (in the units specified by the Omega argument).
>>> g=State("Rb",87,5,0,1/Integer(2))
>>> e=State("Rb"... | [
"def",
"calculate_gamma_matrix",
"(",
"magnetic_states",
",",
"Omega",
"=",
"1",
")",
":",
"Ne",
"=",
"len",
"(",
"magnetic_states",
")",
"II",
"=",
"magnetic_states",
"[",
"0",
"]",
".",
"i",
"gamma",
"=",
"[",
"[",
"0.0",
"for",
"j",
"in",
"range",
... | r"""Calculate the matrix of decay between states.
This function calculates the matrix $\gamma_{ij}$ of decay rates between
states |i> and |j> (in the units specified by the Omega argument).
>>> g=State("Rb",87,5,0,1/Integer(2))
>>> e=State("Rb",87,5,1,3/Integer(2))
>>> magnetic_states=make_list_of... | [
"r",
"Calculate",
"the",
"matrix",
"of",
"decay",
"between",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1316-L1386 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_boundaries | def calculate_boundaries(fine_states, full_magnetic_states):
r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the s... | python | def calculate_boundaries(fine_states, full_magnetic_states):
r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the s... | [
"def",
"calculate_boundaries",
"(",
"fine_states",
",",
"full_magnetic_states",
")",
":",
"N_magnetic",
"=",
"len",
"(",
"full_magnetic_states",
")",
"# We calculate the boundaries of the various detail levels",
"# First we will make a list of indices of that will tell where each fine"... | r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the starting index of a state and
b it's ending index.
>>> g=... | [
"r",
"Calculate",
"the",
"boundary",
"indices",
"within",
"a",
"list",
"of",
"magnetic",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1526-L1567 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | exclude_states | def exclude_states(omega, gamma, r, Lij, states, excluded_states):
"""Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states.
"""
Ne = len(omega)
excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]
omega_new = ... | python | def exclude_states(omega, gamma, r, Lij, states, excluded_states):
"""Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states.
"""
Ne = len(omega)
excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]
omega_new = ... | [
"def",
"exclude_states",
"(",
"omega",
",",
"gamma",
",",
"r",
",",
"Lij",
",",
"states",
",",
"excluded_states",
")",
":",
"Ne",
"=",
"len",
"(",
"omega",
")",
"excluded_indices",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"if",
"st... | Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states. | [
"Exclude",
"states",
"from",
"matrices",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1604-L1637 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | calculate_reduced_matrix_elements_0 | def calculate_reduced_matrix_elements_0(fine_states):
'''This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.'''
#We calculate the reduced matrix elements starting from the list of fine_states
#The factor composed of physical quantities.
factor=sqrt(3*c**3*me**... | python | def calculate_reduced_matrix_elements_0(fine_states):
'''This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.'''
#We calculate the reduced matrix elements starting from the list of fine_states
#The factor composed of physical quantities.
factor=sqrt(3*c**3*me**... | [
"def",
"calculate_reduced_matrix_elements_0",
"(",
"fine_states",
")",
":",
"#We calculate the reduced matrix elements starting from the list of fine_states",
"#The factor composed of physical quantities.",
"factor",
"=",
"sqrt",
"(",
"3",
"*",
"c",
"**",
"3",
"*",
"me",
"**",
... | This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states. | [
"This",
"function",
"calculates",
"the",
"reduced",
"matrix",
"elments",
"<N",
"L",
"J||T^1",
"(",
"r",
")",
"||N",
"L",
"J",
">",
"given",
"a",
"list",
"of",
"fine",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1734-L1767 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | vapour_pressure | def vapour_pressure(Temperature, element):
r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 2... | python | def vapour_pressure(Temperature, element):
r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 2... | [
"def",
"vapour_pressure",
"(",
"Temperature",
",",
"element",
")",
":",
"if",
"element",
"==",
"\"Rb\"",
":",
"Tmelt",
"=",
"39.30",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.857",
"-",
... | r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 273.15,"Rb")
0.000244249795696
>>> print... | [
"r",
"Return",
"the",
"vapour",
"pressure",
"of",
"rubidium",
"or",
"cesium",
"in",
"Pascals",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1904-L1956 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | speed_average | def speed_average(Temperature,element,isotope):
r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) an... | python | def speed_average(Temperature,element,isotope):
r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) an... | [
"def",
"speed_average",
"(",
"Temperature",
",",
"element",
",",
"isotope",
")",
":",
"atom",
"=",
"Atom",
"(",
"element",
",",
"isotope",
")",
"return",
"sqrt",
"(",
"8",
"*",
"k_B",
"*",
"Temperature",
"/",
"atom",
".",
"mass",
"/",
"pi",
")"
] | r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
m is the mass of the atom (in kilograms).
... | [
"r",
"This",
"function",
"calculates",
"the",
"average",
"speed",
"(",
"in",
"meters",
"per",
"second",
")",
"of",
"an",
"atom",
"in",
"a",
"vapour",
"assuming",
"a",
"Maxwell",
"-",
"Boltzmann",
"velocity",
"distribution",
".",
"This",
"is",
"simply"
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L2021-L2039 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | speed_rms | def speed_rms(Temperature,element,isotope):
r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
... | python | def speed_rms(Temperature,element,isotope):
r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
... | [
"def",
"speed_rms",
"(",
"Temperature",
",",
"element",
",",
"isotope",
")",
":",
"atom",
"=",
"Atom",
"(",
"element",
",",
"isotope",
")",
"return",
"sqrt",
"(",
"3",
"*",
"Temperature",
"*",
"k_B",
"/",
"atom",
".",
"mass",
")"
] | r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
m is the mass of the atom (in kilograms).
... | [
"r",
"This",
"function",
"calculates",
"the",
"average",
"speed",
"(",
"in",
"meters",
"per",
"second",
")",
"of",
"an",
"atom",
"in",
"a",
"vapour",
"assuming",
"a",
"Maxwell",
"-",
"Boltzmann",
"velocity",
"distribution",
".",
"This",
"is",
"simply"
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L2042-L2060 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | collision_rate | def collision_rate(Temperature, element, isotope):
r"""This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann velocity distribution, and ta... | python | def collision_rate(Temperature, element, isotope):
r"""This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann velocity distribution, and ta... | [
"def",
"collision_rate",
"(",
"Temperature",
",",
"element",
",",
"isotope",
")",
":",
"atom",
"=",
"Atom",
"(",
"element",
",",
"isotope",
")",
"sigma",
"=",
"pi",
"*",
"(",
"2",
"*",
"atom",
".",
"radius",
")",
"**",
"2",
"v",
"=",
"speed_average",... | r"""This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann velocity distribution, and taking the cross section
of the collision to be
... | [
"r",
"This",
"function",
"recieves",
"the",
"temperature",
"of",
"an",
"atomic",
"vapour",
"(",
"in",
"Kelvin",
")",
"the",
"element",
"and",
"the",
"isotope",
"of",
"the",
"atoms",
"and",
"returns",
"the",
"angular",
"frequency",
"rate",
"of",
"collisions",... | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L2063-L2093 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | Atom.states | def states(self,
Nmax=50, omega_min=None, omega_max=None, return_missing=False):
r"""Find all states of available in an atom.
This function returns all available states up to the fine structure
(ordered by energy) such that the principal quantum number is N<=Nmax.
Nmax is... | python | def states(self,
Nmax=50, omega_min=None, omega_max=None, return_missing=False):
r"""Find all states of available in an atom.
This function returns all available states up to the fine structure
(ordered by energy) such that the principal quantum number is N<=Nmax.
Nmax is... | [
"def",
"states",
"(",
"self",
",",
"Nmax",
"=",
"50",
",",
"omega_min",
"=",
"None",
",",
"omega_max",
"=",
"None",
",",
"return_missing",
"=",
"False",
")",
":",
"# We generate all possible quantum numbers for N<=Nmax.",
"S",
"=",
"1",
"/",
"Integer",
"(",
... | r"""Find all states of available in an atom.
This function returns all available states up to the fine structure
(ordered by energy) such that the principal quantum number is N<=Nmax.
Nmax is 50 by default.
>>> atom=Atom("Rb",85)
>>> states=atom.states()
>>> print state... | [
"r",
"Find",
"all",
"states",
"of",
"available",
"in",
"an",
"atom",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L229-L292 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | Atom.find_decays | def find_decays(self, fine_state):
r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2)... | python | def find_decays(self, fine_state):
r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2)... | [
"def",
"find_decays",
"(",
"self",
",",
"fine_state",
")",
":",
"def",
"decays_from",
"(",
"fine_state",
",",
"transitions",
")",
":",
"states_below",
"=",
"[",
"]",
"for",
"t",
"in",
"transitions",
":",
"if",
"t",
".",
"e2",
"==",
"fine_state",
":",
"... | r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2))
>>> atom.find_decays(e)
[... | [
"r",
"Find",
"all",
"possible",
"decays",
"from",
"a",
"given",
"fine",
"state",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L342-L381 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | State._latex_ | def _latex_(self):
r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
... | python | def _latex_(self):
r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
... | [
"def",
"_latex_",
"(",
"self",
")",
":",
"if",
"self",
".",
"l",
"==",
"0",
":",
"l",
"=",
"'S'",
"elif",
"self",
".",
"l",
"==",
"1",
":",
"l",
"=",
"'P'",
"elif",
"self",
".",
"l",
"==",
"2",
":",
"l",
"=",
"'D'",
"elif",
"self",
".",
"... | r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{... | [
"r",
"The",
"LaTeX",
"routine",
"for",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L926-L955 |
oscarlazoarjona/fast | build/lib/fast/atomic_structure.py | Transition._latex_ | def _latex_(self):
r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^... | python | def _latex_(self):
r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^... | [
"def",
"_latex_",
"(",
"self",
")",
":",
"if",
"self",
".",
"allowed",
":",
"return",
"self",
".",
"e1",
".",
"_latex_",
"(",
")",
"+",
"'\\\\ \\\\rightarrow \\\\ '",
"+",
"self",
".",
"e2",
".",
"_latex_",
"(",
")",
"elif",
"not",
"self",
".",
"allo... | r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}' | [
"r",
"The",
"representation",
"routine",
"for",
"transitions",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L1163-L1179 |
tilde-lab/tilde | tilde/berlinium/cubicspline.py | uFuncConverter | def uFuncConverter(variableIndex):
'''A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This w... | python | def uFuncConverter(variableIndex):
'''A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This w... | [
"def",
"uFuncConverter",
"(",
"variableIndex",
")",
":",
"def",
"wrap",
"(",
"func",
")",
":",
"'''Function to wrap around methods and functions\n '''",
"def",
"npWrapFunc",
"(",
"*",
"args",
")",
":",
"'''Function specifying what the wrapping should do\n ''... | A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This way the function can be used in classes as ... | [
"A",
"decorator",
"to",
"convert",
"python",
"functions",
"to",
"numpy",
"universal",
"functions"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/cubicspline.py#L23-L77 |
tilde-lab/tilde | tilde/berlinium/cubicspline.py | NaturalCubicSpline._findSegment | def _findSegment(self, x):
'''
:param x: x value to place in segment defined by the xData (instantiation)
:return: The lower index in the segment
'''
iLeft = 0
iRight = len(self.xData) - 1
while True:
if iRight - iLeft <= 1:
return iLef... | python | def _findSegment(self, x):
'''
:param x: x value to place in segment defined by the xData (instantiation)
:return: The lower index in the segment
'''
iLeft = 0
iRight = len(self.xData) - 1
while True:
if iRight - iLeft <= 1:
return iLef... | [
"def",
"_findSegment",
"(",
"self",
",",
"x",
")",
":",
"iLeft",
"=",
"0",
"iRight",
"=",
"len",
"(",
"self",
".",
"xData",
")",
"-",
"1",
"while",
"True",
":",
"if",
"iRight",
"-",
"iLeft",
"<=",
"1",
":",
"return",
"iLeft",
"i",
"=",
"(",
"iR... | :param x: x value to place in segment defined by the xData (instantiation)
:return: The lower index in the segment | [
":",
"param",
"x",
":",
"x",
"value",
"to",
"place",
"in",
"segment",
"defined",
"by",
"the",
"xData",
"(",
"instantiation",
")",
":",
"return",
":",
"The",
"lower",
"index",
"in",
"the",
"segment"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/cubicspline.py#L240-L254 |
oscarlazoarjona/fast | fast/atomic_structure.py | unperturbed_hamiltonian | def unperturbed_hamiltonian(states):
r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic"... | python | def unperturbed_hamiltonian(states):
r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic"... | [
"def",
"unperturbed_hamiltonian",
"(",
"states",
")",
":",
"Ne",
"=",
"len",
"(",
"states",
")",
"H0",
"=",
"np",
".",
"zeros",
"(",
"(",
"Ne",
",",
"Ne",
")",
",",
"complex",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"H0",
"[",
"i",... | r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic")
>>> print(np.diag(unperturbed_hamil... | [
"r",
"Return",
"the",
"unperturbed",
"atomic",
"hamiltonian",
"for",
"given",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1433-L1449 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.