repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
eleme/meepo | meepo/apps/eventsourcing/pub.py | sqlalchemy_es_pub.session_rollback | def session_rollback(self, session):
"""Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase.
"""
# this may happen when there's nothing to rollback
if not hasattr(session, 'meepo_unique_id... | python | def session_rollback(self, session):
"""Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase.
"""
# this may happen when there's nothing to rollback
if not hasattr(session, 'meepo_unique_id... | [
"def",
"session_rollback",
"(",
"self",
",",
"session",
")",
":",
"# this may happen when there's nothing to rollback",
"if",
"not",
"hasattr",
"(",
"session",
",",
"'meepo_unique_id'",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"skipped - session_rollback\... | Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase. | [
"Send",
"session_rollback",
"signal",
"in",
"sqlalchemy",
"after_rollback",
"."
] | 8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a | https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/meepo/apps/eventsourcing/pub.py#L119-L133 | train | Send session_rollback signal in sqlalchemy after_rollback phase. |
jam31118/vis | vis/plot.py | augment_polar_mesh_for_colormesh | def augment_polar_mesh_for_colormesh(r_values, theta_values):
"""
Returns polar mesh for matplotlib.pyplot.pcolormesh() in polar coordinates.
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values a... | python | def augment_polar_mesh_for_colormesh(r_values, theta_values):
"""
Returns polar mesh for matplotlib.pyplot.pcolormesh() in polar coordinates.
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values a... | [
"def",
"augment_polar_mesh_for_colormesh",
"(",
"r_values",
",",
"theta_values",
")",
":",
"N_r",
"=",
"len",
"(",
"r_values",
")",
"N_theta",
"=",
"len",
"(",
"theta_values",
")",
"delta_r",
"=",
"(",
"r_values",
"[",
"-",
"1",
"]",
"-",
"r_values",
"[",
... | Returns polar mesh for matplotlib.pyplot.pcolormesh() in polar coordinates.
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values are assumed to be equally-spaced. | [
"Returns",
"polar",
"mesh",
"for",
"matplotlib",
".",
"pyplot",
".",
"pcolormesh",
"()",
"in",
"polar",
"coordinates",
"."
] | 965ebec102c539b323d5756fef04153ac71e50d9 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/plot.py#L22-L43 | train | Augment the polar mesh for colormesh. |
jam31118/vis | vis/plot.py | construct_polar_mesh_for_colormesh | def construct_polar_mesh_for_colormesh(r_values, theta_values):
"""
Returns polar mesh for matplotlib.pyplot.pcolormesh() in Cartesian coordinates
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_val... | python | def construct_polar_mesh_for_colormesh(r_values, theta_values):
"""
Returns polar mesh for matplotlib.pyplot.pcolormesh() in Cartesian coordinates
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_val... | [
"def",
"construct_polar_mesh_for_colormesh",
"(",
"r_values",
",",
"theta_values",
")",
":",
"mesh_R",
",",
"mesh_Theta",
"=",
"augment_polar_mesh_for_colormesh",
"(",
"r_values",
",",
"theta_values",
")",
"mesh_X",
"=",
"mesh_R",
"*",
"np",
".",
"cos",
"(",
"mesh... | Returns polar mesh for matplotlib.pyplot.pcolormesh() in Cartesian coordinates
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values are assumed to be equally-spaced. | [
"Returns",
"polar",
"mesh",
"for",
"matplotlib",
".",
"pyplot",
".",
"pcolormesh",
"()",
"in",
"Cartesian",
"coordinates"
] | 965ebec102c539b323d5756fef04153ac71e50d9 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/plot.py#L46-L60 | train | Constructs a polar mesh for a colormesh with the given values. |
jam31118/vis | vis/plot.py | construct_mesh_for_1d_array | def construct_mesh_for_1d_array(x_values):
"""Construct the corresponding 1D mesh from 1D array for pcolormesh() in ```matplotlib```"""
if not isinstance(x_values, np.ndarray):
try: x_values = np.array(x_values)
except: raise TypeError("Can not convert to numpy.ndarray: {0}".format(x_values))
... | python | def construct_mesh_for_1d_array(x_values):
"""Construct the corresponding 1D mesh from 1D array for pcolormesh() in ```matplotlib```"""
if not isinstance(x_values, np.ndarray):
try: x_values = np.array(x_values)
except: raise TypeError("Can not convert to numpy.ndarray: {0}".format(x_values))
... | [
"def",
"construct_mesh_for_1d_array",
"(",
"x_values",
")",
":",
"if",
"not",
"isinstance",
"(",
"x_values",
",",
"np",
".",
"ndarray",
")",
":",
"try",
":",
"x_values",
"=",
"np",
".",
"array",
"(",
"x_values",
")",
"except",
":",
"raise",
"TypeError",
... | Construct the corresponding 1D mesh from 1D array for pcolormesh() in ```matplotlib``` | [
"Construct",
"the",
"corresponding",
"1D",
"mesh",
"from",
"1D",
"array",
"for",
"pcolormesh",
"()",
"in",
"matplotlib"
] | 965ebec102c539b323d5756fef04153ac71e50d9 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/plot.py#L64-L82 | train | Construct the corresponding 1D mesh from 1D array for pcolormesh() in matplotlib. |
jam31118/vis | vis/plot.py | set_global_fontsize_from_fig | def set_global_fontsize_from_fig(fig, scale=1.5):
"""
Set matplotlib.rcParams['font.size'] value so that
all texts on a plot would look nice in terms of fontsize.
[NOTE] The formula for the font size is:
fontsize = sqrt(fig_area) * 'scale'
where fig_area = fig_height * fig_width (in inch)
... | python | def set_global_fontsize_from_fig(fig, scale=1.5):
"""
Set matplotlib.rcParams['font.size'] value so that
all texts on a plot would look nice in terms of fontsize.
[NOTE] The formula for the font size is:
fontsize = sqrt(fig_area) * 'scale'
where fig_area = fig_height * fig_width (in inch)
... | [
"def",
"set_global_fontsize_from_fig",
"(",
"fig",
",",
"scale",
"=",
"1.5",
")",
":",
"fig_size_inch",
"=",
"fig",
".",
"get_size_inches",
"(",
")",
"fig_size_len_geom_mean",
"=",
"(",
"fig_size_inch",
"[",
"0",
"]",
"*",
"fig_size_inch",
"[",
"1",
"]",
")"... | Set matplotlib.rcParams['font.size'] value so that
all texts on a plot would look nice in terms of fontsize.
[NOTE] The formula for the font size is:
fontsize = sqrt(fig_area) * 'scale'
where fig_area = fig_height * fig_width (in inch) | [
"Set",
"matplotlib",
".",
"rcParams",
"[",
"font",
".",
"size",
"]",
"value",
"so",
"that",
"all",
"texts",
"on",
"a",
"plot",
"would",
"look",
"nice",
"in",
"terms",
"of",
"fontsize",
"."
] | 965ebec102c539b323d5756fef04153ac71e50d9 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/plot.py#L92-L107 | train | Set the global font size to be the same as the figure s size. |
jam31118/vis | vis/plot.py | process_fig_and_ax_argument | def process_fig_and_ax_argument(fig, ax, default_figsize=None):
"""Process 'fig' and 'ax' arguments.
'fig' is of type: 'matplotlib.figure.Figure' (or its child object)
'ax' is of type: 'matplotlib.axes._base._AxesBase' (or its child object)
'fig' and 'ax' should be simultaneously None or of respective... | python | def process_fig_and_ax_argument(fig, ax, default_figsize=None):
"""Process 'fig' and 'ax' arguments.
'fig' is of type: 'matplotlib.figure.Figure' (or its child object)
'ax' is of type: 'matplotlib.axes._base._AxesBase' (or its child object)
'fig' and 'ax' should be simultaneously None or of respective... | [
"def",
"process_fig_and_ax_argument",
"(",
"fig",
",",
"ax",
",",
"default_figsize",
"=",
"None",
")",
":",
"if",
"default_figsize",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"default_figsize",
")",
"in",
"[",
"tuple",
",",
"list",
"]",
"assert",
"l... | Process 'fig' and 'ax' arguments.
'fig' is of type: 'matplotlib.figure.Figure' (or its child object)
'ax' is of type: 'matplotlib.axes._base._AxesBase' (or its child object)
'fig' and 'ax' should be simultaneously None or of respective proper type. | [
"Process",
"fig",
"and",
"ax",
"arguments",
"."
] | 965ebec102c539b323d5756fef04153ac71e50d9 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/plot.py#L123-L139 | train | Process fig and ax arguments. |
jam31118/vis | vis/plot.py | get_square_axes_limits | def get_square_axes_limits(coords, margin=0.05):
"""Return N-dimensional square's limits
## Arguments
# 'coords': list of coordinates of poins to be plotted
# 'margin': margin to be added from boundaries of the square.
- 'margin' can be negative if one wants to reduce the square size.
## Examp... | python | def get_square_axes_limits(coords, margin=0.05):
"""Return N-dimensional square's limits
## Arguments
# 'coords': list of coordinates of poins to be plotted
# 'margin': margin to be added from boundaries of the square.
- 'margin' can be negative if one wants to reduce the square size.
## Examp... | [
"def",
"get_square_axes_limits",
"(",
"coords",
",",
"margin",
"=",
"0.05",
")",
":",
"#coords = [x,y,z]",
"try",
":",
"coords",
"=",
"[",
"np",
".",
"array",
"(",
"coord",
")",
"for",
"coord",
"in",
"coords",
"]",
"except",
":",
"raise",
"Exception",
"(... | Return N-dimensional square's limits
## Arguments
# 'coords': list of coordinates of poins to be plotted
# 'margin': margin to be added from boundaries of the square.
- 'margin' can be negative if one wants to reduce the square size.
## Example
if 'coords' was given as [x,y,z],
then the r... | [
"Return",
"N",
"-",
"dimensional",
"square",
"s",
"limits"
] | 965ebec102c539b323d5756fef04153ac71e50d9 | https://github.com/jam31118/vis/blob/965ebec102c539b323d5756fef04153ac71e50d9/vis/plot.py#L209-L246 | train | Returns a tuple of axes limits for the given coords. |
wistful/pympris | pympris/Player.py | Player.SetPosition | def SetPosition(self, track_id, position):
"""Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If ... | python | def SetPosition(self, track_id, position):
"""Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If ... | [
"def",
"SetPosition",
"(",
"self",
",",
"track_id",
",",
"position",
")",
":",
"self",
".",
"iface",
".",
"SetPosition",
"(",
"convert2dbus",
"(",
"track_id",
",",
"'o'",
")",
",",
"convert2dbus",
"(",
"position",
",",
"'x'",
")",
")"
] | Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If the Position argument is less than 0, do nothing.
... | [
"Sets",
"the",
"current",
"track",
"position",
"in",
"microseconds",
"."
] | 4bd64a1f0d151f2adfc392ab34fd9b38894786cb | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/Player.py#L79-L91 | train | Sets the current position in microseconds. |
thautwarm/Redy | Redy/Tools/_py_hash.py | hash_from_stream | def hash_from_stream(n, hash_stream):
"""
Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3))
"""
_to_int64 = to_int64
x... | python | def hash_from_stream(n, hash_stream):
"""
Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3))
"""
_to_int64 = to_int64
x... | [
"def",
"hash_from_stream",
"(",
"n",
",",
"hash_stream",
")",
":",
"_to_int64",
"=",
"to_int64",
"x",
"=",
"0x345678",
"multiplied",
"=",
"_to_int64",
"(",
"1000003",
")",
"for",
"n",
"in",
"range",
"(",
"n",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
... | Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3)) | [
"Not",
"standard",
"hashing",
"algorithm!",
"Install",
"NumPy",
"for",
"better",
"hashing",
"service",
".",
">>>",
"from",
"Redy",
".",
"Tools",
".",
"_py_hash",
"import",
"hash_from_stream",
">>>",
"s",
"=",
"iter",
"((",
"1",
"2",
"3",
"))",
">>>",
"asse... | 8beee5c5f752edfd2754bb1e6b5f4acb016a7770 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Tools/_py_hash.py#L8-L31 | train | This function uses the stream to generate a random n - bit integer. |
robinandeer/puzzle | puzzle/plugins/base_variant_mixin.py | BaseVariantMixin._get_genes | def _get_genes(self, variant):
"""Add the genes for a variant
Get the hgnc symbols from all transcripts and add them
to the variant
Args:
variant (dict): A variant dictionary
Returns:
genes (list): A list of Genes
"""
ensembl_ids = []
... | python | def _get_genes(self, variant):
"""Add the genes for a variant
Get the hgnc symbols from all transcripts and add them
to the variant
Args:
variant (dict): A variant dictionary
Returns:
genes (list): A list of Genes
"""
ensembl_ids = []
... | [
"def",
"_get_genes",
"(",
"self",
",",
"variant",
")",
":",
"ensembl_ids",
"=",
"[",
"]",
"hgnc_symbols",
"=",
"[",
"]",
"for",
"transcript",
"in",
"variant",
".",
"transcripts",
":",
"if",
"transcript",
".",
"ensembl_id",
":",
"ensembl_ids",
".",
"append"... | Add the genes for a variant
Get the hgnc symbols from all transcripts and add them
to the variant
Args:
variant (dict): A variant dictionary
Returns:
genes (list): A list of Genes | [
"Add",
"the",
"genes",
"for",
"a",
"variant"
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/base_variant_mixin.py#L17-L42 | train | Get the genes from all transcripts and add them
to the variant |
robinandeer/puzzle | puzzle/plugins/base_variant_mixin.py | BaseVariantMixin._add_sv_coordinates | def _add_sv_coordinates(self, variant):
"""Add the neccesary sv coordinates for a variant
Args:
variant (puzzle.models.variant)
"""
variant.stop_chrom = variant.CHROM
variant.start = int(variant.POS)
# If we have a translocation:
if '... | python | def _add_sv_coordinates(self, variant):
"""Add the neccesary sv coordinates for a variant
Args:
variant (puzzle.models.variant)
"""
variant.stop_chrom = variant.CHROM
variant.start = int(variant.POS)
# If we have a translocation:
if '... | [
"def",
"_add_sv_coordinates",
"(",
"self",
",",
"variant",
")",
":",
"variant",
".",
"stop_chrom",
"=",
"variant",
".",
"CHROM",
"variant",
".",
"start",
"=",
"int",
"(",
"variant",
".",
"POS",
")",
"# If we have a translocation:",
"if",
"':'",
"in",
"varian... | Add the neccesary sv coordinates for a variant
Args:
variant (puzzle.models.variant) | [
"Add",
"the",
"neccesary",
"sv",
"coordinates",
"for",
"a",
"variant",
"Args",
":",
"variant",
"(",
"puzzle",
".",
"models",
".",
"variant",
")"
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/base_variant_mixin.py#L44-L74 | train | Add the neccesary sv coordinates for a variant. |
inveniosoftware-contrib/json-merger | json_merger/comparator.py | BaseComparator.process_lists | def process_lists(self):
"""Do any preprocessing of the lists."""
for l1_idx, obj1 in enumerate(self.l1):
for l2_idx, obj2 in enumerate(self.l2):
if self.equal(obj1, obj2):
self.matches.add((l1_idx, l2_idx)) | python | def process_lists(self):
"""Do any preprocessing of the lists."""
for l1_idx, obj1 in enumerate(self.l1):
for l2_idx, obj2 in enumerate(self.l2):
if self.equal(obj1, obj2):
self.matches.add((l1_idx, l2_idx)) | [
"def",
"process_lists",
"(",
"self",
")",
":",
"for",
"l1_idx",
",",
"obj1",
"in",
"enumerate",
"(",
"self",
".",
"l1",
")",
":",
"for",
"l2_idx",
",",
"obj2",
"in",
"enumerate",
"(",
"self",
".",
"l2",
")",
":",
"if",
"self",
".",
"equal",
"(",
... | Do any preprocessing of the lists. | [
"Do",
"any",
"preprocessing",
"of",
"the",
"lists",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L45-L50 | train | Do any preprocessing of the lists. |
inveniosoftware-contrib/json-merger | json_merger/comparator.py | BaseComparator.get_matches | def get_matches(self, src, src_idx):
"""Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0]
"""
if src not in ('l1', 'l2'):
raise ValueError('Must have one of "l1"... | python | def get_matches(self, src, src_idx):
"""Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0]
"""
if src not in ('l1', 'l2'):
raise ValueError('Must have one of "l1"... | [
"def",
"get_matches",
"(",
"self",
",",
"src",
",",
"src_idx",
")",
":",
"if",
"src",
"not",
"in",
"(",
"'l1'",
",",
"'l2'",
")",
":",
"raise",
"ValueError",
"(",
"'Must have one of \"l1\" or \"l2\" as src'",
")",
"if",
"src",
"==",
"'l1'",
":",
"target_li... | Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0] | [
"Get",
"elements",
"equal",
"to",
"the",
"idx",
"th",
"in",
"src",
"from",
"the",
"other",
"list",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L56-L74 | train | Get elements equal to the idx t in src from the other list. |
ldomic/lintools | lintools/data.py | Data.load_topology | def load_topology(self,topology):
"""
Loads the topology file (e.g. GRO,PDB,INPCRD) as a MDAnalysis Universe,
checks if it can be loaded. Needs to be run before the equivalent function
topol.load_trajectory() and provides the snapshot that is going to be used
for final residue pl... | python | def load_topology(self,topology):
"""
Loads the topology file (e.g. GRO,PDB,INPCRD) as a MDAnalysis Universe,
checks if it can be loaded. Needs to be run before the equivalent function
topol.load_trajectory() and provides the snapshot that is going to be used
for final residue pl... | [
"def",
"load_topology",
"(",
"self",
",",
"topology",
")",
":",
"try",
":",
"self",
".",
"universe",
"=",
"MDAnalysis",
".",
"Universe",
"(",
"topology",
")",
"except",
"ValueError",
":",
"print",
"\"Check your topology file - it is either missing or misspelled.\"",
... | Loads the topology file (e.g. GRO,PDB,INPCRD) as a MDAnalysis Universe,
checks if it can be loaded. Needs to be run before the equivalent function
topol.load_trajectory() and provides the snapshot that is going to be used
for final residue placement - i.e. the residue coordinates for placement
... | [
"Loads",
"the",
"topology",
"file",
"(",
"e",
".",
"g",
".",
"GRO",
"PDB",
"INPCRD",
")",
"as",
"a",
"MDAnalysis",
"Universe",
"checks",
"if",
"it",
"can",
"be",
"loaded",
".",
"Needs",
"to",
"be",
"run",
"before",
"the",
"equivalent",
"function",
"top... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L21-L38 | train | Loads the topology file and stores the resulting Universe object in self. uni |
ldomic/lintools | lintools/data.py | Data.load_trajectory | def load_trajectory(self,trajectory):
"""
Loads the trajectory files e.g. XTC, DCD, TRJ together with the topology
file as a MDAnalysis Universe. This will only be run if a trajectory has
been submitted for analysis.
Takes:
* topology * - a topology file e.g. ... | python | def load_trajectory(self,trajectory):
"""
Loads the trajectory files e.g. XTC, DCD, TRJ together with the topology
file as a MDAnalysis Universe. This will only be run if a trajectory has
been submitted for analysis.
Takes:
* topology * - a topology file e.g. ... | [
"def",
"load_trajectory",
"(",
"self",
",",
"trajectory",
")",
":",
"try",
":",
"self",
".",
"universe",
".",
"load_new",
"(",
"trajectory",
")",
"except",
"IOError",
",",
"ValueError",
":",
"print",
"\"Check you trajectory file \"",
"+",
"trajectory",
"+",
"\... | Loads the trajectory files e.g. XTC, DCD, TRJ together with the topology
file as a MDAnalysis Universe. This will only be run if a trajectory has
been submitted for analysis.
Takes:
* topology * - a topology file e.g. GRO, PDB, INPCRD, CARD, DMS
* trajectory *... | [
"Loads",
"the",
"trajectory",
"files",
"e",
".",
"g",
".",
"XTC",
"DCD",
"TRJ",
"together",
"with",
"the",
"topology",
"file",
"as",
"a",
"MDAnalysis",
"Universe",
".",
"This",
"will",
"only",
"be",
"run",
"if",
"a",
"trajectory",
"has",
"been",
"submitt... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L39-L55 | train | Load the trajectory file into the Universe and the topology. |
ldomic/lintools | lintools/data.py | Data.load_mol | def load_mol(self, mol_file):
"""Loads a MOL file of the ligand (submitted by user) into RDKit environment.
Takes:
* mol_file * - user submitted MOL file of the ligand
Output:
* self.mol_mda * - the ligand as MDAnalysis Universe,
* self.mol... | python | def load_mol(self, mol_file):
"""Loads a MOL file of the ligand (submitted by user) into RDKit environment.
Takes:
* mol_file * - user submitted MOL file of the ligand
Output:
* self.mol_mda * - the ligand as MDAnalysis Universe,
* self.mol... | [
"def",
"load_mol",
"(",
"self",
",",
"mol_file",
")",
":",
"#Check if MOL file has been provided correctly and can be loaded in MDAnalysis",
"if",
"mol_file",
"is",
"None",
":",
"mol_file",
"=",
"\"lig.mol\"",
"self",
".",
"mol",
"=",
"Chem",
".",
"MolFromMolFile",
"(... | Loads a MOL file of the ligand (submitted by user) into RDKit environment.
Takes:
* mol_file * - user submitted MOL file of the ligand
Output:
* self.mol_mda * - the ligand as MDAnalysis Universe,
* self.mol * - the ligand in RDKit environment as M... | [
"Loads",
"a",
"MOL",
"file",
"of",
"the",
"ligand",
"(",
"submitted",
"by",
"user",
")",
"into",
"RDKit",
"environment",
".",
"Takes",
":",
"*",
"mol_file",
"*",
"-",
"user",
"submitted",
"MOL",
"file",
"of",
"the",
"ligand",
"Output",
":",
"*",
"self"... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L56-L73 | train | Loads a MOL file into the RDKit environment. |
ldomic/lintools | lintools/data.py | Data.rename_ligand | def rename_ligand(self,ligand_name,mol_file):
"""
Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection ... | python | def rename_ligand(self,ligand_name,mol_file):
"""
Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection ... | [
"def",
"rename_ligand",
"(",
"self",
",",
"ligand_name",
",",
"mol_file",
")",
":",
"self",
".",
"universe",
".",
"ligand",
"=",
"self",
".",
"universe",
".",
"select_atoms",
"(",
"ligand_name",
")",
"#Both resname and resnames options need to be reset in order for co... | Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection for the ligand selected by user
Output:
... | [
"Get",
"an",
"atom",
"selection",
"for",
"the",
"selected",
"from",
"both",
"topology",
"and",
"trajectory",
".",
"Rename",
"the",
"ligand",
"LIG",
"to",
"help",
"with",
"ligand",
"names",
"that",
"are",
"not",
"standard",
"e",
".",
"g",
".",
"contain",
... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L75-L94 | train | Rename the ligand with the given ligand name. |
ldomic/lintools | lintools/data.py | Data.renumber_system | def renumber_system(self, offset):
"""
The residue numbers of the protein can be reformated in case of misallignment with the convention.
Takes:
* offset * - a number that represents by how many residues the numbering has to be shifted.
"""
self.universe.pro... | python | def renumber_system(self, offset):
"""
The residue numbers of the protein can be reformated in case of misallignment with the convention.
Takes:
* offset * - a number that represents by how many residues the numbering has to be shifted.
"""
self.universe.pro... | [
"def",
"renumber_system",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"universe",
".",
"protein",
"=",
"self",
".",
"universe",
".",
"select_atoms",
"(",
"\"protein\"",
")",
"self",
".",
"universe",
".",
"protein",
".",
"residues",
".",
"resids",
... | The residue numbers of the protein can be reformated in case of misallignment with the convention.
Takes:
* offset * - a number that represents by how many residues the numbering has to be shifted. | [
"The",
"residue",
"numbers",
"of",
"the",
"protein",
"can",
"be",
"reformated",
"in",
"case",
"of",
"misallignment",
"with",
"the",
"convention",
".",
"Takes",
":",
"*",
"offset",
"*",
"-",
"a",
"number",
"that",
"represents",
"by",
"how",
"many",
"residue... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L97-L105 | train | renumber the system with the given number |
ldomic/lintools | lintools/data.py | Data.define_residues_for_plotting_topology | def define_residues_for_plotting_topology(self,cutoff):
"""
This function defines the residues for plotting in case only a topology file has been submitted.
In this case the residence time analysis in not necessary and it is enough just to find all
residues within a cutoff distance.
... | python | def define_residues_for_plotting_topology(self,cutoff):
"""
This function defines the residues for plotting in case only a topology file has been submitted.
In this case the residence time analysis in not necessary and it is enough just to find all
residues within a cutoff distance.
... | [
"def",
"define_residues_for_plotting_topology",
"(",
"self",
",",
"cutoff",
")",
":",
"#self.protein_selection = self.universe.select_atoms('all and around '+str(cutoff)+' (segid '+str(self.universe.ligand.segids[0])+' and resid '+str(self.universe.ligand.resids[0])+')')",
"#The previous line was ... | This function defines the residues for plotting in case only a topology file has been submitted.
In this case the residence time analysis in not necessary and it is enough just to find all
residues within a cutoff distance.
Takes:
* cutoff * - cutoff distance in angstroms tha... | [
"This",
"function",
"defines",
"the",
"residues",
"for",
"plotting",
"in",
"case",
"only",
"a",
"topology",
"file",
"has",
"been",
"submitted",
".",
"In",
"this",
"case",
"the",
"residence",
"time",
"analysis",
"in",
"not",
"necessary",
"and",
"it",
"is",
... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L107-L127 | train | This function defines the residues for plotting in case only a topology file has been submitted. This function defines the residues for plotting in case only a topology file has been submitted. |
ldomic/lintools | lintools/data.py | Data.find_the_closest_atoms | def find_the_closest_atoms(self,topology):
"""
This function defines the ligand atoms that are closest to the residues that will be plotted
in the final graph.
"""
# The measurements are made to ligand molecule without hydrogen atoms (ligand_noH) because the
# hydrogen a... | python | def find_the_closest_atoms(self,topology):
"""
This function defines the ligand atoms that are closest to the residues that will be plotted
in the final graph.
"""
# The measurements are made to ligand molecule without hydrogen atoms (ligand_noH) because the
# hydrogen a... | [
"def",
"find_the_closest_atoms",
"(",
"self",
",",
"topology",
")",
":",
"# The measurements are made to ligand molecule without hydrogen atoms (ligand_noH) because the",
"# hydrogen atoms are not plotted in the final graph",
"self",
".",
"universe",
".",
"load_new",
"(",
"topology",... | This function defines the ligand atoms that are closest to the residues that will be plotted
in the final graph. | [
"This",
"function",
"defines",
"the",
"ligand",
"atoms",
"that",
"are",
"closest",
"to",
"the",
"residues",
"that",
"will",
"be",
"plotted",
"in",
"the",
"final",
"graph",
"."
] | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L130-L152 | train | This function defines the ligand atoms that are closest to the residues that will be plotted in the final graph. This function defines the ligand atoms that are closest to the residues that will be plotted in the final graph. This function defines the ligand atoms that are not closest to the residues that will be plott... |
ldomic/lintools | lintools/data.py | Data.load_data | def load_data(self, topology, mol_file, ligand_name, offset=0):
"""
This function loads all relevant data - except trajectories since those are dealt with one at a time.
Therefore, this process only needs to be done once, and every time a trajectory needs to be loaded, it
can be loaded s... | python | def load_data(self, topology, mol_file, ligand_name, offset=0):
"""
This function loads all relevant data - except trajectories since those are dealt with one at a time.
Therefore, this process only needs to be done once, and every time a trajectory needs to be loaded, it
can be loaded s... | [
"def",
"load_data",
"(",
"self",
",",
"topology",
",",
"mol_file",
",",
"ligand_name",
",",
"offset",
"=",
"0",
")",
":",
"self",
".",
"load_topology",
"(",
"topology",
")",
"self",
".",
"renumber_system",
"(",
"offset",
")",
"self",
".",
"rename_ligand",
... | This function loads all relevant data - except trajectories since those are dealt with one at a time.
Therefore, this process only needs to be done once, and every time a trajectory needs to be loaded, it
can be loaded seperataly and the Data object can be shared across LINTools processes. | [
"This",
"function",
"loads",
"all",
"relevant",
"data",
"-",
"except",
"trajectories",
"since",
"those",
"are",
"dealt",
"with",
"one",
"at",
"a",
"time",
".",
"Therefore",
"this",
"process",
"only",
"needs",
"to",
"be",
"done",
"once",
"and",
"every",
"ti... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L153-L163 | train | This function loads all relevant data and creates a Data object |
ldomic/lintools | lintools/data.py | Data.analyse_topology | def analyse_topology(self,topology, cutoff=3.5):
"""
In case user wants to analyse only a single topology file, this process will determine the residues
that should be plotted and find the ligand atoms closest to these residues.
"""
self.define_residues_for_plotting_topology(cut... | python | def analyse_topology(self,topology, cutoff=3.5):
"""
In case user wants to analyse only a single topology file, this process will determine the residues
that should be plotted and find the ligand atoms closest to these residues.
"""
self.define_residues_for_plotting_topology(cut... | [
"def",
"analyse_topology",
"(",
"self",
",",
"topology",
",",
"cutoff",
"=",
"3.5",
")",
":",
"self",
".",
"define_residues_for_plotting_topology",
"(",
"cutoff",
")",
"self",
".",
"find_the_closest_atoms",
"(",
"topology",
")"
] | In case user wants to analyse only a single topology file, this process will determine the residues
that should be plotted and find the ligand atoms closest to these residues. | [
"In",
"case",
"user",
"wants",
"to",
"analyse",
"only",
"a",
"single",
"topology",
"file",
"this",
"process",
"will",
"determine",
"the",
"residues",
"that",
"should",
"be",
"plotted",
"and",
"find",
"the",
"ligand",
"atoms",
"closest",
"to",
"these",
"resid... | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L165-L172 | train | This function will be called by the plot_topology method of the ligand class. It will determine the residues that are closest to these residues and then find the residues that are plotted. |
robinandeer/puzzle | puzzle/utils/headers.py | get_header | def get_header(vcf_file_path):
"""Parse the header and return a header object
Args:
vcf_file_path(str): Path to vcf
Returns:
head: A HeaderParser object
"""
logger.info("Parsing header of file {0}".format(vcf_file_path))
head = HeaderParser()
handle = get_vc... | python | def get_header(vcf_file_path):
"""Parse the header and return a header object
Args:
vcf_file_path(str): Path to vcf
Returns:
head: A HeaderParser object
"""
logger.info("Parsing header of file {0}".format(vcf_file_path))
head = HeaderParser()
handle = get_vc... | [
"def",
"get_header",
"(",
"vcf_file_path",
")",
":",
"logger",
".",
"info",
"(",
"\"Parsing header of file {0}\"",
".",
"format",
"(",
"vcf_file_path",
")",
")",
"head",
"=",
"HeaderParser",
"(",
")",
"handle",
"=",
"get_vcf_handle",
"(",
"infile",
"=",
"vcf_f... | Parse the header and return a header object
Args:
vcf_file_path(str): Path to vcf
Returns:
head: A HeaderParser object | [
"Parse",
"the",
"header",
"and",
"return",
"a",
"header",
"object"
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/utils/headers.py#L20-L45 | train | Parse the header and return a header object |
alphagov/performanceplatform-collector | performanceplatform/collector/pingdom/__init__.py | parse_time_range | def parse_time_range(start_dt, end_dt):
"""
Convert the start/end datetimes specified by the user, specifically:
- truncate any minutes/seconds
- for a missing end time, use start + 24 hours
- for a missing start time, use end - 24 hours
- for missing start and end, use the last 24 hours
"""... | python | def parse_time_range(start_dt, end_dt):
"""
Convert the start/end datetimes specified by the user, specifically:
- truncate any minutes/seconds
- for a missing end time, use start + 24 hours
- for a missing start time, use end - 24 hours
- for missing start and end, use the last 24 hours
"""... | [
"def",
"parse_time_range",
"(",
"start_dt",
",",
"end_dt",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"start_dt",
"and",
"not",
"end_dt",
":",
"end_dt",
"=",
"now",
"elif",
"end_dt",
"and",
"not",
"start_dt",
":",
"start_dt",
"=",
"_... | Convert the start/end datetimes specified by the user, specifically:
- truncate any minutes/seconds
- for a missing end time, use start + 24 hours
- for a missing start time, use end - 24 hours
- for missing start and end, use the last 24 hours | [
"Convert",
"the",
"start",
"/",
"end",
"datetimes",
"specified",
"by",
"the",
"user",
"specifically",
":",
"-",
"truncate",
"any",
"minutes",
"/",
"seconds",
"-",
"for",
"a",
"missing",
"end",
"time",
"use",
"start",
"+",
"24",
"hours",
"-",
"for",
"a",
... | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/pingdom/__init__.py#L26-L46 | train | Convert start and end datetimes to a tuple of time range. |
DarkEnergySurvey/ugali | ugali/analysis/kernel.py | Kernel.integrate | def integrate(self, rmin=0, rmax=np.inf):
"""
Calculate the 2D integral of the 1D surface brightness profile
(i.e, the flux) between rmin and rmax (elliptical radii).
Parameters:
-----------
rmin : minimum integration radius (deg)
rmax : maximum integration rad... | python | def integrate(self, rmin=0, rmax=np.inf):
"""
Calculate the 2D integral of the 1D surface brightness profile
(i.e, the flux) between rmin and rmax (elliptical radii).
Parameters:
-----------
rmin : minimum integration radius (deg)
rmax : maximum integration rad... | [
"def",
"integrate",
"(",
"self",
",",
"rmin",
"=",
"0",
",",
"rmax",
"=",
"np",
".",
"inf",
")",
":",
"if",
"rmin",
"<",
"0",
":",
"raise",
"Exception",
"(",
"'rmin must be >= 0'",
")",
"integrand",
"=",
"lambda",
"r",
":",
"self",
".",
"_pdf",
"("... | Calculate the 2D integral of the 1D surface brightness profile
(i.e, the flux) between rmin and rmax (elliptical radii).
Parameters:
-----------
rmin : minimum integration radius (deg)
rmax : maximum integration radius (deg)
Returns:
--------
integral ... | [
"Calculate",
"the",
"2D",
"integral",
"of",
"the",
"1D",
"surface",
"brightness",
"profile",
"(",
"i",
".",
"e",
"the",
"flux",
")",
"between",
"rmin",
"and",
"rmax",
"(",
"elliptical",
"radii",
")",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/kernel.py#L71-L87 | train | Calculates the 2D integral of the surface brightness profile
. |
DarkEnergySurvey/ugali | ugali/analysis/kernel.py | EllipticalKernel.sample_radius | def sample_radius(self, n):
"""
Sample the radial distribution (deg) from the 2D stellar density.
Output is elliptical radius in true projected coordinates.
"""
edge = self.edge if self.edge<20*self.extension else 20*self.extension
radius = np.linspace(0, edge, 1.e5)
... | python | def sample_radius(self, n):
"""
Sample the radial distribution (deg) from the 2D stellar density.
Output is elliptical radius in true projected coordinates.
"""
edge = self.edge if self.edge<20*self.extension else 20*self.extension
radius = np.linspace(0, edge, 1.e5)
... | [
"def",
"sample_radius",
"(",
"self",
",",
"n",
")",
":",
"edge",
"=",
"self",
".",
"edge",
"if",
"self",
".",
"edge",
"<",
"20",
"*",
"self",
".",
"extension",
"else",
"20",
"*",
"self",
".",
"extension",
"radius",
"=",
"np",
".",
"linspace",
"(",
... | Sample the radial distribution (deg) from the 2D stellar density.
Output is elliptical radius in true projected coordinates. | [
"Sample",
"the",
"radial",
"distribution",
"(",
"deg",
")",
"from",
"the",
"2D",
"stellar",
"density",
".",
"Output",
"is",
"elliptical",
"radius",
"in",
"true",
"projected",
"coordinates",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/kernel.py#L182-L194 | train | Sample the radial distribution from the 2D stellar density. |
DarkEnergySurvey/ugali | ugali/analysis/kernel.py | EllipticalKernel.sample_lonlat | def sample_lonlat(self, n):
"""
Sample 2D distribution of points in lon, lat
"""
# From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form
# However, Martin et al. (2009) use PA theta "from North to East"
# Definition of phi (position angle) is offset by pi/4
... | python | def sample_lonlat(self, n):
"""
Sample 2D distribution of points in lon, lat
"""
# From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form
# However, Martin et al. (2009) use PA theta "from North to East"
# Definition of phi (position angle) is offset by pi/4
... | [
"def",
"sample_lonlat",
"(",
"self",
",",
"n",
")",
":",
"# From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form",
"# However, Martin et al. (2009) use PA theta \"from North to East\"",
"# Definition of phi (position angle) is offset by pi/4",
"# Definition of t (eccentric anamoly... | Sample 2D distribution of points in lon, lat | [
"Sample",
"2D",
"distribution",
"of",
"points",
"in",
"lon",
"lat"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/kernel.py#L196-L222 | train | Sample 2D distribution of points in lon lat |
alphagov/performanceplatform-collector | performanceplatform/collector/ga/plugins/aggregate.py | group | def group(iterable, key):
"""
groupby which sorts the input, discards the key and returns the output
as a sequence of lists.
"""
for _, grouped in groupby(sorted(iterable, key=key), key=key):
yield list(grouped) | python | def group(iterable, key):
"""
groupby which sorts the input, discards the key and returns the output
as a sequence of lists.
"""
for _, grouped in groupby(sorted(iterable, key=key), key=key):
yield list(grouped) | [
"def",
"group",
"(",
"iterable",
",",
"key",
")",
":",
"for",
"_",
",",
"grouped",
"in",
"groupby",
"(",
"sorted",
"(",
"iterable",
",",
"key",
"=",
"key",
")",
",",
"key",
"=",
"key",
")",
":",
"yield",
"list",
"(",
"grouped",
")"
] | groupby which sorts the input, discards the key and returns the output
as a sequence of lists. | [
"groupby",
"which",
"sorts",
"the",
"input",
"discards",
"the",
"key",
"and",
"returns",
"the",
"output",
"as",
"a",
"sequence",
"of",
"lists",
"."
] | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L41-L47 | train | groupby which sorts the input discards the key and returns the output
as a sequence of lists. |
alphagov/performanceplatform-collector | performanceplatform/collector/ga/plugins/aggregate.py | aggregate_count | def aggregate_count(keyname):
"""
Straightforward sum of the given keyname.
"""
def inner(docs):
return sum(doc[keyname] for doc in docs)
return keyname, inner | python | def aggregate_count(keyname):
"""
Straightforward sum of the given keyname.
"""
def inner(docs):
return sum(doc[keyname] for doc in docs)
return keyname, inner | [
"def",
"aggregate_count",
"(",
"keyname",
")",
":",
"def",
"inner",
"(",
"docs",
")",
":",
"return",
"sum",
"(",
"doc",
"[",
"keyname",
"]",
"for",
"doc",
"in",
"docs",
")",
"return",
"keyname",
",",
"inner"
] | Straightforward sum of the given keyname. | [
"Straightforward",
"sum",
"of",
"the",
"given",
"keyname",
"."
] | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L50-L57 | train | Aggregate the count of the given keyname. |
alphagov/performanceplatform-collector | performanceplatform/collector/ga/plugins/aggregate.py | aggregate_rate | def aggregate_rate(rate_key, count_key):
"""
Compute an aggregate rate for `rate_key` weighted according to
`count_rate`.
"""
def inner(docs):
total = sum(doc[count_key] for doc in docs)
weighted_total = sum(doc[rate_key] * doc[count_key] for doc in docs)
total_rate = weighte... | python | def aggregate_rate(rate_key, count_key):
"""
Compute an aggregate rate for `rate_key` weighted according to
`count_rate`.
"""
def inner(docs):
total = sum(doc[count_key] for doc in docs)
weighted_total = sum(doc[rate_key] * doc[count_key] for doc in docs)
total_rate = weighte... | [
"def",
"aggregate_rate",
"(",
"rate_key",
",",
"count_key",
")",
":",
"def",
"inner",
"(",
"docs",
")",
":",
"total",
"=",
"sum",
"(",
"doc",
"[",
"count_key",
"]",
"for",
"doc",
"in",
"docs",
")",
"weighted_total",
"=",
"sum",
"(",
"doc",
"[",
"rate... | Compute an aggregate rate for `rate_key` weighted according to
`count_rate`. | [
"Compute",
"an",
"aggregate",
"rate",
"for",
"rate_key",
"weighted",
"according",
"to",
"count_rate",
"."
] | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L60-L71 | train | Compute an aggregate rate for rate_key weighted according to count_rate. |
alphagov/performanceplatform-collector | performanceplatform/collector/ga/plugins/aggregate.py | make_aggregate | def make_aggregate(docs, aggregations):
"""
Given `docs` and `aggregations` return a single document with the
aggregations applied.
"""
new_doc = dict(docs[0])
for keyname, aggregation_function in aggregations:
new_doc[keyname] = aggregation_function(docs)
return new_doc | python | def make_aggregate(docs, aggregations):
"""
Given `docs` and `aggregations` return a single document with the
aggregations applied.
"""
new_doc = dict(docs[0])
for keyname, aggregation_function in aggregations:
new_doc[keyname] = aggregation_function(docs)
return new_doc | [
"def",
"make_aggregate",
"(",
"docs",
",",
"aggregations",
")",
":",
"new_doc",
"=",
"dict",
"(",
"docs",
"[",
"0",
"]",
")",
"for",
"keyname",
",",
"aggregation_function",
"in",
"aggregations",
":",
"new_doc",
"[",
"keyname",
"]",
"=",
"aggregation_function... | Given `docs` and `aggregations` return a single document with the
aggregations applied. | [
"Given",
"docs",
"and",
"aggregations",
"return",
"a",
"single",
"document",
"with",
"the",
"aggregations",
"applied",
"."
] | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L74-L84 | train | Given a list of documents and aggregations return a single document with the aggregations applied. |
MasterKale/django-cra-helper | cra_helper/templatetags/cra_helper_tags.py | json | def json(value):
'''
Sanitize the JSON string using the Bleach HTML tag remover
'''
uncleaned = jsonlib.dumps(value)
clean = bleach.clean(uncleaned)
return mark_safe(clean) | python | def json(value):
'''
Sanitize the JSON string using the Bleach HTML tag remover
'''
uncleaned = jsonlib.dumps(value)
clean = bleach.clean(uncleaned)
return mark_safe(clean) | [
"def",
"json",
"(",
"value",
")",
":",
"uncleaned",
"=",
"jsonlib",
".",
"dumps",
"(",
"value",
")",
"clean",
"=",
"bleach",
".",
"clean",
"(",
"uncleaned",
")",
"return",
"mark_safe",
"(",
"clean",
")"
] | Sanitize the JSON string using the Bleach HTML tag remover | [
"Sanitize",
"the",
"JSON",
"string",
"using",
"the",
"Bleach",
"HTML",
"tag",
"remover"
] | ba50c643c181a18b80ee9bbdbea74b58abd6daad | https://github.com/MasterKale/django-cra-helper/blob/ba50c643c181a18b80ee9bbdbea74b58abd6daad/cra_helper/templatetags/cra_helper_tags.py#L15-L21 | train | Returns the JSON string as a string using the Bleach HTML tag remover
|
cfusting/fastgp | fastgp/algorithms/afpo.py | find_pareto_front | def find_pareto_front(population):
"""Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals
"""
pareto_front = set(range(len(population)))
for i in range(len(population)):
... | python | def find_pareto_front(population):
"""Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals
"""
pareto_front = set(range(len(population)))
for i in range(len(population)):
... | [
"def",
"find_pareto_front",
"(",
"population",
")",
":",
"pareto_front",
"=",
"set",
"(",
"range",
"(",
"len",
"(",
"population",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"population",
")",
")",
":",
"if",
"i",
"not",
"in",
"pareto_... | Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals | [
"Finds",
"a",
"subset",
"of",
"nondominated",
"individuals",
"in",
"a",
"given",
"list"
] | 6cf3c5d14abedaea064feef6ca434ee806a11756 | https://github.com/cfusting/fastgp/blob/6cf3c5d14abedaea064feef6ca434ee806a11756/fastgp/algorithms/afpo.py#L28-L53 | train | Finds a subset of nondominated individuals in a given list of individuals |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Lexer.t_ID | def t_ID(self, t):
r"""[a-zA-Z_][a-zA-Z_0-9]*"""
# If the value is a reserved name, give it the appropriate type (not ID)
if t.value in self.reserved:
t.type = self.reserved[t.value]
# If it's a function, give it the FUNC type
elif t.value in self.functions:
... | python | def t_ID(self, t):
r"""[a-zA-Z_][a-zA-Z_0-9]*"""
# If the value is a reserved name, give it the appropriate type (not ID)
if t.value in self.reserved:
t.type = self.reserved[t.value]
# If it's a function, give it the FUNC type
elif t.value in self.functions:
... | [
"def",
"t_ID",
"(",
"self",
",",
"t",
")",
":",
"# If the value is a reserved name, give it the appropriate type (not ID)",
"if",
"t",
".",
"value",
"in",
"self",
".",
"reserved",
":",
"t",
".",
"type",
"=",
"self",
".",
"reserved",
"[",
"t",
".",
"value",
"... | r"""[a-zA-Z_][a-zA-Z_0-9]* | [
"r",
"[",
"a",
"-",
"zA",
"-",
"Z_",
"]",
"[",
"a",
"-",
"zA",
"-",
"Z_0",
"-",
"9",
"]",
"*"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L66-L77 | train | t_ID is the ID of the resource t_name is the name of the resource t_function is the function t_ID is the function t_function is the function t_ID is the name of the resource t_ID |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.p_binary_operators | def p_binary_operators(self, p):
"""
conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expre... | python | def p_binary_operators(self, p):
"""
conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expre... | [
"def",
"p_binary_operators",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Instruction",
"(",
"\"op(left, right)\"",
",",
"context",
"=",
"{",
"'op'",
":",
"self",
".",
"binary_operators",
"[",
"p",
"[",
"2",
"]",
"]",
",",
"'left'",
":"... | conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expression
| condition EQ expression
... | [
"conditional",
":",
"conditional",
"AND",
"condition",
"|",
"conditional",
"OR",
"condition",
"condition",
":",
"condition",
"LTE",
"expression",
"|",
"condition",
"GTE",
"expression",
"|",
"condition",
"LT",
"expression",
"|",
"condition",
"GT",
"expression",
"|"... | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L135-L152 | train | The binary operators are used to generate the conditional and the term and the term are used to generate the conditional. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.p_factor_unary_operators | def p_factor_unary_operators(self, p):
"""
term : SUB factor
| ADD factor
"""
p[0] = p[2]
if p[1] == '-':
p[0] = Instruction('-x', context={'x': p[0]}) | python | def p_factor_unary_operators(self, p):
"""
term : SUB factor
| ADD factor
"""
p[0] = p[2]
if p[1] == '-':
p[0] = Instruction('-x', context={'x': p[0]}) | [
"def",
"p_factor_unary_operators",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"2",
"]",
"if",
"p",
"[",
"1",
"]",
"==",
"'-'",
":",
"p",
"[",
"0",
"]",
"=",
"Instruction",
"(",
"'-x'",
",",
"context",
"=",
"{",
"'x'",... | term : SUB factor
| ADD factor | [
"term",
":",
"SUB",
"factor",
"|",
"ADD",
"factor"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L182-L190 | train | A factor operator for duplicate - and - |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.p_factor_id | def p_factor_id(self, p):
"""
factor : ID
"""
def resolve_id(key, context):
try:
return context[key]
except KeyError:
raise NameError("name '{}' is not defined".format(key))
p[0] = Instruction('resolve_id(key, context)', c... | python | def p_factor_id(self, p):
"""
factor : ID
"""
def resolve_id(key, context):
try:
return context[key]
except KeyError:
raise NameError("name '{}' is not defined".format(key))
p[0] = Instruction('resolve_id(key, context)', c... | [
"def",
"p_factor_id",
"(",
"self",
",",
"p",
")",
":",
"def",
"resolve_id",
"(",
"key",
",",
"context",
")",
":",
"try",
":",
"return",
"context",
"[",
"key",
"]",
"except",
"KeyError",
":",
"raise",
"NameError",
"(",
"\"name '{}' is not defined\"",
".",
... | factor : ID | [
"factor",
":",
"ID"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L235-L250 | train | Add a factor ID instruction to the Instruction list p. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.p_fn | def p_fn(self, p):
"""
fn : FUNC LPAREN arguments RPAREN
"""
fn = getattr(self, 'fn_{0}'.format(p[1]))
p[0] = Instruction('fn(*[x.execute() if isinstance(x, Instruction) else x for x in args])', context={
'fn': fn,
'args': p[3],
'Instruction':... | python | def p_fn(self, p):
"""
fn : FUNC LPAREN arguments RPAREN
"""
fn = getattr(self, 'fn_{0}'.format(p[1]))
p[0] = Instruction('fn(*[x.execute() if isinstance(x, Instruction) else x for x in args])', context={
'fn': fn,
'args': p[3],
'Instruction':... | [
"def",
"p_fn",
"(",
"self",
",",
"p",
")",
":",
"fn",
"=",
"getattr",
"(",
"self",
",",
"'fn_{0}'",
".",
"format",
"(",
"p",
"[",
"1",
"]",
")",
")",
"p",
"[",
"0",
"]",
"=",
"Instruction",
"(",
"'fn(*[x.execute() if isinstance(x, Instruction) else x for... | fn : FUNC LPAREN arguments RPAREN | [
"fn",
":",
"FUNC",
"LPAREN",
"arguments",
"RPAREN"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L259-L269 | train | P FUNC LPAREN arguments RPAREN Instruction |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.p_factor_item | def p_factor_item(self, p):
"""
factor : factor LBRACK conditional RBRACK
"""
def resolve_item(obj, index):
if is_ndarray(obj) or isinstance(obj, (list, tuple)):
if not isinstance(index, int):
raise TypeError("Not a valid array index: '{}'... | python | def p_factor_item(self, p):
"""
factor : factor LBRACK conditional RBRACK
"""
def resolve_item(obj, index):
if is_ndarray(obj) or isinstance(obj, (list, tuple)):
if not isinstance(index, int):
raise TypeError("Not a valid array index: '{}'... | [
"def",
"p_factor_item",
"(",
"self",
",",
"p",
")",
":",
"def",
"resolve_item",
"(",
"obj",
",",
"index",
")",
":",
"if",
"is_ndarray",
"(",
"obj",
")",
"or",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"not",
"... | factor : factor LBRACK conditional RBRACK | [
"factor",
":",
"factor",
"LBRACK",
"conditional",
"RBRACK"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L285-L308 | train | A factor item instruction. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser._to_ndarray | def _to_ndarray(self, a):
"""Casts Python lists and tuples to a numpy array or raises an AssertionError."""
if isinstance(a, (list, tuple)):
a = numpy.array(a)
if not is_ndarray(a):
raise TypeError("Expected an ndarray but got object of type '{}' instead".format(type(a)... | python | def _to_ndarray(self, a):
"""Casts Python lists and tuples to a numpy array or raises an AssertionError."""
if isinstance(a, (list, tuple)):
a = numpy.array(a)
if not is_ndarray(a):
raise TypeError("Expected an ndarray but got object of type '{}' instead".format(type(a)... | [
"def",
"_to_ndarray",
"(",
"self",
",",
"a",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"a",
"=",
"numpy",
".",
"array",
"(",
"a",
")",
"if",
"not",
"is_ndarray",
"(",
"a",
")",
":",
"raise",
"TypeErr... | Casts Python lists and tuples to a numpy array or raises an AssertionError. | [
"Casts",
"Python",
"lists",
"and",
"tuples",
"to",
"a",
"numpy",
"array",
"or",
"raises",
"an",
"AssertionError",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L310-L319 | train | Casts Python lists and tuples to a numpy array. Raises an AssertionError if the input is not an array. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_abs | def fn_abs(self, value):
"""
Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number.
"""
if is_ndarray(value):
return numpy.absolute(value)
else:
return abs(value) | python | def fn_abs(self, value):
"""
Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number.
"""
if is_ndarray(value):
return numpy.absolute(value)
else:
return abs(value) | [
"def",
"fn_abs",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
":",
"return",
"numpy",
".",
"absolute",
"(",
"value",
")",
"else",
":",
"return",
"abs",
"(",
"value",
")"
] | Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number. | [
"Return",
"the",
"absolute",
"value",
"of",
"a",
"number",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L321-L332 | train | Returns the absolute value of a number. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_get_mask | def fn_get_mask(self, value):
"""
Return an array mask.
:param value: The array.
:return: The array mask.
"""
value = self._to_ndarray(value)
if numpy.ma.is_masked(value):
return value.mask
else:
return numpy.zeros(value.shape).a... | python | def fn_get_mask(self, value):
"""
Return an array mask.
:param value: The array.
:return: The array mask.
"""
value = self._to_ndarray(value)
if numpy.ma.is_masked(value):
return value.mask
else:
return numpy.zeros(value.shape).a... | [
"def",
"fn_get_mask",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"_to_ndarray",
"(",
"value",
")",
"if",
"numpy",
".",
"ma",
".",
"is_masked",
"(",
"value",
")",
":",
"return",
"value",
".",
"mask",
"else",
":",
"return",
"numpy"... | Return an array mask.
:param value: The array.
:return: The array mask. | [
"Return",
"an",
"array",
"mask",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L334-L347 | train | Returns an array mask. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_min | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | python | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | [
"def",
"fn_min",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanmin",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array. | [
"Return",
"the",
"minimum",
"of",
"an",
"array",
"ignoring",
"any",
"NaNs",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L349-L357 | train | Returns the minimum value of an array ignoring any NaNs. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_max | def fn_max(self, a, axis=None):
"""
Return the maximum of an array, ignoring any NaNs.
:param a: The array.
:return: The maximum value of the array
"""
return numpy.nanmax(self._to_ndarray(a), axis=axis) | python | def fn_max(self, a, axis=None):
"""
Return the maximum of an array, ignoring any NaNs.
:param a: The array.
:return: The maximum value of the array
"""
return numpy.nanmax(self._to_ndarray(a), axis=axis) | [
"def",
"fn_max",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanmax",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Return the maximum of an array, ignoring any NaNs.
:param a: The array.
:return: The maximum value of the array | [
"Return",
"the",
"maximum",
"of",
"an",
"array",
"ignoring",
"any",
"NaNs",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L370-L378 | train | Returns the maximum value of an array ignoring any NaNs. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_median | def fn_median(self, a, axis=None):
"""
Compute the median of an array, ignoring NaNs.
:param a: The array.
:return: The median value of the array.
"""
return numpy.nanmedian(self._to_ndarray(a), axis=axis) | python | def fn_median(self, a, axis=None):
"""
Compute the median of an array, ignoring NaNs.
:param a: The array.
:return: The median value of the array.
"""
return numpy.nanmedian(self._to_ndarray(a), axis=axis) | [
"def",
"fn_median",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanmedian",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Compute the median of an array, ignoring NaNs.
:param a: The array.
:return: The median value of the array. | [
"Compute",
"the",
"median",
"of",
"an",
"array",
"ignoring",
"NaNs",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L380-L388 | train | Compute the median of an array ignoring NaNs. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_mean | def fn_mean(self, a, axis=None):
"""
Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array.
"""
return numpy.nanmean(self._to_ndarray(a), axis=axis) | python | def fn_mean(self, a, axis=None):
"""
Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array.
"""
return numpy.nanmean(self._to_ndarray(a), axis=axis) | [
"def",
"fn_mean",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanmean",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array. | [
"Compute",
"the",
"arithmetic",
"mean",
"of",
"an",
"array",
"ignoring",
"NaNs",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L390-L398 | train | Compute the arithmetic mean of an array ignoring NaNs. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_std | def fn_std(self, a, axis=None):
"""
Compute the standard deviation of an array, ignoring NaNs.
:param a: The array.
:return: The standard deviation of the array.
"""
return numpy.nanstd(self._to_ndarray(a), axis=axis) | python | def fn_std(self, a, axis=None):
"""
Compute the standard deviation of an array, ignoring NaNs.
:param a: The array.
:return: The standard deviation of the array.
"""
return numpy.nanstd(self._to_ndarray(a), axis=axis) | [
"def",
"fn_std",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanstd",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Compute the standard deviation of an array, ignoring NaNs.
:param a: The array.
:return: The standard deviation of the array. | [
"Compute",
"the",
"standard",
"deviation",
"of",
"an",
"array",
"ignoring",
"NaNs",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L400-L408 | train | Compute the standard deviation of an array ignoring NaNs. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_var | def fn_var(self, a, axis=None):
"""
Compute the variance of an array, ignoring NaNs.
:param a: The array.
:return: The variance of the array.
"""
return numpy.nanvar(self._to_ndarray(a), axis=axis) | python | def fn_var(self, a, axis=None):
"""
Compute the variance of an array, ignoring NaNs.
:param a: The array.
:return: The variance of the array.
"""
return numpy.nanvar(self._to_ndarray(a), axis=axis) | [
"def",
"fn_var",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanvar",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Compute the variance of an array, ignoring NaNs.
:param a: The array.
:return: The variance of the array. | [
"Compute",
"the",
"variance",
"of",
"an",
"array",
"ignoring",
"NaNs",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L410-L418 | train | Compute the variance of an array ignoring NaNs. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_floor | def fn_floor(self, value):
"""
Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | python | def fn_floor(self, value):
"""
Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | [
"def",
"fn_floor",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"numpy",
".",
"floor",
"(",
"self",
".",
"_to_ndarray",
"(",
"... | Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number. | [
"Return",
"the",
"floor",
"of",
"a",
"number",
".",
"For",
"negative",
"numbers",
"floor",
"returns",
"a",
"lower",
"value",
".",
"E",
".",
"g",
".",
"floor",
"(",
"-",
"2",
".",
"5",
")",
"==",
"-",
"3"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L420-L431 | train | Returns the floor of a number. For positive numbers floor returns a lower value. Eg., floor returns a higher value. For negative numbers floor returns a lower value. Eg., floor returns a lower value. Eg., floor returns a higher value. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_ceil | def fn_ceil(self, value):
"""
Return the ceiling of a number.
:param value: The number.
:return: The ceiling of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return numpy.ceil(self._to_ndarray(value))
else:
ret... | python | def fn_ceil(self, value):
"""
Return the ceiling of a number.
:param value: The number.
:return: The ceiling of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return numpy.ceil(self._to_ndarray(value))
else:
ret... | [
"def",
"fn_ceil",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"numpy",
".",
"ceil",
"(",
"self",
".",
"_to_ndarray",
"(",
"va... | Return the ceiling of a number.
:param value: The number.
:return: The ceiling of the number. | [
"Return",
"the",
"ceiling",
"of",
"a",
"number",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L433-L444 | train | Returns the ceiling of a number. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_int | def fn_int(self, value):
"""
Return the value cast to an int.
:param value: The number.
:return: The number as an int.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return self._to_ndarray(value).astype('int')
else:
return... | python | def fn_int(self, value):
"""
Return the value cast to an int.
:param value: The number.
:return: The number as an int.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return self._to_ndarray(value).astype('int')
else:
return... | [
"def",
"fn_int",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"self",
".",
"_to_ndarray",
"(",
"value",
")",
".",
"astype",
"(... | Return the value cast to an int.
:param value: The number.
:return: The number as an int. | [
"Return",
"the",
"value",
"cast",
"to",
"an",
"int",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L446-L457 | train | Return the value cast to an int. |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_int8 | def fn_int8(self, value):
"""
Return the value cast to an 8-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | python | def fn_int8(self, value):
"""
Return the value cast to an 8-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | [
"def",
"fn_int8",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"self",
".",
"_to_ndarray",
"(",
"value",
")",
".",
"astype",
"... | Return the value cast to an 8-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8 | [
"Return",
"the",
"value",
"cast",
"to",
"an",
"8",
"-",
"bit",
"signed",
"integer",
"(",
"numpy",
"array",
")",
"or",
"a",
"Python",
"int",
"(",
"single",
"value",
")"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L459-L470 | train | Casts the value to an 8 - bit signed integer or a Python int |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_int16 | def fn_int16(self, value):
"""
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | python | def fn_int16(self, value):
"""
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | [
"def",
"fn_int16",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"self",
".",
"_to_ndarray",
"(",
"value",
")",
".",
"astype",
... | Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8 | [
"Return",
"the",
"value",
"cast",
"to",
"an",
"16",
"-",
"bit",
"signed",
"integer",
"(",
"numpy",
"array",
")",
"or",
"a",
"Python",
"int",
"(",
"single",
"value",
")"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L472-L483 | train | Casts the value to an 16 - bit signed integer or a Python int |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_int32 | def fn_int32(self, value):
"""
Return the value cast to an 32-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | python | def fn_int32(self, value):
"""
Return the value cast to an 32-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | [
"def",
"fn_int32",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"self",
".",
"_to_ndarray",
"(",
"value",
")",
".",
"astype",
... | Return the value cast to an 32-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8 | [
"Return",
"the",
"value",
"cast",
"to",
"an",
"32",
"-",
"bit",
"signed",
"integer",
"(",
"numpy",
"array",
")",
"or",
"a",
"Python",
"int",
"(",
"single",
"value",
")"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L485-L496 | train | Cast the value to an 32 - bit signed integer or a Python int |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | Parser.fn_float | def fn_float(self, value):
"""
Return the value cast to a float.
:param value: The number.
:return: The number as a float.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return self._to_ndarray(value).astype('float')
else:
... | python | def fn_float(self, value):
"""
Return the value cast to a float.
:param value: The number.
:return: The number as a float.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return self._to_ndarray(value).astype('float')
else:
... | [
"def",
"fn_float",
"(",
"self",
",",
"value",
")",
":",
"if",
"is_ndarray",
"(",
"value",
")",
"or",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"self",
".",
"_to_ndarray",
"(",
"value",
")",
".",
"astype",
... | Return the value cast to a float.
:param value: The number.
:return: The number as a float. | [
"Return",
"the",
"value",
"cast",
"to",
"a",
"float",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L511-L522 | train | Return the value cast to a float. |
totalgood/pugnlp | src/pugnlp/tutil.py | make_datetime | def make_datetime(dt, date_parser=parse_date):
"""Coerce a datetime or string into datetime.datetime object
Arguments:
dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date
to be coerced into a `datetime.date` object
Returns:
datetime.time: Time of day portion ... | python | def make_datetime(dt, date_parser=parse_date):
"""Coerce a datetime or string into datetime.datetime object
Arguments:
dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date
to be coerced into a `datetime.date` object
Returns:
datetime.time: Time of day portion ... | [
"def",
"make_datetime",
"(",
"dt",
",",
"date_parser",
"=",
"parse_date",
")",
":",
"if",
"(",
"isinstance",
"(",
"dt",
",",
"(",
"datetime",
".",
"datetime",
",",
"datetime",
".",
"date",
",",
"datetime",
".",
"time",
",",
"pd",
".",
"Timestamp",
",",... | Coerce a datetime or string into datetime.datetime object
Arguments:
dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date
to be coerced into a `datetime.date` object
Returns:
datetime.time: Time of day portion of a `datetime` string or object
>>> make_date(''... | [
"Coerce",
"a",
"datetime",
"or",
"string",
"into",
"datetime",
".",
"datetime",
"object"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L140-L192 | train | Coerce a datetime or string into a datetime. datetime object |
totalgood/pugnlp | src/pugnlp/tutil.py | quantize_datetime | def quantize_datetime(dt, resolution=None):
"""Quantize a datetime to integer years, months, days, hours, minutes, seconds or microseconds
Also works with a `datetime.timetuple` or `time.struct_time` or a 1to9-tuple of ints or floats.
Also works with a sequenece of struct_times, tuples, or datetimes
>... | python | def quantize_datetime(dt, resolution=None):
"""Quantize a datetime to integer years, months, days, hours, minutes, seconds or microseconds
Also works with a `datetime.timetuple` or `time.struct_time` or a 1to9-tuple of ints or floats.
Also works with a sequenece of struct_times, tuples, or datetimes
>... | [
"def",
"quantize_datetime",
"(",
"dt",
",",
"resolution",
"=",
"None",
")",
":",
"# FIXME: this automatically truncates off microseconds just because timtuple() only goes out to sec",
"resolution",
"=",
"int",
"(",
"resolution",
"or",
"6",
")",
"if",
"hasattr",
"(",
"dt",... | Quantize a datetime to integer years, months, days, hours, minutes, seconds or microseconds
Also works with a `datetime.timetuple` or `time.struct_time` or a 1to9-tuple of ints or floats.
Also works with a sequenece of struct_times, tuples, or datetimes
>>> quantize_datetime(datetime.datetime(1970,1,2,3,4... | [
"Quantize",
"a",
"datetime",
"to",
"integer",
"years",
"months",
"days",
"hours",
"minutes",
"seconds",
"or",
"microseconds"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L229-L266 | train | Quantize a datetime to integer years months days hours minutes seconds or microseconds |
totalgood/pugnlp | src/pugnlp/tutil.py | ordinal_float | def ordinal_float(dt):
"""Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1... | python | def ordinal_float(dt):
"""Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1... | [
"def",
"ordinal_float",
"(",
"dt",
")",
":",
"try",
":",
"return",
"dt",
".",
"toordinal",
"(",
")",
"+",
"(",
"(",
"(",
"(",
"dt",
".",
"microsecond",
"/",
"1000000.",
")",
"+",
"dt",
".",
"second",
")",
"/",
"60.",
"+",
"dt",
".",
"minute",
"... | Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1, 2, 3, 4, 5, 6, 7)) # doctes... | [
"Like",
"datetime",
".",
"ordinal",
"but",
"rather",
"than",
"integer",
"allows",
"fractional",
"days",
"(",
"so",
"float",
"not",
"ordinal",
"at",
"all",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L277-L296 | train | Like datetime. ordinal but rather than integer allows fractional days |
totalgood/pugnlp | src/pugnlp/tutil.py | datetime_from_ordinal_float | def datetime_from_ordinal_float(days):
"""Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_f... | python | def datetime_from_ordinal_float(days):
"""Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_f... | [
"def",
"datetime_from_ordinal_float",
"(",
"days",
")",
":",
"if",
"isinstance",
"(",
"days",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"if",
"np",
".",
"isnan",
"(",
"days",
")",
"or",
"days",
"in",
"set",
"(",
"(",
"float",
"(",
"'nan'",
")",... | Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
... | [
"Inverse",
"of",
"ordinal_float",
"()",
"converts",
"a",
"float",
"number",
"of",
"days",
"back",
"to",
"a",
"datetime",
"object"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L299-L316 | train | Inverse of ordinal_float() converts a float number of days back to a datetime object |
totalgood/pugnlp | src/pugnlp/tutil.py | timetag_str | def timetag_str(dt=None, sep='-', filler='0', resolution=6):
"""Generate a date-time tag suitable for appending to a file name.
>>> timetag_str(resolution=3) == '-'.join('{0:02d}'.format(i) for i in
... tuple(datetime.datetime.now().timetuple()[:3]))
True
>>> timetag_str(datetime.dateti... | python | def timetag_str(dt=None, sep='-', filler='0', resolution=6):
"""Generate a date-time tag suitable for appending to a file name.
>>> timetag_str(resolution=3) == '-'.join('{0:02d}'.format(i) for i in
... tuple(datetime.datetime.now().timetuple()[:3]))
True
>>> timetag_str(datetime.dateti... | [
"def",
"timetag_str",
"(",
"dt",
"=",
"None",
",",
"sep",
"=",
"'-'",
",",
"filler",
"=",
"'0'",
",",
"resolution",
"=",
"6",
")",
":",
"resolution",
"=",
"int",
"(",
"resolution",
"or",
"6",
")",
"if",
"sep",
"in",
"(",
"None",
",",
"False",
")"... | Generate a date-time tag suitable for appending to a file name.
>>> timetag_str(resolution=3) == '-'.join('{0:02d}'.format(i) for i in
... tuple(datetime.datetime.now().timetuple()[:3]))
True
>>> timetag_str(datetime.datetime(2004,12,8,1,2,3,400000))
'2004-12-08-01-02-03'
>>> timeta... | [
"Generate",
"a",
"date",
"-",
"time",
"tag",
"suitable",
"for",
"appending",
"to",
"a",
"file",
"name",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L319-L339 | train | Generate a date - time tag suitable for appending to a file name. |
totalgood/pugnlp | src/pugnlp/tutil.py | make_tz_aware | def make_tz_aware(dt, tz='UTC', is_dst=None):
"""Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0,... | python | def make_tz_aware(dt, tz='UTC', is_dst=None):
"""Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0,... | [
"def",
"make_tz_aware",
"(",
"dt",
",",
"tz",
"=",
"'UTC'",
",",
"is_dst",
"=",
"None",
")",
":",
"# make sure dt is a datetime, time, or list of datetime/times",
"dt",
"=",
"make_datetime",
"(",
"dt",
")",
"if",
"not",
"isinstance",
"(",
"dt",
",",
"(",
"list... | Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 S... | [
"Add",
"timezone",
"information",
"to",
"a",
"datetime",
"object",
"only",
"if",
"it",
"is",
"naive",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L349-L408 | train | Add timezone information to a datetime object only if it is naive. |
totalgood/pugnlp | src/pugnlp/tutil.py | clip_datetime | def clip_datetime(dt, tz=DEFAULT_TZ, is_dst=None):
"""Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
... | python | def clip_datetime(dt, tz=DEFAULT_TZ, is_dst=None):
"""Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
... | [
"def",
"clip_datetime",
"(",
"dt",
",",
"tz",
"=",
"DEFAULT_TZ",
",",
"is_dst",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"datetime",
")",
":",
"# TODO: this gives up a day of datetime range due to assumptions about timezone",
"# ... | Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
Timestamp('2262-04-11 23:47:16.854775+0000', tz='UTC') | [
"Limit",
"a",
"datetime",
"to",
"a",
"valid",
"range",
"for",
"datetime",
"datetime64",
"and",
"Timestamp",
"objects",
">>>",
"from",
"datetime",
"import",
"timedelta",
">>>",
"clip_datetime",
"(",
"MAX_DATETIME",
"+",
"timedelta",
"(",
"100",
"))",
"==",
"pd"... | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L478-L500 | train | Limit a datetime to a valid range for datetime64 and Timestamp objects. |
hootnot/postcode-api-wrapper | postcodepy/typedefs.py | translate_addresstype | def translate_addresstype(f):
"""decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type.
"""
@wraps(f)
def wr(r, pc):
at = r["addressType"]
try:
r.update({"addressType": POSTCODE_API_TYPED... | python | def translate_addresstype(f):
"""decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type.
"""
@wraps(f)
def wr(r, pc):
at = r["addressType"]
try:
r.update({"addressType": POSTCODE_API_TYPED... | [
"def",
"translate_addresstype",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wr",
"(",
"r",
",",
"pc",
")",
":",
"at",
"=",
"r",
"[",
"\"addressType\"",
"]",
"try",
":",
"r",
".",
"update",
"(",
"{",
"\"addressType\"",
":",
"POSTCODE_AP... | decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type. | [
"decorator",
"to",
"translate",
"the",
"addressType",
"field",
"."
] | 42359cb9402f84a06f7d58f889f1156d653f5ea9 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/typedefs.py#L55-L72 | train | decorator to translate the addressType field of the API response into a
translated type. |
hootnot/postcode-api-wrapper | postcodepy/typedefs.py | translate_purposes | def translate_purposes(f):
"""decorator to translate the purposes field.
translate the values of the purposes field of the API response into
translated values.
"""
@wraps(f)
def wr(r, pc):
tmp = []
for P in r["purposes"]:
try:
tmp.append(POSTCODE_API_... | python | def translate_purposes(f):
"""decorator to translate the purposes field.
translate the values of the purposes field of the API response into
translated values.
"""
@wraps(f)
def wr(r, pc):
tmp = []
for P in r["purposes"]:
try:
tmp.append(POSTCODE_API_... | [
"def",
"translate_purposes",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wr",
"(",
"r",
",",
"pc",
")",
":",
"tmp",
"=",
"[",
"]",
"for",
"P",
"in",
"r",
"[",
"\"purposes\"",
"]",
":",
"try",
":",
"tmp",
".",
"append",
"(",
"POST... | decorator to translate the purposes field.
translate the values of the purposes field of the API response into
translated values. | [
"decorator",
"to",
"translate",
"the",
"purposes",
"field",
"."
] | 42359cb9402f84a06f7d58f889f1156d653f5ea9 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/typedefs.py#L75-L95 | train | decorator to translate the values of the purposes field of the API response into
translated values. |
consbio/ncdjango | ncdjango/interfaces/data/classify.py | jenks | def jenks(data, num_breaks):
"""
Calculate Jenks natural breaks.
Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
Credit: Daniel Lewis
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
data = numpy.ma.compressed(data)
if... | python | def jenks(data, num_breaks):
"""
Calculate Jenks natural breaks.
Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
Credit: Daniel Lewis
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
data = numpy.ma.compressed(data)
if... | [
"def",
"jenks",
"(",
"data",
",",
"num_breaks",
")",
":",
"data",
"=",
"numpy",
".",
"ma",
".",
"compressed",
"(",
"data",
")",
"if",
"len",
"(",
"data",
")",
">",
"1000",
":",
"data",
".",
"sort",
"(",
")",
"ls",
"=",
"numpy",
".",
"linspace",
... | Calculate Jenks natural breaks.
Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
Credit: Daniel Lewis
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | [
"Calculate",
"Jenks",
"natural",
"breaks",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/data/classify.py#L4-L88 | train | Calculate Jenks natural breaks. |
consbio/ncdjango | ncdjango/interfaces/data/classify.py | quantile | def quantile(data, num_breaks):
"""
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()):
""" function copied from scipy 0... | python | def quantile(data, num_breaks):
"""
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()):
""" function copied from scipy 0... | [
"def",
"quantile",
"(",
"data",
",",
"num_breaks",
")",
":",
"def",
"scipy_mquantiles",
"(",
"a",
",",
"prob",
"=",
"list",
"(",
"[",
".25",
",",
".5",
",",
".75",
"]",
")",
",",
"alphap",
"=",
".4",
",",
"betap",
"=",
".4",
",",
"axis",
"=",
"... | Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | [
"Calculate",
"quantile",
"breaks",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/data/classify.py#L91-L131 | train | Calculates the quantile breaks for a single object. |
consbio/ncdjango | ncdjango/interfaces/data/classify.py | equal | def equal(data, num_breaks):
"""
Calculate equal interval breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
step = (numpy.amax(data) - numpy.amin(data)) / num_breaks
return numpy.linspace(numpy.amin(data) + step, numpy.amax(data), nu... | python | def equal(data, num_breaks):
"""
Calculate equal interval breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
step = (numpy.amax(data) - numpy.amin(data)) / num_breaks
return numpy.linspace(numpy.amin(data) + step, numpy.amax(data), nu... | [
"def",
"equal",
"(",
"data",
",",
"num_breaks",
")",
":",
"step",
"=",
"(",
"numpy",
".",
"amax",
"(",
"data",
")",
"-",
"numpy",
".",
"amin",
"(",
"data",
")",
")",
"/",
"num_breaks",
"return",
"numpy",
".",
"linspace",
"(",
"numpy",
".",
"amin",
... | Calculate equal interval breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | [
"Calculate",
"equal",
"interval",
"breaks",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/data/classify.py#L134-L144 | train | Calculate equal interval breaks. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/validate_sim_population.py | getCatalogFile | def getCatalogFile(catalog_dir, mc_source_id):
"""
Inputs:
catalog_dir = string corresponding to directory containing the stellar catalog infiles
mc_source_id = integer corresponding the target MC_SOURCE_ID value
Outputs:
catalog_infile = string corresponding to filename of stellar c... | python | def getCatalogFile(catalog_dir, mc_source_id):
"""
Inputs:
catalog_dir = string corresponding to directory containing the stellar catalog infiles
mc_source_id = integer corresponding the target MC_SOURCE_ID value
Outputs:
catalog_infile = string corresponding to filename of stellar c... | [
"def",
"getCatalogFile",
"(",
"catalog_dir",
",",
"mc_source_id",
")",
":",
"catalog_infiles",
"=",
"sorted",
"(",
"glob",
".",
"glob",
"(",
"catalog_dir",
"+",
"'/*catalog*.fits'",
")",
")",
"mc_source_id_array",
"=",
"[",
"]",
"catalog_infile_index_array",
"=",
... | Inputs:
catalog_dir = string corresponding to directory containing the stellar catalog infiles
mc_source_id = integer corresponding the target MC_SOURCE_ID value
Outputs:
catalog_infile = string corresponding to filename of stellar catalog containing mc_source_id | [
"Inputs",
":",
"catalog_dir",
"=",
"string",
"corresponding",
"to",
"directory",
"containing",
"the",
"stellar",
"catalog",
"infiles",
"mc_source_id",
"=",
"integer",
"corresponding",
"the",
"target",
"MC_SOURCE_ID",
"value",
"Outputs",
":",
"catalog_infile",
"=",
"... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/validate_sim_population.py#L19-L43 | train | Returns the file containing the stellar catalog containing the given MC_SOURCE_ID value. |
DarkEnergySurvey/ugali | ugali/utils/fileio.py | read | def read(filename,**kwargs):
""" Read a generic input file into a recarray.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : input file name
kwargs : keyword arguments for the reader
Returns:
recarray : data array
"""
base,ext = os.path.splitext(fi... | python | def read(filename,**kwargs):
""" Read a generic input file into a recarray.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : input file name
kwargs : keyword arguments for the reader
Returns:
recarray : data array
"""
base,ext = os.path.splitext(fi... | [
"def",
"read",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"in",
"(",
"'.fits'",
",",
"'.fz'",
")",
":",
"# Abstract fits here...",
"return",
"fit... | Read a generic input file into a recarray.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : input file name
kwargs : keyword arguments for the reader
Returns:
recarray : data array | [
"Read",
"a",
"generic",
"input",
"file",
"into",
"a",
"recarray",
".",
"Accepted",
"file",
"formats",
":",
"[",
".",
"fits",
".",
"fz",
".",
"npy",
".",
"csv",
".",
"txt",
".",
"dat",
"]",
"Parameters",
":",
"filename",
":",
"input",
"file",
"name",
... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L20-L42 | train | Read a generic input file into a recarray. |
DarkEnergySurvey/ugali | ugali/utils/fileio.py | write | def write(filename,data,**kwargs):
""" Write a recarray to a specific format.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : output file name
data : the recarray data
kwargs : keyword arguments for the writer
Returns:
ret : writer return (us... | python | def write(filename,data,**kwargs):
""" Write a recarray to a specific format.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : output file name
data : the recarray data
kwargs : keyword arguments for the writer
Returns:
ret : writer return (us... | [
"def",
"write",
"(",
"filename",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"in",
"(",
"'.fits'",
",",
"'.fz'",
")",
":",
"# Abstract fits here...",
... | Write a recarray to a specific format.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : output file name
data : the recarray data
kwargs : keyword arguments for the writer
Returns:
ret : writer return (usually None) | [
"Write",
"a",
"recarray",
"to",
"a",
"specific",
"format",
".",
"Accepted",
"file",
"formats",
":",
"[",
".",
"fits",
".",
"fz",
".",
"npy",
".",
"csv",
".",
"txt",
".",
"dat",
"]",
"Parameters",
":",
"filename",
":",
"output",
"file",
"name",
"data"... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L44-L67 | train | Writes a recarray to a specific format. |
DarkEnergySurvey/ugali | ugali/utils/fileio.py | add_column | def add_column(filename,column,formula,force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
logger.info("Running file: %s"%filename)
logger.debug(" Reading columns: %s"%columns)
data = fitsio.read(filename,columns=colum... | python | def add_column(filename,column,formula,force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
logger.info("Running file: %s"%filename)
logger.debug(" Reading columns: %s"%columns)
data = fitsio.read(filename,columns=colum... | [
"def",
"add_column",
"(",
"filename",
",",
"column",
",",
"formula",
",",
"force",
"=",
"False",
")",
":",
"columns",
"=",
"parse_formula",
"(",
"formula",
")",
"logger",
".",
"info",
"(",
"\"Running file: %s\"",
"%",
"filename",
")",
"logger",
".",
"debug... | Add a column to a FITS file.
ADW: Could this be replaced by a ftool? | [
"Add",
"a",
"column",
"to",
"a",
"FITS",
"file",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L70-L85 | train | Add a column to a FITS file. |
DarkEnergySurvey/ugali | ugali/utils/fileio.py | load_files | def load_files(filenames,multiproc=False,**kwargs):
""" Load a set of FITS files with kwargs. """
filenames = np.atleast_1d(filenames)
logger.debug("Loading %s files..."%len(filenames))
kwargs = [dict(filename=f,**kwargs) for f in filenames]
if multiproc:
from multiprocessing import Pool
... | python | def load_files(filenames,multiproc=False,**kwargs):
""" Load a set of FITS files with kwargs. """
filenames = np.atleast_1d(filenames)
logger.debug("Loading %s files..."%len(filenames))
kwargs = [dict(filename=f,**kwargs) for f in filenames]
if multiproc:
from multiprocessing import Pool
... | [
"def",
"load_files",
"(",
"filenames",
",",
"multiproc",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"filenames",
"=",
"np",
".",
"atleast_1d",
"(",
"filenames",
")",
"logger",
".",
"debug",
"(",
"\"Loading %s files...\"",
"%",
"len",
"(",
"filenames"... | Load a set of FITS files with kwargs. | [
"Load",
"a",
"set",
"of",
"FITS",
"files",
"with",
"kwargs",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L98-L121 | train | Load a set of FITS files with kwargs. |
DarkEnergySurvey/ugali | ugali/utils/fileio.py | write_membership | def write_membership(loglike,filename):
"""
Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
loglike : input loglikelihood object
filename : output filename
Returns:
--------
None
"""
ra,dec = gal2cel(loglike.ca... | python | def write_membership(loglike,filename):
"""
Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
loglike : input loglikelihood object
filename : output filename
Returns:
--------
None
"""
ra,dec = gal2cel(loglike.ca... | [
"def",
"write_membership",
"(",
"loglike",
",",
"filename",
")",
":",
"ra",
",",
"dec",
"=",
"gal2cel",
"(",
"loglike",
".",
"catalog",
".",
"lon",
",",
"loglike",
".",
"catalog",
".",
"lat",
")",
"name_objid",
"=",
"loglike",
".",
"config",
"[",
"'cat... | Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
loglike : input loglikelihood object
filename : output filename
Returns:
--------
None | [
"Write",
"a",
"catalog",
"file",
"of",
"the",
"likelihood",
"region",
"including",
"membership",
"properties",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L204-L260 | train | Writes a catalog file of the likelihood region including the membership properties. |
DarkEnergySurvey/ugali | ugali/utils/binning.py | take2D | def take2D(histogram, x, y, bins_x, bins_y):
"""
Take the value from a two-dimensional histogram from the bin corresponding to (x, y).
Parameters:
-----------
histogram : The values in the histogram (n,m) (ADW: is this ordering right?)
x : the x-value to take from the hist
y : the y-value t... | python | def take2D(histogram, x, y, bins_x, bins_y):
"""
Take the value from a two-dimensional histogram from the bin corresponding to (x, y).
Parameters:
-----------
histogram : The values in the histogram (n,m) (ADW: is this ordering right?)
x : the x-value to take from the hist
y : the y-value t... | [
"def",
"take2D",
"(",
"histogram",
",",
"x",
",",
"y",
",",
"bins_x",
",",
"bins_y",
")",
":",
"histogram",
"=",
"np",
".",
"array",
"(",
"histogram",
")",
"if",
"np",
".",
"isscalar",
"(",
"x",
")",
":",
"x",
"=",
"[",
"x",
"]",
"if",
"np",
... | Take the value from a two-dimensional histogram from the bin corresponding to (x, y).
Parameters:
-----------
histogram : The values in the histogram (n,m) (ADW: is this ordering right?)
x : the x-value to take from the hist
y : the y-value to take from the hist
bins_x : the xbin edges, includi... | [
"Take",
"the",
"value",
"from",
"a",
"two",
"-",
"dimensional",
"histogram",
"from",
"the",
"bin",
"corresponding",
"to",
"(",
"x",
"y",
")",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/binning.py#L18-L52 | train | Take the value from a two - dimensional histogram from the bin corresponding to x y. |
DarkEnergySurvey/ugali | ugali/utils/binning.py | cloudInCells | def cloudInCells(x, y, bins, weights=None):
"""
Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-va... | python | def cloudInCells(x, y, bins, weights=None):
"""
Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-va... | [
"def",
"cloudInCells",
"(",
"x",
",",
"y",
",",
"bins",
",",
"weights",
"=",
"None",
")",
":",
"# For consistency, the variable names should be changed in this function, but low priority...",
"x_bins",
"=",
"np",
".",
"array",
"(",
"bins",
"[",
"0",
"]",
")",
"del... | Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-values
y: array or y-values
bins: [bins_x,... | [
"Use",
"cloud",
"-",
"in",
"-",
"cells",
"binning",
"algorithm",
".",
"Only",
"valid",
"for",
"equal",
"-",
"spaced",
"linear",
"bins",
".",
"http",
":",
"//",
"ta",
".",
"twi",
".",
"tudelft",
".",
"nl",
"/",
"dv",
"/",
"users",
"/",
"Lemmens",
"/... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/binning.py#L56-L145 | train | Use cloud - in - cells binning algorithm. Only valid for equal - spaced linear bins. |
DarkEnergySurvey/ugali | ugali/utils/binning.py | fast_kde | def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None):
"""
Performs a gaussian kernel density estimate over a regular grid using a
convolution of the gaussian kernel with a 2D histogram of the data.
This function is typically several orders of magnitude faster than
... | python | def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None):
"""
Performs a gaussian kernel density estimate over a regular grid using a
convolution of the gaussian kernel with a 2D histogram of the data.
This function is typically several orders of magnitude faster than
... | [
"def",
"fast_kde",
"(",
"x",
",",
"y",
",",
"gridsize",
"=",
"(",
"200",
",",
"200",
")",
",",
"extents",
"=",
"None",
",",
"nocorrelation",
"=",
"False",
",",
"weights",
"=",
"None",
")",
":",
"#---- Setup -----------------------------------------------------... | Performs a gaussian kernel density estimate over a regular grid using a
convolution of the gaussian kernel with a 2D histogram of the data.
This function is typically several orders of magnitude faster than
scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and
produces an essentially id... | [
"Performs",
"a",
"gaussian",
"kernel",
"density",
"estimate",
"over",
"a",
"regular",
"grid",
"using",
"a",
"convolution",
"of",
"the",
"gaussian",
"kernel",
"with",
"a",
"2D",
"histogram",
"of",
"the",
"data",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/binning.py#L177-L291 | train | Calculates a 2D kernel density estimate over a regular grid. |
DarkEnergySurvey/ugali | ugali/utils/binning.py | reverseHistogram | def reverseHistogram(data,bins=None):
"""
Bins data using np.histogram and calculates the
reverse indices for the entries like IDL.
Parameters:
data : data to pass to np.histogram
bins : bins to pass to np.histogram
Returns:
hist : bin content output by np.histogram
... | python | def reverseHistogram(data,bins=None):
"""
Bins data using np.histogram and calculates the
reverse indices for the entries like IDL.
Parameters:
data : data to pass to np.histogram
bins : bins to pass to np.histogram
Returns:
hist : bin content output by np.histogram
... | [
"def",
"reverseHistogram",
"(",
"data",
",",
"bins",
"=",
"None",
")",
":",
"if",
"bins",
"is",
"None",
":",
"bins",
"=",
"np",
".",
"arange",
"(",
"data",
".",
"max",
"(",
")",
"+",
"2",
")",
"hist",
",",
"edges",
"=",
"np",
".",
"histogram",
... | Bins data using np.histogram and calculates the
reverse indices for the entries like IDL.
Parameters:
data : data to pass to np.histogram
bins : bins to pass to np.histogram
Returns:
hist : bin content output by np.histogram
edges : edges output from np.histogram
rev : reverse i... | [
"Bins",
"data",
"using",
"np",
".",
"histogram",
"and",
"calculates",
"the",
"reverse",
"indices",
"for",
"the",
"entries",
"like",
"IDL",
".",
"Parameters",
":",
"data",
":",
"data",
"to",
"pass",
"to",
"np",
".",
"histogram",
"bins",
":",
"bins",
"to",... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/binning.py#L300-L323 | train | This function calculates the histogram and the reverse indices of the entries in each bin using np. histogram and calculates the reverse indices for the entries like IDL. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | angToPix | def angToPix(nside, lon, lat, nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta = np.radians(90. - lat)
phi = np.radians(lon)
return hp.ang2pix(nside, theta, phi, nest=nest) | python | def angToPix(nside, lon, lat, nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta = np.radians(90. - lat)
phi = np.radians(lon)
return hp.ang2pix(nside, theta, phi, nest=nest) | [
"def",
"angToPix",
"(",
"nside",
",",
"lon",
",",
"lat",
",",
"nest",
"=",
"False",
")",
":",
"theta",
"=",
"np",
".",
"radians",
"(",
"90.",
"-",
"lat",
")",
"phi",
"=",
"np",
".",
"radians",
"(",
"lon",
")",
"return",
"hp",
".",
"ang2pix",
"(... | Input (lon, lat) in degrees instead of (theta, phi) in radians | [
"Input",
"(",
"lon",
"lat",
")",
"in",
"degrees",
"instead",
"of",
"(",
"theta",
"phi",
")",
"in",
"radians"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L34-L40 | train | Convert from ang to pix |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | query_disc | def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
"""
Wrapper around healpy.query_disc to deal with old healpy implementation.
nside : int
The nside of the Healpix map.
vec : float, sequence of 3 elements
The coordinates of unit vector defining the disk center.
rad... | python | def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
"""
Wrapper around healpy.query_disc to deal with old healpy implementation.
nside : int
The nside of the Healpix map.
vec : float, sequence of 3 elements
The coordinates of unit vector defining the disk center.
rad... | [
"def",
"query_disc",
"(",
"nside",
",",
"vec",
",",
"radius",
",",
"inclusive",
"=",
"False",
",",
"fact",
"=",
"4",
",",
"nest",
"=",
"False",
")",
":",
"try",
":",
"# New-style call (healpy 1.6.3)",
"return",
"hp",
".",
"query_disc",
"(",
"nside",
",",... | Wrapper around healpy.query_disc to deal with old healpy implementation.
nside : int
The nside of the Healpix map.
vec : float, sequence of 3 elements
The coordinates of unit vector defining the disk center.
radius : float
The radius (in degrees) of the disc
inclusive : bool, optional
... | [
"Wrapper",
"around",
"healpy",
".",
"query_disc",
"to",
"deal",
"with",
"old",
"healpy",
"implementation",
".",
"nside",
":",
"int",
"The",
"nside",
"of",
"the",
"Healpix",
"map",
".",
"vec",
":",
"float",
"sequence",
"of",
"3",
"elements",
"The",
"coordin... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L50-L76 | train | Wrapper around healpy. query_disc to deal with old healpy implementation. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | angToDisc | def angToDisc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
"""
Wrap `query_disc` to use lon, lat, and radius in degrees.
"""
vec = angToVec(lon,lat)
return query_disc(nside,vec,radius,inclusive,fact,nest) | python | def angToDisc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
"""
Wrap `query_disc` to use lon, lat, and radius in degrees.
"""
vec = angToVec(lon,lat)
return query_disc(nside,vec,radius,inclusive,fact,nest) | [
"def",
"angToDisc",
"(",
"nside",
",",
"lon",
",",
"lat",
",",
"radius",
",",
"inclusive",
"=",
"False",
",",
"fact",
"=",
"4",
",",
"nest",
"=",
"False",
")",
":",
"vec",
"=",
"angToVec",
"(",
"lon",
",",
"lat",
")",
"return",
"query_disc",
"(",
... | Wrap `query_disc` to use lon, lat, and radius in degrees. | [
"Wrap",
"query_disc",
"to",
"use",
"lon",
"lat",
"and",
"radius",
"in",
"degrees",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L78-L83 | train | Wrap query_disc to use lon lat and radius in degrees. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | angsep | def angsep(lon1, lat1, lon2, lat2):
"""
Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alt... | python | def angsep(lon1, lat1, lon2, lat2):
"""
Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alt... | [
"def",
"angsep",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
":",
"lon1",
",",
"lat1",
"=",
"np",
".",
"radians",
"(",
"[",
"lon1",
",",
"lat1",
"]",
")",
"lon2",
",",
"lat2",
"=",
"np",
".",
"radians",
"(",
"[",
"lon2",
",",
"la... | Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alternatives, but is stable at at all distances, in... | [
"Angular",
"separation",
"(",
"deg",
")",
"between",
"two",
"sky",
"coordinates",
".",
"Borrowed",
"from",
"astropy",
"(",
"www",
".",
"astropy",
".",
"org",
")",
"Notes",
"-----",
"The",
"angular",
"separation",
"is",
"calculated",
"using",
"the",
"Vincenty... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L87-L113 | train | Returns the angular separation between two sky coordinates. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | meanFracdet | def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
"""
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length
"""
nside_fracdet = hp.npix2nside(len(map_fracdet))
map_fra... | python | def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
"""
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length
"""
nside_fracdet = hp.npix2nside(len(map_fracdet))
map_fra... | [
"def",
"meanFracdet",
"(",
"map_fracdet",
",",
"lon_population",
",",
"lat_population",
",",
"radius_population",
")",
":",
"nside_fracdet",
"=",
"hp",
".",
"npix2nside",
"(",
"len",
"(",
"map_fracdet",
")",
")",
"map_fracdet_zero",
"=",
"np",
".",
"where",
"(... | Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length | [
"Compute",
"the",
"mean",
"fracdet",
"within",
"circular",
"aperture",
"(",
"radius",
"specified",
"in",
"decimal",
"degrees",
")"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L117-L132 | train | Compute the mean fracdet within a circular aperture |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | surveySelectionFunction.trainClassifier | def trainClassifier(self):
"""
Self-consistently train the classifier
"""
self.loadPopulationMetadata()
self.loadSimResults()
cut_geometry, flags_geometry = self.applyGeometry(self.data_population['RA'], self.data_population['DEC'])
cut_... | python | def trainClassifier(self):
"""
Self-consistently train the classifier
"""
self.loadPopulationMetadata()
self.loadSimResults()
cut_geometry, flags_geometry = self.applyGeometry(self.data_population['RA'], self.data_population['DEC'])
cut_... | [
"def",
"trainClassifier",
"(",
"self",
")",
":",
"self",
".",
"loadPopulationMetadata",
"(",
")",
"self",
".",
"loadSimResults",
"(",
")",
"cut_geometry",
",",
"flags_geometry",
"=",
"self",
".",
"applyGeometry",
"(",
"self",
".",
"data_population",
"[",
"'RA'... | Self-consistently train the classifier | [
"Self",
"-",
"consistently",
"train",
"the",
"classifier"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L173-L280 | train | Train the classifier on the data set. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | surveySelectionFunction.validateClassifier | def validateClassifier(self, cut_detect, cut_train, cut_geometry, y_pred):
"""
Make some diagnostic plots
"""
color = {'detect': 'Red',
'nondetect': 'Gold',
'why_not': 'none',
'actual': 'DodgerBlue',
'hsc': 'lime'}
... | python | def validateClassifier(self, cut_detect, cut_train, cut_geometry, y_pred):
"""
Make some diagnostic plots
"""
color = {'detect': 'Red',
'nondetect': 'Gold',
'why_not': 'none',
'actual': 'DodgerBlue',
'hsc': 'lime'}
... | [
"def",
"validateClassifier",
"(",
"self",
",",
"cut_detect",
",",
"cut_train",
",",
"cut_geometry",
",",
"y_pred",
")",
":",
"color",
"=",
"{",
"'detect'",
":",
"'Red'",
",",
"'nondetect'",
":",
"'Gold'",
",",
"'why_not'",
":",
"'none'",
",",
"'actual'",
"... | Make some diagnostic plots | [
"Make",
"some",
"diagnostic",
"plots"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L282-L371 | train | Validate the classification. |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | surveySelectionFunction.applyFracdet | def applyFracdet(self, lon, lat):
"""
We want to enforce minimum fracdet for a satellite to be considered detectable
True is passes fracdet cut
"""
self.loadFracdet()
fracdet_core = meanFracdet(self.m_fracdet, lon, lat, np.tile(0.1, len(lon)))
fracdet_wide = mean... | python | def applyFracdet(self, lon, lat):
"""
We want to enforce minimum fracdet for a satellite to be considered detectable
True is passes fracdet cut
"""
self.loadFracdet()
fracdet_core = meanFracdet(self.m_fracdet, lon, lat, np.tile(0.1, len(lon)))
fracdet_wide = mean... | [
"def",
"applyFracdet",
"(",
"self",
",",
"lon",
",",
"lat",
")",
":",
"self",
".",
"loadFracdet",
"(",
")",
"fracdet_core",
"=",
"meanFracdet",
"(",
"self",
".",
"m_fracdet",
",",
"lon",
",",
"lat",
",",
"np",
".",
"tile",
"(",
"0.1",
",",
"len",
"... | We want to enforce minimum fracdet for a satellite to be considered detectable
True is passes fracdet cut | [
"We",
"want",
"to",
"enforce",
"minimum",
"fracdet",
"for",
"a",
"satellite",
"to",
"be",
"considered",
"detectable"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L385-L395 | train | Returns True is passes fracdet False is passes fracdet cut
|
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | surveySelectionFunction.applyHotspot | def applyHotspot(self, lon, lat):
"""
Exclude objects that are too close to hotspot
True if passes hotspot cut
"""
self.loadRealResults()
cut_detect_real = (self.data_real['SIG'] >= self.config[self.algorithm]['sig_threshold'])
lon_real = self.data_real['RA'][cut... | python | def applyHotspot(self, lon, lat):
"""
Exclude objects that are too close to hotspot
True if passes hotspot cut
"""
self.loadRealResults()
cut_detect_real = (self.data_real['SIG'] >= self.config[self.algorithm]['sig_threshold'])
lon_real = self.data_real['RA'][cut... | [
"def",
"applyHotspot",
"(",
"self",
",",
"lon",
",",
"lat",
")",
":",
"self",
".",
"loadRealResults",
"(",
")",
"cut_detect_real",
"=",
"(",
"self",
".",
"data_real",
"[",
"'SIG'",
"]",
">=",
"self",
".",
"config",
"[",
"self",
".",
"algorithm",
"]",
... | Exclude objects that are too close to hotspot
True if passes hotspot cut | [
"Exclude",
"objects",
"that",
"are",
"too",
"close",
"to",
"hotspot"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L397-L412 | train | Return a numpy array of the objects that are too close to hotspot True if passes hotspot |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | surveySelectionFunction.predict | def predict(self, lon, lat, **kwargs):
"""
distance, abs_mag, r_physical
"""
assert self.classifier is not None, 'ERROR'
pred = np.zeros(len(lon))
cut_geometry, flags_geometry = self.applyGeometry(lon, lat)
x_test = []
for key, operation ... | python | def predict(self, lon, lat, **kwargs):
"""
distance, abs_mag, r_physical
"""
assert self.classifier is not None, 'ERROR'
pred = np.zeros(len(lon))
cut_geometry, flags_geometry = self.applyGeometry(lon, lat)
x_test = []
for key, operation ... | [
"def",
"predict",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"classifier",
"is",
"not",
"None",
",",
"'ERROR'",
"pred",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"lon",
")",
")",
"cut_geometry",
... | distance, abs_mag, r_physical | [
"distance",
"abs_mag",
"r_physical"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L425-L449 | train | predict the class of the object |
DarkEnergySurvey/ugali | ugali/candidate/associate.py | catalogFactory | def catalogFactory(name, **kwargs):
"""
Factory for various catalogs.
"""
fn = lambda member: inspect.isclass(member) and member.__module__==__name__
catalogs = odict(inspect.getmembers(sys.modules[__name__], fn))
if name not in list(catalogs.keys()):
msg = "%s not found in catalogs:\n ... | python | def catalogFactory(name, **kwargs):
"""
Factory for various catalogs.
"""
fn = lambda member: inspect.isclass(member) and member.__module__==__name__
catalogs = odict(inspect.getmembers(sys.modules[__name__], fn))
if name not in list(catalogs.keys()):
msg = "%s not found in catalogs:\n ... | [
"def",
"catalogFactory",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"fn",
"=",
"lambda",
"member",
":",
"inspect",
".",
"isclass",
"(",
"member",
")",
"and",
"member",
".",
"__module__",
"==",
"__name__",
"catalogs",
"=",
"odict",
"(",
"inspect",
... | Factory for various catalogs. | [
"Factory",
"for",
"various",
"catalogs",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/candidate/associate.py#L447-L460 | train | Factory for various catalogs. |
DarkEnergySurvey/ugali | ugali/analysis/results.py | surfaceBrightness | def surfaceBrightness(abs_mag, r_physical, distance):
"""
Compute the average surface brightness [mag arcsec^-2] within the half-light radius
abs_mag = absolute magnitude [mag]
r_physical = half-light radius [kpc]
distance = [kpc]
The factor 2 in the c_v equation below account for half the lu... | python | def surfaceBrightness(abs_mag, r_physical, distance):
"""
Compute the average surface brightness [mag arcsec^-2] within the half-light radius
abs_mag = absolute magnitude [mag]
r_physical = half-light radius [kpc]
distance = [kpc]
The factor 2 in the c_v equation below account for half the lu... | [
"def",
"surfaceBrightness",
"(",
"abs_mag",
",",
"r_physical",
",",
"distance",
")",
":",
"r_angle",
"=",
"np",
".",
"degrees",
"(",
"np",
".",
"arctan",
"(",
"r_physical",
"/",
"distance",
")",
")",
"c_v",
"=",
"19.78",
"# mag/arcsec^2",
"return",
"abs_ma... | Compute the average surface brightness [mag arcsec^-2] within the half-light radius
abs_mag = absolute magnitude [mag]
r_physical = half-light radius [kpc]
distance = [kpc]
The factor 2 in the c_v equation below account for half the luminosity
within the half-light radius. The 3600.**2 is conver... | [
"Compute",
"the",
"average",
"surface",
"brightness",
"[",
"mag",
"arcsec^",
"-",
"2",
"]",
"within",
"the",
"half",
"-",
"light",
"radius"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L317-L332 | train | Compute the average surface brightness within the half - light radius. |
DarkEnergySurvey/ugali | ugali/analysis/results.py | createResults | def createResults(config,srcfile,section='source',samples=None):
""" Create an MCMC instance """
source = ugali.analysis.source.Source()
source.load(srcfile,section=section)
loglike = ugali.analysis.loglike.createLoglike(config,source)
results = Results(config,loglike,samples)
if samples is no... | python | def createResults(config,srcfile,section='source',samples=None):
""" Create an MCMC instance """
source = ugali.analysis.source.Source()
source.load(srcfile,section=section)
loglike = ugali.analysis.loglike.createLoglike(config,source)
results = Results(config,loglike,samples)
if samples is no... | [
"def",
"createResults",
"(",
"config",
",",
"srcfile",
",",
"section",
"=",
"'source'",
",",
"samples",
"=",
"None",
")",
":",
"source",
"=",
"ugali",
".",
"analysis",
".",
"source",
".",
"Source",
"(",
")",
"source",
".",
"load",
"(",
"srcfile",
",",
... | Create an MCMC instance | [
"Create",
"an",
"MCMC",
"instance"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L334-L345 | train | Create an instance of the results class. |
DarkEnergySurvey/ugali | ugali/analysis/results.py | write_results | def write_results(filename,config,srcfile,samples):
""" Package everything nicely """
results = createResults(config,srcfile,samples=samples)
results.write(filename) | python | def write_results(filename,config,srcfile,samples):
""" Package everything nicely """
results = createResults(config,srcfile,samples=samples)
results.write(filename) | [
"def",
"write_results",
"(",
"filename",
",",
"config",
",",
"srcfile",
",",
"samples",
")",
":",
"results",
"=",
"createResults",
"(",
"config",
",",
"srcfile",
",",
"samples",
"=",
"samples",
")",
"results",
".",
"write",
"(",
"filename",
")"
] | Package everything nicely | [
"Package",
"everything",
"nicely"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L347-L350 | train | Write results to a file. |
DarkEnergySurvey/ugali | ugali/analysis/results.py | Results.estimate | def estimate(self,param,burn=None,clip=10.0,alpha=0.32):
""" Estimate parameter value and uncertainties """
# FIXME: Need to add age and metallicity to composite isochrone params (currently properties)
if param not in list(self.samples.names) + list(self.source.params) + ['age','metallicity']:
... | python | def estimate(self,param,burn=None,clip=10.0,alpha=0.32):
""" Estimate parameter value and uncertainties """
# FIXME: Need to add age and metallicity to composite isochrone params (currently properties)
if param not in list(self.samples.names) + list(self.source.params) + ['age','metallicity']:
... | [
"def",
"estimate",
"(",
"self",
",",
"param",
",",
"burn",
"=",
"None",
",",
"clip",
"=",
"10.0",
",",
"alpha",
"=",
"0.32",
")",
":",
"# FIXME: Need to add age and metallicity to composite isochrone params (currently properties)",
"if",
"param",
"not",
"in",
"list"... | Estimate parameter value and uncertainties | [
"Estimate",
"parameter",
"value",
"and",
"uncertainties"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L57-L81 | train | Estimate the parameter value and uncertainties for the specified parameter. |
DarkEnergySurvey/ugali | ugali/analysis/results.py | Results.estimate_params | def estimate_params(self,burn=None,clip=10.0,alpha=0.32):
""" Estimate all source parameters """
mle = self.get_mle()
out = odict()
for param in mle.keys():
out[param] = self.estimate(param,burn=burn,clip=clip,alpha=alpha)
return out | python | def estimate_params(self,burn=None,clip=10.0,alpha=0.32):
""" Estimate all source parameters """
mle = self.get_mle()
out = odict()
for param in mle.keys():
out[param] = self.estimate(param,burn=burn,clip=clip,alpha=alpha)
return out | [
"def",
"estimate_params",
"(",
"self",
",",
"burn",
"=",
"None",
",",
"clip",
"=",
"10.0",
",",
"alpha",
"=",
"0.32",
")",
":",
"mle",
"=",
"self",
".",
"get_mle",
"(",
")",
"out",
"=",
"odict",
"(",
")",
"for",
"param",
"in",
"mle",
".",
"keys",... | Estimate all source parameters | [
"Estimate",
"all",
"source",
"parameters"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L92-L98 | train | Estimate all source parameters |
DarkEnergySurvey/ugali | ugali/analysis/results.py | Results.estimate_position_angle | def estimate_position_angle(self,param='position_angle',burn=None,clip=10.0,alpha=0.32):
""" Estimate the position angle from the posterior dealing
with periodicity.
"""
# Transform so peak in the middle of the distribution
pa = self.samples.get(param,burn=burn,clip=clip)
... | python | def estimate_position_angle(self,param='position_angle',burn=None,clip=10.0,alpha=0.32):
""" Estimate the position angle from the posterior dealing
with periodicity.
"""
# Transform so peak in the middle of the distribution
pa = self.samples.get(param,burn=burn,clip=clip)
... | [
"def",
"estimate_position_angle",
"(",
"self",
",",
"param",
"=",
"'position_angle'",
",",
"burn",
"=",
"None",
",",
"clip",
"=",
"10.0",
",",
"alpha",
"=",
"0.32",
")",
":",
"# Transform so peak in the middle of the distribution",
"pa",
"=",
"self",
".",
"sampl... | Estimate the position angle from the posterior dealing
with periodicity. | [
"Estimate",
"the",
"position",
"angle",
"from",
"the",
"posterior",
"dealing",
"with",
"periodicity",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L100-L113 | train | Estimate the position angle from the posterior dealing
with periodicity. |
alphagov/performanceplatform-collector | performanceplatform/collector/webtrends/keymetrics.py | Collector.date_range_for_webtrends | def date_range_for_webtrends(cls, start_at=None, end_at=None):
"""
Get the start and end formatted for query
or the last hour if none specified.
Unlike reports, this does not aggregate periods
and so it is possible to just query a range and parse out the
individual hours.... | python | def date_range_for_webtrends(cls, start_at=None, end_at=None):
"""
Get the start and end formatted for query
or the last hour if none specified.
Unlike reports, this does not aggregate periods
and so it is possible to just query a range and parse out the
individual hours.... | [
"def",
"date_range_for_webtrends",
"(",
"cls",
",",
"start_at",
"=",
"None",
",",
"end_at",
"=",
"None",
")",
":",
"if",
"start_at",
"and",
"end_at",
":",
"start_date",
"=",
"cls",
".",
"parse_standard_date_string_to_date",
"(",
"start_at",
")",
"end_date",
"=... | Get the start and end formatted for query
or the last hour if none specified.
Unlike reports, this does not aggregate periods
and so it is possible to just query a range and parse out the
individual hours. | [
"Get",
"the",
"start",
"and",
"end",
"formatted",
"for",
"query",
"or",
"the",
"last",
"hour",
"if",
"none",
"specified",
".",
"Unlike",
"reports",
"this",
"does",
"not",
"aggregate",
"periods",
"and",
"so",
"it",
"is",
"possible",
"to",
"just",
"query",
... | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/webtrends/keymetrics.py#L15-L32 | train | Get the start and end formatted for query
or the last hour for query
. |
DarkEnergySurvey/ugali | ugali/utils/shell.py | get_ugali_dir | def get_ugali_dir():
"""Get the path to the ugali data directory from the environment"""
dirname = os.getenv('UGALIDIR')
# Get the HOME directory
if not dirname:
dirname=os.path.join(os.getenv('HOME'),'.ugali')
if not os.path.exists(dirname):
from ugali.utils.logger import logger
... | python | def get_ugali_dir():
"""Get the path to the ugali data directory from the environment"""
dirname = os.getenv('UGALIDIR')
# Get the HOME directory
if not dirname:
dirname=os.path.join(os.getenv('HOME'),'.ugali')
if not os.path.exists(dirname):
from ugali.utils.logger import logger
... | [
"def",
"get_ugali_dir",
"(",
")",
":",
"dirname",
"=",
"os",
".",
"getenv",
"(",
"'UGALIDIR'",
")",
"# Get the HOME directory",
"if",
"not",
"dirname",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getenv",
"(",
"'HOME'",
")",
"... | Get the path to the ugali data directory from the environment | [
"Get",
"the",
"path",
"to",
"the",
"ugali",
"data",
"directory",
"from",
"the",
"environment"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/shell.py#L48-L62 | train | Get the path to the ugali data directory from the environment |
DarkEnergySurvey/ugali | ugali/utils/shell.py | get_iso_dir | def get_iso_dir():
"""Get the ugali isochrone directory."""
dirname = os.path.join(get_ugali_dir(),'isochrones')
if not os.path.exists(dirname):
from ugali.utils.logger import logger
msg = "Isochrone directory not found:\n%s"%dirname
logger.warning(msg)
return dirname | python | def get_iso_dir():
"""Get the ugali isochrone directory."""
dirname = os.path.join(get_ugali_dir(),'isochrones')
if not os.path.exists(dirname):
from ugali.utils.logger import logger
msg = "Isochrone directory not found:\n%s"%dirname
logger.warning(msg)
return dirname | [
"def",
"get_iso_dir",
"(",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_ugali_dir",
"(",
")",
",",
"'isochrones'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"from",
"ugali",
".",
"utils",
"... | Get the ugali isochrone directory. | [
"Get",
"the",
"ugali",
"isochrone",
"directory",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/shell.py#L64-L73 | train | Get the ugali isochrone directory. |
warrenspe/hconf | hconf/Config.py | ConfigManager.registerParser | def registerParser(self, parser):
"""
Registers a parser to parse configuration inputs.
"""
if not isinstance(parser, Subparser):
raise TypeError("%s is not an instance of a subparser." % parser)
self.parsers.append(parser) | python | def registerParser(self, parser):
"""
Registers a parser to parse configuration inputs.
"""
if not isinstance(parser, Subparser):
raise TypeError("%s is not an instance of a subparser." % parser)
self.parsers.append(parser) | [
"def",
"registerParser",
"(",
"self",
",",
"parser",
")",
":",
"if",
"not",
"isinstance",
"(",
"parser",
",",
"Subparser",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is not an instance of a subparser.\"",
"%",
"parser",
")",
"self",
".",
"parsers",
".",
"appen... | Registers a parser to parse configuration inputs. | [
"Registers",
"a",
"parser",
"to",
"parse",
"configuration",
"inputs",
"."
] | 12074d15dc3641d3903488c95d89a507386a32d5 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L65-L73 | train | Registers a parser to parse configuration inputs. |
warrenspe/hconf | hconf/Config.py | ConfigManager.addConfig | def addConfig(self, name, default=None, cast=None, required=False, description=None):
"""
Adds the given configuration option to the ConfigManager.
Inputs: name - The configuration name to accept.
required - A boolean indicating whether or not the configuration option ... | python | def addConfig(self, name, default=None, cast=None, required=False, description=None):
"""
Adds the given configuration option to the ConfigManager.
Inputs: name - The configuration name to accept.
required - A boolean indicating whether or not the configuration option ... | [
"def",
"addConfig",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"cast",
"=",
"None",
",",
"required",
"=",
"False",
",",
"description",
"=",
"None",
")",
":",
"# Validate the name",
"if",
"not",
"self",
".",
"configNameRE",
".",
"match",
... | Adds the given configuration option to the ConfigManager.
Inputs: name - The configuration name to accept.
required - A boolean indicating whether or not the configuration option is required or not.
cast - A type (or function accepting 1 argument and returning a... | [
"Adds",
"the",
"given",
"configuration",
"option",
"to",
"the",
"ConfigManager",
"."
] | 12074d15dc3641d3903488c95d89a507386a32d5 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L75-L98 | train | Adds a new configuration option to the ConfigManager. |
warrenspe/hconf | hconf/Config.py | ConfigManager.parse | def parse(self):
"""
Executes the registered parsers to parse input configurations.
"""
self._config = _Config()
self._setDefaults()
for parser in self.parsers:
for key, value in parser.parse(self, self._config).items():
key = self._sanitize... | python | def parse(self):
"""
Executes the registered parsers to parse input configurations.
"""
self._config = _Config()
self._setDefaults()
for parser in self.parsers:
for key, value in parser.parse(self, self._config).items():
key = self._sanitize... | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"_config",
"=",
"_Config",
"(",
")",
"self",
".",
"_setDefaults",
"(",
")",
"for",
"parser",
"in",
"self",
".",
"parsers",
":",
"for",
"key",
",",
"value",
"in",
"parser",
".",
"parse",
"(",
"self... | Executes the registered parsers to parse input configurations. | [
"Executes",
"the",
"registered",
"parsers",
"to",
"parse",
"input",
"configurations",
"."
] | 12074d15dc3641d3903488c95d89a507386a32d5 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L100-L120 | train | Parses the input configurations and returns the parsed configuration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.