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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
totalgood/pugnlp | src/pugnlp/util.py | kmer_counter | def kmer_counter(seq, k=4):
"""Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
jellyfish is a C implementation of k-mer counting
If seq is a string generate a... | python | def kmer_counter(seq, k=4):
"""Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
jellyfish is a C implementation of k-mer counting
If seq is a string generate a... | [
"def",
"kmer_counter",
"(",
"seq",
",",
"k",
"=",
"4",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"basestring",
")",
":",
"return",
"Counter",
"(",
"generate_kmers",
"(",
"seq",
",",
"k",
")",
")"
] | Return a sequence of all the unique substrings (k-mer or q-gram) within a short (<128 symbol) string
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
jellyfish is a C implementation of k-mer counting
If seq is a string generate a sequence of k-mer string
If se... | [
"Return",
"a",
"sequence",
"of",
"all",
"the",
"unique",
"substrings",
"(",
"k",
"-",
"mer",
"or",
"q",
"-",
"gram",
")",
"within",
"a",
"short",
"(",
"<128",
"symbol",
")",
"string"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2767-L2786 | train | Return a Counter object for all the k - mer substrings within a short symbol. |
totalgood/pugnlp | src/pugnlp/util.py | kmer_set | def kmer_set(seq, k=4):
"""Return the set of unique k-length substrings within a the sequence/string `seq`
Implements formula:
C_k(s) = C(s) ∩ Σ^k
from http://biorxiv.org/content/early/2014/08/01/007583
>>> sorted(kmer_set('AGATAGATAGACACAGAAATGGGACCACAC')) # doctest: +NORMALIZE_WHITESPACE, +ELLI... | python | def kmer_set(seq, k=4):
"""Return the set of unique k-length substrings within a the sequence/string `seq`
Implements formula:
C_k(s) = C(s) ∩ Σ^k
from http://biorxiv.org/content/early/2014/08/01/007583
>>> sorted(kmer_set('AGATAGATAGACACAGAAATGGGACCACAC')) # doctest: +NORMALIZE_WHITESPACE, +ELLI... | [
"def",
"kmer_set",
"(",
"seq",
",",
"k",
"=",
"4",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"basestring",
")",
":",
"return",
"set",
"(",
"generate_kmers",
"(",
"seq",
",",
"k",
")",
")"
] | Return the set of unique k-length substrings within a the sequence/string `seq`
Implements formula:
C_k(s) = C(s) ∩ Σ^k
from http://biorxiv.org/content/early/2014/08/01/007583
>>> sorted(kmer_set('AGATAGATAGACACAGAAATGGGACCACAC')) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
['AAAT', 'AATG', 'ACAC... | [
"Return",
"the",
"set",
"of",
"unique",
"k",
"-",
"length",
"substrings",
"within",
"a",
"the",
"sequence",
"/",
"string",
"seq"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2789-L2800 | train | Return the set of k - length substrings within a sequence |
totalgood/pugnlp | src/pugnlp/util.py | count_duplicates | def count_duplicates(items):
"""Return a dict of objects and thier counts (like a Counter), but only count > 1"""
c = Counter(items)
return dict((k, v) for (k, v) in viewitems(c) if v > 1) | python | def count_duplicates(items):
"""Return a dict of objects and thier counts (like a Counter), but only count > 1"""
c = Counter(items)
return dict((k, v) for (k, v) in viewitems(c) if v > 1) | [
"def",
"count_duplicates",
"(",
"items",
")",
":",
"c",
"=",
"Counter",
"(",
"items",
")",
"return",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"viewitems",
"(",
"c",
")",
"if",
"v",
">",
"1",
")"
] | Return a dict of objects and thier counts (like a Counter), but only count > 1 | [
"Return",
"a",
"dict",
"of",
"objects",
"and",
"thier",
"counts",
"(",
"like",
"a",
"Counter",
")",
"but",
"only",
"count",
">",
"1"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2858-L2861 | train | Return a dict of objects and thier counts but only count > 1 |
totalgood/pugnlp | src/pugnlp/util.py | slug_from_dict | def slug_from_dict(d, max_len=128, delim='-'):
"""Produce a slug (short URI-friendly string) from an iterable Mapping (dict, OrderedDict)
>>> slug_from_dict(OrderedDict([('a', 1), ('b', 'beta'), (' ', 'alpha')]))
'1-beta-alpha'
"""
return slug_from_iter(list(d.values()), max_len=max_len, delim=deli... | python | def slug_from_dict(d, max_len=128, delim='-'):
"""Produce a slug (short URI-friendly string) from an iterable Mapping (dict, OrderedDict)
>>> slug_from_dict(OrderedDict([('a', 1), ('b', 'beta'), (' ', 'alpha')]))
'1-beta-alpha'
"""
return slug_from_iter(list(d.values()), max_len=max_len, delim=deli... | [
"def",
"slug_from_dict",
"(",
"d",
",",
"max_len",
"=",
"128",
",",
"delim",
"=",
"'-'",
")",
":",
"return",
"slug_from_iter",
"(",
"list",
"(",
"d",
".",
"values",
"(",
")",
")",
",",
"max_len",
"=",
"max_len",
",",
"delim",
"=",
"delim",
")"
] | Produce a slug (short URI-friendly string) from an iterable Mapping (dict, OrderedDict)
>>> slug_from_dict(OrderedDict([('a', 1), ('b', 'beta'), (' ', 'alpha')]))
'1-beta-alpha' | [
"Produce",
"a",
"slug",
"(",
"short",
"URI",
"-",
"friendly",
"string",
")",
"from",
"an",
"iterable",
"Mapping",
"(",
"dict",
"OrderedDict",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2884-L2890 | train | Produce a short URI - friendly string from an iterable Mapping |
totalgood/pugnlp | src/pugnlp/util.py | slug_from_iter | def slug_from_iter(it, max_len=128, delim='-'):
"""Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict)
>>> slug_from_iter(['.a.', '=b=', '--alpha--'])
'a-b-alpha'
"""
nonnull_values = [str(v) for v in it if v or ((isinstance(v, (int, float, Decimal)) and str(v)))]
r... | python | def slug_from_iter(it, max_len=128, delim='-'):
"""Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict)
>>> slug_from_iter(['.a.', '=b=', '--alpha--'])
'a-b-alpha'
"""
nonnull_values = [str(v) for v in it if v or ((isinstance(v, (int, float, Decimal)) and str(v)))]
r... | [
"def",
"slug_from_iter",
"(",
"it",
",",
"max_len",
"=",
"128",
",",
"delim",
"=",
"'-'",
")",
":",
"nonnull_values",
"=",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"it",
"if",
"v",
"or",
"(",
"(",
"isinstance",
"(",
"v",
",",
"(",
"int",
",... | Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict)
>>> slug_from_iter(['.a.', '=b=', '--alpha--'])
'a-b-alpha' | [
"Produce",
"a",
"slug",
"(",
"short",
"URI",
"-",
"friendly",
"string",
")",
"from",
"an",
"iterable",
"(",
"list",
"tuple",
"dict",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2893-L2902 | train | Produce a slug from an iterable |
totalgood/pugnlp | src/pugnlp/util.py | slash_product | def slash_product(string_or_seq, slash='/', space=' '):
"""Return a list of all possible meanings of a phrase containing slashes
TODO:
- Code is not in standard Sedgewick recursion form
- Simplify by removing one of the recursive calls?
- Simplify by using a list comprehension?
# d... | python | def slash_product(string_or_seq, slash='/', space=' '):
"""Return a list of all possible meanings of a phrase containing slashes
TODO:
- Code is not in standard Sedgewick recursion form
- Simplify by removing one of the recursive calls?
- Simplify by using a list comprehension?
# d... | [
"def",
"slash_product",
"(",
"string_or_seq",
",",
"slash",
"=",
"'/'",
",",
"space",
"=",
"' '",
")",
":",
"# Terminating case is a sequence of strings without any slashes",
"if",
"not",
"isinstance",
"(",
"string_or_seq",
",",
"basestring",
")",
":",
"# If it's not ... | Return a list of all possible meanings of a phrase containing slashes
TODO:
- Code is not in standard Sedgewick recursion form
- Simplify by removing one of the recursive calls?
- Simplify by using a list comprehension?
# doctest: +NORMALIZE_WHITESPACE
>>> slash_product("The challe... | [
"Return",
"a",
"list",
"of",
"all",
"possible",
"meanings",
"of",
"a",
"phrase",
"containing",
"slashes"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2916-L2964 | train | Return a list of all possible meanings of a phrase containing slashes. |
DarkEnergySurvey/ugali | ugali/scratch/position_angle.py | create_header | def create_header(coord, radius, proj='ZEA', npix=30):
""" Create a header a new image """
gal = coord.name == 'galactic'
values = [
["NAXIS", 2, ],
["NAXIS1", npix, ],
["NAXIS2", npix, ],
["CTYPE1", 'GLON-%s'%proj if gal else 'RA---%... | python | def create_header(coord, radius, proj='ZEA', npix=30):
""" Create a header a new image """
gal = coord.name == 'galactic'
values = [
["NAXIS", 2, ],
["NAXIS1", npix, ],
["NAXIS2", npix, ],
["CTYPE1", 'GLON-%s'%proj if gal else 'RA---%... | [
"def",
"create_header",
"(",
"coord",
",",
"radius",
",",
"proj",
"=",
"'ZEA'",
",",
"npix",
"=",
"30",
")",
":",
"gal",
"=",
"coord",
".",
"name",
"==",
"'galactic'",
"values",
"=",
"[",
"[",
"\"NAXIS\"",
",",
"2",
",",
"]",
",",
"[",
"\"NAXIS1\""... | Create a header a new image | [
"Create",
"a",
"header",
"a",
"new",
"image"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/position_angle.py#L19-L50 | train | Create a header a new image |
DarkEnergySurvey/ugali | ugali/scratch/position_angle.py | create_header_data | def create_header_data(coord, radius=10., **kwargs):
""" Make an empty sky region at location of skydir
skydir : skymaps.SkyDir object
size : size of region (deg.)
kwargs : arguments passed to create_header
"""
header = create_header(coord, radius=radius, **kwargs)
data = np.zeros( (header... | python | def create_header_data(coord, radius=10., **kwargs):
""" Make an empty sky region at location of skydir
skydir : skymaps.SkyDir object
size : size of region (deg.)
kwargs : arguments passed to create_header
"""
header = create_header(coord, radius=radius, **kwargs)
data = np.zeros( (header... | [
"def",
"create_header_data",
"(",
"coord",
",",
"radius",
"=",
"10.",
",",
"*",
"*",
"kwargs",
")",
":",
"header",
"=",
"create_header",
"(",
"coord",
",",
"radius",
"=",
"radius",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"np",
".",
"zeros",
"(",
... | Make an empty sky region at location of skydir
skydir : skymaps.SkyDir object
size : size of region (deg.)
kwargs : arguments passed to create_header | [
"Make",
"an",
"empty",
"sky",
"region",
"at",
"location",
"of",
"skydir",
"skydir",
":",
"skymaps",
".",
"SkyDir",
"object",
"size",
":",
"size",
"of",
"region",
"(",
"deg",
".",
")",
"kwargs",
":",
"arguments",
"passed",
"to",
"create_header"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/position_angle.py#L52-L60 | train | Create an empty sky region at location of skydir
|
DarkEnergySurvey/ugali | ugali/scratch/position_angle.py | plot_skyreg | def plot_skyreg(header, data, **kwargs):
""" Plot sky region defined by header and data
header : FITS header
data : Data array
"""
kwargs.setdefault('cmap','binary')
fig = plt.figure()
ax = pywcsgrid2.subplot(111, header=header)
ax.set_ticklabel_type("dms")
im = ax.imshow(data, ori... | python | def plot_skyreg(header, data, **kwargs):
""" Plot sky region defined by header and data
header : FITS header
data : Data array
"""
kwargs.setdefault('cmap','binary')
fig = plt.figure()
ax = pywcsgrid2.subplot(111, header=header)
ax.set_ticklabel_type("dms")
im = ax.imshow(data, ori... | [
"def",
"plot_skyreg",
"(",
"header",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'cmap'",
",",
"'binary'",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"pywcsgrid2",
".",
"subplot",
"(",
"111",
... | Plot sky region defined by header and data
header : FITS header
data : Data array | [
"Plot",
"sky",
"region",
"defined",
"by",
"header",
"and",
"data",
"header",
":",
"FITS",
"header",
"data",
":",
"Data",
"array"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/position_angle.py#L63-L76 | train | Plot a sky region defined by header and data. |
DarkEnergySurvey/ugali | ugali/scratch/position_angle.py | estimate_angle | def estimate_angle(coord, angle, new_frame, offset=1e-7):
"""
https://github.com/astropy/astropy/issues/3093
"""
delta = delta_coord(coord, angle, offset)
new_coord = coord.transform_to(new_frame)
new_delta = delta.transform_to(new_frame)
return new_coord.position_angle(new_delta).deg | python | def estimate_angle(coord, angle, new_frame, offset=1e-7):
"""
https://github.com/astropy/astropy/issues/3093
"""
delta = delta_coord(coord, angle, offset)
new_coord = coord.transform_to(new_frame)
new_delta = delta.transform_to(new_frame)
return new_coord.position_angle(new_delta).deg | [
"def",
"estimate_angle",
"(",
"coord",
",",
"angle",
",",
"new_frame",
",",
"offset",
"=",
"1e-7",
")",
":",
"delta",
"=",
"delta_coord",
"(",
"coord",
",",
"angle",
",",
"offset",
")",
"new_coord",
"=",
"coord",
".",
"transform_to",
"(",
"new_frame",
")... | https://github.com/astropy/astropy/issues/3093 | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"astropy",
"/",
"astropy",
"/",
"issues",
"/",
"3093"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/position_angle.py#L117-L124 | train | Estimate the angle of a given coordinate. |
totalgood/pugnlp | src/pugnlp/penn_treebank_tokenizer.py | word_tokenize | def word_tokenize(text):
"""
Split string `text` into word tokens using the Penn Treebank rules
"""
for (regexp, replacement) in RULES1:
text = sub(regexp, replacement, text)
# add extra space to make things easier
text = " " + text + " "
for (regexp, replacement) in RULES2:
... | python | def word_tokenize(text):
"""
Split string `text` into word tokens using the Penn Treebank rules
"""
for (regexp, replacement) in RULES1:
text = sub(regexp, replacement, text)
# add extra space to make things easier
text = " " + text + " "
for (regexp, replacement) in RULES2:
... | [
"def",
"word_tokenize",
"(",
"text",
")",
":",
"for",
"(",
"regexp",
",",
"replacement",
")",
"in",
"RULES1",
":",
"text",
"=",
"sub",
"(",
"regexp",
",",
"replacement",
",",
"text",
")",
"# add extra space to make things easier",
"text",
"=",
"\" \"",
"+",
... | Split string `text` into word tokens using the Penn Treebank rules | [
"Split",
"string",
"text",
"into",
"word",
"tokens",
"using",
"the",
"Penn",
"Treebank",
"rules"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/penn_treebank_tokenizer.py#L83-L96 | train | Split string text into word tokens using the Penn Treebank rules
|
consbio/ncdjango | ncdjango/interfaces/arcgis/form_fields.py | GeometryField.to_python | def to_python(self, value):
"""
This assumes the value has been preprocessed into a dictionary of the form:
{'type': <geometry_type>, 'geometry': <raw_geometry>}
"""
if not value or isinstance(value, BaseGeometry):
return value
geometry_type = value['type']
... | python | def to_python(self, value):
"""
This assumes the value has been preprocessed into a dictionary of the form:
{'type': <geometry_type>, 'geometry': <raw_geometry>}
"""
if not value or isinstance(value, BaseGeometry):
return value
geometry_type = value['type']
... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"isinstance",
"(",
"value",
",",
"BaseGeometry",
")",
":",
"return",
"value",
"geometry_type",
"=",
"value",
"[",
"'type'",
"]",
"geometry",
"=",
"value",
"[",
"'geometr... | This assumes the value has been preprocessed into a dictionary of the form:
{'type': <geometry_type>, 'geometry': <raw_geometry>} | [
"This",
"assumes",
"the",
"value",
"has",
"been",
"preprocessed",
"into",
"a",
"dictionary",
"of",
"the",
"form",
":",
"{",
"type",
":",
"<geometry_type",
">",
"geometry",
":",
"<raw_geometry",
">",
"}"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis/form_fields.py#L47-L92 | train | Converts the value into a Python object. |
hootnot/postcode-api-wrapper | postcodepy/postcodepy.py | EndpointsMixin.get_postcodedata | def get_postcodedata(self, postcode, nr, addition="", **params):
"""get_postcodedata - fetch information for 'postcode'.
Parameters
----------
postcode : string
The full (dutch) postcode
nr : int
The housenumber
addition : string (optional)
... | python | def get_postcodedata(self, postcode, nr, addition="", **params):
"""get_postcodedata - fetch information for 'postcode'.
Parameters
----------
postcode : string
The full (dutch) postcode
nr : int
The housenumber
addition : string (optional)
... | [
"def",
"get_postcodedata",
"(",
"self",
",",
"postcode",
",",
"nr",
",",
"addition",
"=",
"\"\"",
",",
"*",
"*",
"params",
")",
":",
"endpoint",
"=",
"'rest/addresses/%s/%s'",
"%",
"(",
"postcode",
",",
"nr",
")",
"if",
"addition",
":",
"endpoint",
"+=",... | get_postcodedata - fetch information for 'postcode'.
Parameters
----------
postcode : string
The full (dutch) postcode
nr : int
The housenumber
addition : string (optional)
the extension to a housenumber
params : dict (optional)
... | [
"get_postcodedata",
"-",
"fetch",
"information",
"for",
"postcode",
"."
] | 42359cb9402f84a06f7d58f889f1156d653f5ea9 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/postcodepy.py#L14-L51 | train | get_postcodedata - fetch information for postcode. |
hootnot/postcode-api-wrapper | postcodepy/postcodepy.py | EndpointsMixin.get_signalcheck | def get_signalcheck(self, sar, **params):
"""get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.po... | python | def get_signalcheck(self, sar, **params):
"""get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.po... | [
"def",
"get_signalcheck",
"(",
"self",
",",
"sar",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"sar",
"endpoint",
"=",
"'rest/signal/check'",
"# The 'sar'-request dictionary should be sent as valid JSON data, so",
"# we need to convert it to JSON",
"# when we construct ... | get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.postcode.nl/documentation/signal-api-example.
... | [
"get_signalcheck",
"-",
"perform",
"a",
"signal",
"check",
"."
] | 42359cb9402f84a06f7d58f889f1156d653f5ea9 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/postcodepy.py#L53-L75 | train | This is the main function for the signal check API. |
hootnot/postcode-api-wrapper | postcodepy/postcodepy.py | API.__request | def __request(self, endpoint, method='GET', params=None, convJSON=False):
"""request - Returns dict of response from postcode.nl API.
This method is called only by the EndpointMixin methods.
"""
url = '%s/%s' % (self.api_url, endpoint)
method = method.lower()
params = p... | python | def __request(self, endpoint, method='GET', params=None, convJSON=False):
"""request - Returns dict of response from postcode.nl API.
This method is called only by the EndpointMixin methods.
"""
url = '%s/%s' % (self.api_url, endpoint)
method = method.lower()
params = p... | [
"def",
"__request",
"(",
"self",
",",
"endpoint",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"convJSON",
"=",
"False",
")",
":",
"url",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"api_url",
",",
"endpoint",
")",
"method",
"=",
"method"... | request - Returns dict of response from postcode.nl API.
This method is called only by the EndpointMixin methods. | [
"request",
"-",
"Returns",
"dict",
"of",
"response",
"from",
"postcode",
".",
"nl",
"API",
"."
] | 42359cb9402f84a06f7d58f889f1156d653f5ea9 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/postcodepy.py#L122-L163 | train | This method is called by the EndpointMixin methods. It returns dict of response from postcode. nl API. |
DarkEnergySurvey/ugali | ugali/simulation/validation.py | validateSatellite | def validateSatellite(config, isochrone, kernel, stellar_mass, distance_modulus, trials=1, debug=False, seed=0):
"""
Tool for simple MC validation studies -- specifically to create multiple realizations of
a satellite given an CompositeIsochrone object, Kernel object, stellar mass (M_sol) for normalization,... | python | def validateSatellite(config, isochrone, kernel, stellar_mass, distance_modulus, trials=1, debug=False, seed=0):
"""
Tool for simple MC validation studies -- specifically to create multiple realizations of
a satellite given an CompositeIsochrone object, Kernel object, stellar mass (M_sol) for normalization,... | [
"def",
"validateSatellite",
"(",
"config",
",",
"isochrone",
",",
"kernel",
",",
"stellar_mass",
",",
"distance_modulus",
",",
"trials",
"=",
"1",
",",
"debug",
"=",
"False",
",",
"seed",
"=",
"0",
")",
":",
"logger",
".",
"info",
"(",
"'=== Validate Satel... | Tool for simple MC validation studies -- specifically to create multiple realizations of
a satellite given an CompositeIsochrone object, Kernel object, stellar mass (M_sol) for normalization,
and distance_modulus. | [
"Tool",
"for",
"simple",
"MC",
"validation",
"studies",
"--",
"specifically",
"to",
"create",
"multiple",
"realizations",
"of",
"a",
"satellite",
"given",
"an",
"CompositeIsochrone",
"object",
"Kernel",
"object",
"stellar",
"mass",
"(",
"M_sol",
")",
"for",
"nor... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/validation.py#L21-L86 | train | Validate a satellite. |
DarkEnergySurvey/ugali | ugali/simulation/validation.py | validateMembership | def validateMembership(likelihood, p, mc_source_id=1):
"""
Plot membership probabilities and MC source ids together.
"""
cut_mc_source_id = (likelihood.catalog.mc_source_id == mc_source_id)
# Spatial
projector = ugali.utils.projector.Projector(likelihood.kernel.lon, likelihood.kernel.lat)
... | python | def validateMembership(likelihood, p, mc_source_id=1):
"""
Plot membership probabilities and MC source ids together.
"""
cut_mc_source_id = (likelihood.catalog.mc_source_id == mc_source_id)
# Spatial
projector = ugali.utils.projector.Projector(likelihood.kernel.lon, likelihood.kernel.lat)
... | [
"def",
"validateMembership",
"(",
"likelihood",
",",
"p",
",",
"mc_source_id",
"=",
"1",
")",
":",
"cut_mc_source_id",
"=",
"(",
"likelihood",
".",
"catalog",
".",
"mc_source_id",
"==",
"mc_source_id",
")",
"# Spatial",
"projector",
"=",
"ugali",
".",
"utils",... | Plot membership probabilities and MC source ids together. | [
"Plot",
"membership",
"probabilities",
"and",
"MC",
"source",
"ids",
"together",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/validation.py#L90-L221 | train | Validate membership probability and accuracy of a likelihood. |
totalgood/pugnlp | src/pugnlp/plots.py | regression_and_plot | def regression_and_plot(x, y=None):
"""
Fit a line to the x, y data supplied and plot it along with teh raw samples
>>> age = [25, 26, 33, 29, 27, 21, 26, 35, 21, 37, 21, 38, 18, 19, 36, 30, 29, 24, 24, 36, 36, 27,
... 33, 23, 21, 26, 27, 27, 24, 26, 25, 24, 22, 25, 40, 39, 19, 31, 33, 30, 33, 2... | python | def regression_and_plot(x, y=None):
"""
Fit a line to the x, y data supplied and plot it along with teh raw samples
>>> age = [25, 26, 33, 29, 27, 21, 26, 35, 21, 37, 21, 38, 18, 19, 36, 30, 29, 24, 24, 36, 36, 27,
... 33, 23, 21, 26, 27, 27, 24, 26, 25, 24, 22, 25, 40, 39, 19, 31, 33, 30, 33, 2... | [
"def",
"regression_and_plot",
"(",
"x",
",",
"y",
"=",
"None",
")",
":",
"if",
"y",
"is",
"None",
":",
"y",
"=",
"x",
"x",
"=",
"range",
"(",
"len",
"(",
"x",
")",
")",
"if",
"not",
"isinstance",
"(",
"x",
"[",
"0",
"]",
",",
"(",
"float",
... | Fit a line to the x, y data supplied and plot it along with teh raw samples
>>> age = [25, 26, 33, 29, 27, 21, 26, 35, 21, 37, 21, 38, 18, 19, 36, 30, 29, 24, 24, 36, 36, 27,
... 33, 23, 21, 26, 27, 27, 24, 26, 25, 24, 22, 25, 40, 39, 19, 31, 33, 30, 33, 27, 40, 32,
... 31, 35, 26, 34, 27, 34... | [
"Fit",
"a",
"line",
"to",
"the",
"x",
"y",
"data",
"supplied",
"and",
"plot",
"it",
"along",
"with",
"teh",
"raw",
"samples"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L125-L225 | train | Fit a line to the x y data supplied and plot it along with teh raw samples. |
totalgood/pugnlp | src/pugnlp/plots.py | regressionplot | def regressionplot(x, y, poly=None):
"""
Plot a 2-D linear regression (y = slope * x + offset) overlayed over the raw data samples
"""
if not isinstance(x[0], (float, int, np.float64, np.float32)):
x = [row[0] for row in x]
y_regression = poly[0] * np.array(x) + poly[-1]
try:
plt... | python | def regressionplot(x, y, poly=None):
"""
Plot a 2-D linear regression (y = slope * x + offset) overlayed over the raw data samples
"""
if not isinstance(x[0], (float, int, np.float64, np.float32)):
x = [row[0] for row in x]
y_regression = poly[0] * np.array(x) + poly[-1]
try:
plt... | [
"def",
"regressionplot",
"(",
"x",
",",
"y",
",",
"poly",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
"[",
"0",
"]",
",",
"(",
"float",
",",
"int",
",",
"np",
".",
"float64",
",",
"np",
".",
"float32",
")",
")",
":",
"x",
"=",... | Plot a 2-D linear regression (y = slope * x + offset) overlayed over the raw data samples | [
"Plot",
"a",
"2",
"-",
"D",
"linear",
"regression",
"(",
"y",
"=",
"slope",
"*",
"x",
"+",
"offset",
")",
"overlayed",
"over",
"the",
"raw",
"data",
"samples"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L228-L245 | train | Plot a 2 - D linear regression of the raw data |
totalgood/pugnlp | src/pugnlp/plots.py | scatmat | def scatmat(df, category=None, colors='rgob',
num_plots=4, num_topics=100, num_columns=4,
show=False, block=False, data_path=DATA_PATH, save=False, verbose=1):
"""Scatter plot with colored markers depending on the discrete values in a "category" column
FIXME: empty plots that dont go aw... | python | def scatmat(df, category=None, colors='rgob',
num_plots=4, num_topics=100, num_columns=4,
show=False, block=False, data_path=DATA_PATH, save=False, verbose=1):
"""Scatter plot with colored markers depending on the discrete values in a "category" column
FIXME: empty plots that dont go aw... | [
"def",
"scatmat",
"(",
"df",
",",
"category",
"=",
"None",
",",
"colors",
"=",
"'rgob'",
",",
"num_plots",
"=",
"4",
",",
"num_topics",
"=",
"100",
",",
"num_columns",
"=",
"4",
",",
"show",
"=",
"False",
",",
"block",
"=",
"False",
",",
"data_path",... | Scatter plot with colored markers depending on the discrete values in a "category" column
FIXME: empty plots that dont go away, Plot and/save scatter matrix in groups of num_columns topics | [
"Scatter",
"plot",
"with",
"colored",
"markers",
"depending",
"on",
"the",
"discrete",
"values",
"in",
"a",
"category",
"column"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L296-L323 | train | Scatter plot with colored markers depending on the discrete values in a category column. |
totalgood/pugnlp | src/pugnlp/plots.py | point_cloud | def point_cloud(df, columns=[0, 1, 2]):
"""3-D Point cloud for plotting things like mesh models of horses ;)"""
df = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
if not all(c in df.columns for c in columns):
columns = list(df.columns)[:3]
fig = plt.figure()
ax = fig.add_subplot(... | python | def point_cloud(df, columns=[0, 1, 2]):
"""3-D Point cloud for plotting things like mesh models of horses ;)"""
df = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
if not all(c in df.columns for c in columns):
columns = list(df.columns)[:3]
fig = plt.figure()
ax = fig.add_subplot(... | [
"def",
"point_cloud",
"(",
"df",
",",
"columns",
"=",
"[",
"0",
",",
"1",
",",
"2",
"]",
")",
":",
"df",
"=",
"df",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"DataFrame",
")",
"else",
"pd",
".",
"DataFrame",
"(",
"df",
")",
"if",
"not",
... | 3-D Point cloud for plotting things like mesh models of horses ;) | [
"3",
"-",
"D",
"Point",
"cloud",
"for",
"plotting",
"things",
"like",
"mesh",
"models",
"of",
"horses",
";",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L326-L335 | train | 3 - D Point cloud for plotting things like mesh models of horses ; |
totalgood/pugnlp | src/pugnlp/plots.py | mask2spans | def mask2spans(mask, index=None):
"""Convert a sequence of bools (True/False) into a list of the start and stop of the True "sections" or spans"""
index = list(range(len(mask))) if index is None else index
mask = pd.Series(mask)
mask = mask.astype(int).fillna(0).diff().fillna(0)
starts = list(index... | python | def mask2spans(mask, index=None):
"""Convert a sequence of bools (True/False) into a list of the start and stop of the True "sections" or spans"""
index = list(range(len(mask))) if index is None else index
mask = pd.Series(mask)
mask = mask.astype(int).fillna(0).diff().fillna(0)
starts = list(index... | [
"def",
"mask2spans",
"(",
"mask",
",",
"index",
"=",
"None",
")",
":",
"index",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"mask",
")",
")",
")",
"if",
"index",
"is",
"None",
"else",
"index",
"mask",
"=",
"pd",
".",
"Series",
"(",
"mask",
")",
... | Convert a sequence of bools (True/False) into a list of the start and stop of the True "sections" or spans | [
"Convert",
"a",
"sequence",
"of",
"bools",
"(",
"True",
"/",
"False",
")",
"into",
"a",
"list",
"of",
"the",
"start",
"and",
"stop",
"of",
"the",
"True",
"sections",
"or",
"spans"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L383-L394 | train | Convert a sequence of bools ( True / False into a list of the start and stop of the True sections or spans |
totalgood/pugnlp | src/pugnlp/plots.py | ColorMap.show | def show(self, block=False):
""" Display the last image drawn """
try:
plt.show(block=block)
except ValueError:
plt.show() | python | def show(self, block=False):
""" Display the last image drawn """
try:
plt.show(block=block)
except ValueError:
plt.show() | [
"def",
"show",
"(",
"self",
",",
"block",
"=",
"False",
")",
":",
"try",
":",
"plt",
".",
"show",
"(",
"block",
"=",
"block",
")",
"except",
"ValueError",
":",
"plt",
".",
"show",
"(",
")"
] | Display the last image drawn | [
"Display",
"the",
"last",
"image",
"drawn"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L284-L289 | train | Display the last image drawn |
totalgood/pugnlp | src/pugnlp/plots.py | ColorMap.save | def save(self, filename):
""" save colormap to file"""
plt.savefig(filename, fig=self.fig, facecolor='black', edgecolor='black') | python | def save(self, filename):
""" save colormap to file"""
plt.savefig(filename, fig=self.fig, facecolor='black', edgecolor='black') | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"plt",
".",
"savefig",
"(",
"filename",
",",
"fig",
"=",
"self",
".",
"fig",
",",
"facecolor",
"=",
"'black'",
",",
"edgecolor",
"=",
"'black'",
")"
] | save colormap to file | [
"save",
"colormap",
"to",
"file"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/plots.py#L291-L293 | train | save colormap to file |
DarkEnergySurvey/ugali | ugali/analysis/model.py | asscalar | def asscalar(a):
""" https://github.com/numpy/numpy/issues/4701 """
# Do we want to check that the value is numeric?
#if isinstance(value, (int, long, float)): return value
try:
return np.asscalar(a)
except AttributeError as e:
return np.asscalar(np.asarray(a)) | python | def asscalar(a):
""" https://github.com/numpy/numpy/issues/4701 """
# Do we want to check that the value is numeric?
#if isinstance(value, (int, long, float)): return value
try:
return np.asscalar(a)
except AttributeError as e:
return np.asscalar(np.asarray(a)) | [
"def",
"asscalar",
"(",
"a",
")",
":",
"# Do we want to check that the value is numeric?",
"#if isinstance(value, (int, long, float)): return value",
"try",
":",
"return",
"np",
".",
"asscalar",
"(",
"a",
")",
"except",
"AttributeError",
"as",
"e",
":",
"return",
"np"... | https://github.com/numpy/numpy/issues/4701 | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"numpy",
"/",
"numpy",
"/",
"issues",
"/",
"4701"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/model.py#L23-L30 | train | Convert an array to a numpy array. |
DarkEnergySurvey/ugali | ugali/analysis/model.py | Model.getp | def getp(self, name):
"""
Get the named parameter.
Parameters
----------
name : string
The parameter name.
Returns
-------
param :
The parameter object.
"""
name = self._mapping.get(name,name)
return self... | python | def getp(self, name):
"""
Get the named parameter.
Parameters
----------
name : string
The parameter name.
Returns
-------
param :
The parameter object.
"""
name = self._mapping.get(name,name)
return self... | [
"def",
"getp",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"_mapping",
".",
"get",
"(",
"name",
",",
"name",
")",
"return",
"self",
".",
"params",
"[",
"name",
"]"
] | Get the named parameter.
Parameters
----------
name : string
The parameter name.
Returns
-------
param :
The parameter object. | [
"Get",
"the",
"named",
"parameter",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/model.py#L98-L113 | train | Get the named parameter. |
DarkEnergySurvey/ugali | ugali/analysis/model.py | Model.setp | def setp(self, name, value=None, bounds=None, free=None, errors=None):
"""
Set the value (and bounds) of the named parameter.
Parameters
----------
name : string
The parameter name.
value:
The value of the parameter
bounds: None
... | python | def setp(self, name, value=None, bounds=None, free=None, errors=None):
"""
Set the value (and bounds) of the named parameter.
Parameters
----------
name : string
The parameter name.
value:
The value of the parameter
bounds: None
... | [
"def",
"setp",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"free",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"name",
"=",
"self",
".",
"_mapping",
".",
"get",
"(",
"name",
",",
"name",
")",
"se... | Set the value (and bounds) of the named parameter.
Parameters
----------
name : string
The parameter name.
value:
The value of the parameter
bounds: None
The bounds on the parameter
Returns
-------
None | [
"Set",
"the",
"value",
"(",
"and",
"bounds",
")",
"of",
"the",
"named",
"parameter",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/model.py#L115-L133 | train | Set the value and bounds of the named parameter. |
DarkEnergySurvey/ugali | ugali/analysis/model.py | Model.set_attributes | def set_attributes(self, **kwargs):
"""
Set a group of attributes (parameters and members). Calls
`setp` directly, so kwargs can include more than just the
parameter value (e.g., bounds, free, etc.).
"""
kwargs = dict(kwargs)
for name,value in kwargs.items():
... | python | def set_attributes(self, **kwargs):
"""
Set a group of attributes (parameters and members). Calls
`setp` directly, so kwargs can include more than just the
parameter value (e.g., bounds, free, etc.).
"""
kwargs = dict(kwargs)
for name,value in kwargs.items():
... | [
"def",
"set_attributes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"dict",
"(",
"kwargs",
")",
"for",
"name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"# Raise AttributeError if param not found",
"self",
".",
"__getat... | Set a group of attributes (parameters and members). Calls
`setp` directly, so kwargs can include more than just the
parameter value (e.g., bounds, free, etc.). | [
"Set",
"a",
"group",
"of",
"attributes",
"(",
"parameters",
"and",
"members",
")",
".",
"Calls",
"setp",
"directly",
"so",
"kwargs",
"can",
"include",
"more",
"than",
"just",
"the",
"parameter",
"value",
"(",
"e",
".",
"g",
".",
"bounds",
"free",
"etc",
... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/model.py#L135-L150 | train | Set a group of attributes. |
DarkEnergySurvey/ugali | ugali/analysis/model.py | Parameter.representer | def representer(dumper, data):
"""
http://stackoverflow.com/a/14001707/4075339
http://stackoverflow.com/a/21912744/4075339
"""
tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
return dumper.represent_mapping(tag,list(data.todict().items()),flow_style=True) | python | def representer(dumper, data):
"""
http://stackoverflow.com/a/14001707/4075339
http://stackoverflow.com/a/21912744/4075339
"""
tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
return dumper.represent_mapping(tag,list(data.todict().items()),flow_style=True) | [
"def",
"representer",
"(",
"dumper",
",",
"data",
")",
":",
"tag",
"=",
"yaml",
".",
"resolver",
".",
"BaseResolver",
".",
"DEFAULT_MAPPING_TAG",
"return",
"dumper",
".",
"represent_mapping",
"(",
"tag",
",",
"list",
"(",
"data",
".",
"todict",
"(",
")",
... | http://stackoverflow.com/a/14001707/4075339
http://stackoverflow.com/a/21912744/4075339 | [
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"14001707",
"/",
"4075339",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"21912744",
"/",
"4075339"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/model.py#L335-L341 | train | Represent a dictionary of object identifiers. |
DarkEnergySurvey/ugali | ugali/analysis/color_lut.py | writeColorLUT2 | def writeColorLUT2(config,
outfile=None, isochrone=None, distance_modulus_array=None,
delta_mag=None, mag_err_array=None,
mass_steps=10000, plot=False):
"""
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluati... | python | def writeColorLUT2(config,
outfile=None, isochrone=None, distance_modulus_array=None,
delta_mag=None, mag_err_array=None,
mass_steps=10000, plot=False):
"""
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluati... | [
"def",
"writeColorLUT2",
"(",
"config",
",",
"outfile",
"=",
"None",
",",
"isochrone",
"=",
"None",
",",
"distance_modulus_array",
"=",
"None",
",",
"delta_mag",
"=",
"None",
",",
"mag_err_array",
"=",
"None",
",",
"mass_steps",
"=",
"10000",
",",
"plot",
... | Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluation.
Inputs are a Config object (or file name), an Isochrone object,
an array of distance moduli at which to evaluate the signal color probability,
and an array of magnitude uncertainties which set the bin ed... | [
"Precompute",
"a",
"4",
"-",
"dimensional",
"signal",
"color",
"probability",
"look",
"-",
"up",
"table",
"to",
"speed",
"up",
"the",
"likelihood",
"evaluation",
".",
"Inputs",
"are",
"a",
"Config",
"object",
"(",
"or",
"file",
"name",
")",
"an",
"Isochron... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/color_lut.py#L24-L182 | train | Write a color - probability look - up table to a file. |
DarkEnergySurvey/ugali | ugali/analysis/color_lut.py | writeColorLUT | def writeColorLUT(config,
outfile=None, isochrone=None, distance_modulus_array=None,
delta_mag=None, mag_err_array=None,
mass_steps=1000000, plot=False):
"""
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluat... | python | def writeColorLUT(config,
outfile=None, isochrone=None, distance_modulus_array=None,
delta_mag=None, mag_err_array=None,
mass_steps=1000000, plot=False):
"""
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluat... | [
"def",
"writeColorLUT",
"(",
"config",
",",
"outfile",
"=",
"None",
",",
"isochrone",
"=",
"None",
",",
"distance_modulus_array",
"=",
"None",
",",
"delta_mag",
"=",
"None",
",",
"mag_err_array",
"=",
"None",
",",
"mass_steps",
"=",
"1000000",
",",
"plot",
... | Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluation.
Inputs are a Config object (or file name), an Isochrone object,
an array of distance moduli at which to evaluate the signal color probability,
and an array of magnitude uncertainties which set the bin ed... | [
"Precompute",
"a",
"4",
"-",
"dimensional",
"signal",
"color",
"probability",
"look",
"-",
"up",
"table",
"to",
"speed",
"up",
"the",
"likelihood",
"evaluation",
".",
"Inputs",
"are",
"a",
"Config",
"object",
"(",
"or",
"file",
"name",
")",
"an",
"Isochron... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/color_lut.py#L186-L323 | train | Write a color - probability look - up table. |
DarkEnergySurvey/ugali | ugali/analysis/color_lut.py | readColorLUT | def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
"""
Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties.
"""
reader = pyfits.open(infile)
dist... | python | def readColorLUT(infile, distance_modulus, mag_1, mag_2, mag_err_1, mag_err_2):
"""
Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties.
"""
reader = pyfits.open(infile)
dist... | [
"def",
"readColorLUT",
"(",
"infile",
",",
"distance_modulus",
",",
"mag_1",
",",
"mag_2",
",",
"mag_err_1",
",",
"mag_err_2",
")",
":",
"reader",
"=",
"pyfits",
".",
"open",
"(",
"infile",
")",
"distance_modulus_array",
"=",
"reader",
"[",
"'DISTANCE_MODULUS'... | Take in a color look-up table and return the signal color evaluated for each object.
Consider making the argument a Catalog object rather than magnitudes and uncertainties. | [
"Take",
"in",
"a",
"color",
"look",
"-",
"up",
"table",
"and",
"return",
"the",
"signal",
"color",
"evaluated",
"for",
"each",
"object",
".",
"Consider",
"making",
"the",
"argument",
"a",
"Catalog",
"object",
"rather",
"than",
"magnitudes",
"and",
"uncertain... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/color_lut.py#L335-L374 | train | Read a color look - up table and return the signal color evaluated for each object. |
consbio/ncdjango | ncdjango/utils.py | auto_memoize | def auto_memoize(func):
"""
Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object.
Only works with methods taking non-keword arguments. Note that the args to the function must be usable as
dictionary keys. Also, the first argument MUST be self. Thi... | python | def auto_memoize(func):
"""
Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object.
Only works with methods taking non-keword arguments. Note that the args to the function must be usable as
dictionary keys. Also, the first argument MUST be self. Thi... | [
"def",
"auto_memoize",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"inst",
"=",
"args",
"[",
"0",
"]",
"inst",
".",
"_memoized_values",
"=",
"getattr",
"(",
"inst",
",",
"'_memoized_values'",
"... | Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object.
Only works with methods taking non-keword arguments. Note that the args to the function must be usable as
dictionary keys. Also, the first argument MUST be self. This decorator will not work for functi... | [
"Based",
"on",
"django",
".",
"util",
".",
"functional",
".",
"memoize",
".",
"Automatically",
"memoizes",
"instace",
"methods",
"for",
"the",
"lifespan",
"of",
"an",
"object",
".",
"Only",
"works",
"with",
"methods",
"taking",
"non",
"-",
"keword",
"argumen... | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/utils.py#L15-L31 | train | A decorator that automatically memoizes instace methods for the lifespan of an object. |
consbio/ncdjango | ncdjango/utils.py | best_fit | def best_fit(li, value):
"""For a sorted list li, returns the closest item to value"""
index = min(bisect_left(li, value), len(li) - 1)
if index in (0, len(li)):
return index
if li[index] - value < value - li[index-1]:
return index
else:
return index-1 | python | def best_fit(li, value):
"""For a sorted list li, returns the closest item to value"""
index = min(bisect_left(li, value), len(li) - 1)
if index in (0, len(li)):
return index
if li[index] - value < value - li[index-1]:
return index
else:
return index-1 | [
"def",
"best_fit",
"(",
"li",
",",
"value",
")",
":",
"index",
"=",
"min",
"(",
"bisect_left",
"(",
"li",
",",
"value",
")",
",",
"len",
"(",
"li",
")",
"-",
"1",
")",
"if",
"index",
"in",
"(",
"0",
",",
"len",
"(",
"li",
")",
")",
":",
"re... | For a sorted list li, returns the closest item to value | [
"For",
"a",
"sorted",
"list",
"li",
"returns",
"the",
"closest",
"item",
"to",
"value"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/utils.py#L34-L45 | train | For a sorted list li returns the closest item to value |
consbio/ncdjango | ncdjango/utils.py | proj4_to_epsg | def proj4_to_epsg(projection):
"""Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails"""
def make_definition(value):
return {x.strip().lower() for x in value.split('+') if x}
# Use the EPSG in the definition if available
match = EPSG_RE.search(pro... | python | def proj4_to_epsg(projection):
"""Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails"""
def make_definition(value):
return {x.strip().lower() for x in value.split('+') if x}
# Use the EPSG in the definition if available
match = EPSG_RE.search(pro... | [
"def",
"proj4_to_epsg",
"(",
"projection",
")",
":",
"def",
"make_definition",
"(",
"value",
")",
":",
"return",
"{",
"x",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"'+'",
")",
"if",
"x",
"}",
"... | Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails | [
"Attempts",
"to",
"convert",
"a",
"PROJ4",
"projection",
"object",
"to",
"an",
"EPSG",
"code",
"and",
"returns",
"None",
"if",
"conversion",
"fails"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/utils.py#L48-L71 | train | Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails |
consbio/ncdjango | ncdjango/utils.py | wkt_to_proj4 | def wkt_to_proj4(wkt):
"""Converts a well-known text string to a pyproj.Proj object"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromWkt(wkt)
return pyproj.Proj(str(srs.ExportToProj4())) | python | def wkt_to_proj4(wkt):
"""Converts a well-known text string to a pyproj.Proj object"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromWkt(wkt)
return pyproj.Proj(str(srs.ExportToProj4())) | [
"def",
"wkt_to_proj4",
"(",
"wkt",
")",
":",
"srs",
"=",
"osgeo",
".",
"osr",
".",
"SpatialReference",
"(",
")",
"srs",
".",
"ImportFromWkt",
"(",
"wkt",
")",
"return",
"pyproj",
".",
"Proj",
"(",
"str",
"(",
"srs",
".",
"ExportToProj4",
"(",
")",
")... | Converts a well-known text string to a pyproj.Proj object | [
"Converts",
"a",
"well",
"-",
"known",
"text",
"string",
"to",
"a",
"pyproj",
".",
"Proj",
"object"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/utils.py#L74-L80 | train | Converts a well - known text string to a pyproj. Proj object |
consbio/ncdjango | ncdjango/utils.py | proj4_to_wkt | def proj4_to_wkt(projection):
"""Converts a pyproj.Proj object to a well-known text string"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromProj4(projection.srs)
return srs.ExportToWkt() | python | def proj4_to_wkt(projection):
"""Converts a pyproj.Proj object to a well-known text string"""
srs = osgeo.osr.SpatialReference()
srs.ImportFromProj4(projection.srs)
return srs.ExportToWkt() | [
"def",
"proj4_to_wkt",
"(",
"projection",
")",
":",
"srs",
"=",
"osgeo",
".",
"osr",
".",
"SpatialReference",
"(",
")",
"srs",
".",
"ImportFromProj4",
"(",
"projection",
".",
"srs",
")",
"return",
"srs",
".",
"ExportToWkt",
"(",
")"
] | Converts a pyproj.Proj object to a well-known text string | [
"Converts",
"a",
"pyproj",
".",
"Proj",
"object",
"to",
"a",
"well",
"-",
"known",
"text",
"string"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/utils.py#L83-L89 | train | Converts a pyproj. Proj object to a well - known text string |
consbio/ncdjango | ncdjango/utils.py | project_geometry | def project_geometry(geometry, source, target):
"""Projects a shapely geometry object from the source to the target projection."""
project = partial(
pyproj.transform,
source,
target
)
return transform(project, geometry) | python | def project_geometry(geometry, source, target):
"""Projects a shapely geometry object from the source to the target projection."""
project = partial(
pyproj.transform,
source,
target
)
return transform(project, geometry) | [
"def",
"project_geometry",
"(",
"geometry",
",",
"source",
",",
"target",
")",
":",
"project",
"=",
"partial",
"(",
"pyproj",
".",
"transform",
",",
"source",
",",
"target",
")",
"return",
"transform",
"(",
"project",
",",
"geometry",
")"
] | Projects a shapely geometry object from the source to the target projection. | [
"Projects",
"a",
"shapely",
"geometry",
"object",
"from",
"the",
"source",
"to",
"the",
"target",
"projection",
"."
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/utils.py#L92-L101 | train | Projects a shapely geometry object from the source to the target projection. |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config._load | def _load(self, config):
""" Load this config from an existing config
Parameters:
-----------
config : filename, config object, or dict to load
Returns:
--------
params : configuration parameters
"""
if isstring(config):
self.filenam... | python | def _load(self, config):
""" Load this config from an existing config
Parameters:
-----------
config : filename, config object, or dict to load
Returns:
--------
params : configuration parameters
"""
if isstring(config):
self.filenam... | [
"def",
"_load",
"(",
"self",
",",
"config",
")",
":",
"if",
"isstring",
"(",
"config",
")",
":",
"self",
".",
"filename",
"=",
"config",
"params",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"config",
")",
")",
"elif",
"isinstance",
"(",
"config",
... | Load this config from an existing config
Parameters:
-----------
config : filename, config object, or dict to load
Returns:
--------
params : configuration parameters | [
"Load",
"this",
"config",
"from",
"an",
"existing",
"config"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L64-L89 | train | Load this config from an existing config object or dict. |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config._validate | def _validate(self):
""" Enforce some structure to the config file """
# This could be done with a default config
# Check that specific keys exist
sections = odict([
('catalog',['dirname','basename',
'lon_field','lat_field','objid_field',
... | python | def _validate(self):
""" Enforce some structure to the config file """
# This could be done with a default config
# Check that specific keys exist
sections = odict([
('catalog',['dirname','basename',
'lon_field','lat_field','objid_field',
... | [
"def",
"_validate",
"(",
"self",
")",
":",
"# This could be done with a default config",
"# Check that specific keys exist",
"sections",
"=",
"odict",
"(",
"[",
"(",
"'catalog'",
",",
"[",
"'dirname'",
",",
"'basename'",
",",
"'lon_field'",
",",
"'lat_field'",
",",
... | Enforce some structure to the config file | [
"Enforce",
"some",
"structure",
"to",
"the",
"config",
"file"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L91-L124 | train | Enforces some structure to the config file |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config._formatFilepaths | def _formatFilepaths(self):
"""
Join dirnames and filenames from config.
"""
likedir=self['output']['likedir']
self.likefile = join(likedir,self['output']['likefile'])
self.mergefile = join(likedir,self['output']['mergefile'])
self.roifile = join(likedir,self['... | python | def _formatFilepaths(self):
"""
Join dirnames and filenames from config.
"""
likedir=self['output']['likedir']
self.likefile = join(likedir,self['output']['likefile'])
self.mergefile = join(likedir,self['output']['mergefile'])
self.roifile = join(likedir,self['... | [
"def",
"_formatFilepaths",
"(",
"self",
")",
":",
"likedir",
"=",
"self",
"[",
"'output'",
"]",
"[",
"'likedir'",
"]",
"self",
".",
"likefile",
"=",
"join",
"(",
"likedir",
",",
"self",
"[",
"'output'",
"]",
"[",
"'likefile'",
"]",
")",
"self",
".",
... | Join dirnames and filenames from config. | [
"Join",
"dirnames",
"and",
"filenames",
"from",
"config",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L129-L145 | train | Format the file paths for the current instance of the class. |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config.write | def write(self, filename):
"""
Write a copy of this config object.
Parameters:
-----------
outfile : output filename
Returns:
--------
None
"""
ext = os.path.splitext(filename)[1]
writer = open(filename, 'w')
if ex... | python | def write(self, filename):
"""
Write a copy of this config object.
Parameters:
-----------
outfile : output filename
Returns:
--------
None
"""
ext = os.path.splitext(filename)[1]
writer = open(filename, 'w')
if ex... | [
"def",
"write",
"(",
"self",
",",
"filename",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"writer",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"ext",
"==",
"'.py'",
":",
"writer",
".",
... | Write a copy of this config object.
Parameters:
-----------
outfile : output filename
Returns:
--------
None | [
"Write",
"a",
"copy",
"of",
"this",
"config",
"object",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L147-L168 | train | Writes a copy of this config object to a file. |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config._createFilenames | def _createFilenames(self,pixels=None):
"""
Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values.
Examples:
f = getFilenames([1,2,3])
# All possible catalog files
f['catalog'].data
... | python | def _createFilenames(self,pixels=None):
"""
Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values.
Examples:
f = getFilenames([1,2,3])
# All possible catalog files
f['catalog'].data
... | [
"def",
"_createFilenames",
"(",
"self",
",",
"pixels",
"=",
"None",
")",
":",
"nside_catalog",
"=",
"self",
"[",
"'coords'",
"]",
"[",
"'nside_catalog'",
"]",
"# Deprecated: ADW 2018-06-17",
"#if nside_catalog is None:",
"# pixels = [None]",
"if",
"pixels",
"is",
... | Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values.
Examples:
f = getFilenames([1,2,3])
# All possible catalog files
f['catalog'].data
# All existing catalog files
f['catalog'][~f.m... | [
"Create",
"a",
"masked",
"records",
"array",
"of",
"all",
"filenames",
"for",
"the",
"given",
"set",
"of",
"pixels",
"and",
"store",
"the",
"existence",
"of",
"those",
"files",
"in",
"the",
"mask",
"values",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L170-L249 | train | Create a masked record array of all filenames for the given set of pixels and store existence of those files in the mask values. |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config._createFilenames | def _createFilenames(self):
"""
Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values.
Parameters:
-----------
None
Returns:
--------
recarray : pixels and mask value
... | python | def _createFilenames(self):
"""
Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values.
Parameters:
-----------
None
Returns:
--------
recarray : pixels and mask value
... | [
"def",
"_createFilenames",
"(",
"self",
")",
":",
"nside_catalog",
"=",
"self",
"[",
"'coords'",
"]",
"[",
"'nside_catalog'",
"]",
"npix",
"=",
"hp",
".",
"nside2npix",
"(",
"nside_catalog",
")",
"pixels",
"=",
"np",
".",
"arange",
"(",
"npix",
")",
"cat... | Create a masked records array of all filenames for the given set of
pixels and store the existence of those files in the mask values.
Parameters:
-----------
None
Returns:
--------
recarray : pixels and mask value | [
"Create",
"a",
"masked",
"records",
"array",
"of",
"all",
"filenames",
"for",
"the",
"given",
"set",
"of",
"pixels",
"and",
"store",
"the",
"existence",
"of",
"those",
"files",
"in",
"the",
"mask",
"values",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L252-L303 | train | Create a masked records array of all filenames for the given set of pixels and store existence of those files in the mask values. |
DarkEnergySurvey/ugali | ugali/utils/config.py | Config.getFilenames | def getFilenames(self,pixels=None):
"""
Return the requested filenames.
Parameters:
-----------
pixels : requeseted pixels
Returns:
--------
filenames : recarray
"""
logger.debug("Getting filenames...")
if pixels is None:
... | python | def getFilenames(self,pixels=None):
"""
Return the requested filenames.
Parameters:
-----------
pixels : requeseted pixels
Returns:
--------
filenames : recarray
"""
logger.debug("Getting filenames...")
if pixels is None:
... | [
"def",
"getFilenames",
"(",
"self",
",",
"pixels",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting filenames...\"",
")",
"if",
"pixels",
"is",
"None",
":",
"return",
"self",
".",
"filenames",
"else",
":",
"return",
"self",
".",
"filenames",
... | Return the requested filenames.
Parameters:
-----------
pixels : requeseted pixels
Returns:
--------
filenames : recarray | [
"Return",
"the",
"requested",
"filenames",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/config.py#L305-L321 | train | Returns the requested filenames. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | superpixel | def superpixel(subpix, nside_subpix, nside_superpix):
"""
Return the indices of the super-pixels which contain each of the sub-pixels.
"""
if nside_subpix==nside_superpix: return subpix
theta, phi = hp.pix2ang(nside_subpix, subpix)
return hp.ang2pix(nside_superpix, theta, phi) | python | def superpixel(subpix, nside_subpix, nside_superpix):
"""
Return the indices of the super-pixels which contain each of the sub-pixels.
"""
if nside_subpix==nside_superpix: return subpix
theta, phi = hp.pix2ang(nside_subpix, subpix)
return hp.ang2pix(nside_superpix, theta, phi) | [
"def",
"superpixel",
"(",
"subpix",
",",
"nside_subpix",
",",
"nside_superpix",
")",
":",
"if",
"nside_subpix",
"==",
"nside_superpix",
":",
"return",
"subpix",
"theta",
",",
"phi",
"=",
"hp",
".",
"pix2ang",
"(",
"nside_subpix",
",",
"subpix",
")",
"return"... | Return the indices of the super-pixels which contain each of the sub-pixels. | [
"Return",
"the",
"indices",
"of",
"the",
"super",
"-",
"pixels",
"which",
"contain",
"each",
"of",
"the",
"sub",
"-",
"pixels",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L20-L26 | train | Return the indices of the super - pixels which contain each of the sub - pixels. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | subpixel | def subpixel(superpix, nside_superpix, nside_subpix):
"""
Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel with (resolution nside_superpix).
ADW: It would be better to convert to next and do this explicitly
"""
if nside_superpix==nside_subpix: return superpi... | python | def subpixel(superpix, nside_superpix, nside_subpix):
"""
Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel with (resolution nside_superpix).
ADW: It would be better to convert to next and do this explicitly
"""
if nside_superpix==nside_subpix: return superpi... | [
"def",
"subpixel",
"(",
"superpix",
",",
"nside_superpix",
",",
"nside_subpix",
")",
":",
"if",
"nside_superpix",
"==",
"nside_subpix",
":",
"return",
"superpix",
"vec",
"=",
"hp",
".",
"pix2vec",
"(",
"nside_superpix",
",",
"superpix",
")",
"radius",
"=",
"... | Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel with (resolution nside_superpix).
ADW: It would be better to convert to next and do this explicitly | [
"Return",
"the",
"indices",
"of",
"sub",
"-",
"pixels",
"(",
"resolution",
"nside_subpix",
")",
"within",
"the",
"super",
"-",
"pixel",
"with",
"(",
"resolution",
"nside_superpix",
")",
".",
"ADW",
":",
"It",
"would",
"be",
"better",
"to",
"convert",
"to",... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L29-L42 | train | Return the indices of sub - pixels within a given super - pixel with resolution nside_subpix. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | d_grade_ipix | def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Return the indices of the super-pixels which contain each of the
sub-pixels (nside_in > nside_out).
Parameters:
-----------
ipix : index of the input subpixels
nside_in : nside of the input subpix
nside_out : nside of th... | python | def d_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Return the indices of the super-pixels which contain each of the
sub-pixels (nside_in > nside_out).
Parameters:
-----------
ipix : index of the input subpixels
nside_in : nside of the input subpix
nside_out : nside of th... | [
"def",
"d_grade_ipix",
"(",
"ipix",
",",
"nside_in",
",",
"nside_out",
",",
"nest",
"=",
"False",
")",
":",
"if",
"nside_in",
"==",
"nside_out",
":",
"return",
"ipix",
"if",
"not",
"(",
"nside_in",
">",
"nside_out",
")",
":",
"raise",
"ValueError",
"(",
... | Return the indices of the super-pixels which contain each of the
sub-pixels (nside_in > nside_out).
Parameters:
-----------
ipix : index of the input subpixels
nside_in : nside of the input subpix
nside_out : nside of the desired superpixels
Returns:
--------
ipix_out : supe... | [
"Return",
"the",
"indices",
"of",
"the",
"super",
"-",
"pixels",
"which",
"contain",
"each",
"of",
"the",
"sub",
"-",
"pixels",
"(",
"nside_in",
">",
"nside_out",
")",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L44-L64 | train | Returns the indices of the super - pixels which contain each of the subpixels ipix. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | u_grade_ipix | def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel(s) (resolution nside_superpix).
Parameters:
-----------
ipix : index of the input superpixel(s)
nside_in : nside of the input superpixel
... | python | def u_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel(s) (resolution nside_superpix).
Parameters:
-----------
ipix : index of the input superpixel(s)
nside_in : nside of the input superpixel
... | [
"def",
"u_grade_ipix",
"(",
"ipix",
",",
"nside_in",
",",
"nside_out",
",",
"nest",
"=",
"False",
")",
":",
"if",
"nside_in",
"==",
"nside_out",
":",
"return",
"ipix",
"if",
"not",
"(",
"nside_in",
"<",
"nside_out",
")",
":",
"raise",
"ValueError",
"(",
... | Return the indices of sub-pixels (resolution nside_subpix) within
the super-pixel(s) (resolution nside_superpix).
Parameters:
-----------
ipix : index of the input superpixel(s)
nside_in : nside of the input superpixel
nside_out : nside of the desired subpixels
Returns:
-----... | [
"Return",
"the",
"indices",
"of",
"sub",
"-",
"pixels",
"(",
"resolution",
"nside_subpix",
")",
"within",
"the",
"super",
"-",
"pixel",
"(",
"s",
")",
"(",
"resolution",
"nside_superpix",
")",
".",
"Parameters",
":",
"-----------",
"ipix",
":",
"index",
"o... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L66-L96 | train | This function takes a superpixel and returns the indices of sub - pixels within the base image of the base image of the base image of the super - pixel. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | ud_grade_ipix | def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Upgrade or degrade resolution of a pixel list.
Parameters:
-----------
ipix:array-like
the input pixel(s)
nside_in:int
the nside of the input pixel(s)
nside_out:int
the desired nside of the output pixel(s)
ord... | python | def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Upgrade or degrade resolution of a pixel list.
Parameters:
-----------
ipix:array-like
the input pixel(s)
nside_in:int
the nside of the input pixel(s)
nside_out:int
the desired nside of the output pixel(s)
ord... | [
"def",
"ud_grade_ipix",
"(",
"ipix",
",",
"nside_in",
",",
"nside_out",
",",
"nest",
"=",
"False",
")",
":",
"if",
"nside_in",
"==",
"nside_out",
":",
"return",
"ipix",
"elif",
"nside_in",
"<",
"nside_out",
":",
"return",
"u_grade_ipix",
"(",
"ipix",
",",
... | Upgrade or degrade resolution of a pixel list.
Parameters:
-----------
ipix:array-like
the input pixel(s)
nside_in:int
the nside of the input pixel(s)
nside_out:int
the desired nside of the output pixel(s)
order:str
pixel ordering of input and output ("RING" or "NESTED")
... | [
"Upgrade",
"or",
"degrade",
"resolution",
"of",
"a",
"pixel",
"list",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L99-L126 | train | Upgrade or degrade resolution of a pixel list. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | pix2ang | def pix2ang(nside, pix, nest=False):
"""
Return (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta, phi = hp.pix2ang(nside, pix, nest=nest)
lon = phi2lon(phi)
lat = theta2lat(theta)
return lon, lat | python | def pix2ang(nside, pix, nest=False):
"""
Return (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta, phi = hp.pix2ang(nside, pix, nest=nest)
lon = phi2lon(phi)
lat = theta2lat(theta)
return lon, lat | [
"def",
"pix2ang",
"(",
"nside",
",",
"pix",
",",
"nest",
"=",
"False",
")",
":",
"theta",
",",
"phi",
"=",
"hp",
".",
"pix2ang",
"(",
"nside",
",",
"pix",
",",
"nest",
"=",
"nest",
")",
"lon",
"=",
"phi2lon",
"(",
"phi",
")",
"lat",
"=",
"theta... | Return (lon, lat) in degrees instead of (theta, phi) in radians | [
"Return",
"(",
"lon",
"lat",
")",
"in",
"degrees",
"instead",
"of",
"(",
"theta",
"phi",
")",
"in",
"radians"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L138-L145 | train | Convert pixel coordinates to degrees and degrees. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | ang2pix | def ang2pix(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 healpy.ang2pix(nside, theta, phi, nest=nest) | python | def ang2pix(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 healpy.ang2pix(nside, theta, phi, nest=nest) | [
"def",
"ang2pix",
"(",
"nside",
",",
"lon",
",",
"lat",
",",
"nest",
"=",
"False",
")",
":",
"theta",
"=",
"np",
".",
"radians",
"(",
"90.",
"-",
"lat",
")",
"phi",
"=",
"np",
".",
"radians",
"(",
"lon",
")",
"return",
"healpy",
".",
"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/utils/healpix.py#L147-L153 | train | Convert from ang to pix |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | healpixMap | def healpixMap(nside, lon, lat, fill_value=0., nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution
"""
lon_median, lat_median = np.median(lon), np.median(lat)
max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, l... | python | def healpixMap(nside, lon, lat, fill_value=0., nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution
"""
lon_median, lat_median = np.median(lon), np.median(lat)
max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, l... | [
"def",
"healpixMap",
"(",
"nside",
",",
"lon",
",",
"lat",
",",
"fill_value",
"=",
"0.",
",",
"nest",
"=",
"False",
")",
":",
"lon_median",
",",
"lat_median",
"=",
"np",
".",
"median",
"(",
"lon",
")",
",",
"np",
".",
"median",
"(",
"lat",
")",
"... | Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution | [
"Input",
"(",
"lon",
"lat",
")",
"in",
"degrees",
"instead",
"of",
"(",
"theta",
"phi",
")",
"in",
"radians",
".",
"Returns",
"HEALPix",
"map",
"at",
"the",
"desired",
"resolution"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L173-L194 | train | Return a HEALPix map at the desired resolution. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | in_pixels | def in_pixels(lon,lat,pixels,nside):
"""
Check if (lon,lat) in pixel list. Assumes RING formatting.
Parameters:
-----------
lon : longitude (deg)
lat : latitude (deg)
pixels : pixel list [RING format] to check for inclusion
nside : nside of pixel list
Returns:
--------
... | python | def in_pixels(lon,lat,pixels,nside):
"""
Check if (lon,lat) in pixel list. Assumes RING formatting.
Parameters:
-----------
lon : longitude (deg)
lat : latitude (deg)
pixels : pixel list [RING format] to check for inclusion
nside : nside of pixel list
Returns:
--------
... | [
"def",
"in_pixels",
"(",
"lon",
",",
"lat",
",",
"pixels",
",",
"nside",
")",
":",
"pix",
"=",
"ang2pix",
"(",
"nside",
",",
"lon",
",",
"lat",
")",
"return",
"np",
".",
"in1d",
"(",
"pix",
",",
"pixels",
")"
] | Check if (lon,lat) in pixel list. Assumes RING formatting.
Parameters:
-----------
lon : longitude (deg)
lat : latitude (deg)
pixels : pixel list [RING format] to check for inclusion
nside : nside of pixel list
Returns:
--------
inpix : boolean array for inclusion | [
"Check",
"if",
"(",
"lon",
"lat",
")",
"in",
"pixel",
"list",
".",
"Assumes",
"RING",
"formatting",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L198-L214 | train | Checks if a given longitude latitude and nside are contained in a set of pixels. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | index_pix_in_pixels | def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
"""
Find the indices of a set of pixels into another set of pixels.
!!! ASSUMES SORTED PIXELS !!!
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index ... | python | def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
"""
Find the indices of a set of pixels into another set of pixels.
!!! ASSUMES SORTED PIXELS !!!
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index ... | [
"def",
"index_pix_in_pixels",
"(",
"pix",
",",
"pixels",
",",
"sort",
"=",
"False",
",",
"outside",
"=",
"-",
"1",
")",
":",
"# ADW: Not really safe to set index = -1 (accesses last entry); ",
"# -np.inf would be better, but breaks other code...",
"# ADW: Are the pixels always ... | Find the indices of a set of pixels into another set of pixels.
!!! ASSUMES SORTED PIXELS !!!
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels | [
"Find",
"the",
"indices",
"of",
"a",
"set",
"of",
"pixels",
"into",
"another",
"set",
"of",
"pixels",
".",
"!!!",
"ASSUMES",
"SORTED",
"PIXELS",
"!!!"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L217-L244 | train | Find the indices of a set of pixels into another set of pixels. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | index_lonlat_in_pixels | def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
"""
Find the indices of a set of angles into a set of pixels
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels
... | python | def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1):
"""
Find the indices of a set of angles into a set of pixels
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels
... | [
"def",
"index_lonlat_in_pixels",
"(",
"lon",
",",
"lat",
",",
"pixels",
",",
"nside",
",",
"sort",
"=",
"False",
",",
"outside",
"=",
"-",
"1",
")",
":",
"pix",
"=",
"ang2pix",
"(",
"nside",
",",
"lon",
",",
"lat",
")",
"return",
"index_pix_in_pixels",... | Find the indices of a set of angles into a set of pixels
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels | [
"Find",
"the",
"indices",
"of",
"a",
"set",
"of",
"angles",
"into",
"a",
"set",
"of",
"pixels"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L246-L261 | train | Find the indices of a set of angles into a set of pixels |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | ang2disc | def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
"""
Wrap `query_disc` to use lon, lat, and radius in degrees.
"""
vec = ang2vec(lon,lat)
return query_disc(nside,vec,radius,inclusive,fact,nest) | python | def ang2disc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
"""
Wrap `query_disc` to use lon, lat, and radius in degrees.
"""
vec = ang2vec(lon,lat)
return query_disc(nside,vec,radius,inclusive,fact,nest) | [
"def",
"ang2disc",
"(",
"nside",
",",
"lon",
",",
"lat",
",",
"radius",
",",
"inclusive",
"=",
"False",
",",
"fact",
"=",
"4",
",",
"nest",
"=",
"False",
")",
":",
"vec",
"=",
"ang2vec",
"(",
"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/utils/healpix.py#L316-L321 | train | Wrap query_disc to use lon lat and radius in degrees. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | header_odict | def header_odict(nside,nest=False,coord=None, partial=True):
"""Mimic the healpy header keywords."""
hdr = odict([])
hdr['PIXTYPE']=odict([('name','PIXTYPE'),
('value','HEALPIX'),
('comment','HEALPIX pixelisation')])
ordering = 'NEST' if nest else 'RI... | python | def header_odict(nside,nest=False,coord=None, partial=True):
"""Mimic the healpy header keywords."""
hdr = odict([])
hdr['PIXTYPE']=odict([('name','PIXTYPE'),
('value','HEALPIX'),
('comment','HEALPIX pixelisation')])
ordering = 'NEST' if nest else 'RI... | [
"def",
"header_odict",
"(",
"nside",
",",
"nest",
"=",
"False",
",",
"coord",
"=",
"None",
",",
"partial",
"=",
"True",
")",
":",
"hdr",
"=",
"odict",
"(",
"[",
"]",
")",
"hdr",
"[",
"'PIXTYPE'",
"]",
"=",
"odict",
"(",
"[",
"(",
"'name'",
",",
... | Mimic the healpy header keywords. | [
"Mimic",
"the",
"healpy",
"header",
"keywords",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L330-L362 | train | Mimic the healpy header keywords. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | write_partial_map | def write_partial_map(filename, data, nside, coord=None, nest=False,
header=None,dtype=None,**kwargs):
"""
Partial HEALPix maps are used to efficiently store maps of the sky by only
writing out the pixels that contain data.
Three-dimensional data can be saved by supplying a distan... | python | def write_partial_map(filename, data, nside, coord=None, nest=False,
header=None,dtype=None,**kwargs):
"""
Partial HEALPix maps are used to efficiently store maps of the sky by only
writing out the pixels that contain data.
Three-dimensional data can be saved by supplying a distan... | [
"def",
"write_partial_map",
"(",
"filename",
",",
"data",
",",
"nside",
",",
"coord",
"=",
"None",
",",
"nest",
"=",
"False",
",",
"header",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# ADW: Do we want to make everything up... | Partial HEALPix maps are used to efficiently store maps of the sky by only
writing out the pixels that contain data.
Three-dimensional data can be saved by supplying a distance modulus array
which is stored in a separate extension.
Parameters:
-----------
filename : output file name
data ... | [
"Partial",
"HEALPix",
"maps",
"are",
"used",
"to",
"efficiently",
"store",
"maps",
"of",
"the",
"sky",
"by",
"only",
"writing",
"out",
"the",
"pixels",
"that",
"contain",
"data",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L364-L404 | train | Write out a HEALPix map of the same HEALPix image. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | read_partial_map | def read_partial_map(filenames, column, fullsky=True, **kwargs):
"""
Read a partial HEALPix file(s) and return pixels and values/map. Can
handle 3D healpix maps (pix, value, zdim). Returned array has
shape (dimz,npix).
Parameters:
-----------
filenames : list of input filenames
colu... | python | def read_partial_map(filenames, column, fullsky=True, **kwargs):
"""
Read a partial HEALPix file(s) and return pixels and values/map. Can
handle 3D healpix maps (pix, value, zdim). Returned array has
shape (dimz,npix).
Parameters:
-----------
filenames : list of input filenames
colu... | [
"def",
"read_partial_map",
"(",
"filenames",
",",
"column",
",",
"fullsky",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make sure that PIXEL is in columns",
"#kwargs['columns'] = ['PIXEL',column]",
"kwargs",
"[",
"'columns'",
"]",
"=",
"[",
"'PIXEL'",
"]",
... | Read a partial HEALPix file(s) and return pixels and values/map. Can
handle 3D healpix maps (pix, value, zdim). Returned array has
shape (dimz,npix).
Parameters:
-----------
filenames : list of input filenames
column : column of interest
fullsky : partial or fullsky map
... | [
"Read",
"a",
"partial",
"HEALPix",
"file",
"(",
"s",
")",
"and",
"return",
"pixels",
"and",
"values",
"/",
"map",
".",
"Can",
"handle",
"3D",
"healpix",
"maps",
"(",
"pix",
"value",
"zdim",
")",
".",
"Returned",
"array",
"has",
"shape",
"(",
"dimz",
... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L406-L451 | train | Read a partial HEALPix file and return pixels and values and map. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | merge_likelihood_headers | def merge_likelihood_headers(filenames, outfile):
"""
Merge header information from likelihood files.
Parameters:
-----------
filenames : input filenames
oufile : the merged file to write
Returns:
--------
data : the data being written
"""
filenames = np.atleas... | python | def merge_likelihood_headers(filenames, outfile):
"""
Merge header information from likelihood files.
Parameters:
-----------
filenames : input filenames
oufile : the merged file to write
Returns:
--------
data : the data being written
"""
filenames = np.atleas... | [
"def",
"merge_likelihood_headers",
"(",
"filenames",
",",
"outfile",
")",
":",
"filenames",
"=",
"np",
".",
"atleast_1d",
"(",
"filenames",
")",
"ext",
"=",
"'PIX_DATA'",
"nside",
"=",
"fitsio",
".",
"read_header",
"(",
"filenames",
"[",
"0",
"]",
",",
"ex... | Merge header information from likelihood files.
Parameters:
-----------
filenames : input filenames
oufile : the merged file to write
Returns:
--------
data : the data being written | [
"Merge",
"header",
"information",
"from",
"likelihood",
"files",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L479-L518 | train | Merge header information from likelihood files into one single dictionary. |
DarkEnergySurvey/ugali | ugali/utils/healpix.py | read_map | def read_map(filename, nest=False, hdu=None, h=False, verbose=True):
"""Read a healpix map from a fits file. Partial-sky files,
if properly identified, are expanded to full size and filled with UNSEEN.
Uses fitsio to mirror much (but not all) of the functionality of healpy.read_map
Parameters:
... | python | def read_map(filename, nest=False, hdu=None, h=False, verbose=True):
"""Read a healpix map from a fits file. Partial-sky files,
if properly identified, are expanded to full size and filled with UNSEEN.
Uses fitsio to mirror much (but not all) of the functionality of healpy.read_map
Parameters:
... | [
"def",
"read_map",
"(",
"filename",
",",
"nest",
"=",
"False",
",",
"hdu",
"=",
"None",
",",
"h",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"data",
",",
"hdr",
"=",
"fitsio",
".",
"read",
"(",
"filename",
",",
"header",
"=",
"True",
",... | Read a healpix map from a fits file. Partial-sky files,
if properly identified, are expanded to full size and filled with UNSEEN.
Uses fitsio to mirror much (but not all) of the functionality of healpy.read_map
Parameters:
-----------
filename : str
the fits file name
nest : bool, o... | [
"Read",
"a",
"healpix",
"map",
"from",
"a",
"fits",
"file",
".",
"Partial",
"-",
"sky",
"files",
"if",
"properly",
"identified",
"are",
"expanded",
"to",
"full",
"size",
"and",
"filled",
"with",
"UNSEEN",
".",
"Uses",
"fitsio",
"to",
"mirror",
"much",
"(... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/healpix.py#L521-L593 | train | Read a healpix map from a fits file. |
consbio/ncdjango | ncdjango/api.py | TemporaryFileResource._convert_number | def _convert_number(self, number):
"""Converts a number to float or int as appropriate"""
number = float(number)
return int(number) if number.is_integer() else float(number) | python | def _convert_number(self, number):
"""Converts a number to float or int as appropriate"""
number = float(number)
return int(number) if number.is_integer() else float(number) | [
"def",
"_convert_number",
"(",
"self",
",",
"number",
")",
":",
"number",
"=",
"float",
"(",
"number",
")",
"return",
"int",
"(",
"number",
")",
"if",
"number",
".",
"is_integer",
"(",
")",
"else",
"float",
"(",
"number",
")"
] | Converts a number to float or int as appropriate | [
"Converts",
"a",
"number",
"to",
"float",
"or",
"int",
"as",
"appropriate"
] | f807bfd1e4083ab29fbc3c4d4418be108383a710 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/api.py#L46-L50 | train | Converts a number to float or int as appropriate |
DarkEnergySurvey/ugali | ugali/pipeline/run_05.0_followup.py | do_results | def do_results(args):
""" Write the results output file """
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samples = filenames['samfile']
if not exists(srcfile):
logger.warning("Couldn't find %s; skipping..."%srcfile)
retu... | python | def do_results(args):
""" Write the results output file """
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samples = filenames['samfile']
if not exists(srcfile):
logger.warning("Couldn't find %s; skipping..."%srcfile)
retu... | [
"def",
"do_results",
"(",
"args",
")",
":",
"config",
",",
"name",
",",
"label",
",",
"coord",
"=",
"args",
"filenames",
"=",
"make_filenames",
"(",
"config",
",",
"label",
")",
"srcfile",
"=",
"filenames",
"[",
"'srcfile'",
"]",
"samples",
"=",
"filenam... | Write the results output file | [
"Write",
"the",
"results",
"output",
"file"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/pipeline/run_05.0_followup.py#L42-L59 | train | Write the results output file |
DarkEnergySurvey/ugali | ugali/pipeline/run_05.0_followup.py | do_membership | def do_membership(args):
""" Write the membership output file """
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
memfile = filenames['memfile']
logger.info("Writing %s..."%memfile)
from ugali.analysis.loglike import write_membership
... | python | def do_membership(args):
""" Write the membership output file """
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
memfile = filenames['memfile']
logger.info("Writing %s..."%memfile)
from ugali.analysis.loglike import write_membership
... | [
"def",
"do_membership",
"(",
"args",
")",
":",
"config",
",",
"name",
",",
"label",
",",
"coord",
"=",
"args",
"filenames",
"=",
"make_filenames",
"(",
"config",
",",
"label",
")",
"srcfile",
"=",
"filenames",
"[",
"'srcfile'",
"]",
"memfile",
"=",
"file... | Write the membership output file | [
"Write",
"the",
"membership",
"output",
"file"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/pipeline/run_05.0_followup.py#L61-L71 | train | Write the membership output file |
DarkEnergySurvey/ugali | ugali/pipeline/run_05.0_followup.py | do_plot | def do_plot(args):
""" Create plots of mcmc output """
import ugali.utils.plotting
import pylab as plt
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samfile = filenames['samfile']
memfile = filenames['memfile']
if not exists(... | python | def do_plot(args):
""" Create plots of mcmc output """
import ugali.utils.plotting
import pylab as plt
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samfile = filenames['samfile']
memfile = filenames['memfile']
if not exists(... | [
"def",
"do_plot",
"(",
"args",
")",
":",
"import",
"ugali",
".",
"utils",
".",
"plotting",
"import",
"pylab",
"as",
"plt",
"config",
",",
"name",
",",
"label",
",",
"coord",
"=",
"args",
"filenames",
"=",
"make_filenames",
"(",
"config",
",",
"label",
... | Create plots of mcmc output | [
"Create",
"plots",
"of",
"mcmc",
"output"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/pipeline/run_05.0_followup.py#L73-L136 | train | Create plots of mcmc output |
warrenspe/hconf | hconf/subparsers/dictionary.py | Dictionary.parse | def parse(self, *args):
"""
Return our initialized dictionary arguments.
"""
if isinstance(self.dictionary, dict):
return self.dictionary
raise self.subparserException("Argument passed to Dictionary SubParser is not a dict: %s" % type(self.dictionary)) | python | def parse(self, *args):
"""
Return our initialized dictionary arguments.
"""
if isinstance(self.dictionary, dict):
return self.dictionary
raise self.subparserException("Argument passed to Dictionary SubParser is not a dict: %s" % type(self.dictionary)) | [
"def",
"parse",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"dictionary",
",",
"dict",
")",
":",
"return",
"self",
".",
"dictionary",
"raise",
"self",
".",
"subparserException",
"(",
"\"Argument passed to Dictionary SubParser... | Return our initialized dictionary arguments. | [
"Return",
"our",
"initialized",
"dictionary",
"arguments",
"."
] | 12074d15dc3641d3903488c95d89a507386a32d5 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/dictionary.py#L39-L47 | train | Parse the dictionary. |
BertrandBordage/django-terms | terms/managers.py | TermManager._caches_dicts | def _caches_dicts(self):
"""
Caches variants_dict and replace_dict in a single database hit.
"""
qs = (self.get_query_set() if django.VERSION < (1, 6)
else self.get_queryset())
variants_dict = self._get_variants_dict(qs)
cache.set(VARIANTS_DICT_CACHE_KEY, ... | python | def _caches_dicts(self):
"""
Caches variants_dict and replace_dict in a single database hit.
"""
qs = (self.get_query_set() if django.VERSION < (1, 6)
else self.get_queryset())
variants_dict = self._get_variants_dict(qs)
cache.set(VARIANTS_DICT_CACHE_KEY, ... | [
"def",
"_caches_dicts",
"(",
"self",
")",
":",
"qs",
"=",
"(",
"self",
".",
"get_query_set",
"(",
")",
"if",
"django",
".",
"VERSION",
"<",
"(",
"1",
",",
"6",
")",
"else",
"self",
".",
"get_queryset",
"(",
")",
")",
"variants_dict",
"=",
"self",
"... | Caches variants_dict and replace_dict in a single database hit. | [
"Caches",
"variants_dict",
"and",
"replace_dict",
"in",
"a",
"single",
"database",
"hit",
"."
] | 2555c2cf5abf14adef9a8e2dd22c4a9076396a10 | https://github.com/BertrandBordage/django-terms/blob/2555c2cf5abf14adef9a8e2dd22c4a9076396a10/terms/managers.py#L41-L55 | train | Caches variants_dict and replace_dict in a single database hit. |
joeyespo/path-and-address | path_and_address/parsing.py | resolve | def resolve(path_or_address=None, address=None, *ignored):
"""
Returns (path, address) based on consecutive optional arguments,
[path] [address].
"""
if path_or_address is None or address is not None:
return path_or_address, address
path = None
if split_address(path_or_address)[1] i... | python | def resolve(path_or_address=None, address=None, *ignored):
"""
Returns (path, address) based on consecutive optional arguments,
[path] [address].
"""
if path_or_address is None or address is not None:
return path_or_address, address
path = None
if split_address(path_or_address)[1] i... | [
"def",
"resolve",
"(",
"path_or_address",
"=",
"None",
",",
"address",
"=",
"None",
",",
"*",
"ignored",
")",
":",
"if",
"path_or_address",
"is",
"None",
"or",
"address",
"is",
"not",
"None",
":",
"return",
"path_or_address",
",",
"address",
"path",
"=",
... | Returns (path, address) based on consecutive optional arguments,
[path] [address]. | [
"Returns",
"(",
"path",
"address",
")",
"based",
"on",
"consecutive",
"optional",
"arguments",
"[",
"path",
"]",
"[",
"address",
"]",
"."
] | f8193a09f4b785574d920e8a2aeeb55ea6ff4e20 | https://github.com/joeyespo/path-and-address/blob/f8193a09f4b785574d920e8a2aeeb55ea6ff4e20/path_and_address/parsing.py#L4-L18 | train | Resolves the path and address of a resource based on consecutive optional arguments. |
joeyespo/path-and-address | path_and_address/parsing.py | split_address | def split_address(address):
"""
Returns (host, port) with an integer port from the specified address
string. (None, None) is returned if the address is invalid.
"""
invalid = None, None
if not address and address != 0:
return invalid
components = str(address).split(':')
if len(... | python | def split_address(address):
"""
Returns (host, port) with an integer port from the specified address
string. (None, None) is returned if the address is invalid.
"""
invalid = None, None
if not address and address != 0:
return invalid
components = str(address).split(':')
if len(... | [
"def",
"split_address",
"(",
"address",
")",
":",
"invalid",
"=",
"None",
",",
"None",
"if",
"not",
"address",
"and",
"address",
"!=",
"0",
":",
"return",
"invalid",
"components",
"=",
"str",
"(",
"address",
")",
".",
"split",
"(",
"':'",
")",
"if",
... | Returns (host, port) with an integer port from the specified address
string. (None, None) is returned if the address is invalid. | [
"Returns",
"(",
"host",
"port",
")",
"with",
"an",
"integer",
"port",
"from",
"the",
"specified",
"address",
"string",
".",
"(",
"None",
"None",
")",
"is",
"returned",
"if",
"the",
"address",
"is",
"invalid",
"."
] | f8193a09f4b785574d920e8a2aeeb55ea6ff4e20 | https://github.com/joeyespo/path-and-address/blob/f8193a09f4b785574d920e8a2aeeb55ea6ff4e20/path_and_address/parsing.py#L21-L47 | train | Splits an address into host and port. |
stevearc/dynamo3 | dynamo3/exception.py | translate_exception | def translate_exception(exc, kwargs):
""" Translate a botocore.exceptions.ClientError into a dynamo3 error """
error = exc.response['Error']
error.setdefault('Message', '')
err_class = EXC.get(error['Code'], DynamoDBError)
return err_class(exc.response['ResponseMetadata']['HTTPStatusCode'],
... | python | def translate_exception(exc, kwargs):
""" Translate a botocore.exceptions.ClientError into a dynamo3 error """
error = exc.response['Error']
error.setdefault('Message', '')
err_class = EXC.get(error['Code'], DynamoDBError)
return err_class(exc.response['ResponseMetadata']['HTTPStatusCode'],
... | [
"def",
"translate_exception",
"(",
"exc",
",",
"kwargs",
")",
":",
"error",
"=",
"exc",
".",
"response",
"[",
"'Error'",
"]",
"error",
".",
"setdefault",
"(",
"'Message'",
",",
"''",
")",
"err_class",
"=",
"EXC",
".",
"get",
"(",
"error",
"[",
"'Code'"... | Translate a botocore.exceptions.ClientError into a dynamo3 error | [
"Translate",
"a",
"botocore",
".",
"exceptions",
".",
"ClientError",
"into",
"a",
"dynamo3",
"error"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/exception.py#L50-L56 | train | Translate a botocore. exceptions. ClientError into a dynamo3 error |
stevearc/dynamo3 | dynamo3/exception.py | DynamoDBError.re_raise | def re_raise(self):
""" Raise this exception with the original traceback """
if self.exc_info is not None:
six.reraise(type(self), self, self.exc_info[2])
else:
raise self | python | def re_raise(self):
""" Raise this exception with the original traceback """
if self.exc_info is not None:
six.reraise(type(self), self, self.exc_info[2])
else:
raise self | [
"def",
"re_raise",
"(",
"self",
")",
":",
"if",
"self",
".",
"exc_info",
"is",
"not",
"None",
":",
"six",
".",
"reraise",
"(",
"type",
"(",
"self",
")",
",",
"self",
",",
"self",
".",
"exc_info",
"[",
"2",
"]",
")",
"else",
":",
"raise",
"self"
] | Raise this exception with the original traceback | [
"Raise",
"this",
"exception",
"with",
"the",
"original",
"traceback"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/exception.py#L19-L24 | train | Raise this exception with the original traceback |
totalgood/pugnlp | src/pugnlp/segmentation.py | generate_lines | def generate_lines(text, ext=['.txt', '.md', '.rst', '.asciidoc', '.asc']):
r""" Yield text one line at a time from from a single file path, files in a directory, or a text string
>>> list(generate_lines('Hello crazy\r\nMS/Apple world\rof EOLS.\n'))
['Hello crazy\r\n', 'MS/Apple world\r', 'of EOLS.\n']
... | python | def generate_lines(text, ext=['.txt', '.md', '.rst', '.asciidoc', '.asc']):
r""" Yield text one line at a time from from a single file path, files in a directory, or a text string
>>> list(generate_lines('Hello crazy\r\nMS/Apple world\rof EOLS.\n'))
['Hello crazy\r\n', 'MS/Apple world\r', 'of EOLS.\n']
... | [
"def",
"generate_lines",
"(",
"text",
",",
"ext",
"=",
"[",
"'.txt'",
",",
"'.md'",
",",
"'.rst'",
",",
"'.asciidoc'",
",",
"'.asc'",
"]",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"basestring",
")",
":",
"if",
"len",
"(",
"text",
")",
"<=",
... | r""" Yield text one line at a time from from a single file path, files in a directory, or a text string
>>> list(generate_lines('Hello crazy\r\nMS/Apple world\rof EOLS.\n'))
['Hello crazy\r\n', 'MS/Apple world\r', 'of EOLS.\n'] | [
"r",
"Yield",
"text",
"one",
"line",
"at",
"a",
"time",
"from",
"from",
"a",
"single",
"file",
"path",
"files",
"in",
"a",
"directory",
"or",
"a",
"text",
"string"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/segmentation.py#L49-L66 | train | r Yield text one line at a time from a single file path files in a directory or a text string |
totalgood/pugnlp | src/pugnlp/segmentation.py | segment_text | def segment_text(text=os.path.join(DATA_PATH, 'goodreads-omniscient-books.txt'),
start=None, stop=r'^Rate\ this', ignore=r'^[\d]'):
""" Split text into segments (sections, paragraphs) using regular expressions to trigger breaks.start
"""
start = start if hasattr(start, 'match') else re.comp... | python | def segment_text(text=os.path.join(DATA_PATH, 'goodreads-omniscient-books.txt'),
start=None, stop=r'^Rate\ this', ignore=r'^[\d]'):
""" Split text into segments (sections, paragraphs) using regular expressions to trigger breaks.start
"""
start = start if hasattr(start, 'match') else re.comp... | [
"def",
"segment_text",
"(",
"text",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'goodreads-omniscient-books.txt'",
")",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"r'^Rate\\ this'",
",",
"ignore",
"=",
"r'^[\\d]'",
")",
":",
"start",
"="... | Split text into segments (sections, paragraphs) using regular expressions to trigger breaks.start | [
"Split",
"text",
"into",
"segments",
"(",
"sections",
"paragraphs",
")",
"using",
"regular",
"expressions",
"to",
"trigger",
"breaks",
".",
"start"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/segmentation.py#L69-L90 | train | Splits text into segments using regular expressions to trigger breaks. end
|
totalgood/pugnlp | src/pugnlp/segmentation.py | list_ngrams | def list_ngrams(token_list, n=1, join=' '):
"""Return a list of n-tuples, one for each possible sequence of n items in the token_list
Arguments:
join (bool or str): if str, then join ngrom tuples on it before returning
True is equivalent to join=' '
default = True
See: http://stack... | python | def list_ngrams(token_list, n=1, join=' '):
"""Return a list of n-tuples, one for each possible sequence of n items in the token_list
Arguments:
join (bool or str): if str, then join ngrom tuples on it before returning
True is equivalent to join=' '
default = True
See: http://stack... | [
"def",
"list_ngrams",
"(",
"token_list",
",",
"n",
"=",
"1",
",",
"join",
"=",
"' '",
")",
":",
"join",
"=",
"' '",
"if",
"join",
"is",
"True",
"else",
"join",
"if",
"isinstance",
"(",
"join",
",",
"str",
")",
":",
"return",
"[",
"join",
".",
"jo... | Return a list of n-tuples, one for each possible sequence of n items in the token_list
Arguments:
join (bool or str): if str, then join ngrom tuples on it before returning
True is equivalent to join=' '
default = True
See: http://stackoverflow.com/a/30609050/623735
>>> list_ngrams... | [
"Return",
"a",
"list",
"of",
"n",
"-",
"tuples",
"one",
"for",
"each",
"possible",
"sequence",
"of",
"n",
"items",
"in",
"the",
"token_list"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/segmentation.py#L93-L111 | train | Return a list of n - tuples one for each possible sequence of n items in the token_list
|
totalgood/pugnlp | src/pugnlp/segmentation.py | list_ngram_range | def list_ngram_range(token_list, *args, **kwargs):
"""Return a list of n-tuples, one for each possible sequence of n items in the token_list
Arguments:
join (bool or str): if str, then join ngrom tuples on it before returning
True is equivalent to join=' '
default = True
>>> list_n... | python | def list_ngram_range(token_list, *args, **kwargs):
"""Return a list of n-tuples, one for each possible sequence of n items in the token_list
Arguments:
join (bool or str): if str, then join ngrom tuples on it before returning
True is equivalent to join=' '
default = True
>>> list_n... | [
"def",
"list_ngram_range",
"(",
"token_list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
",",
"n",
"=",
"(",
"args",
"if",
"len",
"(",
"args",
")",
">",
"1",
"else",
"(",
"(",
"0",
",",
"args",
"[",
"0",
"]",
")",
"if",
"args",... | Return a list of n-tuples, one for each possible sequence of n items in the token_list
Arguments:
join (bool or str): if str, then join ngrom tuples on it before returning
True is equivalent to join=' '
default = True
>>> list_ngram_range('goodbye cruel world'.split(), 0, 2, join=False... | [
"Return",
"a",
"list",
"of",
"n",
"-",
"tuples",
"one",
"for",
"each",
"possible",
"sequence",
"of",
"n",
"items",
"in",
"the",
"token_list"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/segmentation.py#L114-L133 | train | Return a list of n - tuples one for each possible sequence of n items in the token_list
|
totalgood/pugnlp | src/pugnlp/segmentation.py | generate_sentences | def generate_sentences(text='', train_path=None, case_sensitive=True, ext=['.md', '.txt', '.asc', '.asciidoc'],
normalize_ordinals=1, normalize_newlines=1, normalize_sentence_boundaries=1,
epochs=20, classifier=nlup.BinaryAveragedPerceptron,
re_eol=r'... | python | def generate_sentences(text='', train_path=None, case_sensitive=True, ext=['.md', '.txt', '.asc', '.asciidoc'],
normalize_ordinals=1, normalize_newlines=1, normalize_sentence_boundaries=1,
epochs=20, classifier=nlup.BinaryAveragedPerceptron,
re_eol=r'... | [
"def",
"generate_sentences",
"(",
"text",
"=",
"''",
",",
"train_path",
"=",
"None",
",",
"case_sensitive",
"=",
"True",
",",
"ext",
"=",
"[",
"'.md'",
",",
"'.txt'",
",",
"'.asc'",
",",
"'.asciidoc'",
"]",
",",
"normalize_ordinals",
"=",
"1",
",",
"norm... | Generate sentences from a sequence of characters (text)
Wrapped text (newlines at column 80, for instance) will break this, breaking up sentences.
Wrapper and preprocessor for Kyle Gorman's "DetectorMorse" module
Arguments:
preprocess (bool): whether to assume common sentence delimitters in markdown... | [
"Generate",
"sentences",
"from",
"a",
"sequence",
"of",
"characters",
"(",
"text",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/segmentation.py#L137-L186 | train | Generate sentences from a sequence of text. |
stevearc/dynamo3 | dynamo3/rate.py | DecayingCapacityStore.add | def add(self, now, num):
""" Add a timestamp and date to the data """
if num == 0:
return
self.points.append((now, num)) | python | def add(self, now, num):
""" Add a timestamp and date to the data """
if num == 0:
return
self.points.append((now, num)) | [
"def",
"add",
"(",
"self",
",",
"now",
",",
"num",
")",
":",
"if",
"num",
"==",
"0",
":",
"return",
"self",
".",
"points",
".",
"append",
"(",
"(",
"now",
",",
"num",
")",
")"
] | Add a timestamp and date to the data | [
"Add",
"a",
"timestamp",
"and",
"date",
"to",
"the",
"data"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/rate.py#L27-L31 | train | Add a timestamp and date to the data |
stevearc/dynamo3 | dynamo3/rate.py | DecayingCapacityStore.value | def value(self):
""" Get the summation of all non-expired points """
now = time.time()
cutoff = now - self.window
while self.points and self.points[0][0] < cutoff:
self.points.pop(0)
return sum([p[1] for p in self.points]) | python | def value(self):
""" Get the summation of all non-expired points """
now = time.time()
cutoff = now - self.window
while self.points and self.points[0][0] < cutoff:
self.points.pop(0)
return sum([p[1] for p in self.points]) | [
"def",
"value",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"cutoff",
"=",
"now",
"-",
"self",
".",
"window",
"while",
"self",
".",
"points",
"and",
"self",
".",
"points",
"[",
"0",
"]",
"[",
"0",
"]",
"<",
"cutoff",
":",
... | Get the summation of all non-expired points | [
"Get",
"the",
"summation",
"of",
"all",
"non",
"-",
"expired",
"points"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/rate.py#L34-L40 | train | Get the sum of all non - expired points |
stevearc/dynamo3 | dynamo3/rate.py | RateLimit.get_consumed | def get_consumed(self, key):
""" Getter for a consumed capacity storage dict """
if key not in self._consumed:
self._consumed[key] = {
'read': DecayingCapacityStore(),
'write': DecayingCapacityStore(),
}
return self._consumed[key] | python | def get_consumed(self, key):
""" Getter for a consumed capacity storage dict """
if key not in self._consumed:
self._consumed[key] = {
'read': DecayingCapacityStore(),
'write': DecayingCapacityStore(),
}
return self._consumed[key] | [
"def",
"get_consumed",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_consumed",
":",
"self",
".",
"_consumed",
"[",
"key",
"]",
"=",
"{",
"'read'",
":",
"DecayingCapacityStore",
"(",
")",
",",
"'write'",
":",
"DecayingCapa... | Getter for a consumed capacity storage dict | [
"Getter",
"for",
"a",
"consumed",
"capacity",
"storage",
"dict"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/rate.py#L96-L103 | train | Get a consumed capacity storage dict |
stevearc/dynamo3 | dynamo3/rate.py | RateLimit.on_capacity | def on_capacity(self, connection, command, query_kwargs, response,
capacity):
""" Hook that runs in response to a 'returned capacity' event """
now = time.time()
args = (connection, command, query_kwargs, response, capacity)
# Check total against the total_cap
... | python | def on_capacity(self, connection, command, query_kwargs, response,
capacity):
""" Hook that runs in response to a 'returned capacity' event """
now = time.time()
args = (connection, command, query_kwargs, response, capacity)
# Check total against the total_cap
... | [
"def",
"on_capacity",
"(",
"self",
",",
"connection",
",",
"command",
",",
"query_kwargs",
",",
"response",
",",
"capacity",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"args",
"=",
"(",
"connection",
",",
"command",
",",
"query_kwargs",
",",
... | Hook that runs in response to a 'returned capacity' event | [
"Hook",
"that",
"runs",
"in",
"response",
"to",
"a",
"returned",
"capacity",
"event"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/rate.py#L105-L143 | train | Hook that runs in response to a returned capacity event |
stevearc/dynamo3 | dynamo3/rate.py | RateLimit._wait | def _wait(self, args, now, cap, consumed_history, consumed_capacity):
""" Check the consumed capacity against the limit and sleep """
for key in ['read', 'write']:
if key in cap and cap[key] > 0:
consumed_history[key].add(now, consumed_capacity[key])
consumed ... | python | def _wait(self, args, now, cap, consumed_history, consumed_capacity):
""" Check the consumed capacity against the limit and sleep """
for key in ['read', 'write']:
if key in cap and cap[key] > 0:
consumed_history[key].add(now, consumed_capacity[key])
consumed ... | [
"def",
"_wait",
"(",
"self",
",",
"args",
",",
"now",
",",
"cap",
",",
"consumed_history",
",",
"consumed_capacity",
")",
":",
"for",
"key",
"in",
"[",
"'read'",
",",
"'write'",
"]",
":",
"if",
"key",
"in",
"cap",
"and",
"cap",
"[",
"key",
"]",
">"... | Check the consumed capacity against the limit and sleep | [
"Check",
"the",
"consumed",
"capacity",
"against",
"the",
"limit",
"and",
"sleep"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/rate.py#L145-L159 | train | Wait for the user to see if the capacity is exceeded. |
juju/theblues | theblues/support.py | Support.create_case | def create_case(self, name, email, subject, description, businessImpact,
priority, phone):
""" Send a case creation to SalesForces to create a ticket.
@param name of the person creating the case.
@param email of the person creating the case.
@param subject of the cas... | python | def create_case(self, name, email, subject, description, businessImpact,
priority, phone):
""" Send a case creation to SalesForces to create a ticket.
@param name of the person creating the case.
@param email of the person creating the case.
@param subject of the cas... | [
"def",
"create_case",
"(",
"self",
",",
"name",
",",
"email",
",",
"subject",
",",
"description",
",",
"businessImpact",
",",
"priority",
",",
"phone",
")",
":",
"if",
"not",
"(",
"'@'",
"in",
"parseaddr",
"(",
"email",
")",
"[",
"1",
"]",
")",
":",
... | Send a case creation to SalesForces to create a ticket.
@param name of the person creating the case.
@param email of the person creating the case.
@param subject of the case.
@param description of the case.
@param businessImpact of the case.
@param priority of the case.
... | [
"Send",
"a",
"case",
"creation",
"to",
"SalesForces",
"to",
"create",
"a",
"ticket",
"."
] | f4431f29e43d04fc32f38f4f86cea45cd4e6ae98 | https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/support.py#L51-L105 | train | Create a new case in SalesForces. |
alphagov/performanceplatform-collector | performanceplatform/collector/webtrends/reports.py | Collector.date_range_for_webtrends | def date_range_for_webtrends(cls, start_at=None, end_at=None):
"""
Get the day dates in between start and end formatted for query.
This returns dates inclusive e.g. final day is (end_at, end_at+1 day)
"""
if start_at and end_at:
start_date = cls.parse_standard_date_st... | python | def date_range_for_webtrends(cls, start_at=None, end_at=None):
"""
Get the day dates in between start and end formatted for query.
This returns dates inclusive e.g. final day is (end_at, end_at+1 day)
"""
if start_at and end_at:
start_date = cls.parse_standard_date_st... | [
"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 day dates in between start and end formatted for query.
This returns dates inclusive e.g. final day is (end_at, end_at+1 day) | [
"Get",
"the",
"day",
"dates",
"in",
"between",
"start",
"and",
"end",
"formatted",
"for",
"query",
".",
"This",
"returns",
"dates",
"inclusive",
"e",
".",
"g",
".",
"final",
"day",
"is",
"(",
"end_at",
"end_at",
"+",
"1",
"day",
")"
] | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/webtrends/reports.py#L16-L35 | train | This returns the day dates in between start_at and end_at formatted for query. This returns the day dates inclusive e. g. start_at + 1 day |
alphagov/performanceplatform-collector | performanceplatform/collector/gcloud/aggregate.py | get_cumulative_spend | def get_cumulative_spend(key):
"""
Get the sum of spending for this category up to and including the given
month.
"""
query = ('ROUND(SUM(total_ex_vat), 2) AS total '
'FROM {table} '
'WHERE date <= "{year}-{month:02}-01" '
'AND lot="{lot}" '
'AND c... | python | def get_cumulative_spend(key):
"""
Get the sum of spending for this category up to and including the given
month.
"""
query = ('ROUND(SUM(total_ex_vat), 2) AS total '
'FROM {table} '
'WHERE date <= "{year}-{month:02}-01" '
'AND lot="{lot}" '
'AND c... | [
"def",
"get_cumulative_spend",
"(",
"key",
")",
":",
"query",
"=",
"(",
"'ROUND(SUM(total_ex_vat), 2) AS total '",
"'FROM {table} '",
"'WHERE date <= \"{year}-{month:02}-01\" '",
"'AND lot=\"{lot}\" '",
"'AND customer_sector=\"{sector}\" '",
"'AND supplier_type=\"{sme_large}\"'",
".",
... | Get the sum of spending for this category up to and including the given
month. | [
"Get",
"the",
"sum",
"of",
"spending",
"for",
"this",
"category",
"up",
"to",
"and",
"including",
"the",
"given",
"month",
"."
] | de68ab4aa500c31e436e050fa1268fa928c522a5 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/gcloud/aggregate.py#L130-L151 | train | Get the sum of spending for this category up to and including the given
month. |
DarkEnergySurvey/ugali | ugali/observation/roi.py | ROI.plot | def plot(self, value=None, pixel=None):
"""
Plot the ROI
"""
# DEPRECATED
import ugali.utils.plotting
map_roi = np.array(hp.UNSEEN \
* np.ones(hp.nside2npix(self.config.params['coords']['nside_pixel'])))
if value is None:
... | python | def plot(self, value=None, pixel=None):
"""
Plot the ROI
"""
# DEPRECATED
import ugali.utils.plotting
map_roi = np.array(hp.UNSEEN \
* np.ones(hp.nside2npix(self.config.params['coords']['nside_pixel'])))
if value is None:
... | [
"def",
"plot",
"(",
"self",
",",
"value",
"=",
"None",
",",
"pixel",
"=",
"None",
")",
":",
"# DEPRECATED",
"import",
"ugali",
".",
"utils",
".",
"plotting",
"map_roi",
"=",
"np",
".",
"array",
"(",
"hp",
".",
"UNSEEN",
"*",
"np",
".",
"ones",
"(",... | Plot the ROI | [
"Plot",
"the",
"ROI"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/roi.py#L135-L160 | train | Plot the ROI and the ROI of the region of Interest. |
DarkEnergySurvey/ugali | ugali/observation/roi.py | ROI.inPixels | def inPixels(self,lon,lat,pixels):
""" Function for testing if coordintes in set of ROI pixels. """
nside = self.config.params['coords']['nside_pixel']
return ugali.utils.healpix.in_pixels(lon,lat,pixels,nside) | python | def inPixels(self,lon,lat,pixels):
""" Function for testing if coordintes in set of ROI pixels. """
nside = self.config.params['coords']['nside_pixel']
return ugali.utils.healpix.in_pixels(lon,lat,pixels,nside) | [
"def",
"inPixels",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"pixels",
")",
":",
"nside",
"=",
"self",
".",
"config",
".",
"params",
"[",
"'coords'",
"]",
"[",
"'nside_pixel'",
"]",
"return",
"ugali",
".",
"utils",
".",
"healpix",
".",
"in_pixels",
"... | Function for testing if coordintes in set of ROI pixels. | [
"Function",
"for",
"testing",
"if",
"coordintes",
"in",
"set",
"of",
"ROI",
"pixels",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/roi.py#L163-L166 | train | Test if coordintes in set of HEALPix pixels. |
DarkEnergySurvey/ugali | ugali/observation/roi.py | ROI.getCatalogPixels | def getCatalogPixels(self):
"""
Return the catalog pixels spanned by this ROI.
"""
filenames = self.config.getFilenames()
nside_catalog = self.config.params['coords']['nside_catalog']
nside_pixel = self.config.params['coords']['nside_pixel']
# All possible catalo... | python | def getCatalogPixels(self):
"""
Return the catalog pixels spanned by this ROI.
"""
filenames = self.config.getFilenames()
nside_catalog = self.config.params['coords']['nside_catalog']
nside_pixel = self.config.params['coords']['nside_pixel']
# All possible catalo... | [
"def",
"getCatalogPixels",
"(",
"self",
")",
":",
"filenames",
"=",
"self",
".",
"config",
".",
"getFilenames",
"(",
")",
"nside_catalog",
"=",
"self",
".",
"config",
".",
"params",
"[",
"'coords'",
"]",
"[",
"'nside_catalog'",
"]",
"nside_pixel",
"=",
"se... | Return the catalog pixels spanned by this ROI. | [
"Return",
"the",
"catalog",
"pixels",
"spanned",
"by",
"this",
"ROI",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/roi.py#L196-L209 | train | Return the catalog pixels spanned by this ROI. |
joeyespo/path-and-address | examples/dot/dot.py | main | def main(args=None):
"""The entry point of the application."""
if args is None:
args = sys.argv[1:]
# Parse command-line
args = docopt(__doc__, argv=args)
# Parse arguments
path, address = resolve(args['<path>'], args['<address>'])
host, port = split_address(address)
# Validat... | python | def main(args=None):
"""The entry point of the application."""
if args is None:
args = sys.argv[1:]
# Parse command-line
args = docopt(__doc__, argv=args)
# Parse arguments
path, address = resolve(args['<path>'], args['<address>'])
host, port = split_address(address)
# Validat... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"# Parse command-line",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"args",
")",
"# Parse arguments"... | The entry point of the application. | [
"The",
"entry",
"point",
"of",
"the",
"application",
"."
] | f8193a09f4b785574d920e8a2aeeb55ea6ff4e20 | https://github.com/joeyespo/path-and-address/blob/f8193a09f4b785574d920e8a2aeeb55ea6ff4e20/examples/dot/dot.py#L17-L43 | train | The entry point of the application. |
stevearc/dynamo3 | dynamo3/fields.py | BaseIndex.schema | def schema(self, hash_key):
"""
Create the index schema
Parameters
----------
hash_key : :class:`~.DynamoKey`
The hash key of the table
"""
key_schema = [hash_key.hash_schema()]
if self.range_key is not None:
key_schema.append(sel... | python | def schema(self, hash_key):
"""
Create the index schema
Parameters
----------
hash_key : :class:`~.DynamoKey`
The hash key of the table
"""
key_schema = [hash_key.hash_schema()]
if self.range_key is not None:
key_schema.append(sel... | [
"def",
"schema",
"(",
"self",
",",
"hash_key",
")",
":",
"key_schema",
"=",
"[",
"hash_key",
".",
"hash_schema",
"(",
")",
"]",
"if",
"self",
".",
"range_key",
"is",
"not",
"None",
":",
"key_schema",
".",
"append",
"(",
"self",
".",
"range_key",
".",
... | Create the index schema
Parameters
----------
hash_key : :class:`~.DynamoKey`
The hash key of the table | [
"Create",
"the",
"index",
"schema"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L76-L98 | train | Create the index schema for the specified hash key. |
stevearc/dynamo3 | dynamo3/fields.py | LocalIndex.include | def include(cls, name, range_key, includes):
""" Create an index that projects key attributes plus some others """
return cls(cls.INCLUDE, name, range_key, includes) | python | def include(cls, name, range_key, includes):
""" Create an index that projects key attributes plus some others """
return cls(cls.INCLUDE, name, range_key, includes) | [
"def",
"include",
"(",
"cls",
",",
"name",
",",
"range_key",
",",
"includes",
")",
":",
"return",
"cls",
"(",
"cls",
".",
"INCLUDE",
",",
"name",
",",
"range_key",
",",
"includes",
")"
] | Create an index that projects key attributes plus some others | [
"Create",
"an",
"index",
"that",
"projects",
"key",
"attributes",
"plus",
"some",
"others"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L141-L143 | train | Create an index that projects key attributes plus some others |
stevearc/dynamo3 | dynamo3/fields.py | LocalIndex.from_response | def from_response(cls, response, attrs):
""" Create an index from returned Dynamo data """
proj = response['Projection']
index = cls(proj['ProjectionType'], response['IndexName'],
attrs[response['KeySchema'][1]['AttributeName']],
proj.get('NonKeyAttributes... | python | def from_response(cls, response, attrs):
""" Create an index from returned Dynamo data """
proj = response['Projection']
index = cls(proj['ProjectionType'], response['IndexName'],
attrs[response['KeySchema'][1]['AttributeName']],
proj.get('NonKeyAttributes... | [
"def",
"from_response",
"(",
"cls",
",",
"response",
",",
"attrs",
")",
":",
"proj",
"=",
"response",
"[",
"'Projection'",
"]",
"index",
"=",
"cls",
"(",
"proj",
"[",
"'ProjectionType'",
"]",
",",
"response",
"[",
"'IndexName'",
"]",
",",
"attrs",
"[",
... | Create an index from returned Dynamo data | [
"Create",
"an",
"index",
"from",
"returned",
"Dynamo",
"data"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L146-L153 | train | Create an index from a Dynamo response. |
stevearc/dynamo3 | dynamo3/fields.py | GlobalIndex.all | def all(cls, name, hash_key, range_key=None, throughput=None):
""" Create an index that projects all attributes """
return cls(cls.ALL, name, hash_key, range_key, throughput=throughput) | python | def all(cls, name, hash_key, range_key=None, throughput=None):
""" Create an index that projects all attributes """
return cls(cls.ALL, name, hash_key, range_key, throughput=throughput) | [
"def",
"all",
"(",
"cls",
",",
"name",
",",
"hash_key",
",",
"range_key",
"=",
"None",
",",
"throughput",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"cls",
".",
"ALL",
",",
"name",
",",
"hash_key",
",",
"range_key",
",",
"throughput",
"=",
"through... | Create an index that projects all attributes | [
"Create",
"an",
"index",
"that",
"projects",
"all",
"attributes"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L174-L176 | train | Create an index that projects all attributes |
stevearc/dynamo3 | dynamo3/fields.py | GlobalIndex.keys | def keys(cls, name, hash_key, range_key=None, throughput=None):
""" Create an index that projects only key attributes """
return cls(cls.KEYS, name, hash_key, range_key,
throughput=throughput) | python | def keys(cls, name, hash_key, range_key=None, throughput=None):
""" Create an index that projects only key attributes """
return cls(cls.KEYS, name, hash_key, range_key,
throughput=throughput) | [
"def",
"keys",
"(",
"cls",
",",
"name",
",",
"hash_key",
",",
"range_key",
"=",
"None",
",",
"throughput",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"cls",
".",
"KEYS",
",",
"name",
",",
"hash_key",
",",
"range_key",
",",
"throughput",
"=",
"throu... | Create an index that projects only key attributes | [
"Create",
"an",
"index",
"that",
"projects",
"only",
"key",
"attributes"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L179-L182 | train | Create an index that projects only key attributes |
stevearc/dynamo3 | dynamo3/fields.py | GlobalIndex.include | def include(cls, name, hash_key, range_key=None, includes=None,
throughput=None):
""" Create an index that projects key attributes plus some others """
return cls(cls.INCLUDE, name, hash_key, range_key, includes,
throughput=throughput) | python | def include(cls, name, hash_key, range_key=None, includes=None,
throughput=None):
""" Create an index that projects key attributes plus some others """
return cls(cls.INCLUDE, name, hash_key, range_key, includes,
throughput=throughput) | [
"def",
"include",
"(",
"cls",
",",
"name",
",",
"hash_key",
",",
"range_key",
"=",
"None",
",",
"includes",
"=",
"None",
",",
"throughput",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"cls",
".",
"INCLUDE",
",",
"name",
",",
"hash_key",
",",
"range_... | Create an index that projects key attributes plus some others | [
"Create",
"an",
"index",
"that",
"projects",
"key",
"attributes",
"plus",
"some",
"others"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L185-L189 | train | Create an index that projects key attributes plus some others |
stevearc/dynamo3 | dynamo3/fields.py | GlobalIndex.schema | def schema(self):
""" Construct the schema definition for this index """
schema_data = super(GlobalIndex, self).schema(self.hash_key)
schema_data['ProvisionedThroughput'] = self.throughput.schema()
return schema_data | python | def schema(self):
""" Construct the schema definition for this index """
schema_data = super(GlobalIndex, self).schema(self.hash_key)
schema_data['ProvisionedThroughput'] = self.throughput.schema()
return schema_data | [
"def",
"schema",
"(",
"self",
")",
":",
"schema_data",
"=",
"super",
"(",
"GlobalIndex",
",",
"self",
")",
".",
"schema",
"(",
"self",
".",
"hash_key",
")",
"schema_data",
"[",
"'ProvisionedThroughput'",
"]",
"=",
"self",
".",
"throughput",
".",
"schema",
... | Construct the schema definition for this index | [
"Construct",
"the",
"schema",
"definition",
"for",
"this",
"index"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L191-L195 | train | Construct the schema definition for this index |
stevearc/dynamo3 | dynamo3/fields.py | GlobalIndex.from_response | def from_response(cls, response, attrs):
""" Create an index from returned Dynamo data """
proj = response['Projection']
hash_key = attrs.get(response['KeySchema'][0]['AttributeName'])
range_key = None
if len(response['KeySchema']) > 1:
range_key = attrs[response['Key... | python | def from_response(cls, response, attrs):
""" Create an index from returned Dynamo data """
proj = response['Projection']
hash_key = attrs.get(response['KeySchema'][0]['AttributeName'])
range_key = None
if len(response['KeySchema']) > 1:
range_key = attrs[response['Key... | [
"def",
"from_response",
"(",
"cls",
",",
"response",
",",
"attrs",
")",
":",
"proj",
"=",
"response",
"[",
"'Projection'",
"]",
"hash_key",
"=",
"attrs",
".",
"get",
"(",
"response",
"[",
"'KeySchema'",
"]",
"[",
"0",
"]",
"[",
"'AttributeName'",
"]",
... | Create an index from returned Dynamo data | [
"Create",
"an",
"index",
"from",
"returned",
"Dynamo",
"data"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L198-L210 | train | Create an index from a Dynamo response. |
stevearc/dynamo3 | dynamo3/fields.py | Table.from_response | def from_response(cls, response):
""" Create a Table from returned Dynamo data """
hash_key = None
range_key = None
# KeySchema may not be in the response if the TableStatus is DELETING.
if 'KeySchema' in response:
attrs = dict(((d['AttributeName'],
... | python | def from_response(cls, response):
""" Create a Table from returned Dynamo data """
hash_key = None
range_key = None
# KeySchema may not be in the response if the TableStatus is DELETING.
if 'KeySchema' in response:
attrs = dict(((d['AttributeName'],
... | [
"def",
"from_response",
"(",
"cls",
",",
"response",
")",
":",
"hash_key",
"=",
"None",
"range_key",
"=",
"None",
"# KeySchema may not be in the response if the TableStatus is DELETING.",
"if",
"'KeySchema'",
"in",
"response",
":",
"attrs",
"=",
"dict",
"(",
"(",
"(... | Create a Table from returned Dynamo data | [
"Create",
"a",
"Table",
"from",
"returned",
"Dynamo",
"data"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L296-L328 | train | Create a Table from a Dynamo response. |
stevearc/dynamo3 | dynamo3/fields.py | IndexUpdate.get_attrs | def get_attrs(self):
""" Get all attrs necessary for the update (empty unless Create) """
if self.action != 'Create':
return []
index = self.extra['index']
ret = [index.hash_key]
if index.range_key is not None:
ret.append(index.range_key)
return re... | python | def get_attrs(self):
""" Get all attrs necessary for the update (empty unless Create) """
if self.action != 'Create':
return []
index = self.extra['index']
ret = [index.hash_key]
if index.range_key is not None:
ret.append(index.range_key)
return re... | [
"def",
"get_attrs",
"(",
"self",
")",
":",
"if",
"self",
".",
"action",
"!=",
"'Create'",
":",
"return",
"[",
"]",
"index",
"=",
"self",
".",
"extra",
"[",
"'index'",
"]",
"ret",
"=",
"[",
"index",
".",
"hash_key",
"]",
"if",
"index",
".",
"range_k... | Get all attrs necessary for the update (empty unless Create) | [
"Get",
"all",
"attrs",
"necessary",
"for",
"the",
"update",
"(",
"empty",
"unless",
"Create",
")"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L378-L386 | train | Get all the attrs needed for the update |
stevearc/dynamo3 | dynamo3/fields.py | IndexUpdate.serialize | def serialize(self):
""" Get the serialized Dynamo format for the update """
if self.action == 'Create':
payload = self.extra['index'].schema()
else:
payload = {
'IndexName': self.index_name,
}
if self.action == 'Update':
... | python | def serialize(self):
""" Get the serialized Dynamo format for the update """
if self.action == 'Create':
payload = self.extra['index'].schema()
else:
payload = {
'IndexName': self.index_name,
}
if self.action == 'Update':
... | [
"def",
"serialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"action",
"==",
"'Create'",
":",
"payload",
"=",
"self",
".",
"extra",
"[",
"'index'",
"]",
".",
"schema",
"(",
")",
"else",
":",
"payload",
"=",
"{",
"'IndexName'",
":",
"self",
".",
"i... | Get the serialized Dynamo format for the update | [
"Get",
"the",
"serialized",
"Dynamo",
"format",
"for",
"the",
"update"
] | f897c40ece28586272dbcab8f0d99a14a1831dda | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/fields.py#L388-L401 | train | Get the serialized Dynamo format for the update |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.