repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
evolbioinfo/pastml | pastml/tree.py | name_tree | def name_tree(tree):
"""
Names all the tree nodes that are not named or have non-unique names, with unique names.
:param tree: tree to be named
:type tree: ete3.Tree
:return: void, modifies the original tree
"""
existing_names = Counter((_.name for _ in tree.traverse() if _.name))
if s... | python | def name_tree(tree):
"""
Names all the tree nodes that are not named or have non-unique names, with unique names.
:param tree: tree to be named
:type tree: ete3.Tree
:return: void, modifies the original tree
"""
existing_names = Counter((_.name for _ in tree.traverse() if _.name))
if s... | [
"def",
"name_tree",
"(",
"tree",
")",
":",
"existing_names",
"=",
"Counter",
"(",
"(",
"_",
".",
"name",
"for",
"_",
"in",
"tree",
".",
"traverse",
"(",
")",
"if",
"_",
".",
"name",
")",
")",
"if",
"sum",
"(",
"1",
"for",
"_",
"in",
"tree",
"."... | Names all the tree nodes that are not named or have non-unique names, with unique names.
:param tree: tree to be named
:type tree: ete3.Tree
:return: void, modifies the original tree | [
"Names",
"all",
"the",
"tree",
"nodes",
"that",
"are",
"not",
"named",
"or",
"have",
"non",
"-",
"unique",
"names",
"with",
"unique",
"names",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/tree.py#L46-L66 | train |
geophysics-ubonn/reda | lib/reda/importers/utils/decorators.py | enable_result_transforms | def enable_result_transforms(func):
"""Decorator that tries to use the object provided using a kwarg called
'electrode_transformator' to transform the return values of an import
function. It is intended to be used to transform electrode numbers and
locations, i.e. for use in roll-along-measurement schem... | python | def enable_result_transforms(func):
"""Decorator that tries to use the object provided using a kwarg called
'electrode_transformator' to transform the return values of an import
function. It is intended to be used to transform electrode numbers and
locations, i.e. for use in roll-along-measurement schem... | [
"def",
"enable_result_transforms",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"func_transformator",
"=",
"kwargs",
".",
"pop",
"(",
"'electrode_transformator'",
... | Decorator that tries to use the object provided using a kwarg called
'electrode_transformator' to transform the return values of an import
function. It is intended to be used to transform electrode numbers and
locations, i.e. for use in roll-along-measurement schemes.
The transformator object must have... | [
"Decorator",
"that",
"tries",
"to",
"use",
"the",
"object",
"provided",
"using",
"a",
"kwarg",
"called",
"electrode_transformator",
"to",
"transform",
"the",
"return",
"values",
"of",
"an",
"import",
"function",
".",
"It",
"is",
"intended",
"to",
"be",
"used",... | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/utils/decorators.py#L4-L28 | train |
cfobel/webcam-recorder | webcam_recorder/video_view.py | RecordControl.record_path | def record_path(self):
'''
If recording is not enabled, return `None` as record path.
'''
if self.record_button.get_property('active') and (self.record_path_selector
.selected_path):
return self.record_path_selector.se... | python | def record_path(self):
'''
If recording is not enabled, return `None` as record path.
'''
if self.record_button.get_property('active') and (self.record_path_selector
.selected_path):
return self.record_path_selector.se... | [
"def",
"record_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"record_button",
".",
"get_property",
"(",
"'active'",
")",
"and",
"(",
"self",
".",
"record_path_selector",
".",
"selected_path",
")",
":",
"return",
"self",
".",
"record_path_selector",
".",
"... | If recording is not enabled, return `None` as record path. | [
"If",
"recording",
"is",
"not",
"enabled",
"return",
"None",
"as",
"record",
"path",
"."
] | ffeb57c9044033fbea6372b3e642b83fd42dea87 | https://github.com/cfobel/webcam-recorder/blob/ffeb57c9044033fbea6372b3e642b83fd42dea87/webcam_recorder/video_view.py#L196-L204 | train |
geophysics-ubonn/reda | lib/reda/utils/geom_fac_crtomo.py | _write_crmod_file | def _write_crmod_file(filename):
"""Write a valid crmod configuration file to filename.
TODO: Modify configuration according to, e.g., 2D
"""
crmod_lines = [
'***FILES***',
'../grid/elem.dat',
'../grid/elec.dat',
'../rho/rho.dat',
'../config/config.dat',
... | python | def _write_crmod_file(filename):
"""Write a valid crmod configuration file to filename.
TODO: Modify configuration according to, e.g., 2D
"""
crmod_lines = [
'***FILES***',
'../grid/elem.dat',
'../grid/elec.dat',
'../rho/rho.dat',
'../config/config.dat',
... | [
"def",
"_write_crmod_file",
"(",
"filename",
")",
":",
"crmod_lines",
"=",
"[",
"'***FILES***'",
",",
"'../grid/elem.dat'",
",",
"'../grid/elec.dat'",
",",
"'../rho/rho.dat'",
",",
"'../config/config.dat'",
",",
"'F ! potentials ?'",
",",
"'../mod/pot/pot.dat... | Write a valid crmod configuration file to filename.
TODO: Modify configuration according to, e.g., 2D | [
"Write",
"a",
"valid",
"crmod",
"configuration",
"file",
"to",
"filename",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/geom_fac_crtomo.py#L39-L65 | train |
kaustavdm/pyAvroPhonetic | pyavrophonetic/utils/__init__.py | utf | def utf(text):
"""Shortcut funnction for encoding given text with utf-8"""
try:
output = unicode(text, encoding='utf-8')
except UnicodeDecodeError:
output = text
except TypeError:
output = text
return output | python | def utf(text):
"""Shortcut funnction for encoding given text with utf-8"""
try:
output = unicode(text, encoding='utf-8')
except UnicodeDecodeError:
output = text
except TypeError:
output = text
return output | [
"def",
"utf",
"(",
"text",
")",
":",
"try",
":",
"output",
"=",
"unicode",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"output",
"=",
"text",
"except",
"TypeError",
":",
"output",
"=",
"text",
"return",
"output... | Shortcut funnction for encoding given text with utf-8 | [
"Shortcut",
"funnction",
"for",
"encoding",
"given",
"text",
"with",
"utf",
"-",
"8"
] | 26b7d567d8db025f2cac4de817e716390d7ac337 | https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/__init__.py#L26-L34 | train |
andy-z/ged4py | ged4py/detail/io.py | check_bom | def check_bom(file):
"""Determines file codec from from its BOM record.
If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE)
then corresponding encoding name is returned, otherwise None is returned.
In both cases file current position is set to after-BOM bytes. The file
must be open i... | python | def check_bom(file):
"""Determines file codec from from its BOM record.
If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE)
then corresponding encoding name is returned, otherwise None is returned.
In both cases file current position is set to after-BOM bytes. The file
must be open i... | [
"def",
"check_bom",
"(",
"file",
")",
":",
"lead",
"=",
"file",
".",
"read",
"(",
"3",
")",
"if",
"len",
"(",
"lead",
")",
"==",
"3",
"and",
"lead",
"==",
"codecs",
".",
"BOM_UTF8",
":",
"return",
"codecs",
".",
"lookup",
"(",
"'utf-8'",
")",
"."... | Determines file codec from from its BOM record.
If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE)
then corresponding encoding name is returned, otherwise None is returned.
In both cases file current position is set to after-BOM bytes. The file
must be open in binary mode and positioned... | [
"Determines",
"file",
"codec",
"from",
"from",
"its",
"BOM",
"record",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/io.py#L10-L37 | train |
andy-z/ged4py | ged4py/detail/io.py | guess_lineno | def guess_lineno(file):
"""Guess current line number in a file.
Guessing is done in a very crude way - scanning file from beginning
until current offset and counting newlines. Only meant to be used in
exceptional cases - generating line number for error message.
"""
offset = file.tell()
fil... | python | def guess_lineno(file):
"""Guess current line number in a file.
Guessing is done in a very crude way - scanning file from beginning
until current offset and counting newlines. Only meant to be used in
exceptional cases - generating line number for error message.
"""
offset = file.tell()
fil... | [
"def",
"guess_lineno",
"(",
"file",
")",
":",
"offset",
"=",
"file",
".",
"tell",
"(",
")",
"file",
".",
"seek",
"(",
"0",
")",
"startpos",
"=",
"0",
"lineno",
"=",
"1",
"while",
"True",
":",
"line",
"=",
"file",
".",
"readline",
"(",
")",
"if",
... | Guess current line number in a file.
Guessing is done in a very crude way - scanning file from beginning
until current offset and counting newlines. Only meant to be used in
exceptional cases - generating line number for error message. | [
"Guess",
"current",
"line",
"number",
"in",
"a",
"file",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/io.py#L40-L62 | train |
pennlabs/penn-sdk-python | penn/libraries.py | search | def search(query):
"""Search Penn Libraries Franklin for documents
The maximum pagesize currently is 50.
"""
params = {
's.cmd': 'setTextQuery(%s)setPageSize(50)setHoldingsOnly(true)' % query
}
return requests.get(BASE_URL, params=params, timeout=10).json() | python | def search(query):
"""Search Penn Libraries Franklin for documents
The maximum pagesize currently is 50.
"""
params = {
's.cmd': 'setTextQuery(%s)setPageSize(50)setHoldingsOnly(true)' % query
}
return requests.get(BASE_URL, params=params, timeout=10).json() | [
"def",
"search",
"(",
"query",
")",
":",
"params",
"=",
"{",
"'s.cmd'",
":",
"'setTextQuery(%s)setPageSize(50)setHoldingsOnly(true)'",
"%",
"query",
"}",
"return",
"requests",
".",
"get",
"(",
"BASE_URL",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"10"... | Search Penn Libraries Franklin for documents
The maximum pagesize currently is 50. | [
"Search",
"Penn",
"Libraries",
"Franklin",
"for",
"documents",
"The",
"maximum",
"pagesize",
"currently",
"is",
"50",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/libraries.py#L7-L14 | train |
andy-z/ged4py | ged4py/model.py | make_record | def make_record(level, xref_id, tag, value, sub_records, offset, dialect,
parser=None):
"""Create Record instance based on parameters.
:param int level: Record level number.
:param str xref_id: Record reference ID, possibly empty.
:param str tag: Tag name.
:param value: Record value... | python | def make_record(level, xref_id, tag, value, sub_records, offset, dialect,
parser=None):
"""Create Record instance based on parameters.
:param int level: Record level number.
:param str xref_id: Record reference ID, possibly empty.
:param str tag: Tag name.
:param value: Record value... | [
"def",
"make_record",
"(",
"level",
",",
"xref_id",
",",
"tag",
",",
"value",
",",
"sub_records",
",",
"offset",
",",
"dialect",
",",
"parser",
"=",
"None",
")",
":",
"if",
"value",
"and",
"len",
"(",
"value",
")",
">",
"2",
"and",
"(",
"(",
"value... | Create Record instance based on parameters.
:param int level: Record level number.
:param str xref_id: Record reference ID, possibly empty.
:param str tag: Tag name.
:param value: Record value, possibly empty. Value can be None, bytes, or
string object, if it is bytes then it should be decoded ... | [
"Create",
"Record",
"instance",
"based",
"on",
"parameters",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L413-L450 | train |
andy-z/ged4py | ged4py/model.py | Record.sub_tag | def sub_tag(self, path, follow=True):
"""Returns direct sub-record with given tag name or None.
Path can be a simple tag name, in which case the first direct
sub-record of this record with the matching tag is returned. Path
can also consist of several tags separated by slashes, in that ... | python | def sub_tag(self, path, follow=True):
"""Returns direct sub-record with given tag name or None.
Path can be a simple tag name, in which case the first direct
sub-record of this record with the matching tag is returned. Path
can also consist of several tags separated by slashes, in that ... | [
"def",
"sub_tag",
"(",
"self",
",",
"path",
",",
"follow",
"=",
"True",
")",
":",
"tags",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"rec",
"=",
"self",
"for",
"tag",
"in",
"tags",
":",
"recs",
"=",
"[",
"x",
"for",
"x",
"in",
"(",
"rec",
".... | Returns direct sub-record with given tag name or None.
Path can be a simple tag name, in which case the first direct
sub-record of this record with the matching tag is returned. Path
can also consist of several tags separated by slashes, in that case
sub-records are searched recursively... | [
"Returns",
"direct",
"sub",
"-",
"record",
"with",
"given",
"tag",
"name",
"or",
"None",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L69-L95 | train |
andy-z/ged4py | ged4py/model.py | Record.sub_tag_value | def sub_tag_value(self, path, follow=True):
"""Returns value of a direct sub-record or None.
Works as :py:meth:`sub_tag` but returns value of a sub-record
instead of sub-record itself.
:param str path: tag names separated by slashes.
:param boolean follow: If True then resolve ... | python | def sub_tag_value(self, path, follow=True):
"""Returns value of a direct sub-record or None.
Works as :py:meth:`sub_tag` but returns value of a sub-record
instead of sub-record itself.
:param str path: tag names separated by slashes.
:param boolean follow: If True then resolve ... | [
"def",
"sub_tag_value",
"(",
"self",
",",
"path",
",",
"follow",
"=",
"True",
")",
":",
"rec",
"=",
"self",
".",
"sub_tag",
"(",
"path",
",",
"follow",
")",
"if",
"rec",
":",
"return",
"rec",
".",
"value",
"return",
"None"
] | Returns value of a direct sub-record or None.
Works as :py:meth:`sub_tag` but returns value of a sub-record
instead of sub-record itself.
:param str path: tag names separated by slashes.
:param boolean follow: If True then resolve pointers.
:return: String or `None` if sub-reco... | [
"Returns",
"value",
"of",
"a",
"direct",
"sub",
"-",
"record",
"or",
"None",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L97-L111 | train |
andy-z/ged4py | ged4py/model.py | Record.sub_tags | def sub_tags(self, *tags, **kw):
"""Returns list of direct sub-records matching any tag name.
Unlike :py:meth:`sub_tag` method this method does not support
hierarchical paths and does not resolve pointers.
:param str tags: Names of the sub-record tag
:param kw: Keyword argument... | python | def sub_tags(self, *tags, **kw):
"""Returns list of direct sub-records matching any tag name.
Unlike :py:meth:`sub_tag` method this method does not support
hierarchical paths and does not resolve pointers.
:param str tags: Names of the sub-record tag
:param kw: Keyword argument... | [
"def",
"sub_tags",
"(",
"self",
",",
"*",
"tags",
",",
"**",
"kw",
")",
":",
"records",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"sub_records",
"if",
"x",
".",
"tag",
"in",
"tags",
"]",
"if",
"kw",
".",
"get",
"(",
"'follow'",
",",
"True",... | Returns list of direct sub-records matching any tag name.
Unlike :py:meth:`sub_tag` method this method does not support
hierarchical paths and does not resolve pointers.
:param str tags: Names of the sub-record tag
:param kw: Keyword arguments, only recognized keyword is `follow`
... | [
"Returns",
"list",
"of",
"direct",
"sub",
"-",
"records",
"matching",
"any",
"tag",
"name",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L113-L128 | train |
andy-z/ged4py | ged4py/model.py | NameRec.freeze | def freeze(self):
"""Method called by parser when updates to this record finish.
:return: self
"""
# None is the same as empty string
if self.value is None:
self.value = ""
if self.dialect in [DIALECT_ALTREE]:
name_tuple = parse_name_altree(self)
... | python | def freeze(self):
"""Method called by parser when updates to this record finish.
:return: self
"""
# None is the same as empty string
if self.value is None:
self.value = ""
if self.dialect in [DIALECT_ALTREE]:
name_tuple = parse_name_altree(self)
... | [
"def",
"freeze",
"(",
"self",
")",
":",
"if",
"self",
".",
"value",
"is",
"None",
":",
"self",
".",
"value",
"=",
"\"\"",
"if",
"self",
".",
"dialect",
"in",
"[",
"DIALECT_ALTREE",
"]",
":",
"name_tuple",
"=",
"parse_name_altree",
"(",
"self",
")",
"... | Method called by parser when updates to this record finish.
:return: self | [
"Method",
"called",
"by",
"parser",
"when",
"updates",
"to",
"this",
"record",
"finish",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L200-L217 | train |
andy-z/ged4py | ged4py/model.py | Name.given | def given(self):
"""Given name could include both first and middle name"""
if self._primary.value[0] and self._primary.value[2]:
return self._primary.value[0] + ' ' + self._primary.value[2]
return self._primary.value[0] or self._primary.value[2] | python | def given(self):
"""Given name could include both first and middle name"""
if self._primary.value[0] and self._primary.value[2]:
return self._primary.value[0] + ' ' + self._primary.value[2]
return self._primary.value[0] or self._primary.value[2] | [
"def",
"given",
"(",
"self",
")",
":",
"if",
"self",
".",
"_primary",
".",
"value",
"[",
"0",
"]",
"and",
"self",
".",
"_primary",
".",
"value",
"[",
"2",
"]",
":",
"return",
"self",
".",
"_primary",
".",
"value",
"[",
"0",
"]",
"+",
"' '",
"+"... | Given name could include both first and middle name | [
"Given",
"name",
"could",
"include",
"both",
"first",
"and",
"middle",
"name"
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L268-L272 | train |
andy-z/ged4py | ged4py/model.py | Name.maiden | def maiden(self):
"""Maiden last name, can be None"""
if self._dialect == DIALECT_DEFAULT:
# for default/unknown dialect try "maiden" name record first
for name in self._names:
if name.type == "maiden":
return name.value[1]
# rely on Na... | python | def maiden(self):
"""Maiden last name, can be None"""
if self._dialect == DIALECT_DEFAULT:
# for default/unknown dialect try "maiden" name record first
for name in self._names:
if name.type == "maiden":
return name.value[1]
# rely on Na... | [
"def",
"maiden",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dialect",
"==",
"DIALECT_DEFAULT",
":",
"for",
"name",
"in",
"self",
".",
"_names",
":",
"if",
"name",
".",
"type",
"==",
"\"maiden\"",
":",
"return",
"name",
".",
"value",
"[",
"1",
"]",
... | Maiden last name, can be None | [
"Maiden",
"last",
"name",
"can",
"be",
"None"
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L283-L293 | train |
andy-z/ged4py | ged4py/model.py | Name.order | def order(self, order):
"""Returns name order key.
Returns tuple with two strings that can be compared to other such
tuple obtained from different name. Note that if you want
locale-dependent ordering then you need to compare strings using
locale-aware method (e.g. ``locale.strx... | python | def order(self, order):
"""Returns name order key.
Returns tuple with two strings that can be compared to other such
tuple obtained from different name. Note that if you want
locale-dependent ordering then you need to compare strings using
locale-aware method (e.g. ``locale.strx... | [
"def",
"order",
"(",
"self",
",",
"order",
")",
":",
"given",
"=",
"self",
".",
"given",
"surname",
"=",
"self",
".",
"surname",
"if",
"order",
"in",
"(",
"ORDER_MAIDEN_GIVEN",
",",
"ORDER_GIVEN_MAIDEN",
")",
":",
"surname",
"=",
"self",
".",
"maiden",
... | Returns name order key.
Returns tuple with two strings that can be compared to other such
tuple obtained from different name. Note that if you want
locale-dependent ordering then you need to compare strings using
locale-aware method (e.g. ``locale.strxfrm``).
:param order: One ... | [
"Returns",
"name",
"order",
"key",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L295-L321 | train |
andy-z/ged4py | ged4py/model.py | Name.format | def format(self):
"""Format name for output.
:return: Formatted name representation.
"""
name = self._primary.value[0]
if self.surname:
if name:
name += ' '
name += self.surname
if self._primary.value[2]:
if name:
... | python | def format(self):
"""Format name for output.
:return: Formatted name representation.
"""
name = self._primary.value[0]
if self.surname:
if name:
name += ' '
name += self.surname
if self._primary.value[2]:
if name:
... | [
"def",
"format",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_primary",
".",
"value",
"[",
"0",
"]",
"if",
"self",
".",
"surname",
":",
"if",
"name",
":",
"name",
"+=",
"' '",
"name",
"+=",
"self",
".",
"surname",
"if",
"self",
".",
"_prima... | Format name for output.
:return: Formatted name representation. | [
"Format",
"name",
"for",
"output",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/model.py#L323-L337 | train |
frasertweedale/ledgertools | ltlib/rule.py | Rule.match | def match(self, xn):
"""Processes a transaction against this rule
If all conditions are satisfied, a list of outcomes is returned.
If any condition is unsatisifed, None is returned.
"""
if all(map(lambda x: x.match(xn), self.conditions)):
return self.outcomes
... | python | def match(self, xn):
"""Processes a transaction against this rule
If all conditions are satisfied, a list of outcomes is returned.
If any condition is unsatisifed, None is returned.
"""
if all(map(lambda x: x.match(xn), self.conditions)):
return self.outcomes
... | [
"def",
"match",
"(",
"self",
",",
"xn",
")",
":",
"if",
"all",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"match",
"(",
"xn",
")",
",",
"self",
".",
"conditions",
")",
")",
":",
"return",
"self",
".",
"outcomes",
"return",
"None"
] | Processes a transaction against this rule
If all conditions are satisfied, a list of outcomes is returned.
If any condition is unsatisifed, None is returned. | [
"Processes",
"a",
"transaction",
"against",
"this",
"rule"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/rule.py#L152-L160 | train |
geophysics-ubonn/reda | lib/reda/importers/sip04.py | import_sip04_data_all | def import_sip04_data_all(data_filename):
"""Import ALL data from the result files
Parameters
----------
data_filename : string
Path to .mat or .csv file containing SIP-04 measurement results. Note
that the .csv file does not contain all data contained in the .mat
file!
Ret... | python | def import_sip04_data_all(data_filename):
"""Import ALL data from the result files
Parameters
----------
data_filename : string
Path to .mat or .csv file containing SIP-04 measurement results. Note
that the .csv file does not contain all data contained in the .mat
file!
Ret... | [
"def",
"import_sip04_data_all",
"(",
"data_filename",
")",
":",
"filename",
",",
"fformat",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"data_filename",
")",
"if",
"fformat",
"==",
"'.csv'",
":",
"print",
"(",
"'Import SIP04 data from .csv file'",
")",
"df_all... | Import ALL data from the result files
Parameters
----------
data_filename : string
Path to .mat or .csv file containing SIP-04 measurement results. Note
that the .csv file does not contain all data contained in the .mat
file!
Returns
-------
df_all : :py:class:`pandas.D... | [
"Import",
"ALL",
"data",
"from",
"the",
"result",
"files"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/sip04.py#L94-L121 | train |
YosaiProject/yosai_alchemystore | yosai_alchemystore/meta/meta.py | init_session | def init_session(db_url=None, echo=False, engine=None, settings=None):
"""
A SQLAlchemy Session requires that an engine be initialized if one isn't
provided.
"""
if engine is None:
engine = init_engine(db_url=db_url, echo=echo, settings=settings)
return sessionmaker(bind=engine) | python | def init_session(db_url=None, echo=False, engine=None, settings=None):
"""
A SQLAlchemy Session requires that an engine be initialized if one isn't
provided.
"""
if engine is None:
engine = init_engine(db_url=db_url, echo=echo, settings=settings)
return sessionmaker(bind=engine) | [
"def",
"init_session",
"(",
"db_url",
"=",
"None",
",",
"echo",
"=",
"False",
",",
"engine",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"if",
"engine",
"is",
"None",
":",
"engine",
"=",
"init_engine",
"(",
"db_url",
"=",
"db_url",
",",
"ech... | A SQLAlchemy Session requires that an engine be initialized if one isn't
provided. | [
"A",
"SQLAlchemy",
"Session",
"requires",
"that",
"an",
"engine",
"be",
"initialized",
"if",
"one",
"isn",
"t",
"provided",
"."
] | 6479c159ab2ac357e6b70cdd71a2d673279e86bb | https://github.com/YosaiProject/yosai_alchemystore/blob/6479c159ab2ac357e6b70cdd71a2d673279e86bb/yosai_alchemystore/meta/meta.py#L58-L65 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | importers.import_sip256c | def import_sip256c(self, filename, settings=None, reciprocal=None,
**kwargs):
"""Radic SIP256c data import"""
if settings is None:
settings = {}
# we get not electrode positions (dummy1) and no topography data
# (dummy2)
df, dummy1, dummy2 = red... | python | def import_sip256c(self, filename, settings=None, reciprocal=None,
**kwargs):
"""Radic SIP256c data import"""
if settings is None:
settings = {}
# we get not electrode positions (dummy1) and no topography data
# (dummy2)
df, dummy1, dummy2 = red... | [
"def",
"import_sip256c",
"(",
"self",
",",
"filename",
",",
"settings",
"=",
"None",
",",
"reciprocal",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"settings",
"is",
"None",
":",
"settings",
"=",
"{",
"}",
"df",
",",
"dummy1",
",",
"dummy2",
"=... | Radic SIP256c data import | [
"Radic",
"SIP256c",
"data",
"import"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L72-L84 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | importers.import_eit_fzj | def import_eit_fzj(self, filename, configfile, correction_file=None,
timestep=None, **kwargs):
"""EIT data import for FZJ Medusa systems"""
# we get not electrode positions (dummy1) and no topography data
# (dummy2)
df_emd, dummy1, dummy2 = eit_fzj.read_3p_data(
... | python | def import_eit_fzj(self, filename, configfile, correction_file=None,
timestep=None, **kwargs):
"""EIT data import for FZJ Medusa systems"""
# we get not electrode positions (dummy1) and no topography data
# (dummy2)
df_emd, dummy1, dummy2 = eit_fzj.read_3p_data(
... | [
"def",
"import_eit_fzj",
"(",
"self",
",",
"filename",
",",
"configfile",
",",
"correction_file",
"=",
"None",
",",
"timestep",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"df_emd",
",",
"dummy1",
",",
"dummy2",
"=",
"eit_fzj",
".",
"read_3p_data",
"(",
... | EIT data import for FZJ Medusa systems | [
"EIT",
"data",
"import",
"for",
"FZJ",
"Medusa",
"systems"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L86-L105 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.check_dataframe | def check_dataframe(self, dataframe):
"""Check the given dataframe for the required columns
"""
required_columns = (
'a',
'b',
'm',
'n',
'r',
)
for column in required_columns:
if column not in dataframe:
... | python | def check_dataframe(self, dataframe):
"""Check the given dataframe for the required columns
"""
required_columns = (
'a',
'b',
'm',
'n',
'r',
)
for column in required_columns:
if column not in dataframe:
... | [
"def",
"check_dataframe",
"(",
"self",
",",
"dataframe",
")",
":",
"required_columns",
"=",
"(",
"'a'",
",",
"'b'",
",",
"'m'",
",",
"'n'",
",",
"'r'",
",",
")",
"for",
"column",
"in",
"required_columns",
":",
"if",
"column",
"not",
"in",
"dataframe",
... | Check the given dataframe for the required columns | [
"Check",
"the",
"given",
"dataframe",
"for",
"the",
"required",
"columns"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L118-L132 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.query | def query(self, query, inplace=True):
"""State what you want to keep
"""
# TODO: add to queue
result = self.data.query(query, inplace=inplace)
return result | python | def query(self, query, inplace=True):
"""State what you want to keep
"""
# TODO: add to queue
result = self.data.query(query, inplace=inplace)
return result | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"inplace",
"=",
"True",
")",
":",
"result",
"=",
"self",
".",
"data",
".",
"query",
"(",
"query",
",",
"inplace",
"=",
"inplace",
")",
"return",
"result"
] | State what you want to keep | [
"State",
"what",
"you",
"want",
"to",
"keep"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L163-L169 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.remove_frequencies | def remove_frequencies(self, fmin, fmax):
"""Remove frequencies from the dataset
"""
self.data.query(
'frequency > {0} and frequency < {1}'.format(fmin, fmax),
inplace=True
)
g = self.data.groupby('frequency')
print('Remaining frequencies:')
... | python | def remove_frequencies(self, fmin, fmax):
"""Remove frequencies from the dataset
"""
self.data.query(
'frequency > {0} and frequency < {1}'.format(fmin, fmax),
inplace=True
)
g = self.data.groupby('frequency')
print('Remaining frequencies:')
... | [
"def",
"remove_frequencies",
"(",
"self",
",",
"fmin",
",",
"fmax",
")",
":",
"self",
".",
"data",
".",
"query",
"(",
"'frequency > {0} and frequency < {1}'",
".",
"format",
"(",
"fmin",
",",
"fmax",
")",
",",
"inplace",
"=",
"True",
")",
"g",
"=",
"self... | Remove frequencies from the dataset | [
"Remove",
"frequencies",
"from",
"the",
"dataset"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L196-L205 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.compute_K_analytical | def compute_K_analytical(self, spacing):
"""Assuming an equal electrode spacing, compute the K-factor over a
homogeneous half-space.
For more complex grids, please refer to the module:
reda.utils.geometric_factors
Parameters
----------
spacing: float
... | python | def compute_K_analytical(self, spacing):
"""Assuming an equal electrode spacing, compute the K-factor over a
homogeneous half-space.
For more complex grids, please refer to the module:
reda.utils.geometric_factors
Parameters
----------
spacing: float
... | [
"def",
"compute_K_analytical",
"(",
"self",
",",
"spacing",
")",
":",
"assert",
"isinstance",
"(",
"spacing",
",",
"Number",
")",
"K",
"=",
"geometric_factors",
".",
"compute_K_analytical",
"(",
"self",
".",
"data",
",",
"spacing",
")",
"self",
".",
"data",
... | Assuming an equal electrode spacing, compute the K-factor over a
homogeneous half-space.
For more complex grids, please refer to the module:
reda.utils.geometric_factors
Parameters
----------
spacing: float
Electrode spacing | [
"Assuming",
"an",
"equal",
"electrode",
"spacing",
"compute",
"the",
"K",
"-",
"factor",
"over",
"a",
"homogeneous",
"half",
"-",
"space",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L207-L223 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.scatter_norrec | def scatter_norrec(self, filename=None, individual=False):
"""Create a scatter plot for all diff pairs
Parameters
----------
filename : string, optional
if given, save plot to file
individual : bool, optional
if set to True, return one figure for each ro... | python | def scatter_norrec(self, filename=None, individual=False):
"""Create a scatter plot for all diff pairs
Parameters
----------
filename : string, optional
if given, save plot to file
individual : bool, optional
if set to True, return one figure for each ro... | [
"def",
"scatter_norrec",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"individual",
"=",
"False",
")",
":",
"std_diff_labels",
"=",
"{",
"'r'",
":",
"'rdiff'",
",",
"'rpha'",
":",
"'rphadiff'",
",",
"}",
"diff_labels",
"=",
"std_diff_labels",
"labels_to_u... | Create a scatter plot for all diff pairs
Parameters
----------
filename : string, optional
if given, save plot to file
individual : bool, optional
if set to True, return one figure for each row
Returns
-------
fig : matplotlib.Figure or ... | [
"Create",
"a",
"scatter",
"plot",
"for",
"all",
"diff",
"pairs"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L230-L305 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.get_spectrum | def get_spectrum(self, nr_id=None, abmn=None, plot_filename=None):
"""Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response... | python | def get_spectrum(self, nr_id=None, abmn=None, plot_filename=None):
"""Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response... | [
"def",
"get_spectrum",
"(",
"self",
",",
"nr_id",
"=",
"None",
",",
"abmn",
"=",
"None",
",",
"plot_filename",
"=",
"None",
")",
":",
"assert",
"nr_id",
"is",
"None",
"or",
"abmn",
"is",
"None",
"if",
"abmn",
"is",
"not",
"None",
":",
"subdata",
"=",... | Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response`
Normal spectrum. None if no normal spectrum is available
... | [
"Return",
"a",
"spectrum",
"and",
"its",
"reciprocal",
"counter",
"part",
"if",
"present",
"in",
"the",
"dataset",
".",
"Optimally",
"refer",
"to",
"the",
"spectrum",
"by",
"its",
"normal",
"-",
"reciprocal",
"id",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L357-L419 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.plot_all_spectra | def plot_all_spectra(self, outdir):
"""This is a convenience function to plot ALL spectra currently
stored in the container. It is useful to asses whether data filters
do perform correctly.
Note that the function just iterates over all ids and plots the
corresponding spectra, th... | python | def plot_all_spectra(self, outdir):
"""This is a convenience function to plot ALL spectra currently
stored in the container. It is useful to asses whether data filters
do perform correctly.
Note that the function just iterates over all ids and plots the
corresponding spectra, th... | [
"def",
"plot_all_spectra",
"(",
"self",
",",
"outdir",
")",
":",
"os",
".",
"makedirs",
"(",
"outdir",
",",
"exist_ok",
"=",
"True",
")",
"g",
"=",
"self",
".",
"data",
".",
"groupby",
"(",
"'id'",
")",
"for",
"nr",
",",
"(",
"name",
",",
"item",
... | This is a convenience function to plot ALL spectra currently
stored in the container. It is useful to asses whether data filters
do perform correctly.
Note that the function just iterates over all ids and plots the
corresponding spectra, thus it is slow.
Spectra a named using t... | [
"This",
"is",
"a",
"convenience",
"function",
"to",
"plot",
"ALL",
"spectra",
"currently",
"stored",
"in",
"the",
"container",
".",
"It",
"is",
"useful",
"to",
"asses",
"whether",
"data",
"filters",
"do",
"perform",
"correctly",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L421-L453 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.plot_pseudosections | def plot_pseudosections(self, column, filename=None, return_fig=False):
"""Create a multi-plot with one pseudosection for each frequency.
Parameters
----------
column : string
which column to plot
filename : None|string
output filename. If set to None, do... | python | def plot_pseudosections(self, column, filename=None, return_fig=False):
"""Create a multi-plot with one pseudosection for each frequency.
Parameters
----------
column : string
which column to plot
filename : None|string
output filename. If set to None, do... | [
"def",
"plot_pseudosections",
"(",
"self",
",",
"column",
",",
"filename",
"=",
"None",
",",
"return_fig",
"=",
"False",
")",
":",
"assert",
"column",
"in",
"self",
".",
"data",
".",
"columns",
"g",
"=",
"self",
".",
"data",
".",
"groupby",
"(",
"'freq... | Create a multi-plot with one pseudosection for each frequency.
Parameters
----------
column : string
which column to plot
filename : None|string
output filename. If set to None, do not write to file. Default:
None
return_fig : bool
... | [
"Create",
"a",
"multi",
"-",
"plot",
"with",
"one",
"pseudosection",
"for",
"each",
"frequency",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L455-L493 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.export_to_directory_crtomo | def export_to_directory_crtomo(self, directory, norrec='norrec'):
"""Export the sEIT data into data files that can be read by CRTomo.
Parameters
----------
directory : string
output directory. will be created if required
norrec : string (nor|rec|norrec)
W... | python | def export_to_directory_crtomo(self, directory, norrec='norrec'):
"""Export the sEIT data into data files that can be read by CRTomo.
Parameters
----------
directory : string
output directory. will be created if required
norrec : string (nor|rec|norrec)
W... | [
"def",
"export_to_directory_crtomo",
"(",
"self",
",",
"directory",
",",
"norrec",
"=",
"'norrec'",
")",
":",
"exporter_crtomo",
".",
"write_files_to_directory",
"(",
"self",
".",
"data",
",",
"directory",
",",
"norrec",
"=",
"norrec",
")"
] | Export the sEIT data into data files that can be read by CRTomo.
Parameters
----------
directory : string
output directory. will be created if required
norrec : string (nor|rec|norrec)
Which data to export. Default: norrec | [
"Export",
"the",
"sEIT",
"data",
"into",
"data",
"files",
"that",
"can",
"be",
"read",
"by",
"CRTomo",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L495-L508 | train |
geophysics-ubonn/reda | lib/reda/containers/sEIT.py | sEIT.export_to_crtomo_seit_manager | def export_to_crtomo_seit_manager(self, grid):
"""Return a ready-initialized seit-manager object from the CRTomo
tools. This function only works if the crtomo_tools are installed.
"""
import crtomo
g = self.data.groupby('frequency')
seit_data = {}
for name, item i... | python | def export_to_crtomo_seit_manager(self, grid):
"""Return a ready-initialized seit-manager object from the CRTomo
tools. This function only works if the crtomo_tools are installed.
"""
import crtomo
g = self.data.groupby('frequency')
seit_data = {}
for name, item i... | [
"def",
"export_to_crtomo_seit_manager",
"(",
"self",
",",
"grid",
")",
":",
"import",
"crtomo",
"g",
"=",
"self",
".",
"data",
".",
"groupby",
"(",
"'frequency'",
")",
"seit_data",
"=",
"{",
"}",
"for",
"name",
",",
"item",
"in",
"g",
":",
"print",
"("... | Return a ready-initialized seit-manager object from the CRTomo
tools. This function only works if the crtomo_tools are installed. | [
"Return",
"a",
"ready",
"-",
"initialized",
"seit",
"-",
"manager",
"object",
"from",
"the",
"CRTomo",
"tools",
".",
"This",
"function",
"only",
"works",
"if",
"the",
"crtomo_tools",
"are",
"installed",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/sEIT.py#L510-L524 | train |
joelbm24/brainy | lib/bfinter.py | Brainy.get_tape | def get_tape(self, start=0, end=10):
'''Pretty prints the tape values'''
self.tape_start = start
self.tape_end = end
self.tape_length = end - start
tmp = '\n'+"|"+str(start)+"| "
for i in xrange(len(self.tape[start:end])):
if i == self.cur_cell:
... | python | def get_tape(self, start=0, end=10):
'''Pretty prints the tape values'''
self.tape_start = start
self.tape_end = end
self.tape_length = end - start
tmp = '\n'+"|"+str(start)+"| "
for i in xrange(len(self.tape[start:end])):
if i == self.cur_cell:
... | [
"def",
"get_tape",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"10",
")",
":",
"self",
".",
"tape_start",
"=",
"start",
"self",
".",
"tape_end",
"=",
"end",
"self",
".",
"tape_length",
"=",
"end",
"-",
"start",
"tmp",
"=",
"'\\n'",
"+",
... | Pretty prints the tape values | [
"Pretty",
"prints",
"the",
"tape",
"values"
] | bc3e1d6e020f1bb884a9bbbda834dac3a7a7fdb4 | https://github.com/joelbm24/brainy/blob/bc3e1d6e020f1bb884a9bbbda834dac3a7a7fdb4/lib/bfinter.py#L79-L90 | train |
geophysics-ubonn/reda | lib/reda/containers/SIP.py | importers.import_sip04 | def import_sip04(self, filename, timestep=None):
"""SIP04 data import
Parameters
----------
filename: string
Path to .mat or .csv file containing SIP-04 measurement results
Examples
--------
::
import tempfile
import reda
... | python | def import_sip04(self, filename, timestep=None):
"""SIP04 data import
Parameters
----------
filename: string
Path to .mat or .csv file containing SIP-04 measurement results
Examples
--------
::
import tempfile
import reda
... | [
"def",
"import_sip04",
"(",
"self",
",",
"filename",
",",
"timestep",
"=",
"None",
")",
":",
"df",
"=",
"reda_sip04",
".",
"import_sip04_data",
"(",
"filename",
")",
"if",
"timestep",
"is",
"not",
"None",
":",
"print",
"(",
"'adding timestep'",
")",
"df",
... | SIP04 data import
Parameters
----------
filename: string
Path to .mat or .csv file containing SIP-04 measurement results
Examples
--------
::
import tempfile
import reda
with tempfile.TemporaryDirectory() as fid:
... | [
"SIP04",
"data",
"import"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/SIP.py#L26-L54 | train |
geophysics-ubonn/reda | lib/reda/containers/SIP.py | SIP.check_dataframe | def check_dataframe(self, dataframe):
"""Check the given dataframe for the required type and columns
"""
if dataframe is None:
return None
# is this a DataFrame
if not isinstance(dataframe, pd.DataFrame):
raise Exception(
'The provided dat... | python | def check_dataframe(self, dataframe):
"""Check the given dataframe for the required type and columns
"""
if dataframe is None:
return None
# is this a DataFrame
if not isinstance(dataframe, pd.DataFrame):
raise Exception(
'The provided dat... | [
"def",
"check_dataframe",
"(",
"self",
",",
"dataframe",
")",
":",
"if",
"dataframe",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"dataframe",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"Exception",
"(",
"'The provided dataframe... | Check the given dataframe for the required type and columns | [
"Check",
"the",
"given",
"dataframe",
"for",
"the",
"required",
"type",
"and",
"columns"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/SIP.py#L73-L90 | train |
geophysics-ubonn/reda | lib/reda/containers/SIP.py | SIP.reduce_duplicate_frequencies | def reduce_duplicate_frequencies(self):
"""In case multiple frequencies were measured, average them and compute
std, min, max values for zt.
In case timesteps were added (i.e., multiple separate measurements),
group over those and average for each timestep.
Examples
---... | python | def reduce_duplicate_frequencies(self):
"""In case multiple frequencies were measured, average them and compute
std, min, max values for zt.
In case timesteps were added (i.e., multiple separate measurements),
group over those and average for each timestep.
Examples
---... | [
"def",
"reduce_duplicate_frequencies",
"(",
"self",
")",
":",
"group_keys",
"=",
"[",
"'frequency'",
",",
"]",
"if",
"'timestep'",
"in",
"self",
".",
"data",
".",
"columns",
":",
"group_keys",
"=",
"group_keys",
"+",
"[",
"'timestep'",
",",
"]",
"g",
"=",
... | In case multiple frequencies were measured, average them and compute
std, min, max values for zt.
In case timesteps were added (i.e., multiple separate measurements),
group over those and average for each timestep.
Examples
--------
::
import tempfile
... | [
"In",
"case",
"multiple",
"frequencies",
"were",
"measured",
"average",
"them",
"and",
"compute",
"std",
"min",
"max",
"values",
"for",
"zt",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/containers/SIP.py#L92-L153 | train |
cloudbase/python-hnvclient | hnv/config/factory.py | _load_class | def _load_class(class_path):
"""Load the module and return the required class."""
parts = class_path.rsplit('.', 1)
module = __import__(parts[0], fromlist=parts[1])
return getattr(module, parts[1]) | python | def _load_class(class_path):
"""Load the module and return the required class."""
parts = class_path.rsplit('.', 1)
module = __import__(parts[0], fromlist=parts[1])
return getattr(module, parts[1]) | [
"def",
"_load_class",
"(",
"class_path",
")",
":",
"parts",
"=",
"class_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"__import__",
"(",
"parts",
"[",
"0",
"]",
",",
"fromlist",
"=",
"parts",
"[",
"1",
"]",
")",
"return",
"getattr",... | Load the module and return the required class. | [
"Load",
"the",
"module",
"and",
"return",
"the",
"required",
"class",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/config/factory.py#L22-L26 | train |
RobersonLab/motif_scraper | motif_scraper/__init__.py | rev_comp | def rev_comp( seq, molecule='dna' ):
""" DNA|RNA seq -> reverse complement
"""
if molecule == 'dna':
nuc_dict = { "A":"T", "B":"V", "C":"G", "D":"H", "G":"C", "H":"D", "K":"M", "M":"K", "N":"N", "R":"Y", "S":"S", "T":"A", "V":"B", "W":"W", "Y":"R" }
elif molecule == 'rna':
nuc_dict = { "A":"U", "B":"V", "C":"... | python | def rev_comp( seq, molecule='dna' ):
""" DNA|RNA seq -> reverse complement
"""
if molecule == 'dna':
nuc_dict = { "A":"T", "B":"V", "C":"G", "D":"H", "G":"C", "H":"D", "K":"M", "M":"K", "N":"N", "R":"Y", "S":"S", "T":"A", "V":"B", "W":"W", "Y":"R" }
elif molecule == 'rna':
nuc_dict = { "A":"U", "B":"V", "C":"... | [
"def",
"rev_comp",
"(",
"seq",
",",
"molecule",
"=",
"'dna'",
")",
":",
"if",
"molecule",
"==",
"'dna'",
":",
"nuc_dict",
"=",
"{",
"\"A\"",
":",
"\"T\"",
",",
"\"B\"",
":",
"\"V\"",
",",
"\"C\"",
":",
"\"G\"",
",",
"\"D\"",
":",
"\"H\"",
",",
"\"G... | DNA|RNA seq -> reverse complement | [
"DNA|RNA",
"seq",
"-",
">",
"reverse",
"complement"
] | 382dcb5932d9750282906c356ca35e802bd68bd0 | https://github.com/RobersonLab/motif_scraper/blob/382dcb5932d9750282906c356ca35e802bd68bd0/motif_scraper/__init__.py#L28-L42 | train |
miedzinski/google-oauth | google_oauth/service.py | ServiceAccount.from_json | def from_json(cls, key, scopes, subject=None):
"""Alternate constructor intended for using JSON format of private key.
Args:
key (dict) - Parsed JSON with service account credentials.
scopes (Union[str, collections.Iterable[str]]) -
List of permissions that the a... | python | def from_json(cls, key, scopes, subject=None):
"""Alternate constructor intended for using JSON format of private key.
Args:
key (dict) - Parsed JSON with service account credentials.
scopes (Union[str, collections.Iterable[str]]) -
List of permissions that the a... | [
"def",
"from_json",
"(",
"cls",
",",
"key",
",",
"scopes",
",",
"subject",
"=",
"None",
")",
":",
"credentials_type",
"=",
"key",
"[",
"'type'",
"]",
"if",
"credentials_type",
"!=",
"'service_account'",
":",
"raise",
"ValueError",
"(",
"'key: expected type ser... | Alternate constructor intended for using JSON format of private key.
Args:
key (dict) - Parsed JSON with service account credentials.
scopes (Union[str, collections.Iterable[str]]) -
List of permissions that the application requests.
subject (str) - The email... | [
"Alternate",
"constructor",
"intended",
"for",
"using",
"JSON",
"format",
"of",
"private",
"key",
"."
] | aef2e19d87281b1d8e42d6b158111e14e80128db | https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L75-L96 | train |
miedzinski/google-oauth | google_oauth/service.py | ServiceAccount.from_pkcs12 | def from_pkcs12(cls, key, email, scopes, subject=None,
passphrase=PKCS12_PASSPHRASE):
"""Alternate constructor intended for using .p12 files.
Args:
key (dict) - Parsed JSON with service account credentials.
email (str) - Service account email.
sco... | python | def from_pkcs12(cls, key, email, scopes, subject=None,
passphrase=PKCS12_PASSPHRASE):
"""Alternate constructor intended for using .p12 files.
Args:
key (dict) - Parsed JSON with service account credentials.
email (str) - Service account email.
sco... | [
"def",
"from_pkcs12",
"(",
"cls",
",",
"key",
",",
"email",
",",
"scopes",
",",
"subject",
"=",
"None",
",",
"passphrase",
"=",
"PKCS12_PASSPHRASE",
")",
":",
"key",
"=",
"OpenSSL",
".",
"crypto",
".",
"load_pkcs12",
"(",
"key",
",",
"passphrase",
")",
... | Alternate constructor intended for using .p12 files.
Args:
key (dict) - Parsed JSON with service account credentials.
email (str) - Service account email.
scopes (Union[str, collections.Iterable[str]]) -
List of permissions that the application requests.
... | [
"Alternate",
"constructor",
"intended",
"for",
"using",
".",
"p12",
"files",
"."
] | aef2e19d87281b1d8e42d6b158111e14e80128db | https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L99-L119 | train |
miedzinski/google-oauth | google_oauth/service.py | ServiceAccount.issued_at | def issued_at(self):
"""Time when access token was requested, as seconds since epoch.
Note:
Accessing this property when there wasn't any request attempts
will return current time.
Returns:
int
"""
issued_at = self._issued_at
if issue... | python | def issued_at(self):
"""Time when access token was requested, as seconds since epoch.
Note:
Accessing this property when there wasn't any request attempts
will return current time.
Returns:
int
"""
issued_at = self._issued_at
if issue... | [
"def",
"issued_at",
"(",
"self",
")",
":",
"issued_at",
"=",
"self",
".",
"_issued_at",
"if",
"issued_at",
"is",
"None",
":",
"self",
".",
"_issued_at",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"return",
"self",
".",
"_issued_at"
] | Time when access token was requested, as seconds since epoch.
Note:
Accessing this property when there wasn't any request attempts
will return current time.
Returns:
int | [
"Time",
"when",
"access",
"token",
"was",
"requested",
"as",
"seconds",
"since",
"epoch",
"."
] | aef2e19d87281b1d8e42d6b158111e14e80128db | https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L181-L194 | train |
miedzinski/google-oauth | google_oauth/service.py | ServiceAccount.access_token | def access_token(self):
"""Stores always valid OAuth2 access token.
Note:
Accessing this property may result in HTTP request.
Returns:
str
"""
if (self._access_token is None or
self.expiration_time <= int(time.time())):
resp =... | python | def access_token(self):
"""Stores always valid OAuth2 access token.
Note:
Accessing this property may result in HTTP request.
Returns:
str
"""
if (self._access_token is None or
self.expiration_time <= int(time.time())):
resp =... | [
"def",
"access_token",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_access_token",
"is",
"None",
"or",
"self",
".",
"expiration_time",
"<=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
":",
"resp",
"=",
"self",
".",
"make_access_request",
... | Stores always valid OAuth2 access token.
Note:
Accessing this property may result in HTTP request.
Returns:
str | [
"Stores",
"always",
"valid",
"OAuth2",
"access",
"token",
"."
] | aef2e19d87281b1d8e42d6b158111e14e80128db | https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L214-L228 | train |
miedzinski/google-oauth | google_oauth/service.py | ServiceAccount.make_access_request | def make_access_request(self):
"""Makes an OAuth2 access token request with crafted JWT and signature.
The core of this module. Based on arguments it creates proper JWT
for you and signs it with supplied private key.
Regardless of present valid token, it always clears
``issued_a... | python | def make_access_request(self):
"""Makes an OAuth2 access token request with crafted JWT and signature.
The core of this module. Based on arguments it creates proper JWT
for you and signs it with supplied private key.
Regardless of present valid token, it always clears
``issued_a... | [
"def",
"make_access_request",
"(",
"self",
")",
":",
"del",
"self",
".",
"issued_at",
"assertion",
"=",
"b'.'",
".",
"join",
"(",
"(",
"self",
".",
"header",
"(",
")",
",",
"self",
".",
"claims",
"(",
")",
",",
"self",
".",
"signature",
"(",
")",
"... | Makes an OAuth2 access token request with crafted JWT and signature.
The core of this module. Based on arguments it creates proper JWT
for you and signs it with supplied private key.
Regardless of present valid token, it always clears
``issued_at`` property, which in turn results in req... | [
"Makes",
"an",
"OAuth2",
"access",
"token",
"request",
"with",
"crafted",
"JWT",
"and",
"signature",
"."
] | aef2e19d87281b1d8e42d6b158111e14e80128db | https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L259-L290 | train |
miedzinski/google-oauth | google_oauth/service.py | ServiceAccount.authorized_request | def authorized_request(self, method, url, **kwargs):
"""Shortcut for requests.request with proper Authorization header.
Note:
If you put auth keyword argument or Authorization in headers
keyword argument, this will raise an exception.
Decide what you want to do!
... | python | def authorized_request(self, method, url, **kwargs):
"""Shortcut for requests.request with proper Authorization header.
Note:
If you put auth keyword argument or Authorization in headers
keyword argument, this will raise an exception.
Decide what you want to do!
... | [
"def",
"authorized_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"**",
"kwargs",
")",
":",
"headers",
"=",
"kwargs",
".",
"pop",
"(",
"'headers'",
",",
"{",
"}",
")",
"if",
"headers",
".",
"get",
"(",
"'Authorization'",
")",
"or",
"kwargs",
... | Shortcut for requests.request with proper Authorization header.
Note:
If you put auth keyword argument or Authorization in headers
keyword argument, this will raise an exception.
Decide what you want to do!
Args:
method (str) - HTTP method of this reques... | [
"Shortcut",
"for",
"requests",
".",
"request",
"with",
"proper",
"Authorization",
"header",
"."
] | aef2e19d87281b1d8e42d6b158111e14e80128db | https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L292-L321 | train |
geophysics-ubonn/reda | lib/reda/importers/iris_syscal_pro.py | import_txt | def import_txt(filename, **kwargs):
"""Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as... | python | def import_txt(filename, **kwargs):
"""Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as... | [
"def",
"import_txt",
"(",
"filename",
",",
"**",
"kwargs",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fid",
":",
"text",
"=",
"fid",
".",
"read",
"(",
")",
"strings_to_replace",
"=",
"{",
"'Mixed / non conventional'",
":",
"'Mixed... | Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as the first electrode.
spacing: float
... | [
"Import",
"Syscal",
"measurements",
"from",
"a",
"text",
"file",
"exported",
"as",
"Spreadsheet",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/iris_syscal_pro.py#L80-L156 | train |
geophysics-ubonn/reda | lib/reda/importers/iris_syscal_pro.py | import_bin | def import_bin(filename, **kwargs):
"""Read a .bin file generated by the IRIS Instruments Syscal Pro System and
return a curated dataframe for further processing. This dataframe contains
only information currently deemed important. Use the function
reda.importers.iris_syscal_pro_binary._import_bin to ex... | python | def import_bin(filename, **kwargs):
"""Read a .bin file generated by the IRIS Instruments Syscal Pro System and
return a curated dataframe for further processing. This dataframe contains
only information currently deemed important. Use the function
reda.importers.iris_syscal_pro_binary._import_bin to ex... | [
"def",
"import_bin",
"(",
"filename",
",",
"**",
"kwargs",
")",
":",
"metadata",
",",
"data_raw",
"=",
"_import_bin",
"(",
"filename",
")",
"skip_rows",
"=",
"kwargs",
".",
"get",
"(",
"'skip_rows'",
",",
"0",
")",
"if",
"skip_rows",
">",
"0",
":",
"da... | Read a .bin file generated by the IRIS Instruments Syscal Pro System and
return a curated dataframe for further processing. This dataframe contains
only information currently deemed important. Use the function
reda.importers.iris_syscal_pro_binary._import_bin to extract ALL
information from a given .bin... | [
"Read",
"a",
".",
"bin",
"file",
"generated",
"by",
"the",
"IRIS",
"Instruments",
"Syscal",
"Pro",
"System",
"and",
"return",
"a",
"curated",
"dataframe",
"for",
"further",
"processing",
".",
"This",
"dataframe",
"contains",
"only",
"information",
"currently",
... | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/iris_syscal_pro.py#L160-L266 | train |
lambdalisue/notify | src/notify/notifier.py | call_and_notificate | def call_and_notificate(args, opts):
"""
Execute specified arguments and send notification email
Parameters
----------
args : list
A execution command/arguments list
opts : object
A option instance
"""
# store starttime
stctime = time.clock()
stttime = time.time(... | python | def call_and_notificate(args, opts):
"""
Execute specified arguments and send notification email
Parameters
----------
args : list
A execution command/arguments list
opts : object
A option instance
"""
# store starttime
stctime = time.clock()
stttime = time.time(... | [
"def",
"call_and_notificate",
"(",
"args",
",",
"opts",
")",
":",
"stctime",
"=",
"time",
".",
"clock",
"(",
")",
"stttime",
"=",
"time",
".",
"time",
"(",
")",
"stdtime",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"exit_code",
",",
"out... | Execute specified arguments and send notification email
Parameters
----------
args : list
A execution command/arguments list
opts : object
A option instance | [
"Execute",
"specified",
"arguments",
"and",
"send",
"notification",
"email"
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/notifier.py#L28-L78 | train |
gtaylor/django-athumb | athumb/fields.py | ImageWithThumbsFieldFile.get_thumbnail_format | def get_thumbnail_format(self):
"""
Determines the target thumbnail type either by looking for a format
override specified at the model level, or by using the format the
user uploaded.
"""
if self.field.thumbnail_format:
# Over-ride was given, use that instead... | python | def get_thumbnail_format(self):
"""
Determines the target thumbnail type either by looking for a format
override specified at the model level, or by using the format the
user uploaded.
"""
if self.field.thumbnail_format:
# Over-ride was given, use that instead... | [
"def",
"get_thumbnail_format",
"(",
"self",
")",
":",
"if",
"self",
".",
"field",
".",
"thumbnail_format",
":",
"return",
"self",
".",
"field",
".",
"thumbnail_format",
".",
"lower",
"(",
")",
"else",
":",
"filename_split",
"=",
"self",
".",
"name",
".",
... | Determines the target thumbnail type either by looking for a format
override specified at the model level, or by using the format the
user uploaded. | [
"Determines",
"the",
"target",
"thumbnail",
"type",
"either",
"by",
"looking",
"for",
"a",
"format",
"override",
"specified",
"at",
"the",
"model",
"level",
"or",
"by",
"using",
"the",
"format",
"the",
"user",
"uploaded",
"."
] | 69261ace0dff81e33156a54440874456a7b38dfb | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/fields.py#L94-L106 | train |
gtaylor/django-athumb | athumb/fields.py | ImageWithThumbsFieldFile.save | def save(self, name, content, save=True):
"""
Handles some extra logic to generate the thumbnails when the original
file is uploaded.
"""
super(ImageWithThumbsFieldFile, self).save(name, content, save)
try:
self.generate_thumbs(name, content)
except IO... | python | def save(self, name, content, save=True):
"""
Handles some extra logic to generate the thumbnails when the original
file is uploaded.
"""
super(ImageWithThumbsFieldFile, self).save(name, content, save)
try:
self.generate_thumbs(name, content)
except IO... | [
"def",
"save",
"(",
"self",
",",
"name",
",",
"content",
",",
"save",
"=",
"True",
")",
":",
"super",
"(",
"ImageWithThumbsFieldFile",
",",
"self",
")",
".",
"save",
"(",
"name",
",",
"content",
",",
"save",
")",
"try",
":",
"self",
".",
"generate_th... | Handles some extra logic to generate the thumbnails when the original
file is uploaded. | [
"Handles",
"some",
"extra",
"logic",
"to",
"generate",
"the",
"thumbnails",
"when",
"the",
"original",
"file",
"is",
"uploaded",
"."
] | 69261ace0dff81e33156a54440874456a7b38dfb | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/fields.py#L108-L124 | train |
gtaylor/django-athumb | athumb/fields.py | ImageWithThumbsFieldFile.delete | def delete(self, save=True):
"""
Deletes the original, plus any thumbnails. Fails silently if there
are errors deleting the thumbnails.
"""
for thumb in self.field.thumbs:
thumb_name, thumb_options = thumb
thumb_filename = self._calc_thumb_filename(thumb_n... | python | def delete(self, save=True):
"""
Deletes the original, plus any thumbnails. Fails silently if there
are errors deleting the thumbnails.
"""
for thumb in self.field.thumbs:
thumb_name, thumb_options = thumb
thumb_filename = self._calc_thumb_filename(thumb_n... | [
"def",
"delete",
"(",
"self",
",",
"save",
"=",
"True",
")",
":",
"for",
"thumb",
"in",
"self",
".",
"field",
".",
"thumbs",
":",
"thumb_name",
",",
"thumb_options",
"=",
"thumb",
"thumb_filename",
"=",
"self",
".",
"_calc_thumb_filename",
"(",
"thumb_name... | Deletes the original, plus any thumbnails. Fails silently if there
are errors deleting the thumbnails. | [
"Deletes",
"the",
"original",
"plus",
"any",
"thumbnails",
".",
"Fails",
"silently",
"if",
"there",
"are",
"errors",
"deleting",
"the",
"thumbnails",
"."
] | 69261ace0dff81e33156a54440874456a7b38dfb | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/fields.py#L197-L207 | train |
tony-landis/datomic-py | datomic/datomic.py | dump_edn_val | def dump_edn_val(v):
" edn simple value dump"
if isinstance(v, (str, unicode)):
return json.dumps(v)
elif isinstance(v, E):
return unicode(v)
else:
return dumps(v) | python | def dump_edn_val(v):
" edn simple value dump"
if isinstance(v, (str, unicode)):
return json.dumps(v)
elif isinstance(v, E):
return unicode(v)
else:
return dumps(v) | [
"def",
"dump_edn_val",
"(",
"v",
")",
":",
"\" edn simple value dump\"",
"if",
"isinstance",
"(",
"v",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"v",
")",
"elif",
"isinstance",
"(",
"v",
",",
"E",
")",
":",
... | edn simple value dump | [
"edn",
"simple",
"value",
"dump"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L644-L651 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.tx_schema | def tx_schema(self, **kwargs):
""" Builds the data structure edn, and puts it in the db
"""
for s in self.schema.schema:
tx = self.tx(s, **kwargs) | python | def tx_schema(self, **kwargs):
""" Builds the data structure edn, and puts it in the db
"""
for s in self.schema.schema:
tx = self.tx(s, **kwargs) | [
"def",
"tx_schema",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"for",
"s",
"in",
"self",
".",
"schema",
".",
"schema",
":",
"tx",
"=",
"self",
".",
"tx",
"(",
"s",
",",
"**",
"kwargs",
")"
] | Builds the data structure edn, and puts it in the db | [
"Builds",
"the",
"data",
"structure",
"edn",
"and",
"puts",
"it",
"in",
"the",
"db"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L67-L71 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.tx | def tx(self, *args, **kwargs):
""" Executes a raw tx string, or get a new TX object to work with.
Passing a raw string or list of strings will immedately transact
and return the API response as a dict.
>>> resp = tx('{:db/id #db/id[:db.part/user] :person/name "Bob"}')
{db-before: db-after: tempids... | python | def tx(self, *args, **kwargs):
""" Executes a raw tx string, or get a new TX object to work with.
Passing a raw string or list of strings will immedately transact
and return the API response as a dict.
>>> resp = tx('{:db/id #db/id[:db.part/user] :person/name "Bob"}')
{db-before: db-after: tempids... | [
"def",
"tx",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"0",
"==",
"len",
"(",
"args",
")",
":",
"return",
"TX",
"(",
"self",
")",
"ops",
"=",
"[",
"]",
"for",
"op",
"in",
"args",
":",
"if",
"isinstance",
"(",
"op",
... | Executes a raw tx string, or get a new TX object to work with.
Passing a raw string or list of strings will immedately transact
and return the API response as a dict.
>>> resp = tx('{:db/id #db/id[:db.part/user] :person/name "Bob"}')
{db-before: db-after: tempids: }
This gets a fresh `TX()` to pr... | [
"Executes",
"a",
"raw",
"tx",
"string",
"or",
"get",
"a",
"new",
"TX",
"object",
"to",
"work",
"with",
"."
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L73-L118 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.e | def e(self, eid):
"""Get an Entity
"""
ta = datetime.datetime.now()
rs = self.rest('GET', self.uri_db + '-/entity', data={'e':int(eid)}, parse=True)
tb = datetime.datetime.now() - ta
print cl('<<< fetched entity %s in %sms' % (eid, tb.microseconds/1000.0), 'cyan')
return rs | python | def e(self, eid):
"""Get an Entity
"""
ta = datetime.datetime.now()
rs = self.rest('GET', self.uri_db + '-/entity', data={'e':int(eid)}, parse=True)
tb = datetime.datetime.now() - ta
print cl('<<< fetched entity %s in %sms' % (eid, tb.microseconds/1000.0), 'cyan')
return rs | [
"def",
"e",
"(",
"self",
",",
"eid",
")",
":",
"ta",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"rs",
"=",
"self",
".",
"rest",
"(",
"'GET'",
",",
"self",
".",
"uri_db",
"+",
"'-/entity'",
",",
"data",
"=",
"{",
"'e'",
":",
"int",
... | Get an Entity | [
"Get",
"an",
"Entity"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L120-L127 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.retract | def retract(self, e, a, v):
""" redact the value of an attribute
"""
ta = datetime.datetime.now()
ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v))
rs = self.tx(ret)
tb = datetime.datetime.now() - ta
print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan'... | python | def retract(self, e, a, v):
""" redact the value of an attribute
"""
ta = datetime.datetime.now()
ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v))
rs = self.tx(ret)
tb = datetime.datetime.now() - ta
print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan'... | [
"def",
"retract",
"(",
"self",
",",
"e",
",",
"a",
",",
"v",
")",
":",
"ta",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"ret",
"=",
"u\"[:db/retract %i :%s %s]\"",
"%",
"(",
"e",
",",
"a",
",",
"dump_edn_val",
"(",
"v",
")",
")",
"rs... | redact the value of an attribute | [
"redact",
"the",
"value",
"of",
"an",
"attribute"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L129-L137 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.datoms | def datoms(self, index='aevt', e='', a='', v='',
limit=0, offset=0, chunk=100,
start='', end='', since='', as_of='', history='', **kwargs):
""" Returns a lazy generator that will only fetch groups of datoms
at the chunk size specified.
http://docs.datomic.com/clo... | python | def datoms(self, index='aevt', e='', a='', v='',
limit=0, offset=0, chunk=100,
start='', end='', since='', as_of='', history='', **kwargs):
""" Returns a lazy generator that will only fetch groups of datoms
at the chunk size specified.
http://docs.datomic.com/clo... | [
"def",
"datoms",
"(",
"self",
",",
"index",
"=",
"'aevt'",
",",
"e",
"=",
"''",
",",
"a",
"=",
"''",
",",
"v",
"=",
"''",
",",
"limit",
"=",
"0",
",",
"offset",
"=",
"0",
",",
"chunk",
"=",
"100",
",",
"start",
"=",
"''",
",",
"end",
"=",
... | Returns a lazy generator that will only fetch groups of datoms
at the chunk size specified.
http://docs.datomic.com/clojure/index.html#datomic.api/datoms | [
"Returns",
"a",
"lazy",
"generator",
"that",
"will",
"only",
"fetch",
"groups",
"of",
"datoms",
"at",
"the",
"chunk",
"size",
"specified",
"."
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L140-L172 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.debug | def debug(self, defn, args, kwargs, fmt=None, color='green'):
""" debug timing, colored terminal output
"""
ta = datetime.datetime.now()
rs = defn(*args, **kwargs)
tb = datetime.datetime.now() - ta
fmt = fmt or "processed {defn} in {ms}ms"
logmsg = fmt.format(ms=tb.microseconds/1000.0, def... | python | def debug(self, defn, args, kwargs, fmt=None, color='green'):
""" debug timing, colored terminal output
"""
ta = datetime.datetime.now()
rs = defn(*args, **kwargs)
tb = datetime.datetime.now() - ta
fmt = fmt or "processed {defn} in {ms}ms"
logmsg = fmt.format(ms=tb.microseconds/1000.0, def... | [
"def",
"debug",
"(",
"self",
",",
"defn",
",",
"args",
",",
"kwargs",
",",
"fmt",
"=",
"None",
",",
"color",
"=",
"'green'",
")",
":",
"ta",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"rs",
"=",
"defn",
"(",
"*",
"args",
",",
"**",... | debug timing, colored terminal output | [
"debug",
"timing",
"colored",
"terminal",
"output"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L193-L205 | train |
tony-landis/datomic-py | datomic/datomic.py | DB.find | def find(self, *args, **kwargs):
" new query builder on current db"
return Query(*args, db=self, schema=self.schema) | python | def find(self, *args, **kwargs):
" new query builder on current db"
return Query(*args, db=self, schema=self.schema) | [
"def",
"find",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"\" new query builder on current db\"",
"return",
"Query",
"(",
"*",
"args",
",",
"db",
"=",
"self",
",",
"schema",
"=",
"self",
".",
"schema",
")"
] | new query builder on current db | [
"new",
"query",
"builder",
"on",
"current",
"db"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L223-L225 | train |
tony-landis/datomic-py | datomic/datomic.py | Query.hashone | def hashone(self):
"execute query, get back"
rs = self.one()
if not rs:
return {}
else:
finds = " ".join(self._find).split(' ')
return dict(zip((x.replace('?','') for x in finds), rs)) | python | def hashone(self):
"execute query, get back"
rs = self.one()
if not rs:
return {}
else:
finds = " ".join(self._find).split(' ')
return dict(zip((x.replace('?','') for x in finds), rs)) | [
"def",
"hashone",
"(",
"self",
")",
":",
"\"execute query, get back\"",
"rs",
"=",
"self",
".",
"one",
"(",
")",
"if",
"not",
"rs",
":",
"return",
"{",
"}",
"else",
":",
"finds",
"=",
"\" \"",
".",
"join",
"(",
"self",
".",
"_find",
")",
".",
"spli... | execute query, get back | [
"execute",
"query",
"get",
"back"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L302-L309 | train |
tony-landis/datomic-py | datomic/datomic.py | Query.all | def all(self):
" execute query, get all list of lists"
query,inputs = self._toedn()
return self.db.q(query,
inputs = inputs,
limit = self._limit,
offset = self._offset,
history = self._history) | python | def all(self):
" execute query, get all list of lists"
query,inputs = self._toedn()
return self.db.q(query,
inputs = inputs,
limit = self._limit,
offset = self._offset,
history = self._history) | [
"def",
"all",
"(",
"self",
")",
":",
"\" execute query, get all list of lists\"",
"query",
",",
"inputs",
"=",
"self",
".",
"_toedn",
"(",
")",
"return",
"self",
".",
"db",
".",
"q",
"(",
"query",
",",
"inputs",
"=",
"inputs",
",",
"limit",
"=",
"self",
... | execute query, get all list of lists | [
"execute",
"query",
"get",
"all",
"list",
"of",
"lists"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L320-L327 | train |
tony-landis/datomic-py | datomic/datomic.py | Query._toedn | def _toedn(self):
""" prepare the query for the rest api
"""
finds = u""
inputs = u""
wheres = u""
args = []
": in and args"
for a,b in self._input:
inputs += " {0}".format(a)
args.append(dump_edn_val(b))
if inputs:
inputs = u":in ${0}".format(inputs)
" :wher... | python | def _toedn(self):
""" prepare the query for the rest api
"""
finds = u""
inputs = u""
wheres = u""
args = []
": in and args"
for a,b in self._input:
inputs += " {0}".format(a)
args.append(dump_edn_val(b))
if inputs:
inputs = u":in ${0}".format(inputs)
" :wher... | [
"def",
"_toedn",
"(",
"self",
")",
":",
"finds",
"=",
"u\"\"",
"inputs",
"=",
"u\"\"",
"wheres",
"=",
"u\"\"",
"args",
"=",
"[",
"]",
"\": in and args\"",
"for",
"a",
",",
"b",
"in",
"self",
".",
"_input",
":",
"inputs",
"+=",
"\" {0}\"",
".",
"forma... | prepare the query for the rest api | [
"prepare",
"the",
"query",
"for",
"the",
"rest",
"api"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L329-L359 | train |
tony-landis/datomic-py | datomic/datomic.py | TX.add | def add(self, *args, **kwargs):
""" Accumulate datums for the transaction
Start a transaction on an existing db connection
>>> tx = TX(db)
Get get an entity object with a tempid
>>> ref = add()
>>> ref = add(0)
>>> ref = add(None)
>>> ref = add(False)
Entity id passed as first arg... | python | def add(self, *args, **kwargs):
""" Accumulate datums for the transaction
Start a transaction on an existing db connection
>>> tx = TX(db)
Get get an entity object with a tempid
>>> ref = add()
>>> ref = add(0)
>>> ref = add(None)
>>> ref = add(False)
Entity id passed as first arg... | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"assert",
"self",
".",
"resp",
"is",
"None",
",",
"\"Transaction already committed\"",
"entity",
",",
"av_pairs",
",",
"args",
"=",
"None",
",",
"[",
"]",
",",
"list",
"(",
"... | Accumulate datums for the transaction
Start a transaction on an existing db connection
>>> tx = TX(db)
Get get an entity object with a tempid
>>> ref = add()
>>> ref = add(0)
>>> ref = add(None)
>>> ref = add(False)
Entity id passed as first argument (int|long)
>>> tx.add(1, 'thin... | [
"Accumulate",
"datums",
"for",
"the",
"transaction"
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L515-L594 | train |
tony-landis/datomic-py | datomic/datomic.py | TX.resolve | def resolve(self):
""" Resolve one or more tempids.
Automatically takes place after transaction is executed.
"""
assert isinstance(self.resp, dict), "Transaction in uncommitted or failed state"
rids = [(v) for k,v in self.resp['tempids'].items()]
self.txid = self.resp['tx-data'][0]['tx']
ri... | python | def resolve(self):
""" Resolve one or more tempids.
Automatically takes place after transaction is executed.
"""
assert isinstance(self.resp, dict), "Transaction in uncommitted or failed state"
rids = [(v) for k,v in self.resp['tempids'].items()]
self.txid = self.resp['tx-data'][0]['tx']
ri... | [
"def",
"resolve",
"(",
"self",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"resp",
",",
"dict",
")",
",",
"\"Transaction in uncommitted or failed state\"",
"rids",
"=",
"[",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"resp",
"[",
"... | Resolve one or more tempids.
Automatically takes place after transaction is executed. | [
"Resolve",
"one",
"or",
"more",
"tempids",
".",
"Automatically",
"takes",
"place",
"after",
"transaction",
"is",
"executed",
"."
] | 54f713d29ad85ba86d53d5115c9b312ff14b7846 | https://github.com/tony-landis/datomic-py/blob/54f713d29ad85ba86d53d5115c9b312ff14b7846/datomic/datomic.py#L611-L623 | train |
pennlabs/penn-sdk-python | penn/fitness.py | Fitness.get_usage | def get_usage(self):
"""Get fitness locations and their current usage."""
resp = requests.get(FITNESS_URL, timeout=30)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html5lib")
eastern = pytz.timezone('US/Eastern')
output = []
for item in soup.findAll(... | python | def get_usage(self):
"""Get fitness locations and their current usage."""
resp = requests.get(FITNESS_URL, timeout=30)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html5lib")
eastern = pytz.timezone('US/Eastern')
output = []
for item in soup.findAll(... | [
"def",
"get_usage",
"(",
"self",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"FITNESS_URL",
",",
"timeout",
"=",
"30",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"resp",
".",
"text",
",",
"\"html5lib\"",
... | Get fitness locations and their current usage. | [
"Get",
"fitness",
"locations",
"and",
"their",
"current",
"usage",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/fitness.py#L49-L69 | train |
pennlabs/penn-sdk-python | penn/map.py | Map.search | def search(self, keyword):
"""Return all buildings related to the provided query.
:param keyword:
The keyword for your map search
>>> results = n.search('Harrison')
"""
params = {
"source": "map",
"description": keyword
}
data... | python | def search(self, keyword):
"""Return all buildings related to the provided query.
:param keyword:
The keyword for your map search
>>> results = n.search('Harrison')
"""
params = {
"source": "map",
"description": keyword
}
data... | [
"def",
"search",
"(",
"self",
",",
"keyword",
")",
":",
"params",
"=",
"{",
"\"source\"",
":",
"\"map\"",
",",
"\"description\"",
":",
"keyword",
"}",
"data",
"=",
"self",
".",
"_request",
"(",
"ENDPOINTS",
"[",
"'SEARCH'",
"]",
",",
"params",
")",
"da... | Return all buildings related to the provided query.
:param keyword:
The keyword for your map search
>>> results = n.search('Harrison') | [
"Return",
"all",
"buildings",
"related",
"to",
"the",
"provided",
"query",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/map.py#L21-L35 | train |
geophysics-ubonn/reda | lib/reda/utils/geometric_factors.py | compute_K_numerical | def compute_K_numerical(dataframe, settings=None, keep_dir=None):
"""Use a finite-element modeling code to infer geometric factors for meshes
with topography or irregular electrode spacings.
Parameters
----------
dataframe : pandas.DataFrame
the data frame that contains the data
setting... | python | def compute_K_numerical(dataframe, settings=None, keep_dir=None):
"""Use a finite-element modeling code to infer geometric factors for meshes
with topography or irregular electrode spacings.
Parameters
----------
dataframe : pandas.DataFrame
the data frame that contains the data
setting... | [
"def",
"compute_K_numerical",
"(",
"dataframe",
",",
"settings",
"=",
"None",
",",
"keep_dir",
"=",
"None",
")",
":",
"inversion_code",
"=",
"reda",
".",
"rcParams",
".",
"get",
"(",
"'geom_factor.inversion_code'",
",",
"'crtomo'",
")",
"if",
"inversion_code",
... | Use a finite-element modeling code to infer geometric factors for meshes
with topography or irregular electrode spacings.
Parameters
----------
dataframe : pandas.DataFrame
the data frame that contains the data
settings : dict
The settings required to compute the geometric factors. ... | [
"Use",
"a",
"finite",
"-",
"element",
"modeling",
"code",
"to",
"infer",
"geometric",
"factors",
"for",
"meshes",
"with",
"topography",
"or",
"irregular",
"electrode",
"spacings",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/geometric_factors.py#L29-L74 | train |
fuzeman/PyUPnP | pyupnp/lict.py | Lict._get_object_key | def _get_object_key(self, p_object):
"""Get key from object"""
matched_key = None
matched_index = None
if hasattr(p_object, self._searchNames[0]):
return getattr(p_object, self._searchNames[0])
for x in xrange(len(self._searchNames)):
key = self._searchN... | python | def _get_object_key(self, p_object):
"""Get key from object"""
matched_key = None
matched_index = None
if hasattr(p_object, self._searchNames[0]):
return getattr(p_object, self._searchNames[0])
for x in xrange(len(self._searchNames)):
key = self._searchN... | [
"def",
"_get_object_key",
"(",
"self",
",",
"p_object",
")",
":",
"matched_key",
"=",
"None",
"matched_index",
"=",
"None",
"if",
"hasattr",
"(",
"p_object",
",",
"self",
".",
"_searchNames",
"[",
"0",
"]",
")",
":",
"return",
"getattr",
"(",
"p_object",
... | Get key from object | [
"Get",
"key",
"from",
"object"
] | 6dea64be299952346a14300ab6cc7dac42736433 | https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/lict.py#L52-L72 | train |
south-coast-science/scs_core | src/scs_core/gas/pid_temp_comp.py | PIDTempComp.correct | def correct(self, temp, we_t):
"""
Compute weC from weT
"""
if not PIDTempComp.in_range(temp):
return None
n_t = self.cf_t(temp)
if n_t is None:
return None
we_c = we_t * n_t
return we_c | python | def correct(self, temp, we_t):
"""
Compute weC from weT
"""
if not PIDTempComp.in_range(temp):
return None
n_t = self.cf_t(temp)
if n_t is None:
return None
we_c = we_t * n_t
return we_c | [
"def",
"correct",
"(",
"self",
",",
"temp",
",",
"we_t",
")",
":",
"if",
"not",
"PIDTempComp",
".",
"in_range",
"(",
"temp",
")",
":",
"return",
"None",
"n_t",
"=",
"self",
".",
"cf_t",
"(",
"temp",
")",
"if",
"n_t",
"is",
"None",
":",
"return",
... | Compute weC from weT | [
"Compute",
"weC",
"from",
"weT"
] | a4152b0bbed6acbbf257e1bba6a912f6ebe578e5 | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_temp_comp.py#L66-L80 | train |
geophysics-ubonn/reda | lib/reda/utils/norrec.py | compute_norrec_differences | def compute_norrec_differences(df, keys_diff):
"""DO NOT USE ANY MORE - DEPRECIATED!
"""
raise Exception('This function is depreciated!')
print('computing normal-reciprocal differences')
# df.sort_index(level='norrec')
def norrec_diff(x):
"""compute norrec_diff"""
if x.shape[0]... | python | def compute_norrec_differences(df, keys_diff):
"""DO NOT USE ANY MORE - DEPRECIATED!
"""
raise Exception('This function is depreciated!')
print('computing normal-reciprocal differences')
# df.sort_index(level='norrec')
def norrec_diff(x):
"""compute norrec_diff"""
if x.shape[0]... | [
"def",
"compute_norrec_differences",
"(",
"df",
",",
"keys_diff",
")",
":",
"raise",
"Exception",
"(",
"'This function is depreciated!'",
")",
"print",
"(",
"'computing normal-reciprocal differences'",
")",
"def",
"norrec_diff",
"(",
"x",
")",
":",
"if",
"x",
".",
... | DO NOT USE ANY MORE - DEPRECIATED! | [
"DO",
"NOT",
"USE",
"ANY",
"MORE",
"-",
"DEPRECIATED!"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/norrec.py#L48-L75 | train |
geophysics-ubonn/reda | lib/reda/utils/norrec.py | _normalize_abmn | def _normalize_abmn(abmn):
"""return a normalized version of abmn
"""
abmn_2d = np.atleast_2d(abmn)
abmn_normalized = np.hstack((
np.sort(abmn_2d[:, 0:2], axis=1),
np.sort(abmn_2d[:, 2:4], axis=1),
))
return abmn_normalized | python | def _normalize_abmn(abmn):
"""return a normalized version of abmn
"""
abmn_2d = np.atleast_2d(abmn)
abmn_normalized = np.hstack((
np.sort(abmn_2d[:, 0:2], axis=1),
np.sort(abmn_2d[:, 2:4], axis=1),
))
return abmn_normalized | [
"def",
"_normalize_abmn",
"(",
"abmn",
")",
":",
"abmn_2d",
"=",
"np",
".",
"atleast_2d",
"(",
"abmn",
")",
"abmn_normalized",
"=",
"np",
".",
"hstack",
"(",
"(",
"np",
".",
"sort",
"(",
"abmn_2d",
"[",
":",
",",
"0",
":",
"2",
"]",
",",
"axis",
... | return a normalized version of abmn | [
"return",
"a",
"normalized",
"version",
"of",
"abmn"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/norrec.py#L78-L86 | train |
geophysics-ubonn/reda | lib/reda/utils/norrec.py | assign_norrec_diffs | def assign_norrec_diffs(df, diff_list):
"""Compute and write the difference between normal and reciprocal values
for all columns specified in the diff_list parameter.
Note that the DataFrame is directly written to. That is, it is changed
during the call of this function. No need to use the returned obj... | python | def assign_norrec_diffs(df, diff_list):
"""Compute and write the difference between normal and reciprocal values
for all columns specified in the diff_list parameter.
Note that the DataFrame is directly written to. That is, it is changed
during the call of this function. No need to use the returned obj... | [
"def",
"assign_norrec_diffs",
"(",
"df",
",",
"diff_list",
")",
":",
"extra_dims",
"=",
"[",
"x",
"for",
"x",
"in",
"(",
"'timestep'",
",",
"'frequency'",
",",
"'id'",
")",
"if",
"x",
"in",
"df",
".",
"columns",
"]",
"g",
"=",
"df",
".",
"groupby",
... | Compute and write the difference between normal and reciprocal values
for all columns specified in the diff_list parameter.
Note that the DataFrame is directly written to. That is, it is changed
during the call of this function. No need to use the returned object.
Parameters
----------
df: pan... | [
"Compute",
"and",
"write",
"the",
"difference",
"between",
"normal",
"and",
"reciprocal",
"values",
"for",
"all",
"columns",
"specified",
"in",
"the",
"diff_list",
"parameter",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/norrec.py#L336-L378 | train |
marazmiki/django-ulogin | django_ulogin/views.py | PostBackView.handle_authenticated_user | def handle_authenticated_user(self, response):
"""
Handles the ULogin response if user is already
authenticated
"""
current_user = get_user(self.request)
ulogin, registered = ULoginUser.objects.get_or_create(
uid=response['uid'],
network=response[... | python | def handle_authenticated_user(self, response):
"""
Handles the ULogin response if user is already
authenticated
"""
current_user = get_user(self.request)
ulogin, registered = ULoginUser.objects.get_or_create(
uid=response['uid'],
network=response[... | [
"def",
"handle_authenticated_user",
"(",
"self",
",",
"response",
")",
":",
"current_user",
"=",
"get_user",
"(",
"self",
".",
"request",
")",
"ulogin",
",",
"registered",
"=",
"ULoginUser",
".",
"objects",
".",
"get_or_create",
"(",
"uid",
"=",
"response",
... | Handles the ULogin response if user is already
authenticated | [
"Handles",
"the",
"ULogin",
"response",
"if",
"user",
"is",
"already",
"authenticated"
] | f41ad4b4ca130ad8af25be72ad882c8cf94a80dc | https://github.com/marazmiki/django-ulogin/blob/f41ad4b4ca130ad8af25be72ad882c8cf94a80dc/django_ulogin/views.py#L82-L107 | train |
marazmiki/django-ulogin | django_ulogin/views.py | PostBackView.form_valid | def form_valid(self, form):
"""
The request from ulogin service is correct
"""
response = self.ulogin_response(form.cleaned_data['token'],
self.request.get_host())
if 'error' in response:
return render(self.request, self.error_... | python | def form_valid(self, form):
"""
The request from ulogin service is correct
"""
response = self.ulogin_response(form.cleaned_data['token'],
self.request.get_host())
if 'error' in response:
return render(self.request, self.error_... | [
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"response",
"=",
"self",
".",
"ulogin_response",
"(",
"form",
".",
"cleaned_data",
"[",
"'token'",
"]",
",",
"self",
".",
"request",
".",
"get_host",
"(",
")",
")",
"if",
"'error'",
"in",
"respon... | The request from ulogin service is correct | [
"The",
"request",
"from",
"ulogin",
"service",
"is",
"correct"
] | f41ad4b4ca130ad8af25be72ad882c8cf94a80dc | https://github.com/marazmiki/django-ulogin/blob/f41ad4b4ca130ad8af25be72ad882c8cf94a80dc/django_ulogin/views.py#L135-L159 | train |
marazmiki/django-ulogin | django_ulogin/views.py | PostBackView.ulogin_response | def ulogin_response(self, token, host):
"""
Makes a request to ULOGIN
"""
response = requests.get(
settings.TOKEN_URL,
params={
'token': token,
'host': host
})
content = response.content
if sys.version_i... | python | def ulogin_response(self, token, host):
"""
Makes a request to ULOGIN
"""
response = requests.get(
settings.TOKEN_URL,
params={
'token': token,
'host': host
})
content = response.content
if sys.version_i... | [
"def",
"ulogin_response",
"(",
"self",
",",
"token",
",",
"host",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"settings",
".",
"TOKEN_URL",
",",
"params",
"=",
"{",
"'token'",
":",
"token",
",",
"'host'",
":",
"host",
"}",
")",
"content",
... | Makes a request to ULOGIN | [
"Makes",
"a",
"request",
"to",
"ULOGIN"
] | f41ad4b4ca130ad8af25be72ad882c8cf94a80dc | https://github.com/marazmiki/django-ulogin/blob/f41ad4b4ca130ad8af25be72ad882c8cf94a80dc/django_ulogin/views.py#L167-L182 | train |
evolbioinfo/pastml | pastml/parsimony.py | initialise_parsimonious_states | def initialise_parsimonious_states(tree, feature, states):
"""
Initializes the bottom-up state arrays for tips based on their states given by the feature.
:param tree: ete3.Tree, tree for which the tip states are to be initialized
:param feature: str, feature in which the tip states are stored (the val... | python | def initialise_parsimonious_states(tree, feature, states):
"""
Initializes the bottom-up state arrays for tips based on their states given by the feature.
:param tree: ete3.Tree, tree for which the tip states are to be initialized
:param feature: str, feature in which the tip states are stored (the val... | [
"def",
"initialise_parsimonious_states",
"(",
"tree",
",",
"feature",
",",
"states",
")",
":",
"ps_feature_down",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"BU_PARS_STATES",
")",
"ps_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
... | Initializes the bottom-up state arrays for tips based on their states given by the feature.
:param tree: ete3.Tree, tree for which the tip states are to be initialized
:param feature: str, feature in which the tip states are stored (the value could be None for a missing state)
:param states: numpy array, p... | [
"Initializes",
"the",
"bottom",
"-",
"up",
"state",
"arrays",
"for",
"tips",
"based",
"on",
"their",
"states",
"given",
"by",
"the",
"feature",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/parsimony.py#L48-L67 | train |
evolbioinfo/pastml | pastml/parsimony.py | uppass | def uppass(tree, feature):
"""
UPPASS traverses the tree starting from the tips and going up till the root,
and assigns to each parent node a state based on the states of its child nodes.
if N is a tip:
S(N) <- state of N
else:
L, R <- left and right children of N
UPPASS(L)
UP... | python | def uppass(tree, feature):
"""
UPPASS traverses the tree starting from the tips and going up till the root,
and assigns to each parent node a state based on the states of its child nodes.
if N is a tip:
S(N) <- state of N
else:
L, R <- left and right children of N
UPPASS(L)
UP... | [
"def",
"uppass",
"(",
"tree",
",",
"feature",
")",
":",
"ps_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"BU_PARS_STATES",
")",
"for",
"node",
"in",
"tree",
".",
"traverse",
"(",
"'postorder'",
")",
":",
"if",
"not",
"node",
".",
"i... | UPPASS traverses the tree starting from the tips and going up till the root,
and assigns to each parent node a state based on the states of its child nodes.
if N is a tip:
S(N) <- state of N
else:
L, R <- left and right children of N
UPPASS(L)
UPPASS(R)
if S(L) intersects with S... | [
"UPPASS",
"traverses",
"the",
"tree",
"starting",
"from",
"the",
"tips",
"and",
"going",
"up",
"till",
"the",
"root",
"and",
"assigns",
"to",
"each",
"parent",
"node",
"a",
"state",
"based",
"on",
"the",
"states",
"of",
"its",
"child",
"nodes",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/parsimony.py#L83-L111 | train |
evolbioinfo/pastml | pastml/parsimony.py | parsimonious_acr | def parsimonious_acr(tree, character, prediction_method, states, num_nodes, num_tips):
"""
Calculates parsimonious states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param prediction_method: str, ACCTRAN (accelerated transformation), DELTRAN ... | python | def parsimonious_acr(tree, character, prediction_method, states, num_nodes, num_tips):
"""
Calculates parsimonious states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param prediction_method: str, ACCTRAN (accelerated transformation), DELTRAN ... | [
"def",
"parsimonious_acr",
"(",
"tree",
",",
"character",
",",
"prediction_method",
",",
"states",
",",
"num_nodes",
",",
"num_tips",
")",
":",
"initialise_parsimonious_states",
"(",
"tree",
",",
"character",
",",
"states",
")",
"uppass",
"(",
"tree",
",",
"ch... | Calculates parsimonious states on the tree and stores them in the corresponding feature.
:param states: numpy array of possible states
:param prediction_method: str, ACCTRAN (accelerated transformation), DELTRAN (delayed transformation) or DOWNPASS
:param tree: ete3.Tree, the tree of interest
:param ch... | [
"Calculates",
"parsimonious",
"states",
"on",
"the",
"tree",
"and",
"stores",
"them",
"in",
"the",
"corresponding",
"feature",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/parsimony.py#L224-L289 | train |
frasertweedale/ledgertools | ltlib/chart.py | balance_to_ringchart_items | def balance_to_ringchart_items(balance, account='', show=SHOW_CREDIT):
"""Convert a balance data structure into RingChartItem objects."""
show = show if show else SHOW_CREDIT # cannot show all in ring chart
rcis = []
for item in balance:
subaccount = item['account_fragment'] if not account \
... | python | def balance_to_ringchart_items(balance, account='', show=SHOW_CREDIT):
"""Convert a balance data structure into RingChartItem objects."""
show = show if show else SHOW_CREDIT # cannot show all in ring chart
rcis = []
for item in balance:
subaccount = item['account_fragment'] if not account \
... | [
"def",
"balance_to_ringchart_items",
"(",
"balance",
",",
"account",
"=",
"''",
",",
"show",
"=",
"SHOW_CREDIT",
")",
":",
"show",
"=",
"show",
"if",
"show",
"else",
"SHOW_CREDIT",
"rcis",
"=",
"[",
"]",
"for",
"item",
"in",
"balance",
":",
"subaccount",
... | Convert a balance data structure into RingChartItem objects. | [
"Convert",
"a",
"balance",
"data",
"structure",
"into",
"RingChartItem",
"objects",
"."
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/chart.py#L27-L45 | train |
orlandodiaz/log3 | log3/log.py | log_to_file | def log_to_file(log_path, log_urllib=False, limit=None):
""" Add file_handler to logger"""
log_path = log_path
file_handler = logging.FileHandler(log_path)
if limit:
file_handler = RotatingFileHandler(
log_path,
mode='a',
maxBytes=limit * 1024 * 1024,
... | python | def log_to_file(log_path, log_urllib=False, limit=None):
""" Add file_handler to logger"""
log_path = log_path
file_handler = logging.FileHandler(log_path)
if limit:
file_handler = RotatingFileHandler(
log_path,
mode='a',
maxBytes=limit * 1024 * 1024,
... | [
"def",
"log_to_file",
"(",
"log_path",
",",
"log_urllib",
"=",
"False",
",",
"limit",
"=",
"None",
")",
":",
"log_path",
"=",
"log_path",
"file_handler",
"=",
"logging",
".",
"FileHandler",
"(",
"log_path",
")",
"if",
"limit",
":",
"file_handler",
"=",
"Ro... | Add file_handler to logger | [
"Add",
"file_handler",
"to",
"logger"
] | aeedf83159be8dd3d4757e0d9240f9cdbc9c3ea2 | https://github.com/orlandodiaz/log3/blob/aeedf83159be8dd3d4757e0d9240f9cdbc9c3ea2/log3/log.py#L34-L53 | train |
YosaiProject/yosai_alchemystore | yosai_alchemystore/accountstore/accountstore.py | session_context | def session_context(fn):
"""
Handles session setup and teardown
"""
@functools.wraps(fn)
def wrap(*args, **kwargs):
session = args[0].Session() # obtain from self
result = fn(*args, session=session, **kwargs)
session.close()
return result
return wrap | python | def session_context(fn):
"""
Handles session setup and teardown
"""
@functools.wraps(fn)
def wrap(*args, **kwargs):
session = args[0].Session() # obtain from self
result = fn(*args, session=session, **kwargs)
session.close()
return result
return wrap | [
"def",
"session_context",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"session",
"=",
"args",
"[",
"0",
"]",
".",
"Session",
"(",
")",
"result",
"=",
"fn",
... | Handles session setup and teardown | [
"Handles",
"session",
"setup",
"and",
"teardown"
] | 6479c159ab2ac357e6b70cdd71a2d673279e86bb | https://github.com/YosaiProject/yosai_alchemystore/blob/6479c159ab2ac357e6b70cdd71a2d673279e86bb/yosai_alchemystore/accountstore/accountstore.py#L66-L76 | train |
geophysics-ubonn/reda | lib/reda/exporters/syscal.py | _syscal_write_electrode_coords | def _syscal_write_electrode_coords(fid, spacing, N):
"""helper function that writes out electrode positions to a file descriptor
Parameters
----------
fid: file descriptor
data is written here
spacing: float
spacing of electrodes
N: int
number of electrodes
"""
f... | python | def _syscal_write_electrode_coords(fid, spacing, N):
"""helper function that writes out electrode positions to a file descriptor
Parameters
----------
fid: file descriptor
data is written here
spacing: float
spacing of electrodes
N: int
number of electrodes
"""
f... | [
"def",
"_syscal_write_electrode_coords",
"(",
"fid",
",",
"spacing",
",",
"N",
")",
":",
"fid",
".",
"write",
"(",
"'# X Y Z\\n'",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"N",
")",
":",
"fid",
".",
"write",
"(",
"'{0} {1} {2} {3}\\n'",
".",
"for... | helper function that writes out electrode positions to a file descriptor
Parameters
----------
fid: file descriptor
data is written here
spacing: float
spacing of electrodes
N: int
number of electrodes | [
"helper",
"function",
"that",
"writes",
"out",
"electrode",
"positions",
"to",
"a",
"file",
"descriptor"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/syscal.py#L5-L19 | train |
geophysics-ubonn/reda | lib/reda/exporters/syscal.py | _syscal_write_quadpoles | def _syscal_write_quadpoles(fid, quadpoles):
"""helper function that writes the actual measurement configurations to a
file descriptor.
Parameters
----------
fid: file descriptor
data is written here
quadpoles: numpy.ndarray
measurement configurations
"""
fid.write('# A... | python | def _syscal_write_quadpoles(fid, quadpoles):
"""helper function that writes the actual measurement configurations to a
file descriptor.
Parameters
----------
fid: file descriptor
data is written here
quadpoles: numpy.ndarray
measurement configurations
"""
fid.write('# A... | [
"def",
"_syscal_write_quadpoles",
"(",
"fid",
",",
"quadpoles",
")",
":",
"fid",
".",
"write",
"(",
"'# A B M N\\n'",
")",
"for",
"nr",
",",
"quadpole",
"in",
"enumerate",
"(",
"quadpoles",
")",
":",
"fid",
".",
"write",
"(",
"'{0} {1} {2} {3} {4}\\n'",
".",... | helper function that writes the actual measurement configurations to a
file descriptor.
Parameters
----------
fid: file descriptor
data is written here
quadpoles: numpy.ndarray
measurement configurations | [
"helper",
"function",
"that",
"writes",
"the",
"actual",
"measurement",
"configurations",
"to",
"a",
"file",
"descriptor",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/syscal.py#L22-L38 | train |
geophysics-ubonn/reda | lib/reda/exporters/syscal.py | syscal_save_to_config_txt | def syscal_save_to_config_txt(filename, configs, spacing=1):
"""Write configurations to a Syscal ascii file that can be read by the
Electre Pro program.
Parameters
----------
filename: string
output filename
configs: numpy.ndarray
Nx4 array with measurement configurations A-B-M-... | python | def syscal_save_to_config_txt(filename, configs, spacing=1):
"""Write configurations to a Syscal ascii file that can be read by the
Electre Pro program.
Parameters
----------
filename: string
output filename
configs: numpy.ndarray
Nx4 array with measurement configurations A-B-M-... | [
"def",
"syscal_save_to_config_txt",
"(",
"filename",
",",
"configs",
",",
"spacing",
"=",
"1",
")",
":",
"print",
"(",
"'Number of measurements: '",
",",
"configs",
".",
"shape",
"[",
"0",
"]",
")",
"number_of_electrodes",
"=",
"configs",
".",
"max",
"(",
")... | Write configurations to a Syscal ascii file that can be read by the
Electre Pro program.
Parameters
----------
filename: string
output filename
configs: numpy.ndarray
Nx4 array with measurement configurations A-B-M-N | [
"Write",
"configurations",
"to",
"a",
"Syscal",
"ascii",
"file",
"that",
"can",
"be",
"read",
"by",
"the",
"Electre",
"Pro",
"program",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/syscal.py#L41-L58 | train |
geophysics-ubonn/reda | lib/reda/utils/mpl.py | setup | def setup(use_latex=False, overwrite=False):
"""Set up matplotlib imports and settings.
Parameters
----------
use_latex: bool, optional
Determine if Latex output should be used. Latex will only be enable if
a 'latex' binary is found in the system.
overwrite: bool, optional
O... | python | def setup(use_latex=False, overwrite=False):
"""Set up matplotlib imports and settings.
Parameters
----------
use_latex: bool, optional
Determine if Latex output should be used. Latex will only be enable if
a 'latex' binary is found in the system.
overwrite: bool, optional
O... | [
"def",
"setup",
"(",
"use_latex",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"import",
"matplotlib",
"as",
"mpl",
"if",
"overwrite",
":",
"mpl",
".",
"rcParams",
"[",
"\"lines.linewidth\"",
"]",
"=",
"2.0",
"mpl",
".",
"rcParams",
"[",
"\"li... | Set up matplotlib imports and settings.
Parameters
----------
use_latex: bool, optional
Determine if Latex output should be used. Latex will only be enable if
a 'latex' binary is found in the system.
overwrite: bool, optional
Overwrite some matplotlib config values.
Returns... | [
"Set",
"up",
"matplotlib",
"imports",
"and",
"settings",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/mpl.py#L19-L64 | train |
geophysics-ubonn/reda | lib/reda/importers/crtomo.py | load_seit_data | def load_seit_data(directory, frequency_file='frequencies.dat',
data_prefix='volt_', **kwargs):
"""Load sEIT data from data directory. This function loads data previously
exported from reda using reda.exporters.crtomo.write_files_to_directory
Parameters
----------
directory : str... | python | def load_seit_data(directory, frequency_file='frequencies.dat',
data_prefix='volt_', **kwargs):
"""Load sEIT data from data directory. This function loads data previously
exported from reda using reda.exporters.crtomo.write_files_to_directory
Parameters
----------
directory : str... | [
"def",
"load_seit_data",
"(",
"directory",
",",
"frequency_file",
"=",
"'frequencies.dat'",
",",
"data_prefix",
"=",
"'volt_'",
",",
"**",
"kwargs",
")",
":",
"frequencies",
"=",
"np",
".",
"loadtxt",
"(",
"directory",
"+",
"os",
".",
"sep",
"+",
"frequency_... | Load sEIT data from data directory. This function loads data previously
exported from reda using reda.exporters.crtomo.write_files_to_directory
Parameters
----------
directory : string
input directory
frequency_file : string, optional
file (located in directory) that contains the fr... | [
"Load",
"sEIT",
"data",
"from",
"data",
"directory",
".",
"This",
"function",
"loads",
"data",
"previously",
"exported",
"from",
"reda",
"using",
"reda",
".",
"exporters",
".",
"crtomo",
".",
"write_files_to_directory"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/crtomo.py#L59-L100 | train |
evolbioinfo/pastml | pastml/models/generator.py | get_diagonalisation | def get_diagonalisation(frequencies, rate_matrix=None):
"""
Normalises and diagonalises the rate matrix.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: nu... | python | def get_diagonalisation(frequencies, rate_matrix=None):
"""
Normalises and diagonalises the rate matrix.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: nu... | [
"def",
"get_diagonalisation",
"(",
"frequencies",
",",
"rate_matrix",
"=",
"None",
")",
":",
"Q",
"=",
"get_normalised_generator",
"(",
"frequencies",
",",
"rate_matrix",
")",
"d",
",",
"A",
"=",
"np",
".",
"linalg",
".",
"eig",
"(",
"Q",
")",
"return",
... | Normalises and diagonalises the rate matrix.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: numpy.ndarray
:return: matrix diagonalisation (d, A, A^{-1})
... | [
"Normalises",
"and",
"diagonalises",
"the",
"rate",
"matrix",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/models/generator.py#L4-L18 | train |
evolbioinfo/pastml | pastml/models/generator.py | get_normalised_generator | def get_normalised_generator(frequencies, rate_matrix=None):
"""
Calculates the normalised generator from the rate matrix and character state frequencies.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-eq... | python | def get_normalised_generator(frequencies, rate_matrix=None):
"""
Calculates the normalised generator from the rate matrix and character state frequencies.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-eq... | [
"def",
"get_normalised_generator",
"(",
"frequencies",
",",
"rate_matrix",
"=",
"None",
")",
":",
"if",
"rate_matrix",
"is",
"None",
":",
"n",
"=",
"len",
"(",
"frequencies",
")",
"rate_matrix",
"=",
"np",
".",
"ones",
"(",
"shape",
"=",
"(",
"n",
",",
... | Calculates the normalised generator from the rate matrix and character state frequencies.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: numpy.ndarray
:return... | [
"Calculates",
"the",
"normalised",
"generator",
"from",
"the",
"rate",
"matrix",
"and",
"character",
"state",
"frequencies",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/models/generator.py#L21-L39 | train |
evolbioinfo/pastml | pastml/models/generator.py | get_pij_matrix | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | python | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))... | [
"def",
"get_pij_matrix",
"(",
"t",
",",
"diag",
",",
"A",
",",
"A_inv",
")",
":",
"return",
"A",
".",
"dot",
"(",
"np",
".",
"diag",
"(",
"np",
".",
"exp",
"(",
"diag",
"*",
"t",
")",
")",
")",
".",
"dot",
"(",
"A_inv",
")"
] | Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | [
"Calculates",
"the",
"probability",
"matrix",
"of",
"substitutions",
"i",
"-",
">",
"j",
"over",
"time",
"t",
"given",
"the",
"normalised",
"generator",
"diagonalisation",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/models/generator.py#L42-L53 | train |
lambdalisue/notify | src/notify/arguments.py | split_arguments | def split_arguments(args):
"""
Split specified arguments to two list.
This is used to distinguish the options of the program and
execution command/arguments.
Parameters
----------
args : list
Command line arguments
Returns
-------
list : options, arguments
opti... | python | def split_arguments(args):
"""
Split specified arguments to two list.
This is used to distinguish the options of the program and
execution command/arguments.
Parameters
----------
args : list
Command line arguments
Returns
-------
list : options, arguments
opti... | [
"def",
"split_arguments",
"(",
"args",
")",
":",
"prev",
"=",
"False",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"args",
"[",
"1",
":",
"]",
")",
":",
"if",
"value",
".",
"startswith",
"(",
"'-'",
")",
":",
"prev",
"=",
"True",
"elif",
"p... | Split specified arguments to two list.
This is used to distinguish the options of the program and
execution command/arguments.
Parameters
----------
args : list
Command line arguments
Returns
-------
list : options, arguments
options indicate the optional arguments for... | [
"Split",
"specified",
"arguments",
"to",
"two",
"list",
"."
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/arguments.py#L8-L34 | train |
lambdalisue/notify | src/notify/arguments.py | parse_arguments | def parse_arguments(args, config):
"""
Parse specified arguments via config
Parameters
----------
args : list
Command line arguments
config : object
ConfigParser instance which values are used as default values of
options
Returns
-------
list : arguments, op... | python | def parse_arguments(args, config):
"""
Parse specified arguments via config
Parameters
----------
args : list
Command line arguments
config : object
ConfigParser instance which values are used as default values of
options
Returns
-------
list : arguments, op... | [
"def",
"parse_arguments",
"(",
"args",
",",
"config",
")",
":",
"import",
"notify",
"from",
"conf",
"import",
"config_to_options",
"opts",
"=",
"config_to_options",
"(",
"config",
")",
"usage",
"=",
"(",
"\"%(prog)s \"",
"\"[-h] [-t TO_ADDR] [-f FROM_ADDR] [-e ENCODIN... | Parse specified arguments via config
Parameters
----------
args : list
Command line arguments
config : object
ConfigParser instance which values are used as default values of
options
Returns
-------
list : arguments, options
options indicate the return value... | [
"Parse",
"specified",
"arguments",
"via",
"config"
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/arguments.py#L36-L117 | train |
jonashaag/httpauth | httpauth.py | BaseHttpAuthMiddleware.should_require_authentication | def should_require_authentication(self, url):
""" Returns True if we should require authentication for the URL given """
return (not self.routes # require auth for all URLs
or any(route.match(url) for route in self.routes)) | python | def should_require_authentication(self, url):
""" Returns True if we should require authentication for the URL given """
return (not self.routes # require auth for all URLs
or any(route.match(url) for route in self.routes)) | [
"def",
"should_require_authentication",
"(",
"self",
",",
"url",
")",
":",
"return",
"(",
"not",
"self",
".",
"routes",
"or",
"any",
"(",
"route",
".",
"match",
"(",
"url",
")",
"for",
"route",
"in",
"self",
".",
"routes",
")",
")"
] | Returns True if we should require authentication for the URL given | [
"Returns",
"True",
"if",
"we",
"should",
"require",
"authentication",
"for",
"the",
"URL",
"given"
] | 1b2ab9cb5192b474c9723182690c352337f754bc | https://github.com/jonashaag/httpauth/blob/1b2ab9cb5192b474c9723182690c352337f754bc/httpauth.py#L99-L102 | train |
jonashaag/httpauth | httpauth.py | BaseHttpAuthMiddleware.authenticate | def authenticate(self, environ):
"""
Returns True if the credentials passed in the Authorization header are
valid, False otherwise.
"""
try:
hd = parse_dict_header(environ['HTTP_AUTHORIZATION'])
except (KeyError, ValueError):
return False
... | python | def authenticate(self, environ):
"""
Returns True if the credentials passed in the Authorization header are
valid, False otherwise.
"""
try:
hd = parse_dict_header(environ['HTTP_AUTHORIZATION'])
except (KeyError, ValueError):
return False
... | [
"def",
"authenticate",
"(",
"self",
",",
"environ",
")",
":",
"try",
":",
"hd",
"=",
"parse_dict_header",
"(",
"environ",
"[",
"'HTTP_AUTHORIZATION'",
"]",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"return",
"False",
"return",
"self",
".... | Returns True if the credentials passed in the Authorization header are
valid, False otherwise. | [
"Returns",
"True",
"if",
"the",
"credentials",
"passed",
"in",
"the",
"Authorization",
"header",
"are",
"valid",
"False",
"otherwise",
"."
] | 1b2ab9cb5192b474c9723182690c352337f754bc | https://github.com/jonashaag/httpauth/blob/1b2ab9cb5192b474c9723182690c352337f754bc/httpauth.py#L104-L120 | train |
frasertweedale/ledgertools | ltlib/readers/CSV.py | Reader.next | def next(self):
"""Return the next transaction object.
StopIteration will be propagated from self.csvreader.next()
"""
try:
return self.dict_to_xn(self.csvreader.next())
except MetadataException:
# row was metadata; proceed to next row
return ... | python | def next(self):
"""Return the next transaction object.
StopIteration will be propagated from self.csvreader.next()
"""
try:
return self.dict_to_xn(self.csvreader.next())
except MetadataException:
# row was metadata; proceed to next row
return ... | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"dict_to_xn",
"(",
"self",
".",
"csvreader",
".",
"next",
"(",
")",
")",
"except",
"MetadataException",
":",
"return",
"next",
"(",
"self",
")"
] | Return the next transaction object.
StopIteration will be propagated from self.csvreader.next() | [
"Return",
"the",
"next",
"transaction",
"object",
"."
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/readers/CSV.py#L92-L101 | train |
frasertweedale/ledgertools | ltlib/readers/CSV.py | Reader.parse_date | def parse_date(self, date):
"""Parse the date and return a datetime object
The heuristic for determining the date is:
- if ``date_format`` is set, parse using strptime
- if one field of 8 digits, YYYYMMDD
- split by '-' or '/'
- (TODO: substitute string months with t... | python | def parse_date(self, date):
"""Parse the date and return a datetime object
The heuristic for determining the date is:
- if ``date_format`` is set, parse using strptime
- if one field of 8 digits, YYYYMMDD
- split by '-' or '/'
- (TODO: substitute string months with t... | [
"def",
"parse_date",
"(",
"self",
",",
"date",
")",
":",
"if",
"self",
".",
"date_format",
"is",
"not",
"None",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"date",
",",
"self",
".",
"date_format",
")",
".",
"date",
"(",
")",
"if... | Parse the date and return a datetime object
The heuristic for determining the date is:
- if ``date_format`` is set, parse using strptime
- if one field of 8 digits, YYYYMMDD
- split by '-' or '/'
- (TODO: substitute string months with their numbers)
- if (2, 2, 4), ... | [
"Parse",
"the",
"date",
"and",
"return",
"a",
"datetime",
"object"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/readers/CSV.py#L103-L140 | train |
digidotcom/python-wvalib | wva/subscriptions.py | WVASubscription.create | def create(self, uri, buffer="queue", interval=10):
"""Create a subscription with this short name and the provided parameters
For more information on what the parameters required here mean, please
refer to the `WVA Documentation <http://goo.gl/DRcOQf>`_.
:raises WVAError: If there is a... | python | def create(self, uri, buffer="queue", interval=10):
"""Create a subscription with this short name and the provided parameters
For more information on what the parameters required here mean, please
refer to the `WVA Documentation <http://goo.gl/DRcOQf>`_.
:raises WVAError: If there is a... | [
"def",
"create",
"(",
"self",
",",
"uri",
",",
"buffer",
"=",
"\"queue\"",
",",
"interval",
"=",
"10",
")",
":",
"return",
"self",
".",
"_http_client",
".",
"put_json",
"(",
"\"subscriptions/{}\"",
".",
"format",
"(",
"self",
".",
"short_name",
")",
",",... | Create a subscription with this short name and the provided parameters
For more information on what the parameters required here mean, please
refer to the `WVA Documentation <http://goo.gl/DRcOQf>`_.
:raises WVAError: If there is a problem creating the new subscription | [
"Create",
"a",
"subscription",
"with",
"this",
"short",
"name",
"and",
"the",
"provided",
"parameters"
] | 4252735e2775f80ebaffd813fbe84046d26906b3 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/subscriptions.py#L15-L29 | train |
Starlink/palpy | support/palvers.py | read_pal_version | def read_pal_version():
"""
Scans the PAL configure.ac looking for the version number.
(vers, maj, min, patchlevel) = read_pal_version()
Returns the version as a string and the major, minor
and patchlevel version integers
"""
verfile = os.path.join("cextern", "pal", "configure.ac")
ve... | python | def read_pal_version():
"""
Scans the PAL configure.ac looking for the version number.
(vers, maj, min, patchlevel) = read_pal_version()
Returns the version as a string and the major, minor
and patchlevel version integers
"""
verfile = os.path.join("cextern", "pal", "configure.ac")
ve... | [
"def",
"read_pal_version",
"(",
")",
":",
"verfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"cextern\"",
",",
"\"pal\"",
",",
"\"configure.ac\"",
")",
"verstring",
"=",
"\"-1.-1.-1\"",
"for",
"line",
"in",
"open",
"(",
"verfile",
")",
":",
"if",
"li... | Scans the PAL configure.ac looking for the version number.
(vers, maj, min, patchlevel) = read_pal_version()
Returns the version as a string and the major, minor
and patchlevel version integers | [
"Scans",
"the",
"PAL",
"configure",
".",
"ac",
"looking",
"for",
"the",
"version",
"number",
"."
] | a7ad77058614a93b29a004bbad6bc0e61c73b6e0 | https://github.com/Starlink/palpy/blob/a7ad77058614a93b29a004bbad6bc0e61c73b6e0/support/palvers.py#L35-L55 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel._reset_model | def _reset_model(self, response):
"""Update the fields value with the received information."""
# pylint: disable=no-member
# Reset the model to the initial state
self._provision_done = False # Set back the provision flag
self._changes.clear() # Clear the changes
... | python | def _reset_model(self, response):
"""Update the fields value with the received information."""
# pylint: disable=no-member
# Reset the model to the initial state
self._provision_done = False # Set back the provision flag
self._changes.clear() # Clear the changes
... | [
"def",
"_reset_model",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_provision_done",
"=",
"False",
"self",
".",
"_changes",
".",
"clear",
"(",
")",
"fields",
"=",
"self",
".",
"process_raw_data",
"(",
"response",
")",
"self",
".",
"_set_fields",
... | Update the fields value with the received information. | [
"Update",
"the",
"fields",
"value",
"with",
"the",
"received",
"information",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L105-L120 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel.is_ready | def is_ready(self):
"""Check if the current model is ready to be used."""
if not self.provisioning_state:
raise exception.ServiceException("The object doesn't contain "
"`provisioningState`.")
elif self.provisioning_state == constant.FAILE... | python | def is_ready(self):
"""Check if the current model is ready to be used."""
if not self.provisioning_state:
raise exception.ServiceException("The object doesn't contain "
"`provisioningState`.")
elif self.provisioning_state == constant.FAILE... | [
"def",
"is_ready",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"provisioning_state",
":",
"raise",
"exception",
".",
"ServiceException",
"(",
"\"The object doesn't contain \"",
"\"`provisioningState`.\"",
")",
"elif",
"self",
".",
"provisioning_state",
"==",
"c... | Check if the current model is ready to be used. | [
"Check",
"if",
"the",
"current",
"model",
"is",
"ready",
"to",
"be",
"used",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L122-L136 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel._get_all | def _get_all(cls, parent_id=None, grandparent_id=None):
"""Retrives all the required resources."""
client = cls._get_client()
endpoint = cls._endpoint.format(resource_id="",
parent_id=parent_id or "",
grandparent_id=... | python | def _get_all(cls, parent_id=None, grandparent_id=None):
"""Retrives all the required resources."""
client = cls._get_client()
endpoint = cls._endpoint.format(resource_id="",
parent_id=parent_id or "",
grandparent_id=... | [
"def",
"_get_all",
"(",
"cls",
",",
"parent_id",
"=",
"None",
",",
"grandparent_id",
"=",
"None",
")",
":",
"client",
"=",
"cls",
".",
"_get_client",
"(",
")",
"endpoint",
"=",
"cls",
".",
"_endpoint",
".",
"format",
"(",
"resource_id",
"=",
"\"\"",
",... | Retrives all the required resources. | [
"Retrives",
"all",
"the",
"required",
"resources",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L148-L164 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel.get | def get(cls, resource_id=None, parent_id=None, grandparent_id=None):
"""Retrieves the required resources.
:param resource_id: The identifier for the specific resource
within the resource type.
:param parent_id: The identifier for the specific ancesto... | python | def get(cls, resource_id=None, parent_id=None, grandparent_id=None):
"""Retrieves the required resources.
:param resource_id: The identifier for the specific resource
within the resource type.
:param parent_id: The identifier for the specific ancesto... | [
"def",
"get",
"(",
"cls",
",",
"resource_id",
"=",
"None",
",",
"parent_id",
"=",
"None",
",",
"grandparent_id",
"=",
"None",
")",
":",
"if",
"not",
"resource_id",
":",
"return",
"cls",
".",
"_get_all",
"(",
"parent_id",
",",
"grandparent_id",
")",
"else... | Retrieves the required resources.
:param resource_id: The identifier for the specific resource
within the resource type.
:param parent_id: The identifier for the specific ancestor
resource within the resource type.
:p... | [
"Retrieves",
"the",
"required",
"resources",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L179-L194 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.