id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
234,700 | daviddrysdale/python-phonenumbers | tools/python/buildprefixdata.py | load_locale_prefixdata | def load_locale_prefixdata(indir, separator=None):
"""Load per-prefix data from the given top-level directory.
Prefix data is assumed to be held in files <indir>/<locale>/<prefix>.txt.
The same prefix may occur in multiple files, giving the prefix's description
in different locales.
"""
prefixdata = {} # prefix => dict mapping locale to description
for locale in os.listdir(indir):
if not os.path.isdir(os.path.join(indir, locale)):
continue
for filename in glob.glob(os.path.join(indir, locale, "*%s" % PREFIXDATA_SUFFIX)):
overall_prefix, ext = os.path.splitext(os.path.basename(filename))
load_locale_prefixdata_file(prefixdata, filename, locale, overall_prefix, separator)
return prefixdata | python | def load_locale_prefixdata(indir, separator=None):
prefixdata = {} # prefix => dict mapping locale to description
for locale in os.listdir(indir):
if not os.path.isdir(os.path.join(indir, locale)):
continue
for filename in glob.glob(os.path.join(indir, locale, "*%s" % PREFIXDATA_SUFFIX)):
overall_prefix, ext = os.path.splitext(os.path.basename(filename))
load_locale_prefixdata_file(prefixdata, filename, locale, overall_prefix, separator)
return prefixdata | [
"def",
"load_locale_prefixdata",
"(",
"indir",
",",
"separator",
"=",
"None",
")",
":",
"prefixdata",
"=",
"{",
"}",
"# prefix => dict mapping locale to description",
"for",
"locale",
"in",
"os",
".",
"listdir",
"(",
"indir",
")",
":",
"if",
"not",
"os",
".",
... | Load per-prefix data from the given top-level directory.
Prefix data is assumed to be held in files <indir>/<locale>/<prefix>.txt.
The same prefix may occur in multiple files, giving the prefix's description
in different locales. | [
"Load",
"per",
"-",
"prefix",
"data",
"from",
"the",
"given",
"top",
"-",
"level",
"directory",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L131-L145 |
234,701 | daviddrysdale/python-phonenumbers | tools/python/buildprefixdata.py | output_prefixdata_code | def output_prefixdata_code(prefixdata, outfilename, module_prefix, varprefix, per_locale, chunks):
"""Output the per-prefix data in Python form to the given file """
sorted_keys = sorted(prefixdata.keys())
total_keys = len(sorted_keys)
if chunks == -1:
chunk_size = PREFIXDATA_CHUNK_SIZE
total_chunks = int(math.ceil(total_keys / float(chunk_size)))
else:
chunk_size = int(math.ceil(total_keys / float(chunks)))
total_chunks = chunks
outdirname = os.path.dirname(outfilename)
longest_prefix = 0
for chunk_num in range(total_chunks):
chunk_index = chunk_size * chunk_num
chunk_keys = sorted_keys[chunk_index:chunk_index + chunk_size]
chunk_data = {}
for key in chunk_keys:
chunk_data[key] = prefixdata[key]
chunk_file = os.path.join(outdirname, 'data%d.py' % chunk_num)
chunk_longest = output_prefixdata_chunk(
chunk_data, chunk_file, module_prefix, per_locale)
if chunk_longest > longest_prefix:
longest_prefix = chunk_longest
with open(outfilename, "w") as outfile:
if per_locale:
prnt(PREFIXDATA_LOCALE_FILE_PROLOG % {'module': module_prefix}, file=outfile)
else:
prnt(PREFIXDATA_FILE_PROLOG % {'module': module_prefix}, file=outfile)
prnt(COPYRIGHT_NOTICE, file=outfile)
prnt("%s_DATA = {}" % varprefix, file=outfile)
for chunk_num in range(total_chunks):
prnt("from .data%d import data" % chunk_num, file=outfile)
prnt("%s_DATA.update(data)" % varprefix, file=outfile)
prnt("del data", file=outfile)
prnt("%s_LONGEST_PREFIX = %d" % (varprefix, longest_prefix), file=outfile) | python | def output_prefixdata_code(prefixdata, outfilename, module_prefix, varprefix, per_locale, chunks):
sorted_keys = sorted(prefixdata.keys())
total_keys = len(sorted_keys)
if chunks == -1:
chunk_size = PREFIXDATA_CHUNK_SIZE
total_chunks = int(math.ceil(total_keys / float(chunk_size)))
else:
chunk_size = int(math.ceil(total_keys / float(chunks)))
total_chunks = chunks
outdirname = os.path.dirname(outfilename)
longest_prefix = 0
for chunk_num in range(total_chunks):
chunk_index = chunk_size * chunk_num
chunk_keys = sorted_keys[chunk_index:chunk_index + chunk_size]
chunk_data = {}
for key in chunk_keys:
chunk_data[key] = prefixdata[key]
chunk_file = os.path.join(outdirname, 'data%d.py' % chunk_num)
chunk_longest = output_prefixdata_chunk(
chunk_data, chunk_file, module_prefix, per_locale)
if chunk_longest > longest_prefix:
longest_prefix = chunk_longest
with open(outfilename, "w") as outfile:
if per_locale:
prnt(PREFIXDATA_LOCALE_FILE_PROLOG % {'module': module_prefix}, file=outfile)
else:
prnt(PREFIXDATA_FILE_PROLOG % {'module': module_prefix}, file=outfile)
prnt(COPYRIGHT_NOTICE, file=outfile)
prnt("%s_DATA = {}" % varprefix, file=outfile)
for chunk_num in range(total_chunks):
prnt("from .data%d import data" % chunk_num, file=outfile)
prnt("%s_DATA.update(data)" % varprefix, file=outfile)
prnt("del data", file=outfile)
prnt("%s_LONGEST_PREFIX = %d" % (varprefix, longest_prefix), file=outfile) | [
"def",
"output_prefixdata_code",
"(",
"prefixdata",
",",
"outfilename",
",",
"module_prefix",
",",
"varprefix",
",",
"per_locale",
",",
"chunks",
")",
":",
"sorted_keys",
"=",
"sorted",
"(",
"prefixdata",
".",
"keys",
"(",
")",
")",
"total_keys",
"=",
"len",
... | Output the per-prefix data in Python form to the given file | [
"Output",
"the",
"per",
"-",
"prefix",
"data",
"in",
"Python",
"form",
"to",
"the",
"given",
"file"
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L164-L200 |
234,702 | daviddrysdale/python-phonenumbers | tools/python/buildprefixdata.py | _standalone | def _standalone(argv):
"""Parse the given input directory and emit generated code."""
varprefix = "GEOCODE"
per_locale = True
separator = None
chunks = -1
try:
opts, args = getopt.getopt(argv, "hv:fs:c:", ("help", "var=", "flat", "sep=", "chunks="))
except getopt.GetoptError:
prnt(__doc__, file=sys.stderr)
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
prnt(__doc__, file=sys.stderr)
sys.exit(1)
elif opt in ("-v", "--var"):
varprefix = arg
elif opt in ("-f", "--flat"):
per_locale = False
elif opt in ("-s", "--sep"):
separator = arg
elif opt in ("-c", "--chunks"):
chunks = int(arg)
else:
prnt("Unknown option %s" % opt, file=sys.stderr)
prnt(__doc__, file=sys.stderr)
sys.exit(1)
if len(args) != 3:
prnt(__doc__, file=sys.stderr)
sys.exit(1)
if per_locale:
prefixdata = load_locale_prefixdata(args[0], separator=separator)
else:
prefixdata = {}
load_locale_prefixdata_file(prefixdata, args[0], separator=separator)
output_prefixdata_code(prefixdata, args[1], args[2], varprefix, per_locale, chunks) | python | def _standalone(argv):
varprefix = "GEOCODE"
per_locale = True
separator = None
chunks = -1
try:
opts, args = getopt.getopt(argv, "hv:fs:c:", ("help", "var=", "flat", "sep=", "chunks="))
except getopt.GetoptError:
prnt(__doc__, file=sys.stderr)
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
prnt(__doc__, file=sys.stderr)
sys.exit(1)
elif opt in ("-v", "--var"):
varprefix = arg
elif opt in ("-f", "--flat"):
per_locale = False
elif opt in ("-s", "--sep"):
separator = arg
elif opt in ("-c", "--chunks"):
chunks = int(arg)
else:
prnt("Unknown option %s" % opt, file=sys.stderr)
prnt(__doc__, file=sys.stderr)
sys.exit(1)
if len(args) != 3:
prnt(__doc__, file=sys.stderr)
sys.exit(1)
if per_locale:
prefixdata = load_locale_prefixdata(args[0], separator=separator)
else:
prefixdata = {}
load_locale_prefixdata_file(prefixdata, args[0], separator=separator)
output_prefixdata_code(prefixdata, args[1], args[2], varprefix, per_locale, chunks) | [
"def",
"_standalone",
"(",
"argv",
")",
":",
"varprefix",
"=",
"\"GEOCODE\"",
"per_locale",
"=",
"True",
"separator",
"=",
"None",
"chunks",
"=",
"-",
"1",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
",",
"\"hv:fs:c:\"",
... | Parse the given input directory and emit generated code. | [
"Parse",
"the",
"given",
"input",
"directory",
"and",
"emit",
"generated",
"code",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L223-L258 |
234,703 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | _limit | def _limit(lower, upper):
"""Returns a regular expression quantifier with an upper and lower limit."""
if ((lower < 0) or (upper <= 0) or (upper < lower)):
raise Exception("Illegal argument to _limit")
return unicod("{%d,%d}") % (lower, upper) | python | def _limit(lower, upper):
if ((lower < 0) or (upper <= 0) or (upper < lower)):
raise Exception("Illegal argument to _limit")
return unicod("{%d,%d}") % (lower, upper) | [
"def",
"_limit",
"(",
"lower",
",",
"upper",
")",
":",
"if",
"(",
"(",
"lower",
"<",
"0",
")",
"or",
"(",
"upper",
"<=",
"0",
")",
"or",
"(",
"upper",
"<",
"lower",
")",
")",
":",
"raise",
"Exception",
"(",
"\"Illegal argument to _limit\"",
")",
"r... | Returns a regular expression quantifier with an upper and lower limit. | [
"Returns",
"a",
"regular",
"expression",
"quantifier",
"with",
"an",
"upper",
"and",
"lower",
"limit",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L57-L61 |
234,704 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | _verify | def _verify(leniency, numobj, candidate, matcher):
"""Returns True if number is a verified number according to the
leniency."""
if leniency == Leniency.POSSIBLE:
return is_possible_number(numobj)
elif leniency == Leniency.VALID:
if (not is_valid_number(numobj) or
not _contains_only_valid_x_chars(numobj, candidate)):
return False
return _is_national_prefix_present_if_required(numobj)
elif leniency == Leniency.STRICT_GROUPING:
return _verify_strict_grouping(numobj, candidate, matcher)
elif leniency == Leniency.EXACT_GROUPING:
return _verify_exact_grouping(numobj, candidate, matcher)
else:
raise Exception("Error: unsupported Leniency value %s" % leniency) | python | def _verify(leniency, numobj, candidate, matcher):
if leniency == Leniency.POSSIBLE:
return is_possible_number(numobj)
elif leniency == Leniency.VALID:
if (not is_valid_number(numobj) or
not _contains_only_valid_x_chars(numobj, candidate)):
return False
return _is_national_prefix_present_if_required(numobj)
elif leniency == Leniency.STRICT_GROUPING:
return _verify_strict_grouping(numobj, candidate, matcher)
elif leniency == Leniency.EXACT_GROUPING:
return _verify_exact_grouping(numobj, candidate, matcher)
else:
raise Exception("Error: unsupported Leniency value %s" % leniency) | [
"def",
"_verify",
"(",
"leniency",
",",
"numobj",
",",
"candidate",
",",
"matcher",
")",
":",
"if",
"leniency",
"==",
"Leniency",
".",
"POSSIBLE",
":",
"return",
"is_possible_number",
"(",
"numobj",
")",
"elif",
"leniency",
"==",
"Leniency",
".",
"VALID",
... | Returns True if number is a verified number according to the
leniency. | [
"Returns",
"True",
"if",
"number",
"is",
"a",
"verified",
"number",
"according",
"to",
"the",
"leniency",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L209-L224 |
234,705 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | _get_national_number_groups_without_pattern | def _get_national_number_groups_without_pattern(numobj):
"""Helper method to get the national-number part of a number, formatted without any national
prefix, and return it as a set of digit blocks that would be formatted together following
standard formatting rules."""
# This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of
# digits.
rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966)
# We remove the extension part from the formatted string before splitting
# it into different groups.
end_index = rfc3966_format.find(U_SEMICOLON)
if end_index < 0:
end_index = len(rfc3966_format)
# The country-code will have a '-' following it.
start_index = rfc3966_format.find(U_DASH) + 1
return rfc3966_format[start_index:end_index].split(U_DASH) | python | def _get_national_number_groups_without_pattern(numobj):
# This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of
# digits.
rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966)
# We remove the extension part from the formatted string before splitting
# it into different groups.
end_index = rfc3966_format.find(U_SEMICOLON)
if end_index < 0:
end_index = len(rfc3966_format)
# The country-code will have a '-' following it.
start_index = rfc3966_format.find(U_DASH) + 1
return rfc3966_format[start_index:end_index].split(U_DASH) | [
"def",
"_get_national_number_groups_without_pattern",
"(",
"numobj",
")",
":",
"# This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of",
"# digits.",
"rfc3966_format",
"=",
"format_number",
"(",
"numobj",
",",
"PhoneNumberFormat",
".",
"RFC3966",
"... | Helper method to get the national-number part of a number, formatted without any national
prefix, and return it as a set of digit blocks that would be formatted together following
standard formatting rules. | [
"Helper",
"method",
"to",
"get",
"the",
"national",
"-",
"number",
"part",
"of",
"a",
"number",
"formatted",
"without",
"any",
"national",
"prefix",
"and",
"return",
"it",
"as",
"a",
"set",
"of",
"digit",
"blocks",
"that",
"would",
"be",
"formatted",
"toge... | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L337-L352 |
234,706 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | _get_national_number_groups | def _get_national_number_groups(numobj, formatting_pattern):
"""Helper method to get the national-number part of a number, formatted without any national
prefix, and return it as a set of digit blocks that should be formatted together according to
the formatting pattern passed in."""
# If a format is provided, we format the NSN only, and split that according to the separator.
nsn = national_significant_number(numobj)
return _format_nsn_using_pattern(nsn, formatting_pattern,
PhoneNumberFormat.RFC3966).split(U_DASH) | python | def _get_national_number_groups(numobj, formatting_pattern):
# If a format is provided, we format the NSN only, and split that according to the separator.
nsn = national_significant_number(numobj)
return _format_nsn_using_pattern(nsn, formatting_pattern,
PhoneNumberFormat.RFC3966).split(U_DASH) | [
"def",
"_get_national_number_groups",
"(",
"numobj",
",",
"formatting_pattern",
")",
":",
"# If a format is provided, we format the NSN only, and split that according to the separator.",
"nsn",
"=",
"national_significant_number",
"(",
"numobj",
")",
"return",
"_format_nsn_using_patte... | Helper method to get the national-number part of a number, formatted without any national
prefix, and return it as a set of digit blocks that should be formatted together according to
the formatting pattern passed in. | [
"Helper",
"method",
"to",
"get",
"the",
"national",
"-",
"number",
"part",
"of",
"a",
"number",
"formatted",
"without",
"any",
"national",
"prefix",
"and",
"return",
"it",
"as",
"a",
"set",
"of",
"digit",
"blocks",
"that",
"should",
"be",
"formatted",
"tog... | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L355-L362 |
234,707 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher._find | def _find(self, index):
"""Attempts to find the next subsequence in the searched sequence on or after index
that represents a phone number. Returns the next match, None if none was found.
Arguments:
index -- The search index to start searching at.
Returns the phone number match found, None if none can be found.
"""
match = _PATTERN.search(self.text, index)
while self._max_tries > 0 and match is not None:
start = match.start()
candidate = self.text[start:match.end()]
# Check for extra numbers at the end.
# TODO: This is the place to start when trying to support
# extraction of multiple phone number from split notations (+41 79
# 123 45 67 / 68).
candidate = self._trim_after_first_match(_SECOND_NUMBER_START_PATTERN,
candidate)
match = self._extract_match(candidate, start)
if match is not None:
return match
# Move along
index = start + len(candidate)
self._max_tries -= 1
match = _PATTERN.search(self.text, index)
return None | python | def _find(self, index):
match = _PATTERN.search(self.text, index)
while self._max_tries > 0 and match is not None:
start = match.start()
candidate = self.text[start:match.end()]
# Check for extra numbers at the end.
# TODO: This is the place to start when trying to support
# extraction of multiple phone number from split notations (+41 79
# 123 45 67 / 68).
candidate = self._trim_after_first_match(_SECOND_NUMBER_START_PATTERN,
candidate)
match = self._extract_match(candidate, start)
if match is not None:
return match
# Move along
index = start + len(candidate)
self._max_tries -= 1
match = _PATTERN.search(self.text, index)
return None | [
"def",
"_find",
"(",
"self",
",",
"index",
")",
":",
"match",
"=",
"_PATTERN",
".",
"search",
"(",
"self",
".",
"text",
",",
"index",
")",
"while",
"self",
".",
"_max_tries",
">",
"0",
"and",
"match",
"is",
"not",
"None",
":",
"start",
"=",
"match"... | Attempts to find the next subsequence in the searched sequence on or after index
that represents a phone number. Returns the next match, None if none was found.
Arguments:
index -- The search index to start searching at.
Returns the phone number match found, None if none can be found. | [
"Attempts",
"to",
"find",
"the",
"next",
"subsequence",
"in",
"the",
"searched",
"sequence",
"on",
"or",
"after",
"index",
"that",
"represents",
"a",
"phone",
"number",
".",
"Returns",
"the",
"next",
"match",
"None",
"if",
"none",
"was",
"found",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L497-L524 |
234,708 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher._trim_after_first_match | def _trim_after_first_match(self, pattern, candidate):
"""Trims away any characters after the first match of pattern in
candidate, returning the trimmed version."""
trailing_chars_match = pattern.search(candidate)
if trailing_chars_match:
candidate = candidate[:trailing_chars_match.start()]
return candidate | python | def _trim_after_first_match(self, pattern, candidate):
trailing_chars_match = pattern.search(candidate)
if trailing_chars_match:
candidate = candidate[:trailing_chars_match.start()]
return candidate | [
"def",
"_trim_after_first_match",
"(",
"self",
",",
"pattern",
",",
"candidate",
")",
":",
"trailing_chars_match",
"=",
"pattern",
".",
"search",
"(",
"candidate",
")",
"if",
"trailing_chars_match",
":",
"candidate",
"=",
"candidate",
"[",
":",
"trailing_chars_mat... | Trims away any characters after the first match of pattern in
candidate, returning the trimmed version. | [
"Trims",
"away",
"any",
"characters",
"after",
"the",
"first",
"match",
"of",
"pattern",
"in",
"candidate",
"returning",
"the",
"trimmed",
"version",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L526-L532 |
234,709 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher._is_latin_letter | def _is_latin_letter(cls, letter):
"""Helper method to determine if a character is a Latin-script letter
or not. For our purposes, combining marks should also return True
since we assume they have been added to a preceding Latin character."""
# Combining marks are a subset of non-spacing-mark
if (not is_letter(letter) and
Category.get(letter) != Category.NON_SPACING_MARK):
return False
block = Block.get(letter)
return (block == Block.BASIC_LATIN or
block == Block.LATIN_1_SUPPLEMENT or
block == Block.LATIN_EXTENDED_A or
block == Block.LATIN_EXTENDED_ADDITIONAL or
block == Block.LATIN_EXTENDED_B or
block == Block.COMBINING_DIACRITICAL_MARKS) | python | def _is_latin_letter(cls, letter):
# Combining marks are a subset of non-spacing-mark
if (not is_letter(letter) and
Category.get(letter) != Category.NON_SPACING_MARK):
return False
block = Block.get(letter)
return (block == Block.BASIC_LATIN or
block == Block.LATIN_1_SUPPLEMENT or
block == Block.LATIN_EXTENDED_A or
block == Block.LATIN_EXTENDED_ADDITIONAL or
block == Block.LATIN_EXTENDED_B or
block == Block.COMBINING_DIACRITICAL_MARKS) | [
"def",
"_is_latin_letter",
"(",
"cls",
",",
"letter",
")",
":",
"# Combining marks are a subset of non-spacing-mark",
"if",
"(",
"not",
"is_letter",
"(",
"letter",
")",
"and",
"Category",
".",
"get",
"(",
"letter",
")",
"!=",
"Category",
".",
"NON_SPACING_MARK",
... | Helper method to determine if a character is a Latin-script letter
or not. For our purposes, combining marks should also return True
since we assume they have been added to a preceding Latin character. | [
"Helper",
"method",
"to",
"determine",
"if",
"a",
"character",
"is",
"a",
"Latin",
"-",
"script",
"letter",
"or",
"not",
".",
"For",
"our",
"purposes",
"combining",
"marks",
"should",
"also",
"return",
"True",
"since",
"we",
"assume",
"they",
"have",
"been... | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L535-L549 |
234,710 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher._extract_match | def _extract_match(self, candidate, offset):
"""Attempts to extract a match from a candidate string.
Arguments:
candidate -- The candidate text that might contain a phone number.
offset -- The offset of candidate within self.text
Returns the match found, None if none can be found
"""
# Skip a match that is more likely a publication page reference or a
# date.
if (_SLASH_SEPARATED_DATES.search(candidate)):
return None
# Skip potential time-stamps.
if _TIME_STAMPS.search(candidate):
following_text = self.text[offset + len(candidate):]
if _TIME_STAMPS_SUFFIX.match(following_text):
return None
# Try to come up with a valid match given the entire candidate.
match = self._parse_and_verify(candidate, offset)
if match is not None:
return match
# If that failed, try to find an "inner match" -- there might be a
# phone number within this candidate.
return self._extract_inner_match(candidate, offset) | python | def _extract_match(self, candidate, offset):
# Skip a match that is more likely a publication page reference or a
# date.
if (_SLASH_SEPARATED_DATES.search(candidate)):
return None
# Skip potential time-stamps.
if _TIME_STAMPS.search(candidate):
following_text = self.text[offset + len(candidate):]
if _TIME_STAMPS_SUFFIX.match(following_text):
return None
# Try to come up with a valid match given the entire candidate.
match = self._parse_and_verify(candidate, offset)
if match is not None:
return match
# If that failed, try to find an "inner match" -- there might be a
# phone number within this candidate.
return self._extract_inner_match(candidate, offset) | [
"def",
"_extract_match",
"(",
"self",
",",
"candidate",
",",
"offset",
")",
":",
"# Skip a match that is more likely a publication page reference or a",
"# date.",
"if",
"(",
"_SLASH_SEPARATED_DATES",
".",
"search",
"(",
"candidate",
")",
")",
":",
"return",
"None",
"... | Attempts to extract a match from a candidate string.
Arguments:
candidate -- The candidate text that might contain a phone number.
offset -- The offset of candidate within self.text
Returns the match found, None if none can be found | [
"Attempts",
"to",
"extract",
"a",
"match",
"from",
"a",
"candidate",
"string",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L556-L582 |
234,711 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher._extract_inner_match | def _extract_inner_match(self, candidate, offset):
"""Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.
Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate within text
Returns the match found, None if none can be found
"""
for possible_inner_match in _INNER_MATCHES:
group_match = possible_inner_match.search(candidate)
is_first_match = True
while group_match and self._max_tries > 0:
if is_first_match:
# We should handle any group before this one too.
group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN,
candidate[:group_match.start()])
match = self._parse_and_verify(group, offset)
if match is not None:
return match
self._max_tries -= 1
is_first_match = False
group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN,
group_match.group(1))
match = self._parse_and_verify(group, offset + group_match.start(1))
if match is not None:
return match
self._max_tries -= 1
group_match = possible_inner_match.search(candidate, group_match.start() + 1)
return None | python | def _extract_inner_match(self, candidate, offset):
for possible_inner_match in _INNER_MATCHES:
group_match = possible_inner_match.search(candidate)
is_first_match = True
while group_match and self._max_tries > 0:
if is_first_match:
# We should handle any group before this one too.
group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN,
candidate[:group_match.start()])
match = self._parse_and_verify(group, offset)
if match is not None:
return match
self._max_tries -= 1
is_first_match = False
group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN,
group_match.group(1))
match = self._parse_and_verify(group, offset + group_match.start(1))
if match is not None:
return match
self._max_tries -= 1
group_match = possible_inner_match.search(candidate, group_match.start() + 1)
return None | [
"def",
"_extract_inner_match",
"(",
"self",
",",
"candidate",
",",
"offset",
")",
":",
"for",
"possible_inner_match",
"in",
"_INNER_MATCHES",
":",
"group_match",
"=",
"possible_inner_match",
".",
"search",
"(",
"candidate",
")",
"is_first_match",
"=",
"True",
"whi... | Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.
Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate within text
Returns the match found, None if none can be found | [
"Attempts",
"to",
"extract",
"a",
"match",
"from",
"candidate",
"if",
"the",
"whole",
"candidate",
"does",
"not",
"qualify",
"as",
"a",
"match",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L584-L613 |
234,712 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher._parse_and_verify | def _parse_and_verify(self, candidate, offset):
"""Parses a phone number from the candidate using phonenumberutil.parse and
verifies it matches the requested leniency. If parsing and verification succeed, a
corresponding PhoneNumberMatch is returned, otherwise this method returns None.
Arguments:
candidate -- The candidate match.
offset -- The offset of candidate within self.text.
Returns the parsed and validated phone number match, or None.
"""
try:
# Check the candidate doesn't contain any formatting which would
# indicate that it really isn't a phone number.
if (not fullmatch(_MATCHING_BRACKETS, candidate) or _PUB_PAGES.search(candidate)):
return None
# If leniency is set to VALID or stricter, we also want to skip
# numbers that are surrounded by Latin alphabetic characters, to
# skip cases like abc8005001234 or 8005001234def.
if self.leniency >= Leniency.VALID:
# If the candidate is not at the start of the text, and does
# not start with phone-number punctuation, check the previous
# character
if (offset > 0 and
not _LEAD_PATTERN.match(candidate)):
previous_char = self.text[offset - 1]
# We return None if it is a latin letter or an invalid
# punctuation symbol
if (self._is_invalid_punctuation_symbol(previous_char) or
self._is_latin_letter(previous_char)):
return None
last_char_index = offset + len(candidate)
if last_char_index < len(self.text):
next_char = self.text[last_char_index]
if (self._is_invalid_punctuation_symbol(next_char) or
self._is_latin_letter(next_char)):
return None
numobj = parse(candidate, self.preferred_region, keep_raw_input=True)
if _verify(self.leniency, numobj, candidate, self):
# We used parse(keep_raw_input=True) to create this number,
# but for now we don't return the extra values parsed.
# TODO: stop clearing all values here and switch all users
# over to using raw_input rather than the raw_string of
# PhoneNumberMatch.
numobj.country_code_source = CountryCodeSource.UNSPECIFIED
numobj.raw_input = None
numobj.preferred_domestic_carrier_code = None
return PhoneNumberMatch(offset, candidate, numobj)
except NumberParseException:
# ignore and continue
pass
return None | python | def _parse_and_verify(self, candidate, offset):
try:
# Check the candidate doesn't contain any formatting which would
# indicate that it really isn't a phone number.
if (not fullmatch(_MATCHING_BRACKETS, candidate) or _PUB_PAGES.search(candidate)):
return None
# If leniency is set to VALID or stricter, we also want to skip
# numbers that are surrounded by Latin alphabetic characters, to
# skip cases like abc8005001234 or 8005001234def.
if self.leniency >= Leniency.VALID:
# If the candidate is not at the start of the text, and does
# not start with phone-number punctuation, check the previous
# character
if (offset > 0 and
not _LEAD_PATTERN.match(candidate)):
previous_char = self.text[offset - 1]
# We return None if it is a latin letter or an invalid
# punctuation symbol
if (self._is_invalid_punctuation_symbol(previous_char) or
self._is_latin_letter(previous_char)):
return None
last_char_index = offset + len(candidate)
if last_char_index < len(self.text):
next_char = self.text[last_char_index]
if (self._is_invalid_punctuation_symbol(next_char) or
self._is_latin_letter(next_char)):
return None
numobj = parse(candidate, self.preferred_region, keep_raw_input=True)
if _verify(self.leniency, numobj, candidate, self):
# We used parse(keep_raw_input=True) to create this number,
# but for now we don't return the extra values parsed.
# TODO: stop clearing all values here and switch all users
# over to using raw_input rather than the raw_string of
# PhoneNumberMatch.
numobj.country_code_source = CountryCodeSource.UNSPECIFIED
numobj.raw_input = None
numobj.preferred_domestic_carrier_code = None
return PhoneNumberMatch(offset, candidate, numobj)
except NumberParseException:
# ignore and continue
pass
return None | [
"def",
"_parse_and_verify",
"(",
"self",
",",
"candidate",
",",
"offset",
")",
":",
"try",
":",
"# Check the candidate doesn't contain any formatting which would",
"# indicate that it really isn't a phone number.",
"if",
"(",
"not",
"fullmatch",
"(",
"_MATCHING_BRACKETS",
","... | Parses a phone number from the candidate using phonenumberutil.parse and
verifies it matches the requested leniency. If parsing and verification succeed, a
corresponding PhoneNumberMatch is returned, otherwise this method returns None.
Arguments:
candidate -- The candidate match.
offset -- The offset of candidate within self.text.
Returns the parsed and validated phone number match, or None. | [
"Parses",
"a",
"phone",
"number",
"from",
"the",
"candidate",
"using",
"phonenumberutil",
".",
"parse",
"and",
"verifies",
"it",
"matches",
"the",
"requested",
"leniency",
".",
"If",
"parsing",
"and",
"verification",
"succeed",
"a",
"corresponding",
"PhoneNumberMa... | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L615-L667 |
234,713 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher.has_next | def has_next(self):
"""Indicates whether there is another match available"""
if self._state == PhoneNumberMatcher._NOT_READY:
self._last_match = self._find(self._search_index)
if self._last_match is None:
self._state = PhoneNumberMatcher._DONE
else:
self._search_index = self._last_match.end
self._state = PhoneNumberMatcher._READY
return (self._state == PhoneNumberMatcher._READY) | python | def has_next(self):
if self._state == PhoneNumberMatcher._NOT_READY:
self._last_match = self._find(self._search_index)
if self._last_match is None:
self._state = PhoneNumberMatcher._DONE
else:
self._search_index = self._last_match.end
self._state = PhoneNumberMatcher._READY
return (self._state == PhoneNumberMatcher._READY) | [
"def",
"has_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"PhoneNumberMatcher",
".",
"_NOT_READY",
":",
"self",
".",
"_last_match",
"=",
"self",
".",
"_find",
"(",
"self",
".",
"_search_index",
")",
"if",
"self",
".",
"_last_match",
"i... | Indicates whether there is another match available | [
"Indicates",
"whether",
"there",
"is",
"another",
"match",
"available"
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L690-L699 |
234,714 | daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumbermatcher.py | PhoneNumberMatcher.next | def next(self):
"""Return the next match; raises Exception if no next match available"""
# Check the state and find the next match as a side-effect if necessary.
if not self.has_next():
raise StopIteration("No next match")
# Don't retain that memory any longer than necessary.
result = self._last_match
self._last_match = None
self._state = PhoneNumberMatcher._NOT_READY
return result | python | def next(self):
# Check the state and find the next match as a side-effect if necessary.
if not self.has_next():
raise StopIteration("No next match")
# Don't retain that memory any longer than necessary.
result = self._last_match
self._last_match = None
self._state = PhoneNumberMatcher._NOT_READY
return result | [
"def",
"next",
"(",
"self",
")",
":",
"# Check the state and find the next match as a side-effect if necessary.",
"if",
"not",
"self",
".",
"has_next",
"(",
")",
":",
"raise",
"StopIteration",
"(",
"\"No next match\"",
")",
"# Don't retain that memory any longer than necessar... | Return the next match; raises Exception if no next match available | [
"Return",
"the",
"next",
"match",
";",
"raises",
"Exception",
"if",
"no",
"next",
"match",
"available"
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L701-L710 |
234,715 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | is_possible_short_number_for_region | def is_possible_short_number_for_region(short_numobj, region_dialing_from):
"""Check whether a short number is a possible number when dialled from a
region. This provides a more lenient check than
is_valid_short_number_for_region.
Arguments:
short_numobj -- the short number to check as a PhoneNumber object.
region_dialing_from -- the region from which the number is dialed
Return whether the number is a possible short number.
"""
if not _region_dialing_from_matches_number(short_numobj, region_dialing_from):
return False
metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)
if metadata is None: # pragma no cover
return False
short_numlen = len(national_significant_number(short_numobj))
return (short_numlen in metadata.general_desc.possible_length) | python | def is_possible_short_number_for_region(short_numobj, region_dialing_from):
if not _region_dialing_from_matches_number(short_numobj, region_dialing_from):
return False
metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)
if metadata is None: # pragma no cover
return False
short_numlen = len(national_significant_number(short_numobj))
return (short_numlen in metadata.general_desc.possible_length) | [
"def",
"is_possible_short_number_for_region",
"(",
"short_numobj",
",",
"region_dialing_from",
")",
":",
"if",
"not",
"_region_dialing_from_matches_number",
"(",
"short_numobj",
",",
"region_dialing_from",
")",
":",
"return",
"False",
"metadata",
"=",
"PhoneMetadata",
"."... | Check whether a short number is a possible number when dialled from a
region. This provides a more lenient check than
is_valid_short_number_for_region.
Arguments:
short_numobj -- the short number to check as a PhoneNumber object.
region_dialing_from -- the region from which the number is dialed
Return whether the number is a possible short number. | [
"Check",
"whether",
"a",
"short",
"number",
"is",
"a",
"possible",
"number",
"when",
"dialled",
"from",
"a",
"region",
".",
"This",
"provides",
"a",
"more",
"lenient",
"check",
"than",
"is_valid_short_number_for_region",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L66-L83 |
234,716 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | is_possible_short_number | def is_possible_short_number(numobj):
"""Check whether a short number is a possible number.
If a country calling code is shared by multiple regions, this returns True
if it's possible in any of them. This provides a more lenient check than
is_valid_short_number.
Arguments:
numobj -- the short number to check
Return whether the number is a possible short number.
"""
region_codes = region_codes_for_country_code(numobj.country_code)
short_number_len = len(national_significant_number(numobj))
for region in region_codes:
metadata = PhoneMetadata.short_metadata_for_region(region)
if metadata is None:
continue
if short_number_len in metadata.general_desc.possible_length:
return True
return False | python | def is_possible_short_number(numobj):
region_codes = region_codes_for_country_code(numobj.country_code)
short_number_len = len(national_significant_number(numobj))
for region in region_codes:
metadata = PhoneMetadata.short_metadata_for_region(region)
if metadata is None:
continue
if short_number_len in metadata.general_desc.possible_length:
return True
return False | [
"def",
"is_possible_short_number",
"(",
"numobj",
")",
":",
"region_codes",
"=",
"region_codes_for_country_code",
"(",
"numobj",
".",
"country_code",
")",
"short_number_len",
"=",
"len",
"(",
"national_significant_number",
"(",
"numobj",
")",
")",
"for",
"region",
"... | Check whether a short number is a possible number.
If a country calling code is shared by multiple regions, this returns True
if it's possible in any of them. This provides a more lenient check than
is_valid_short_number.
Arguments:
numobj -- the short number to check
Return whether the number is a possible short number. | [
"Check",
"whether",
"a",
"short",
"number",
"is",
"a",
"possible",
"number",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L86-L107 |
234,717 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | is_valid_short_number_for_region | def is_valid_short_number_for_region(short_numobj, region_dialing_from):
"""Tests whether a short number matches a valid pattern in a region.
Note that this doesn't verify the number is actually in use, which is
impossible to tell by just looking at the number itself.
Arguments:
short_numobj -- the short number to check as a PhoneNumber object.
region_dialing_from -- the region from which the number is dialed
Return whether the short number matches a valid pattern
"""
if not _region_dialing_from_matches_number(short_numobj, region_dialing_from):
return False
metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)
if metadata is None: # pragma no cover
return False
short_number = national_significant_number(short_numobj)
general_desc = metadata.general_desc
if not _matches_possible_number_and_national_number(short_number, general_desc):
return False
short_number_desc = metadata.short_code
if short_number_desc.national_number_pattern is None: # pragma no cover
return False
return _matches_possible_number_and_national_number(short_number, short_number_desc) | python | def is_valid_short_number_for_region(short_numobj, region_dialing_from):
if not _region_dialing_from_matches_number(short_numobj, region_dialing_from):
return False
metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)
if metadata is None: # pragma no cover
return False
short_number = national_significant_number(short_numobj)
general_desc = metadata.general_desc
if not _matches_possible_number_and_national_number(short_number, general_desc):
return False
short_number_desc = metadata.short_code
if short_number_desc.national_number_pattern is None: # pragma no cover
return False
return _matches_possible_number_and_national_number(short_number, short_number_desc) | [
"def",
"is_valid_short_number_for_region",
"(",
"short_numobj",
",",
"region_dialing_from",
")",
":",
"if",
"not",
"_region_dialing_from_matches_number",
"(",
"short_numobj",
",",
"region_dialing_from",
")",
":",
"return",
"False",
"metadata",
"=",
"PhoneMetadata",
".",
... | Tests whether a short number matches a valid pattern in a region.
Note that this doesn't verify the number is actually in use, which is
impossible to tell by just looking at the number itself.
Arguments:
short_numobj -- the short number to check as a PhoneNumber object.
region_dialing_from -- the region from which the number is dialed
Return whether the short number matches a valid pattern | [
"Tests",
"whether",
"a",
"short",
"number",
"matches",
"a",
"valid",
"pattern",
"in",
"a",
"region",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L110-L134 |
234,718 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | is_valid_short_number | def is_valid_short_number(numobj):
"""Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossible to tell by just looking at the number
itself. See is_valid_short_number_for_region for details.
Arguments:
numobj - the short number for which we want to test the validity
Return whether the short number matches a valid pattern
"""
region_codes = region_codes_for_country_code(numobj.country_code)
region_code = _region_code_for_short_number_from_region_list(numobj, region_codes)
if len(region_codes) > 1 and region_code is not None:
# If a matching region had been found for the phone number from among two or more regions,
# then we have already implicitly verified its validity for that region.
return True
return is_valid_short_number_for_region(numobj, region_code) | python | def is_valid_short_number(numobj):
region_codes = region_codes_for_country_code(numobj.country_code)
region_code = _region_code_for_short_number_from_region_list(numobj, region_codes)
if len(region_codes) > 1 and region_code is not None:
# If a matching region had been found for the phone number from among two or more regions,
# then we have already implicitly verified its validity for that region.
return True
return is_valid_short_number_for_region(numobj, region_code) | [
"def",
"is_valid_short_number",
"(",
"numobj",
")",
":",
"region_codes",
"=",
"region_codes_for_country_code",
"(",
"numobj",
".",
"country_code",
")",
"region_code",
"=",
"_region_code_for_short_number_from_region_list",
"(",
"numobj",
",",
"region_codes",
")",
"if",
"... | Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossible to tell by just looking at the number
itself. See is_valid_short_number_for_region for details.
Arguments:
numobj - the short number for which we want to test the validity
Return whether the short number matches a valid pattern | [
"Tests",
"whether",
"a",
"short",
"number",
"matches",
"a",
"valid",
"pattern",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L137-L156 |
234,719 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | _region_code_for_short_number_from_region_list | def _region_code_for_short_number_from_region_list(numobj, region_codes):
"""Helper method to get the region code for a given phone number, from a list of possible region
codes. If the list contains more than one region, the first region for which the number is
valid is returned.
"""
if len(region_codes) == 0:
return None
elif len(region_codes) == 1:
return region_codes[0]
national_number = national_significant_number(numobj)
for region_code in region_codes:
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if metadata is not None and _matches_possible_number_and_national_number(national_number, metadata.short_code):
# The number is valid for this region.
return region_code
return None | python | def _region_code_for_short_number_from_region_list(numobj, region_codes):
if len(region_codes) == 0:
return None
elif len(region_codes) == 1:
return region_codes[0]
national_number = national_significant_number(numobj)
for region_code in region_codes:
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if metadata is not None and _matches_possible_number_and_national_number(national_number, metadata.short_code):
# The number is valid for this region.
return region_code
return None | [
"def",
"_region_code_for_short_number_from_region_list",
"(",
"numobj",
",",
"region_codes",
")",
":",
"if",
"len",
"(",
"region_codes",
")",
"==",
"0",
":",
"return",
"None",
"elif",
"len",
"(",
"region_codes",
")",
"==",
"1",
":",
"return",
"region_codes",
"... | Helper method to get the region code for a given phone number, from a list of possible region
codes. If the list contains more than one region, the first region for which the number is
valid is returned. | [
"Helper",
"method",
"to",
"get",
"the",
"region",
"code",
"for",
"a",
"given",
"phone",
"number",
"from",
"a",
"list",
"of",
"possible",
"region",
"codes",
".",
"If",
"the",
"list",
"contains",
"more",
"than",
"one",
"region",
"the",
"first",
"region",
"... | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L259-L274 |
234,720 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | _example_short_number | def _example_short_number(region_code):
"""Gets a valid short number for the specified region.
Arguments:
region_code -- the region for which an example short number is needed.
Returns a valid short number for the specified region. Returns an empty
string when the metadata does not contain such information.
"""
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if metadata is None:
return U_EMPTY_STRING
desc = metadata.short_code
if desc.example_number is not None:
return desc.example_number
return U_EMPTY_STRING | python | def _example_short_number(region_code):
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if metadata is None:
return U_EMPTY_STRING
desc = metadata.short_code
if desc.example_number is not None:
return desc.example_number
return U_EMPTY_STRING | [
"def",
"_example_short_number",
"(",
"region_code",
")",
":",
"metadata",
"=",
"PhoneMetadata",
".",
"short_metadata_for_region",
"(",
"region_code",
")",
"if",
"metadata",
"is",
"None",
":",
"return",
"U_EMPTY_STRING",
"desc",
"=",
"metadata",
".",
"short_code",
... | Gets a valid short number for the specified region.
Arguments:
region_code -- the region for which an example short number is needed.
Returns a valid short number for the specified region. Returns an empty
string when the metadata does not contain such information. | [
"Gets",
"a",
"valid",
"short",
"number",
"for",
"the",
"specified",
"region",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L277-L292 |
234,721 | daviddrysdale/python-phonenumbers | python/phonenumbers/shortnumberinfo.py | _example_short_number_for_cost | def _example_short_number_for_cost(region_code, cost):
"""Gets a valid short number for the specified cost category.
Arguments:
region_code -- the region for which an example short number is needed.
cost -- the cost category of number that is needed.
Returns a valid short number for the specified region and cost
category. Returns an empty string when the metadata does not contain such
information, or the cost is UNKNOWN_COST.
"""
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if metadata is None:
return U_EMPTY_STRING
desc = None
if cost == ShortNumberCost.TOLL_FREE:
desc = metadata.toll_free
elif cost == ShortNumberCost.STANDARD_RATE:
desc = metadata.standard_rate
elif cost == ShortNumberCost.PREMIUM_RATE:
desc = metadata.premium_rate
else:
# ShortNumberCost.UNKNOWN_COST numbers are computed by the process of
# elimination from the other cost categoried.
pass
if desc is not None and desc.example_number is not None:
return desc.example_number
return U_EMPTY_STRING | python | def _example_short_number_for_cost(region_code, cost):
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if metadata is None:
return U_EMPTY_STRING
desc = None
if cost == ShortNumberCost.TOLL_FREE:
desc = metadata.toll_free
elif cost == ShortNumberCost.STANDARD_RATE:
desc = metadata.standard_rate
elif cost == ShortNumberCost.PREMIUM_RATE:
desc = metadata.premium_rate
else:
# ShortNumberCost.UNKNOWN_COST numbers are computed by the process of
# elimination from the other cost categoried.
pass
if desc is not None and desc.example_number is not None:
return desc.example_number
return U_EMPTY_STRING | [
"def",
"_example_short_number_for_cost",
"(",
"region_code",
",",
"cost",
")",
":",
"metadata",
"=",
"PhoneMetadata",
".",
"short_metadata_for_region",
"(",
"region_code",
")",
"if",
"metadata",
"is",
"None",
":",
"return",
"U_EMPTY_STRING",
"desc",
"=",
"None",
"... | Gets a valid short number for the specified cost category.
Arguments:
region_code -- the region for which an example short number is needed.
cost -- the cost category of number that is needed.
Returns a valid short number for the specified region and cost
category. Returns an empty string when the metadata does not contain such
information, or the cost is UNKNOWN_COST. | [
"Gets",
"a",
"valid",
"short",
"number",
"for",
"the",
"specified",
"cost",
"category",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L295-L322 |
234,722 | Shopify/shopify_python_api | shopify/base.py | ShopifyResourceMeta.connection | def connection(cls):
"""HTTP connection for the current thread"""
local = cls._threadlocal
if not getattr(local, 'connection', None):
# Make sure these variables are no longer affected by other threads.
local.user = cls.user
local.password = cls.password
local.site = cls.site
local.timeout = cls.timeout
local.headers = cls.headers
local.format = cls.format
local.version = cls.version
local.url = cls.url
if cls.site is None:
raise ValueError("No shopify session is active")
local.connection = ShopifyConnection(
cls.site, cls.user, cls.password, cls.timeout, cls.format)
return local.connection | python | def connection(cls):
local = cls._threadlocal
if not getattr(local, 'connection', None):
# Make sure these variables are no longer affected by other threads.
local.user = cls.user
local.password = cls.password
local.site = cls.site
local.timeout = cls.timeout
local.headers = cls.headers
local.format = cls.format
local.version = cls.version
local.url = cls.url
if cls.site is None:
raise ValueError("No shopify session is active")
local.connection = ShopifyConnection(
cls.site, cls.user, cls.password, cls.timeout, cls.format)
return local.connection | [
"def",
"connection",
"(",
"cls",
")",
":",
"local",
"=",
"cls",
".",
"_threadlocal",
"if",
"not",
"getattr",
"(",
"local",
",",
"'connection'",
",",
"None",
")",
":",
"# Make sure these variables are no longer affected by other threads.",
"local",
".",
"user",
"="... | HTTP connection for the current thread | [
"HTTP",
"connection",
"for",
"the",
"current",
"thread"
] | 88d3ba332fb2cd331f87517a16f2c2d4296cee90 | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/base.py#L33-L50 |
234,723 | Shopify/shopify_python_api | shopify/base.py | ShopifyResourceMeta.get_prefix_source | def get_prefix_source(cls):
"""Return the prefix source, by default derived from site."""
try:
return cls.override_prefix()
except AttributeError:
if hasattr(cls, '_prefix_source'):
return cls.site + cls._prefix_source
else:
return cls.site | python | def get_prefix_source(cls):
try:
return cls.override_prefix()
except AttributeError:
if hasattr(cls, '_prefix_source'):
return cls.site + cls._prefix_source
else:
return cls.site | [
"def",
"get_prefix_source",
"(",
"cls",
")",
":",
"try",
":",
"return",
"cls",
".",
"override_prefix",
"(",
")",
"except",
"AttributeError",
":",
"if",
"hasattr",
"(",
"cls",
",",
"'_prefix_source'",
")",
":",
"return",
"cls",
".",
"site",
"+",
"cls",
".... | Return the prefix source, by default derived from site. | [
"Return",
"the",
"prefix",
"source",
"by",
"default",
"derived",
"from",
"site",
"."
] | 88d3ba332fb2cd331f87517a16f2c2d4296cee90 | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/base.py#L119-L127 |
234,724 | Shopify/shopify_python_api | shopify/session.py | Session.__encoded_params_for_signature | def __encoded_params_for_signature(cls, params):
"""
Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&'
"""
def encoded_pairs(params):
for k, v in six.iteritems(params):
if k == 'hmac':
continue
if k.endswith('[]'):
#foo[]=1&foo[]=2 has to be transformed as foo=["1", "2"] note the whitespace after comma
k = k.rstrip('[]')
v = json.dumps(list(map(str, v)))
# escape delimiters to avoid tampering
k = str(k).replace("%", "%25").replace("=", "%3D")
v = str(v).replace("%", "%25")
yield '{0}={1}'.format(k, v).replace("&", "%26")
return "&".join(sorted(encoded_pairs(params))) | python | def __encoded_params_for_signature(cls, params):
def encoded_pairs(params):
for k, v in six.iteritems(params):
if k == 'hmac':
continue
if k.endswith('[]'):
#foo[]=1&foo[]=2 has to be transformed as foo=["1", "2"] note the whitespace after comma
k = k.rstrip('[]')
v = json.dumps(list(map(str, v)))
# escape delimiters to avoid tampering
k = str(k).replace("%", "%25").replace("=", "%3D")
v = str(v).replace("%", "%25")
yield '{0}={1}'.format(k, v).replace("&", "%26")
return "&".join(sorted(encoded_pairs(params))) | [
"def",
"__encoded_params_for_signature",
"(",
"cls",
",",
"params",
")",
":",
"def",
"encoded_pairs",
"(",
"params",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"params",
")",
":",
"if",
"k",
"==",
"'hmac'",
":",
"continue",
"if... | Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&' | [
"Sort",
"and",
"combine",
"query",
"parameters",
"into",
"a",
"single",
"string",
"excluding",
"those",
"that",
"should",
"be",
"removed",
"and",
"joining",
"with",
"&"
] | 88d3ba332fb2cd331f87517a16f2c2d4296cee90 | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/session.py#L141-L160 |
234,725 | Shopify/shopify_python_api | shopify/resources/refund.py | Refund.calculate | def calculate(cls, order_id, shipping=None, refund_line_items=None):
"""
Calculates refund transactions based on line items and shipping.
When you want to create a refund, you should first use the calculate
endpoint to generate accurate refund transactions.
Args:
order_id: Order ID for which the Refund has to created.
shipping: Specify how much shipping to refund.
refund_line_items: A list of line item IDs and quantities to refund.
Returns:
Unsaved refund record
"""
data = {}
if shipping:
data['shipping'] = shipping
data['refund_line_items'] = refund_line_items or []
body = {'refund': data}
resource = cls.post(
"calculate", order_id=order_id, body=json.dumps(body).encode()
)
return cls(
cls.format.decode(resource.body),
prefix_options={'order_id': order_id}
) | python | def calculate(cls, order_id, shipping=None, refund_line_items=None):
data = {}
if shipping:
data['shipping'] = shipping
data['refund_line_items'] = refund_line_items or []
body = {'refund': data}
resource = cls.post(
"calculate", order_id=order_id, body=json.dumps(body).encode()
)
return cls(
cls.format.decode(resource.body),
prefix_options={'order_id': order_id}
) | [
"def",
"calculate",
"(",
"cls",
",",
"order_id",
",",
"shipping",
"=",
"None",
",",
"refund_line_items",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"shipping",
":",
"data",
"[",
"'shipping'",
"]",
"=",
"shipping",
"data",
"[",
"'refund_line_item... | Calculates refund transactions based on line items and shipping.
When you want to create a refund, you should first use the calculate
endpoint to generate accurate refund transactions.
Args:
order_id: Order ID for which the Refund has to created.
shipping: Specify how much shipping to refund.
refund_line_items: A list of line item IDs and quantities to refund.
Returns:
Unsaved refund record | [
"Calculates",
"refund",
"transactions",
"based",
"on",
"line",
"items",
"and",
"shipping",
".",
"When",
"you",
"want",
"to",
"create",
"a",
"refund",
"you",
"should",
"first",
"use",
"the",
"calculate",
"endpoint",
"to",
"generate",
"accurate",
"refund",
"tran... | 88d3ba332fb2cd331f87517a16f2c2d4296cee90 | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/resources/refund.py#L10-L34 |
234,726 | Shopify/shopify_python_api | scripts/shopify_api.py | TasksMeta.help | def help(cls, task=None):
"""Describe available tasks or one specific task"""
if task is None:
usage_list = []
for task in iter(cls._tasks):
task_func = getattr(cls, task)
usage_string = " %s %s" % (cls._prog, task_func.usage)
desc = task_func.__doc__.splitlines()[0]
usage_list.append((usage_string, desc))
max_len = functools.reduce(lambda m, item: max(m, len(item[0])), usage_list, 0)
print("Tasks:")
cols = int(os.environ.get("COLUMNS", 80))
for line, desc in usage_list:
task_func = getattr(cls, task)
if desc:
line = "%s%s # %s" % (line, " " * (max_len - len(line)), desc)
if len(line) > cols:
line = line[:cols - 3] + "..."
print(line)
else:
task_func = getattr(cls, task)
print("Usage:")
print(" %s %s" % (cls._prog, task_func.usage))
print("")
print(task_func.__doc__) | python | def help(cls, task=None):
if task is None:
usage_list = []
for task in iter(cls._tasks):
task_func = getattr(cls, task)
usage_string = " %s %s" % (cls._prog, task_func.usage)
desc = task_func.__doc__.splitlines()[0]
usage_list.append((usage_string, desc))
max_len = functools.reduce(lambda m, item: max(m, len(item[0])), usage_list, 0)
print("Tasks:")
cols = int(os.environ.get("COLUMNS", 80))
for line, desc in usage_list:
task_func = getattr(cls, task)
if desc:
line = "%s%s # %s" % (line, " " * (max_len - len(line)), desc)
if len(line) > cols:
line = line[:cols - 3] + "..."
print(line)
else:
task_func = getattr(cls, task)
print("Usage:")
print(" %s %s" % (cls._prog, task_func.usage))
print("")
print(task_func.__doc__) | [
"def",
"help",
"(",
"cls",
",",
"task",
"=",
"None",
")",
":",
"if",
"task",
"is",
"None",
":",
"usage_list",
"=",
"[",
"]",
"for",
"task",
"in",
"iter",
"(",
"cls",
".",
"_tasks",
")",
":",
"task_func",
"=",
"getattr",
"(",
"cls",
",",
"task",
... | Describe available tasks or one specific task | [
"Describe",
"available",
"tasks",
"or",
"one",
"specific",
"task"
] | 88d3ba332fb2cd331f87517a16f2c2d4296cee90 | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/scripts/shopify_api.py#L62-L86 |
234,727 | Shopify/shopify_python_api | shopify/resources/gift_card.py | GiftCard.add_adjustment | def add_adjustment(self, adjustment):
"""
Create a new Gift Card Adjustment
"""
resource = self.post("adjustments", adjustment.encode())
return GiftCardAdjustment(GiftCard.format.decode(resource.body)) | python | def add_adjustment(self, adjustment):
resource = self.post("adjustments", adjustment.encode())
return GiftCardAdjustment(GiftCard.format.decode(resource.body)) | [
"def",
"add_adjustment",
"(",
"self",
",",
"adjustment",
")",
":",
"resource",
"=",
"self",
".",
"post",
"(",
"\"adjustments\"",
",",
"adjustment",
".",
"encode",
"(",
")",
")",
"return",
"GiftCardAdjustment",
"(",
"GiftCard",
".",
"format",
".",
"decode",
... | Create a new Gift Card Adjustment | [
"Create",
"a",
"new",
"Gift",
"Card",
"Adjustment"
] | 88d3ba332fb2cd331f87517a16f2c2d4296cee90 | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/resources/gift_card.py#L26-L31 |
234,728 | aiven/pghoard | pghoard/rohmu/object_storage/local.py | atomic_create_file | def atomic_create_file(file_path):
"""Open a temporary file for writing, rename to final name when done"""
fd, tmp_file_path = tempfile.mkstemp(
prefix=os.path.basename(file_path), dir=os.path.dirname(file_path), suffix=".metadata_tmp"
)
try:
with os.fdopen(fd, "w") as out_file:
yield out_file
os.rename(tmp_file_path, file_path)
except Exception: # pytest: disable=broad-except
with contextlib.suppress(Exception):
os.unlink(tmp_file_path)
raise | python | def atomic_create_file(file_path):
fd, tmp_file_path = tempfile.mkstemp(
prefix=os.path.basename(file_path), dir=os.path.dirname(file_path), suffix=".metadata_tmp"
)
try:
with os.fdopen(fd, "w") as out_file:
yield out_file
os.rename(tmp_file_path, file_path)
except Exception: # pytest: disable=broad-except
with contextlib.suppress(Exception):
os.unlink(tmp_file_path)
raise | [
"def",
"atomic_create_file",
"(",
"file_path",
")",
":",
"fd",
",",
"tmp_file_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_path",
")",
",",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"("... | Open a temporary file for writing, rename to final name when done | [
"Open",
"a",
"temporary",
"file",
"for",
"writing",
"rename",
"to",
"final",
"name",
"when",
"done"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/local.py#L217-L230 |
234,729 | aiven/pghoard | pghoard/rohmu/object_storage/azure.py | AzureTransfer._stream_blob | def _stream_blob(self, key, fileobj, progress_callback):
"""Streams contents of given key to given fileobj. Data is read sequentially in chunks
without any seeks. This requires duplicating some functionality of the Azure SDK, which only
allows reading entire blob into memory at once or returning data from random offsets"""
file_size = None
start_range = 0
chunk_size = self.conn.MAX_CHUNK_GET_SIZE
end_range = chunk_size - 1
while True:
try:
# pylint: disable=protected-access
blob = self.conn._get_blob(self.container_name, key, start_range=start_range, end_range=end_range)
if file_size is None:
file_size = self._parse_length_from_content_range(blob.properties.content_range)
fileobj.write(blob.content)
start_range += blob.properties.content_length
if start_range == file_size:
break
if blob.properties.content_length == 0:
raise StorageError(
"Empty response received for {}, range {}-{}".format(key, start_range, end_range)
)
end_range += blob.properties.content_length
if end_range >= file_size:
end_range = file_size - 1
if progress_callback:
progress_callback(start_range, file_size)
except azure.common.AzureHttpError as ex: # pylint: disable=no-member
if ex.status_code == 416: # Empty file
return
raise | python | def _stream_blob(self, key, fileobj, progress_callback):
file_size = None
start_range = 0
chunk_size = self.conn.MAX_CHUNK_GET_SIZE
end_range = chunk_size - 1
while True:
try:
# pylint: disable=protected-access
blob = self.conn._get_blob(self.container_name, key, start_range=start_range, end_range=end_range)
if file_size is None:
file_size = self._parse_length_from_content_range(blob.properties.content_range)
fileobj.write(blob.content)
start_range += blob.properties.content_length
if start_range == file_size:
break
if blob.properties.content_length == 0:
raise StorageError(
"Empty response received for {}, range {}-{}".format(key, start_range, end_range)
)
end_range += blob.properties.content_length
if end_range >= file_size:
end_range = file_size - 1
if progress_callback:
progress_callback(start_range, file_size)
except azure.common.AzureHttpError as ex: # pylint: disable=no-member
if ex.status_code == 416: # Empty file
return
raise | [
"def",
"_stream_blob",
"(",
"self",
",",
"key",
",",
"fileobj",
",",
"progress_callback",
")",
":",
"file_size",
"=",
"None",
"start_range",
"=",
"0",
"chunk_size",
"=",
"self",
".",
"conn",
".",
"MAX_CHUNK_GET_SIZE",
"end_range",
"=",
"chunk_size",
"-",
"1"... | Streams contents of given key to given fileobj. Data is read sequentially in chunks
without any seeks. This requires duplicating some functionality of the Azure SDK, which only
allows reading entire blob into memory at once or returning data from random offsets | [
"Streams",
"contents",
"of",
"given",
"key",
"to",
"given",
"fileobj",
".",
"Data",
"is",
"read",
"sequentially",
"in",
"chunks",
"without",
"any",
"seeks",
".",
"This",
"requires",
"duplicating",
"some",
"functionality",
"of",
"the",
"Azure",
"SDK",
"which",
... | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/azure.py#L161-L191 |
234,730 | aiven/pghoard | pghoard/rohmu/object_storage/base.py | BaseTransfer.format_key_for_backend | def format_key_for_backend(self, key, remove_slash_prefix=False, trailing_slash=False):
"""Add a possible prefix to the key before sending it to the backend"""
path = self.prefix + key
if trailing_slash:
if not path or path[-1] != "/":
path += "/"
else:
path = path.rstrip("/")
if remove_slash_prefix: # Azure defines slashes in the beginning as "dirs" for listing purposes
path = path.lstrip("/")
return path | python | def format_key_for_backend(self, key, remove_slash_prefix=False, trailing_slash=False):
path = self.prefix + key
if trailing_slash:
if not path or path[-1] != "/":
path += "/"
else:
path = path.rstrip("/")
if remove_slash_prefix: # Azure defines slashes in the beginning as "dirs" for listing purposes
path = path.lstrip("/")
return path | [
"def",
"format_key_for_backend",
"(",
"self",
",",
"key",
",",
"remove_slash_prefix",
"=",
"False",
",",
"trailing_slash",
"=",
"False",
")",
":",
"path",
"=",
"self",
".",
"prefix",
"+",
"key",
"if",
"trailing_slash",
":",
"if",
"not",
"path",
"or",
"path... | Add a possible prefix to the key before sending it to the backend | [
"Add",
"a",
"possible",
"prefix",
"to",
"the",
"key",
"before",
"sending",
"it",
"to",
"the",
"backend"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L34-L44 |
234,731 | aiven/pghoard | pghoard/rohmu/object_storage/base.py | BaseTransfer.format_key_from_backend | def format_key_from_backend(self, key):
"""Strip the configured prefix from a key retrieved from the backend
before passing it on to other pghoard code and presenting it to the
user."""
if not self.prefix:
return key
if not key.startswith(self.prefix):
raise StorageError("Key {!r} does not start with expected prefix {!r}".format(key, self.prefix))
return key[len(self.prefix):] | python | def format_key_from_backend(self, key):
if not self.prefix:
return key
if not key.startswith(self.prefix):
raise StorageError("Key {!r} does not start with expected prefix {!r}".format(key, self.prefix))
return key[len(self.prefix):] | [
"def",
"format_key_from_backend",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"prefix",
":",
"return",
"key",
"if",
"not",
"key",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"raise",
"StorageError",
"(",
"\"Key {!r} does not s... | Strip the configured prefix from a key retrieved from the backend
before passing it on to other pghoard code and presenting it to the
user. | [
"Strip",
"the",
"configured",
"prefix",
"from",
"a",
"key",
"retrieved",
"from",
"the",
"backend",
"before",
"passing",
"it",
"on",
"to",
"other",
"pghoard",
"code",
"and",
"presenting",
"it",
"to",
"the",
"user",
"."
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L46-L54 |
234,732 | aiven/pghoard | pghoard/rohmu/object_storage/base.py | BaseTransfer.delete_tree | def delete_tree(self, key):
"""Delete all keys under given root key. Basic implementation works by just listing all available
keys and deleting them individually but storage providers can implement more efficient logic."""
self.log.debug("Deleting tree: %r", key)
names = [item["name"] for item in self.list_path(key, with_metadata=False, deep=True)]
for name in names:
self.delete_key(name) | python | def delete_tree(self, key):
self.log.debug("Deleting tree: %r", key)
names = [item["name"] for item in self.list_path(key, with_metadata=False, deep=True)]
for name in names:
self.delete_key(name) | [
"def",
"delete_tree",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Deleting tree: %r\"",
",",
"key",
")",
"names",
"=",
"[",
"item",
"[",
"\"name\"",
"]",
"for",
"item",
"in",
"self",
".",
"list_path",
"(",
"key",
",",... | Delete all keys under given root key. Basic implementation works by just listing all available
keys and deleting them individually but storage providers can implement more efficient logic. | [
"Delete",
"all",
"keys",
"under",
"given",
"root",
"key",
".",
"Basic",
"implementation",
"works",
"by",
"just",
"listing",
"all",
"available",
"keys",
"and",
"deleting",
"them",
"individually",
"but",
"storage",
"providers",
"can",
"implement",
"more",
"efficie... | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L59-L65 |
234,733 | aiven/pghoard | pghoard/rohmu/object_storage/base.py | BaseTransfer.sanitize_metadata | def sanitize_metadata(self, metadata, replace_hyphen_with="-"):
"""Convert non-string metadata values to strings and drop null values"""
return {str(k).replace("-", replace_hyphen_with): str(v)
for k, v in (metadata or {}).items() if v is not None} | python | def sanitize_metadata(self, metadata, replace_hyphen_with="-"):
return {str(k).replace("-", replace_hyphen_with): str(v)
for k, v in (metadata or {}).items() if v is not None} | [
"def",
"sanitize_metadata",
"(",
"self",
",",
"metadata",
",",
"replace_hyphen_with",
"=",
"\"-\"",
")",
":",
"return",
"{",
"str",
"(",
"k",
")",
".",
"replace",
"(",
"\"-\"",
",",
"replace_hyphen_with",
")",
":",
"str",
"(",
"v",
")",
"for",
"k",
","... | Convert non-string metadata values to strings and drop null values | [
"Convert",
"non",
"-",
"string",
"metadata",
"values",
"to",
"strings",
"and",
"drop",
"null",
"values"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L112-L115 |
234,734 | aiven/pghoard | pghoard/rohmu/dates.py | parse_timestamp | def parse_timestamp(ts, *, with_tz=True, assume_local=False):
"""Parse a given timestamp and return a datetime object with or without tzinfo.
If `with_tz` is False and we can't parse a timezone from the timestamp the datetime object is returned
as-is and we assume the timezone is whatever was requested. If `with_tz` is False and we can parse a
timezone, the timestamp is converted to either local or UTC time based on `assume_local` after which tzinfo
is stripped and the timestamp is returned.
When `with_tz` is True and there's a timezone in the timestamp we return it as-is. If `with_tz` is True
but we can't parse a timezone we add either local or UTC timezone to the datetime based on `assume_local`.
"""
parse_result = dateutil.parser.parse(ts)
# pylint thinks dateutil.parser.parse always returns a tuple even though we didn't request it.
# So this check is pointless but convinces pylint that we really have a datetime object now.
dt = parse_result[0] if isinstance(parse_result, tuple) else parse_result # pylint: disable=unsubscriptable-object
if with_tz is False:
if not dt.tzinfo:
return dt
tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc
return dt.astimezone(tz).replace(tzinfo=None)
if dt.tzinfo:
return dt
tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc
return dt.replace(tzinfo=tz) | python | def parse_timestamp(ts, *, with_tz=True, assume_local=False):
parse_result = dateutil.parser.parse(ts)
# pylint thinks dateutil.parser.parse always returns a tuple even though we didn't request it.
# So this check is pointless but convinces pylint that we really have a datetime object now.
dt = parse_result[0] if isinstance(parse_result, tuple) else parse_result # pylint: disable=unsubscriptable-object
if with_tz is False:
if not dt.tzinfo:
return dt
tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc
return dt.astimezone(tz).replace(tzinfo=None)
if dt.tzinfo:
return dt
tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc
return dt.replace(tzinfo=tz) | [
"def",
"parse_timestamp",
"(",
"ts",
",",
"*",
",",
"with_tz",
"=",
"True",
",",
"assume_local",
"=",
"False",
")",
":",
"parse_result",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"ts",
")",
"# pylint thinks dateutil.parser.parse always returns a tuple eve... | Parse a given timestamp and return a datetime object with or without tzinfo.
If `with_tz` is False and we can't parse a timezone from the timestamp the datetime object is returned
as-is and we assume the timezone is whatever was requested. If `with_tz` is False and we can parse a
timezone, the timestamp is converted to either local or UTC time based on `assume_local` after which tzinfo
is stripped and the timestamp is returned.
When `with_tz` is True and there's a timezone in the timestamp we return it as-is. If `with_tz` is True
but we can't parse a timezone we add either local or UTC timezone to the datetime based on `assume_local`. | [
"Parse",
"a",
"given",
"timestamp",
"and",
"return",
"a",
"datetime",
"object",
"with",
"or",
"without",
"tzinfo",
"."
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/dates.py#L12-L40 |
234,735 | aiven/pghoard | pghoard/common.py | create_pgpass_file | def create_pgpass_file(connection_string_or_info):
"""Look up password from the given object which can be a dict or a
string and write a possible password in a pgpass file;
returns a connection_string without a password in it"""
info = pgutil.get_connection_info(connection_string_or_info)
if "password" not in info:
return pgutil.create_connection_string(info)
linekey = "{host}:{port}:{dbname}:{user}:".format(
host=info.get("host", "localhost"),
port=info.get("port", 5432),
user=info.get("user", ""),
dbname=info.get("dbname", "*"))
pwline = "{linekey}{password}".format(linekey=linekey, password=info.pop("password"))
pgpass_path = os.path.join(os.environ.get("HOME"), ".pgpass")
if os.path.exists(pgpass_path):
with open(pgpass_path, "r") as fp:
pgpass_lines = fp.read().splitlines()
else:
pgpass_lines = []
if pwline in pgpass_lines:
LOG.debug("Not adding authentication data to: %s since it's already there", pgpass_path)
else:
# filter out any existing lines with our linekey and add the new line
pgpass_lines = [line for line in pgpass_lines if not line.startswith(linekey)] + [pwline]
content = "\n".join(pgpass_lines) + "\n"
with open(pgpass_path, "w") as fp:
os.fchmod(fp.fileno(), 0o600)
fp.write(content)
LOG.debug("Wrote %r to %r", pwline, pgpass_path)
return pgutil.create_connection_string(info) | python | def create_pgpass_file(connection_string_or_info):
info = pgutil.get_connection_info(connection_string_or_info)
if "password" not in info:
return pgutil.create_connection_string(info)
linekey = "{host}:{port}:{dbname}:{user}:".format(
host=info.get("host", "localhost"),
port=info.get("port", 5432),
user=info.get("user", ""),
dbname=info.get("dbname", "*"))
pwline = "{linekey}{password}".format(linekey=linekey, password=info.pop("password"))
pgpass_path = os.path.join(os.environ.get("HOME"), ".pgpass")
if os.path.exists(pgpass_path):
with open(pgpass_path, "r") as fp:
pgpass_lines = fp.read().splitlines()
else:
pgpass_lines = []
if pwline in pgpass_lines:
LOG.debug("Not adding authentication data to: %s since it's already there", pgpass_path)
else:
# filter out any existing lines with our linekey and add the new line
pgpass_lines = [line for line in pgpass_lines if not line.startswith(linekey)] + [pwline]
content = "\n".join(pgpass_lines) + "\n"
with open(pgpass_path, "w") as fp:
os.fchmod(fp.fileno(), 0o600)
fp.write(content)
LOG.debug("Wrote %r to %r", pwline, pgpass_path)
return pgutil.create_connection_string(info) | [
"def",
"create_pgpass_file",
"(",
"connection_string_or_info",
")",
":",
"info",
"=",
"pgutil",
".",
"get_connection_info",
"(",
"connection_string_or_info",
")",
"if",
"\"password\"",
"not",
"in",
"info",
":",
"return",
"pgutil",
".",
"create_connection_string",
"(",... | Look up password from the given object which can be a dict or a
string and write a possible password in a pgpass file;
returns a connection_string without a password in it | [
"Look",
"up",
"password",
"from",
"the",
"given",
"object",
"which",
"can",
"be",
"a",
"dict",
"or",
"a",
"string",
"and",
"write",
"a",
"possible",
"password",
"in",
"a",
"pgpass",
"file",
";",
"returns",
"a",
"connection_string",
"without",
"a",
"passwor... | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/common.py#L26-L55 |
234,736 | aiven/pghoard | pghoard/common.py | replication_connection_string_and_slot_using_pgpass | def replication_connection_string_and_slot_using_pgpass(target_node_info):
"""Like `connection_string_and_slot_using_pgpass` but returns a
connection string for a replication connection."""
connection_info, slot = connection_info_and_slot(target_node_info)
connection_info["dbname"] = "replication"
connection_info["replication"] = "true"
connection_string = create_pgpass_file(connection_info)
return connection_string, slot | python | def replication_connection_string_and_slot_using_pgpass(target_node_info):
connection_info, slot = connection_info_and_slot(target_node_info)
connection_info["dbname"] = "replication"
connection_info["replication"] = "true"
connection_string = create_pgpass_file(connection_info)
return connection_string, slot | [
"def",
"replication_connection_string_and_slot_using_pgpass",
"(",
"target_node_info",
")",
":",
"connection_info",
",",
"slot",
"=",
"connection_info_and_slot",
"(",
"target_node_info",
")",
"connection_info",
"[",
"\"dbname\"",
"]",
"=",
"\"replication\"",
"connection_info"... | Like `connection_string_and_slot_using_pgpass` but returns a
connection string for a replication connection. | [
"Like",
"connection_string_and_slot_using_pgpass",
"but",
"returns",
"a",
"connection",
"string",
"for",
"a",
"replication",
"connection",
"."
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/common.py#L85-L92 |
234,737 | aiven/pghoard | pghoard/transfer.py | TransferAgent.transmit_metrics | def transmit_metrics(self):
"""
Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running.
"""
global _last_stats_transmit_time # pylint: disable=global-statement
with _STATS_LOCK: # pylint: disable=not-context-manager
if time.monotonic() - _last_stats_transmit_time < 10.0:
return
for site in self.state:
for filetype, prop in self.state[site]["upload"].items():
if prop["last_success"]:
self.metrics.gauge(
"pghoard.last_upload_age",
time.monotonic() - prop["last_success"],
tags={
"site": site,
"type": filetype,
}
)
_last_stats_transmit_time = time.monotonic() | python | def transmit_metrics(self):
global _last_stats_transmit_time # pylint: disable=global-statement
with _STATS_LOCK: # pylint: disable=not-context-manager
if time.monotonic() - _last_stats_transmit_time < 10.0:
return
for site in self.state:
for filetype, prop in self.state[site]["upload"].items():
if prop["last_success"]:
self.metrics.gauge(
"pghoard.last_upload_age",
time.monotonic() - prop["last_success"],
tags={
"site": site,
"type": filetype,
}
)
_last_stats_transmit_time = time.monotonic() | [
"def",
"transmit_metrics",
"(",
"self",
")",
":",
"global",
"_last_stats_transmit_time",
"# pylint: disable=global-statement",
"with",
"_STATS_LOCK",
":",
"# pylint: disable=not-context-manager",
"if",
"time",
".",
"monotonic",
"(",
")",
"-",
"_last_stats_transmit_time",
"<... | Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running. | [
"Keep",
"metrics",
"updated",
"about",
"how",
"long",
"time",
"ago",
"each",
"filetype",
"was",
"successfully",
"uploaded",
".",
"Transmits",
"max",
"once",
"per",
"ten",
"seconds",
"regardless",
"of",
"how",
"many",
"threads",
"are",
"running",
"."
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/transfer.py#L80-L101 |
234,738 | aiven/pghoard | pghoard/rohmu/encryptor.py | EncryptorFile.write | def write(self, data):
"""Encrypt and write the given bytes"""
self._check_not_closed()
if not data:
return 0
enc_data = self.encryptor.update(data)
self.next_fp.write(enc_data)
self.offset += len(data)
return len(data) | python | def write(self, data):
self._check_not_closed()
if not data:
return 0
enc_data = self.encryptor.update(data)
self.next_fp.write(enc_data)
self.offset += len(data)
return len(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_check_not_closed",
"(",
")",
"if",
"not",
"data",
":",
"return",
"0",
"enc_data",
"=",
"self",
".",
"encryptor",
".",
"update",
"(",
"data",
")",
"self",
".",
"next_fp",
".",
"write",... | Encrypt and write the given bytes | [
"Encrypt",
"and",
"write",
"the",
"given",
"bytes"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/encryptor.py#L101-L109 |
234,739 | aiven/pghoard | pghoard/rohmu/encryptor.py | DecryptorFile.read | def read(self, size=-1):
"""Read up to size decrypted bytes"""
self._check_not_closed()
if self.state == "EOF" or size == 0:
return b""
elif size < 0:
return self._read_all()
else:
return self._read_block(size) | python | def read(self, size=-1):
self._check_not_closed()
if self.state == "EOF" or size == 0:
return b""
elif size < 0:
return self._read_all()
else:
return self._read_block(size) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"self",
".",
"_check_not_closed",
"(",
")",
"if",
"self",
".",
"state",
"==",
"\"EOF\"",
"or",
"size",
"==",
"0",
":",
"return",
"b\"\"",
"elif",
"size",
"<",
"0",
":",
"return",
"... | Read up to size decrypted bytes | [
"Read",
"up",
"to",
"size",
"decrypted",
"bytes"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/encryptor.py#L314-L322 |
234,740 | aiven/pghoard | pghoard/gnutaremu.py | SedStatementParser.tokenize_string | def tokenize_string(cls, string, separator):
"""Split string with given separator unless the separator is escaped with backslash"""
results = []
token = ""
found_escape = False
for c in string:
if found_escape:
if c == separator:
token += separator
else:
token += "\\" + c
found_escape = False
continue
if c == "\\":
found_escape = True
elif c == separator:
results.append(token)
token = ""
else:
token += c
results.append(token)
return results | python | def tokenize_string(cls, string, separator):
results = []
token = ""
found_escape = False
for c in string:
if found_escape:
if c == separator:
token += separator
else:
token += "\\" + c
found_escape = False
continue
if c == "\\":
found_escape = True
elif c == separator:
results.append(token)
token = ""
else:
token += c
results.append(token)
return results | [
"def",
"tokenize_string",
"(",
"cls",
",",
"string",
",",
"separator",
")",
":",
"results",
"=",
"[",
"]",
"token",
"=",
"\"\"",
"found_escape",
"=",
"False",
"for",
"c",
"in",
"string",
":",
"if",
"found_escape",
":",
"if",
"c",
"==",
"separator",
":"... | Split string with given separator unless the separator is escaped with backslash | [
"Split",
"string",
"with",
"given",
"separator",
"unless",
"the",
"separator",
"is",
"escaped",
"with",
"backslash"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/gnutaremu.py#L148-L170 |
234,741 | aiven/pghoard | pghoard/rohmu/object_storage/google.py | GoogleTransfer._unpaginate | def _unpaginate(self, domain, initial_op, *, on_properties):
"""Iterate thru the request pages until all items have been processed"""
request = initial_op(domain)
while request is not None:
result = self._retry_on_reset(request, request.execute)
for on_property in on_properties:
items = result.get(on_property)
if items is not None:
yield on_property, items
request = domain.list_next(request, result) | python | def _unpaginate(self, domain, initial_op, *, on_properties):
request = initial_op(domain)
while request is not None:
result = self._retry_on_reset(request, request.execute)
for on_property in on_properties:
items = result.get(on_property)
if items is not None:
yield on_property, items
request = domain.list_next(request, result) | [
"def",
"_unpaginate",
"(",
"self",
",",
"domain",
",",
"initial_op",
",",
"*",
",",
"on_properties",
")",
":",
"request",
"=",
"initial_op",
"(",
"domain",
")",
"while",
"request",
"is",
"not",
"None",
":",
"result",
"=",
"self",
".",
"_retry_on_reset",
... | Iterate thru the request pages until all items have been processed | [
"Iterate",
"thru",
"the",
"request",
"pages",
"until",
"all",
"items",
"have",
"been",
"processed"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/google.py#L194-L203 |
234,742 | aiven/pghoard | pghoard/rohmu/object_storage/google.py | GoogleTransfer.get_or_create_bucket | def get_or_create_bucket(self, bucket_name):
"""Look up the bucket if it already exists and try to create the
bucket in case it doesn't. Note that we can't just always try to
unconditionally create the bucket as Google imposes a strict rate
limit on bucket creation operations, even if it doesn't result in a
new bucket.
Quietly handle the case where the bucket already exists to avoid
race conditions. Note that we'll get a 400 Bad Request response for
invalid bucket names ("Invalid bucket name") as well as for invalid
project ("Invalid argument"), try to handle both gracefully."""
start_time = time.time()
gs_buckets = self.gs.buckets() # pylint: disable=no-member
try:
request = gs_buckets.get(bucket=bucket_name)
self._retry_on_reset(request, request.execute)
self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time)
except HttpError as ex:
if ex.resp["status"] == "404":
pass # we need to create it
elif ex.resp["status"] == "403":
raise InvalidConfigurationError("Bucket {0!r} exists but isn't accessible".format(bucket_name))
else:
raise
else:
return bucket_name
try:
req = gs_buckets.insert(project=self.project_id, body={"name": bucket_name})
self._retry_on_reset(req, req.execute)
self.log.debug("Created bucket: %r successfully, took: %.3fs", bucket_name, time.time() - start_time)
except HttpError as ex:
error = json.loads(ex.content.decode("utf-8"))["error"]
if error["message"].startswith("You already own this bucket"):
self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time)
elif error["message"] == "Invalid argument.":
raise InvalidConfigurationError("Invalid project id {0!r}".format(self.project_id))
elif error["message"].startswith("Invalid bucket name"):
raise InvalidConfigurationError("Invalid bucket name {0!r}".format(bucket_name))
else:
raise
return bucket_name | python | def get_or_create_bucket(self, bucket_name):
start_time = time.time()
gs_buckets = self.gs.buckets() # pylint: disable=no-member
try:
request = gs_buckets.get(bucket=bucket_name)
self._retry_on_reset(request, request.execute)
self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time)
except HttpError as ex:
if ex.resp["status"] == "404":
pass # we need to create it
elif ex.resp["status"] == "403":
raise InvalidConfigurationError("Bucket {0!r} exists but isn't accessible".format(bucket_name))
else:
raise
else:
return bucket_name
try:
req = gs_buckets.insert(project=self.project_id, body={"name": bucket_name})
self._retry_on_reset(req, req.execute)
self.log.debug("Created bucket: %r successfully, took: %.3fs", bucket_name, time.time() - start_time)
except HttpError as ex:
error = json.loads(ex.content.decode("utf-8"))["error"]
if error["message"].startswith("You already own this bucket"):
self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time)
elif error["message"] == "Invalid argument.":
raise InvalidConfigurationError("Invalid project id {0!r}".format(self.project_id))
elif error["message"].startswith("Invalid bucket name"):
raise InvalidConfigurationError("Invalid bucket name {0!r}".format(bucket_name))
else:
raise
return bucket_name | [
"def",
"get_or_create_bucket",
"(",
"self",
",",
"bucket_name",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"gs_buckets",
"=",
"self",
".",
"gs",
".",
"buckets",
"(",
")",
"# pylint: disable=no-member",
"try",
":",
"request",
"=",
"gs_buckets... | Look up the bucket if it already exists and try to create the
bucket in case it doesn't. Note that we can't just always try to
unconditionally create the bucket as Google imposes a strict rate
limit on bucket creation operations, even if it doesn't result in a
new bucket.
Quietly handle the case where the bucket already exists to avoid
race conditions. Note that we'll get a 400 Bad Request response for
invalid bucket names ("Invalid bucket name") as well as for invalid
project ("Invalid argument"), try to handle both gracefully. | [
"Look",
"up",
"the",
"bucket",
"if",
"it",
"already",
"exists",
"and",
"try",
"to",
"create",
"the",
"bucket",
"in",
"case",
"it",
"doesn",
"t",
".",
"Note",
"that",
"we",
"can",
"t",
"just",
"always",
"try",
"to",
"unconditionally",
"create",
"the",
"... | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/google.py#L348-L390 |
234,743 | aiven/pghoard | pghoard/walreceiver.py | WALReceiver.fetch_timeline_history_files | def fetch_timeline_history_files(self, max_timeline):
"""Copy all timeline history files found on the server without
checking if we have them or not. The history files are very small
so reuploading them should not matter."""
while max_timeline > 1:
self.c.execute("TIMELINE_HISTORY {}".format(max_timeline))
timeline_history = self.c.fetchone()
history_filename = timeline_history[0]
history_data = timeline_history[1].tobytes()
self.log.debug("Received timeline history: %s for timeline %r",
history_filename, max_timeline)
compression_event = {
"type": "CLOSE_WRITE",
"compress_to_memory": True,
"delete_file_after_compression": False,
"input_data": BytesIO(history_data),
"full_path": history_filename,
"site": self.site,
}
self.compression_queue.put(compression_event)
max_timeline -= 1 | python | def fetch_timeline_history_files(self, max_timeline):
while max_timeline > 1:
self.c.execute("TIMELINE_HISTORY {}".format(max_timeline))
timeline_history = self.c.fetchone()
history_filename = timeline_history[0]
history_data = timeline_history[1].tobytes()
self.log.debug("Received timeline history: %s for timeline %r",
history_filename, max_timeline)
compression_event = {
"type": "CLOSE_WRITE",
"compress_to_memory": True,
"delete_file_after_compression": False,
"input_data": BytesIO(history_data),
"full_path": history_filename,
"site": self.site,
}
self.compression_queue.put(compression_event)
max_timeline -= 1 | [
"def",
"fetch_timeline_history_files",
"(",
"self",
",",
"max_timeline",
")",
":",
"while",
"max_timeline",
">",
"1",
":",
"self",
".",
"c",
".",
"execute",
"(",
"\"TIMELINE_HISTORY {}\"",
".",
"format",
"(",
"max_timeline",
")",
")",
"timeline_history",
"=",
... | Copy all timeline history files found on the server without
checking if we have them or not. The history files are very small
so reuploading them should not matter. | [
"Copy",
"all",
"timeline",
"history",
"files",
"found",
"on",
"the",
"server",
"without",
"checking",
"if",
"we",
"have",
"them",
"or",
"not",
".",
"The",
"history",
"files",
"are",
"very",
"small",
"so",
"reuploading",
"them",
"should",
"not",
"matter",
"... | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/walreceiver.py#L60-L81 |
234,744 | aiven/pghoard | pghoard/pghoard.py | PGHoard.check_backup_count_and_state | def check_backup_count_and_state(self, site):
"""Look up basebackups from the object store, prune any extra
backups and return the datetime of the latest backup."""
basebackups = self.get_remote_basebackups_info(site)
self.log.debug("Found %r basebackups", basebackups)
if basebackups:
last_backup_time = basebackups[-1]["metadata"]["start-time"]
else:
last_backup_time = None
allowed_basebackup_count = self.config["backup_sites"][site]["basebackup_count"]
if allowed_basebackup_count is None:
allowed_basebackup_count = len(basebackups)
while len(basebackups) > allowed_basebackup_count:
self.log.warning("Too many basebackups: %d > %d, %r, starting to get rid of %r",
len(basebackups), allowed_basebackup_count, basebackups, basebackups[0]["name"])
basebackup_to_be_deleted = basebackups.pop(0)
pg_version = basebackup_to_be_deleted["metadata"].get("pg-version")
last_wal_segment_still_needed = 0
if basebackups:
last_wal_segment_still_needed = basebackups[0]["metadata"]["start-wal-segment"]
if last_wal_segment_still_needed:
self.delete_remote_wal_before(last_wal_segment_still_needed, site, pg_version)
self.delete_remote_basebackup(site, basebackup_to_be_deleted["name"], basebackup_to_be_deleted["metadata"])
self.state["backup_sites"][site]["basebackups"] = basebackups
return last_backup_time | python | def check_backup_count_and_state(self, site):
basebackups = self.get_remote_basebackups_info(site)
self.log.debug("Found %r basebackups", basebackups)
if basebackups:
last_backup_time = basebackups[-1]["metadata"]["start-time"]
else:
last_backup_time = None
allowed_basebackup_count = self.config["backup_sites"][site]["basebackup_count"]
if allowed_basebackup_count is None:
allowed_basebackup_count = len(basebackups)
while len(basebackups) > allowed_basebackup_count:
self.log.warning("Too many basebackups: %d > %d, %r, starting to get rid of %r",
len(basebackups), allowed_basebackup_count, basebackups, basebackups[0]["name"])
basebackup_to_be_deleted = basebackups.pop(0)
pg_version = basebackup_to_be_deleted["metadata"].get("pg-version")
last_wal_segment_still_needed = 0
if basebackups:
last_wal_segment_still_needed = basebackups[0]["metadata"]["start-wal-segment"]
if last_wal_segment_still_needed:
self.delete_remote_wal_before(last_wal_segment_still_needed, site, pg_version)
self.delete_remote_basebackup(site, basebackup_to_be_deleted["name"], basebackup_to_be_deleted["metadata"])
self.state["backup_sites"][site]["basebackups"] = basebackups
return last_backup_time | [
"def",
"check_backup_count_and_state",
"(",
"self",
",",
"site",
")",
":",
"basebackups",
"=",
"self",
".",
"get_remote_basebackups_info",
"(",
"site",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Found %r basebackups\"",
",",
"basebackups",
")",
"if",
"baseba... | Look up basebackups from the object store, prune any extra
backups and return the datetime of the latest backup. | [
"Look",
"up",
"basebackups",
"from",
"the",
"object",
"store",
"prune",
"any",
"extra",
"backups",
"and",
"return",
"the",
"datetime",
"of",
"the",
"latest",
"backup",
"."
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L311-L340 |
234,745 | aiven/pghoard | pghoard/pghoard.py | PGHoard.startup_walk_for_missed_files | def startup_walk_for_missed_files(self):
"""Check xlog and xlog_incoming directories for files that receivexlog has received but not yet
compressed as well as the files we have compressed but not yet uploaded and process them."""
for site in self.config["backup_sites"]:
compressed_xlog_path, _ = self.create_backup_site_paths(site)
uncompressed_xlog_path = compressed_xlog_path + "_incoming"
# Process uncompressed files (ie WAL pg_receivexlog received)
for filename in os.listdir(uncompressed_xlog_path):
full_path = os.path.join(uncompressed_xlog_path, filename)
if not wal.WAL_RE.match(filename) and not wal.TIMELINE_RE.match(filename):
self.log.warning("Found invalid file %r from incoming xlog directory", full_path)
continue
compression_event = {
"delete_file_after_compression": True,
"full_path": full_path,
"site": site,
"src_path": "{}.partial",
"type": "MOVE",
}
self.log.debug("Found: %r when starting up, adding to compression queue", compression_event)
self.compression_queue.put(compression_event)
# Process compressed files (ie things we've processed but not yet uploaded)
for filename in os.listdir(compressed_xlog_path):
if filename.endswith(".metadata"):
continue # silently ignore .metadata files, they're expected and processed below
full_path = os.path.join(compressed_xlog_path, filename)
metadata_path = full_path + ".metadata"
is_xlog = wal.WAL_RE.match(filename)
is_timeline = wal.TIMELINE_RE.match(filename)
if not ((is_xlog or is_timeline) and os.path.exists(metadata_path)):
self.log.warning("Found invalid file %r from compressed xlog directory", full_path)
continue
with open(metadata_path, "r") as fp:
metadata = json.load(fp)
transfer_event = {
"file_size": os.path.getsize(full_path),
"filetype": "xlog" if is_xlog else "timeline",
"local_path": full_path,
"metadata": metadata,
"site": site,
"type": "UPLOAD",
}
self.log.debug("Found: %r when starting up, adding to transfer queue", transfer_event)
self.transfer_queue.put(transfer_event) | python | def startup_walk_for_missed_files(self):
for site in self.config["backup_sites"]:
compressed_xlog_path, _ = self.create_backup_site_paths(site)
uncompressed_xlog_path = compressed_xlog_path + "_incoming"
# Process uncompressed files (ie WAL pg_receivexlog received)
for filename in os.listdir(uncompressed_xlog_path):
full_path = os.path.join(uncompressed_xlog_path, filename)
if not wal.WAL_RE.match(filename) and not wal.TIMELINE_RE.match(filename):
self.log.warning("Found invalid file %r from incoming xlog directory", full_path)
continue
compression_event = {
"delete_file_after_compression": True,
"full_path": full_path,
"site": site,
"src_path": "{}.partial",
"type": "MOVE",
}
self.log.debug("Found: %r when starting up, adding to compression queue", compression_event)
self.compression_queue.put(compression_event)
# Process compressed files (ie things we've processed but not yet uploaded)
for filename in os.listdir(compressed_xlog_path):
if filename.endswith(".metadata"):
continue # silently ignore .metadata files, they're expected and processed below
full_path = os.path.join(compressed_xlog_path, filename)
metadata_path = full_path + ".metadata"
is_xlog = wal.WAL_RE.match(filename)
is_timeline = wal.TIMELINE_RE.match(filename)
if not ((is_xlog or is_timeline) and os.path.exists(metadata_path)):
self.log.warning("Found invalid file %r from compressed xlog directory", full_path)
continue
with open(metadata_path, "r") as fp:
metadata = json.load(fp)
transfer_event = {
"file_size": os.path.getsize(full_path),
"filetype": "xlog" if is_xlog else "timeline",
"local_path": full_path,
"metadata": metadata,
"site": site,
"type": "UPLOAD",
}
self.log.debug("Found: %r when starting up, adding to transfer queue", transfer_event)
self.transfer_queue.put(transfer_event) | [
"def",
"startup_walk_for_missed_files",
"(",
"self",
")",
":",
"for",
"site",
"in",
"self",
".",
"config",
"[",
"\"backup_sites\"",
"]",
":",
"compressed_xlog_path",
",",
"_",
"=",
"self",
".",
"create_backup_site_paths",
"(",
"site",
")",
"uncompressed_xlog_path"... | Check xlog and xlog_incoming directories for files that receivexlog has received but not yet
compressed as well as the files we have compressed but not yet uploaded and process them. | [
"Check",
"xlog",
"and",
"xlog_incoming",
"directories",
"for",
"files",
"that",
"receivexlog",
"has",
"received",
"but",
"not",
"yet",
"compressed",
"as",
"well",
"as",
"the",
"files",
"we",
"have",
"compressed",
"but",
"not",
"yet",
"uploaded",
"and",
"proces... | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L346-L392 |
234,746 | aiven/pghoard | pghoard/pghoard.py | PGHoard.write_backup_state_to_json_file | def write_backup_state_to_json_file(self):
"""Periodically write a JSON state file to disk"""
start_time = time.time()
state_file_path = self.config["json_state_file_path"]
self.state["walreceivers"] = {
key: {"latest_activity": value.latest_activity, "running": value.running,
"last_flushed_lsn": value.last_flushed_lsn}
for key, value in self.walreceivers.items()
}
self.state["pg_receivexlogs"] = {
key: {"latest_activity": value.latest_activity, "running": value.running}
for key, value in self.receivexlogs.items()
}
self.state["pg_basebackups"] = {
key: {"latest_activity": value.latest_activity, "running": value.running}
for key, value in self.basebackups.items()
}
self.state["compressors"] = [compressor.state for compressor in self.compressors]
self.state["transfer_agents"] = [ta.state for ta in self.transfer_agents]
self.state["queues"] = {
"compression_queue": self.compression_queue.qsize(),
"transfer_queue": self.transfer_queue.qsize(),
}
self.log.debug("Writing JSON state file to %r", state_file_path)
write_json_file(state_file_path, self.state)
self.log.debug("Wrote JSON state file to disk, took %.4fs", time.time() - start_time) | python | def write_backup_state_to_json_file(self):
start_time = time.time()
state_file_path = self.config["json_state_file_path"]
self.state["walreceivers"] = {
key: {"latest_activity": value.latest_activity, "running": value.running,
"last_flushed_lsn": value.last_flushed_lsn}
for key, value in self.walreceivers.items()
}
self.state["pg_receivexlogs"] = {
key: {"latest_activity": value.latest_activity, "running": value.running}
for key, value in self.receivexlogs.items()
}
self.state["pg_basebackups"] = {
key: {"latest_activity": value.latest_activity, "running": value.running}
for key, value in self.basebackups.items()
}
self.state["compressors"] = [compressor.state for compressor in self.compressors]
self.state["transfer_agents"] = [ta.state for ta in self.transfer_agents]
self.state["queues"] = {
"compression_queue": self.compression_queue.qsize(),
"transfer_queue": self.transfer_queue.qsize(),
}
self.log.debug("Writing JSON state file to %r", state_file_path)
write_json_file(state_file_path, self.state)
self.log.debug("Wrote JSON state file to disk, took %.4fs", time.time() - start_time) | [
"def",
"write_backup_state_to_json_file",
"(",
"self",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"state_file_path",
"=",
"self",
".",
"config",
"[",
"\"json_state_file_path\"",
"]",
"self",
".",
"state",
"[",
"\"walreceivers\"",
"]",
"=",
"{"... | Periodically write a JSON state file to disk | [
"Periodically",
"write",
"a",
"JSON",
"state",
"file",
"to",
"disk"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L493-L518 |
234,747 | aiven/pghoard | pghoard/pgutil.py | get_connection_info | def get_connection_info(info):
"""turn a connection info object into a dict or return it if it was a
dict already. supports both the traditional libpq format and the new
url format"""
if isinstance(info, dict):
return info.copy()
elif info.startswith("postgres://") or info.startswith("postgresql://"):
return parse_connection_string_url(info)
else:
return parse_connection_string_libpq(info) | python | def get_connection_info(info):
if isinstance(info, dict):
return info.copy()
elif info.startswith("postgres://") or info.startswith("postgresql://"):
return parse_connection_string_url(info)
else:
return parse_connection_string_libpq(info) | [
"def",
"get_connection_info",
"(",
"info",
")",
":",
"if",
"isinstance",
"(",
"info",
",",
"dict",
")",
":",
"return",
"info",
".",
"copy",
"(",
")",
"elif",
"info",
".",
"startswith",
"(",
"\"postgres://\"",
")",
"or",
"info",
".",
"startswith",
"(",
... | turn a connection info object into a dict or return it if it was a
dict already. supports both the traditional libpq format and the new
url format | [
"turn",
"a",
"connection",
"info",
"object",
"into",
"a",
"dict",
"or",
"return",
"it",
"if",
"it",
"was",
"a",
"dict",
"already",
".",
"supports",
"both",
"the",
"traditional",
"libpq",
"format",
"and",
"the",
"new",
"url",
"format"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pgutil.py#L34-L43 |
234,748 | aiven/pghoard | pghoard/restore.py | Restore.list_basebackups_http | def list_basebackups_http(self, arg):
"""List available basebackups from a HTTP source"""
self.storage = HTTPRestore(arg.host, arg.port, arg.site)
self.storage.show_basebackup_list(verbose=arg.verbose) | python | def list_basebackups_http(self, arg):
self.storage = HTTPRestore(arg.host, arg.port, arg.site)
self.storage.show_basebackup_list(verbose=arg.verbose) | [
"def",
"list_basebackups_http",
"(",
"self",
",",
"arg",
")",
":",
"self",
".",
"storage",
"=",
"HTTPRestore",
"(",
"arg",
".",
"host",
",",
"arg",
".",
"port",
",",
"arg",
".",
"site",
")",
"self",
".",
"storage",
".",
"show_basebackup_list",
"(",
"ve... | List available basebackups from a HTTP source | [
"List",
"available",
"basebackups",
"from",
"a",
"HTTP",
"source"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L184-L187 |
234,749 | aiven/pghoard | pghoard/restore.py | Restore.list_basebackups | def list_basebackups(self, arg):
"""List basebackups from an object store"""
self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False)
site = config.get_site_from_config(self.config, arg.site)
self.storage = self._get_object_storage(site, pgdata=None)
self.storage.show_basebackup_list(verbose=arg.verbose) | python | def list_basebackups(self, arg):
self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False)
site = config.get_site_from_config(self.config, arg.site)
self.storage = self._get_object_storage(site, pgdata=None)
self.storage.show_basebackup_list(verbose=arg.verbose) | [
"def",
"list_basebackups",
"(",
"self",
",",
"arg",
")",
":",
"self",
".",
"config",
"=",
"config",
".",
"read_json_config_file",
"(",
"arg",
".",
"config",
",",
"check_commands",
"=",
"False",
",",
"check_pgdata",
"=",
"False",
")",
"site",
"=",
"config",... | List basebackups from an object store | [
"List",
"basebackups",
"from",
"an",
"object",
"store"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L194-L199 |
234,750 | aiven/pghoard | pghoard/restore.py | Restore.get_basebackup | def get_basebackup(self, arg):
"""Download a basebackup from an object store"""
if not arg.tablespace_dir:
tablespace_mapping = {}
else:
try:
tablespace_mapping = dict(v.split("=", 1) for v in arg.tablespace_dir)
except ValueError:
raise RestoreError("Invalid tablespace mapping {!r}".format(arg.tablespace_dir))
self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False)
site = config.get_site_from_config(self.config, arg.site)
try:
self.storage = self._get_object_storage(site, arg.target_dir)
self._get_basebackup(
pgdata=arg.target_dir,
basebackup=arg.basebackup,
site=site,
debug=arg.debug,
status_output_file=arg.status_output_file,
primary_conninfo=arg.primary_conninfo,
recovery_end_command=arg.recovery_end_command,
recovery_target_action=arg.recovery_target_action,
recovery_target_name=arg.recovery_target_name,
recovery_target_time=arg.recovery_target_time,
recovery_target_xid=arg.recovery_target_xid,
restore_to_master=arg.restore_to_master,
overwrite=arg.overwrite,
tablespace_mapping=tablespace_mapping,
tablespace_base_dir=arg.tablespace_base_dir,
)
except RestoreError: # pylint: disable=try-except-raise
# Pass RestoreErrors thru
raise
except Exception as ex:
if self.log_tracebacks:
self.log.exception("Unexpected _get_basebackup failure")
raise RestoreError("{}: {}".format(ex.__class__.__name__, ex)) | python | def get_basebackup(self, arg):
if not arg.tablespace_dir:
tablespace_mapping = {}
else:
try:
tablespace_mapping = dict(v.split("=", 1) for v in arg.tablespace_dir)
except ValueError:
raise RestoreError("Invalid tablespace mapping {!r}".format(arg.tablespace_dir))
self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False)
site = config.get_site_from_config(self.config, arg.site)
try:
self.storage = self._get_object_storage(site, arg.target_dir)
self._get_basebackup(
pgdata=arg.target_dir,
basebackup=arg.basebackup,
site=site,
debug=arg.debug,
status_output_file=arg.status_output_file,
primary_conninfo=arg.primary_conninfo,
recovery_end_command=arg.recovery_end_command,
recovery_target_action=arg.recovery_target_action,
recovery_target_name=arg.recovery_target_name,
recovery_target_time=arg.recovery_target_time,
recovery_target_xid=arg.recovery_target_xid,
restore_to_master=arg.restore_to_master,
overwrite=arg.overwrite,
tablespace_mapping=tablespace_mapping,
tablespace_base_dir=arg.tablespace_base_dir,
)
except RestoreError: # pylint: disable=try-except-raise
# Pass RestoreErrors thru
raise
except Exception as ex:
if self.log_tracebacks:
self.log.exception("Unexpected _get_basebackup failure")
raise RestoreError("{}: {}".format(ex.__class__.__name__, ex)) | [
"def",
"get_basebackup",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"arg",
".",
"tablespace_dir",
":",
"tablespace_mapping",
"=",
"{",
"}",
"else",
":",
"try",
":",
"tablespace_mapping",
"=",
"dict",
"(",
"v",
".",
"split",
"(",
"\"=\"",
",",
"1",... | Download a basebackup from an object store | [
"Download",
"a",
"basebackup",
"from",
"an",
"object",
"store"
] | 2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L201-L238 |
234,751 | scikit-hep/uproot | uproot/rootio.py | TKey.get | def get(self, dismiss=True):
"""Extract the object this key points to.
Objects are not read or decompressed until this function is explicitly called.
"""
try:
return _classof(self._context, self._fClassName).read(self._source, self._cursor.copied(), self._context, self)
finally:
if dismiss:
self._source.dismiss() | python | def get(self, dismiss=True):
try:
return _classof(self._context, self._fClassName).read(self._source, self._cursor.copied(), self._context, self)
finally:
if dismiss:
self._source.dismiss() | [
"def",
"get",
"(",
"self",
",",
"dismiss",
"=",
"True",
")",
":",
"try",
":",
"return",
"_classof",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_fClassName",
")",
".",
"read",
"(",
"self",
".",
"_source",
",",
"self",
".",
"_cursor",
".",
"cop... | Extract the object this key points to.
Objects are not read or decompressed until this function is explicitly called. | [
"Extract",
"the",
"object",
"this",
"key",
"points",
"to",
"."
] | fc406827e36ed87cfb1062806e118f53fd3a3b0a | https://github.com/scikit-hep/uproot/blob/fc406827e36ed87cfb1062806e118f53fd3a3b0a/uproot/rootio.py#L883-L893 |
234,752 | zarr-developers/zarr | zarr/hierarchy.py | open_group | def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None,
chunk_store=None):
"""Open a group using file-mode-like semantics.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
read/write (must exist); 'a' means read/write (create if doesn't
exist); 'w' means create (overwrite if exists); 'w-' means create
(fail if exists).
cache_attrs : bool, optional
If True (default), user attributes will be cached for attribute read
operations. If False, user attributes are reloaded from the store prior
to all attribute read operations.
synchronizer : object, optional
Array synchronizer.
path : string, optional
Group path within store.
chunk_store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> root = zarr.open_group('data/example.zarr', mode='w')
>>> foo = root.create_group('foo')
>>> bar = root.create_group('bar')
>>> root
<zarr.hierarchy.Group '/'>
>>> root2 = zarr.open_group('data/example.zarr', mode='a')
>>> root2
<zarr.hierarchy.Group '/'>
>>> root == root2
True
"""
# handle polymorphic store arg
store = _normalize_store_arg(store)
if chunk_store is not None:
chunk_store = _normalize_store_arg(chunk_store)
path = normalize_storage_path(path)
# ensure store is initialized
if mode in ['r', 'r+']:
if contains_array(store, path=path):
err_contains_array(path)
elif not contains_group(store, path=path):
err_group_not_found(path)
elif mode == 'w':
init_group(store, overwrite=True, path=path, chunk_store=chunk_store)
elif mode == 'a':
if contains_array(store, path=path):
err_contains_array(path)
if not contains_group(store, path=path):
init_group(store, path=path, chunk_store=chunk_store)
elif mode in ['w-', 'x']:
if contains_array(store, path=path):
err_contains_array(path)
elif contains_group(store, path=path):
err_contains_group(path)
else:
init_group(store, path=path, chunk_store=chunk_store)
# determine read only status
read_only = mode == 'r'
return Group(store, read_only=read_only, cache_attrs=cache_attrs,
synchronizer=synchronizer, path=path, chunk_store=chunk_store) | python | def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None,
chunk_store=None):
# handle polymorphic store arg
store = _normalize_store_arg(store)
if chunk_store is not None:
chunk_store = _normalize_store_arg(chunk_store)
path = normalize_storage_path(path)
# ensure store is initialized
if mode in ['r', 'r+']:
if contains_array(store, path=path):
err_contains_array(path)
elif not contains_group(store, path=path):
err_group_not_found(path)
elif mode == 'w':
init_group(store, overwrite=True, path=path, chunk_store=chunk_store)
elif mode == 'a':
if contains_array(store, path=path):
err_contains_array(path)
if not contains_group(store, path=path):
init_group(store, path=path, chunk_store=chunk_store)
elif mode in ['w-', 'x']:
if contains_array(store, path=path):
err_contains_array(path)
elif contains_group(store, path=path):
err_contains_group(path)
else:
init_group(store, path=path, chunk_store=chunk_store)
# determine read only status
read_only = mode == 'r'
return Group(store, read_only=read_only, cache_attrs=cache_attrs,
synchronizer=synchronizer, path=path, chunk_store=chunk_store) | [
"def",
"open_group",
"(",
"store",
"=",
"None",
",",
"mode",
"=",
"'a'",
",",
"cache_attrs",
"=",
"True",
",",
"synchronizer",
"=",
"None",
",",
"path",
"=",
"None",
",",
"chunk_store",
"=",
"None",
")",
":",
"# handle polymorphic store arg",
"store",
"=",... | Open a group using file-mode-like semantics.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
read/write (must exist); 'a' means read/write (create if doesn't
exist); 'w' means create (overwrite if exists); 'w-' means create
(fail if exists).
cache_attrs : bool, optional
If True (default), user attributes will be cached for attribute read
operations. If False, user attributes are reloaded from the store prior
to all attribute read operations.
synchronizer : object, optional
Array synchronizer.
path : string, optional
Group path within store.
chunk_store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> root = zarr.open_group('data/example.zarr', mode='w')
>>> foo = root.create_group('foo')
>>> bar = root.create_group('bar')
>>> root
<zarr.hierarchy.Group '/'>
>>> root2 = zarr.open_group('data/example.zarr', mode='a')
>>> root2
<zarr.hierarchy.Group '/'>
>>> root == root2
True | [
"Open",
"a",
"group",
"using",
"file",
"-",
"mode",
"-",
"like",
"semantics",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L1060-L1139 |
234,753 | zarr-developers/zarr | zarr/hierarchy.py | Group.name | def name(self):
"""Group name following h5py convention."""
if self._path:
# follow h5py convention: add leading slash
name = self._path
if name[0] != '/':
name = '/' + name
return name
return '/' | python | def name(self):
if self._path:
# follow h5py convention: add leading slash
name = self._path
if name[0] != '/':
name = '/' + name
return name
return '/' | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_path",
":",
"# follow h5py convention: add leading slash",
"name",
"=",
"self",
".",
"_path",
"if",
"name",
"[",
"0",
"]",
"!=",
"'/'",
":",
"name",
"=",
"'/'",
"+",
"name",
"return",
"name",
"... | Group name following h5py convention. | [
"Group",
"name",
"following",
"h5py",
"convention",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L136-L144 |
234,754 | zarr-developers/zarr | zarr/hierarchy.py | Group.group_keys | def group_keys(self):
"""Return an iterator over member names for groups only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.group_keys())
['bar', 'foo']
"""
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_group(self._store, path):
yield key | python | def group_keys(self):
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_group(self._store, path):
yield key | [
"def",
"group_keys",
"(",
"self",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"listdir",
"(",
"self",
".",
"_store",
",",
"self",
".",
"_path",
")",
")",
":",
"path",
"=",
"self",
".",
"_key_prefix",
"+",
"key",
"if",
"contains_group",
"(",
"self",
... | Return an iterator over member names for groups only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.group_keys())
['bar', 'foo'] | [
"Return",
"an",
"iterator",
"over",
"member",
"names",
"for",
"groups",
"only",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L368-L386 |
234,755 | zarr-developers/zarr | zarr/hierarchy.py | Group.array_keys | def array_keys(self):
"""Return an iterator over member names for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.array_keys())
['baz', 'quux']
"""
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_array(self._store, path):
yield key | python | def array_keys(self):
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_array(self._store, path):
yield key | [
"def",
"array_keys",
"(",
"self",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"listdir",
"(",
"self",
".",
"_store",
",",
"self",
".",
"_path",
")",
")",
":",
"path",
"=",
"self",
".",
"_key_prefix",
"+",
"key",
"if",
"contains_array",
"(",
"self",
... | Return an iterator over member names for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.array_keys())
['baz', 'quux'] | [
"Return",
"an",
"iterator",
"over",
"member",
"names",
"for",
"arrays",
"only",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L413-L431 |
234,756 | zarr-developers/zarr | zarr/hierarchy.py | Group.visitvalues | def visitvalues(self, func):
"""Run ``func`` on each object.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(obj):
... print(obj)
>>> g1.visitvalues(print_visitor)
<zarr.hierarchy.Group '/bar'>
<zarr.hierarchy.Group '/bar/baz'>
<zarr.hierarchy.Group '/bar/quux'>
<zarr.hierarchy.Group '/foo'>
>>> g3.visitvalues(print_visitor)
<zarr.hierarchy.Group '/bar/baz'>
<zarr.hierarchy.Group '/bar/quux'>
"""
def _visit(obj):
yield obj
keys = sorted(getattr(obj, "keys", lambda: [])())
for k in keys:
for v in _visit(obj[k]):
yield v
for each_obj in islice(_visit(self), 1, None):
value = func(each_obj)
if value is not None:
return value | python | def visitvalues(self, func):
def _visit(obj):
yield obj
keys = sorted(getattr(obj, "keys", lambda: [])())
for k in keys:
for v in _visit(obj[k]):
yield v
for each_obj in islice(_visit(self), 1, None):
value = func(each_obj)
if value is not None:
return value | [
"def",
"visitvalues",
"(",
"self",
",",
"func",
")",
":",
"def",
"_visit",
"(",
"obj",
")",
":",
"yield",
"obj",
"keys",
"=",
"sorted",
"(",
"getattr",
"(",
"obj",
",",
"\"keys\"",
",",
"lambda",
":",
"[",
"]",
")",
"(",
")",
")",
"for",
"k",
"... | Run ``func`` on each object.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(obj):
... print(obj)
>>> g1.visitvalues(print_visitor)
<zarr.hierarchy.Group '/bar'>
<zarr.hierarchy.Group '/bar/baz'>
<zarr.hierarchy.Group '/bar/quux'>
<zarr.hierarchy.Group '/foo'>
>>> g3.visitvalues(print_visitor)
<zarr.hierarchy.Group '/bar/baz'>
<zarr.hierarchy.Group '/bar/quux'> | [
"Run",
"func",
"on",
"each",
"object",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L458-L496 |
234,757 | zarr-developers/zarr | zarr/hierarchy.py | Group.visit | def visit(self, func):
"""Run ``func`` on each object's path.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(name):
... print(name)
>>> g1.visit(print_visitor)
bar
bar/baz
bar/quux
foo
>>> g3.visit(print_visitor)
baz
quux
"""
base_len = len(self.name)
return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/"))) | python | def visit(self, func):
base_len = len(self.name)
return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/"))) | [
"def",
"visit",
"(",
"self",
",",
"func",
")",
":",
"base_len",
"=",
"len",
"(",
"self",
".",
"name",
")",
"return",
"self",
".",
"visitvalues",
"(",
"lambda",
"o",
":",
"func",
"(",
"o",
".",
"name",
"[",
"base_len",
":",
"]",
".",
"lstrip",
"("... | Run ``func`` on each object's path.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(name):
... print(name)
>>> g1.visit(print_visitor)
bar
bar/baz
bar/quux
foo
>>> g3.visit(print_visitor)
baz
quux | [
"Run",
"func",
"on",
"each",
"object",
"s",
"path",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L498-L527 |
234,758 | zarr-developers/zarr | zarr/hierarchy.py | Group.tree | def tree(self, expand=False, level=None):
"""Provide a ``print``-able display of the hierarchy.
Parameters
----------
expand : bool, optional
Only relevant for HTML representation. If True, tree will be fully expanded.
level : int, optional
Maximum depth to descend into hierarchy.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> d1 = g5.create_dataset('baz', shape=100, chunks=10)
>>> g1.tree()
/
├── bar
│ ├── baz
│ └── quux
│ └── baz (100,) float64
└── foo
>>> g1.tree(level=2)
/
├── bar
│ ├── baz
│ └── quux
└── foo
>>> g3.tree()
bar
├── baz
└── quux
└── baz (100,) float64
Notes
-----
Please note that this is an experimental feature. The behaviour of this
function is still evolving and the default output and/or parameters may change
in future versions.
"""
return TreeViewer(self, expand=expand, level=level) | python | def tree(self, expand=False, level=None):
return TreeViewer(self, expand=expand, level=level) | [
"def",
"tree",
"(",
"self",
",",
"expand",
"=",
"False",
",",
"level",
"=",
"None",
")",
":",
"return",
"TreeViewer",
"(",
"self",
",",
"expand",
"=",
"expand",
",",
"level",
"=",
"level",
")"
] | Provide a ``print``-able display of the hierarchy.
Parameters
----------
expand : bool, optional
Only relevant for HTML representation. If True, tree will be fully expanded.
level : int, optional
Maximum depth to descend into hierarchy.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> d1 = g5.create_dataset('baz', shape=100, chunks=10)
>>> g1.tree()
/
├── bar
│ ├── baz
│ └── quux
│ └── baz (100,) float64
└── foo
>>> g1.tree(level=2)
/
├── bar
│ ├── baz
│ └── quux
└── foo
>>> g3.tree()
bar
├── baz
└── quux
└── baz (100,) float64
Notes
-----
Please note that this is an experimental feature. The behaviour of this
function is still evolving and the default output and/or parameters may change
in future versions. | [
"Provide",
"a",
"print",
"-",
"able",
"display",
"of",
"the",
"hierarchy",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L566-L612 |
234,759 | zarr-developers/zarr | zarr/hierarchy.py | Group.create_group | def create_group(self, name, overwrite=False):
"""Create a sub-group.
Parameters
----------
name : string
Group name.
overwrite : bool, optional
If True, overwrite any existing array with the given name.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g1.create_group('baz/quux')
"""
return self._write_op(self._create_group_nosync, name, overwrite=overwrite) | python | def create_group(self, name, overwrite=False):
return self._write_op(self._create_group_nosync, name, overwrite=overwrite) | [
"def",
"create_group",
"(",
"self",
",",
"name",
",",
"overwrite",
"=",
"False",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_create_group_nosync",
",",
"name",
",",
"overwrite",
"=",
"overwrite",
")"
] | Create a sub-group.
Parameters
----------
name : string
Group name.
overwrite : bool, optional
If True, overwrite any existing array with the given name.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g1.create_group('baz/quux') | [
"Create",
"a",
"sub",
"-",
"group",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L630-L654 |
234,760 | zarr-developers/zarr | zarr/hierarchy.py | Group.create_groups | def create_groups(self, *names, **kwargs):
"""Convenience method to create multiple groups in a single call."""
return tuple(self.create_group(name, **kwargs) for name in names) | python | def create_groups(self, *names, **kwargs):
return tuple(self.create_group(name, **kwargs) for name in names) | [
"def",
"create_groups",
"(",
"self",
",",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"create_group",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"for",
"name",
"in",
"names",
")"
] | Convenience method to create multiple groups in a single call. | [
"Convenience",
"method",
"to",
"create",
"multiple",
"groups",
"in",
"a",
"single",
"call",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L667-L669 |
234,761 | zarr-developers/zarr | zarr/hierarchy.py | Group.require_group | def require_group(self, name, overwrite=False):
"""Obtain a sub-group, creating one if it doesn't exist.
Parameters
----------
name : string
Group name.
overwrite : bool, optional
Overwrite any existing array with given `name` if present.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.require_group('foo')
>>> g3 = g1.require_group('foo')
>>> g2 == g3
True
"""
return self._write_op(self._require_group_nosync, name,
overwrite=overwrite) | python | def require_group(self, name, overwrite=False):
return self._write_op(self._require_group_nosync, name,
overwrite=overwrite) | [
"def",
"require_group",
"(",
"self",
",",
"name",
",",
"overwrite",
"=",
"False",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_require_group_nosync",
",",
"name",
",",
"overwrite",
"=",
"overwrite",
")"
] | Obtain a sub-group, creating one if it doesn't exist.
Parameters
----------
name : string
Group name.
overwrite : bool, optional
Overwrite any existing array with given `name` if present.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.require_group('foo')
>>> g3 = g1.require_group('foo')
>>> g2 == g3
True | [
"Obtain",
"a",
"sub",
"-",
"group",
"creating",
"one",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L671-L697 |
234,762 | zarr-developers/zarr | zarr/hierarchy.py | Group.move | def move(self, source, dest):
"""Move contents from one path to another relative to the Group.
Parameters
----------
source : string
Name or path to a Zarr object to move.
dest : string
New name or path of the Zarr object.
"""
source = self._item_path(source)
dest = self._item_path(dest)
# Check that source exists.
if not (contains_array(self._store, source) or
contains_group(self._store, source)):
raise ValueError('The source, "%s", does not exist.' % source)
if contains_array(self._store, dest) or contains_group(self._store, dest):
raise ValueError('The dest, "%s", already exists.' % dest)
# Ensure groups needed for `dest` exist.
if "/" in dest:
self.require_group("/" + dest.rsplit("/", 1)[0])
self._write_op(self._move_nosync, source, dest) | python | def move(self, source, dest):
source = self._item_path(source)
dest = self._item_path(dest)
# Check that source exists.
if not (contains_array(self._store, source) or
contains_group(self._store, source)):
raise ValueError('The source, "%s", does not exist.' % source)
if contains_array(self._store, dest) or contains_group(self._store, dest):
raise ValueError('The dest, "%s", already exists.' % dest)
# Ensure groups needed for `dest` exist.
if "/" in dest:
self.require_group("/" + dest.rsplit("/", 1)[0])
self._write_op(self._move_nosync, source, dest) | [
"def",
"move",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"source",
"=",
"self",
".",
"_item_path",
"(",
"source",
")",
"dest",
"=",
"self",
".",
"_item_path",
"(",
"dest",
")",
"# Check that source exists.",
"if",
"not",
"(",
"contains_array",
"... | Move contents from one path to another relative to the Group.
Parameters
----------
source : string
Name or path to a Zarr object to move.
dest : string
New name or path of the Zarr object. | [
"Move",
"contents",
"from",
"one",
"path",
"to",
"another",
"relative",
"to",
"the",
"Group",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L970-L995 |
234,763 | zarr-developers/zarr | zarr/attrs.py | Attributes.asdict | def asdict(self):
"""Retrieve all attributes as a dictionary."""
if self.cache and self._cached_asdict is not None:
return self._cached_asdict
d = self._get_nosync()
if self.cache:
self._cached_asdict = d
return d | python | def asdict(self):
if self.cache and self._cached_asdict is not None:
return self._cached_asdict
d = self._get_nosync()
if self.cache:
self._cached_asdict = d
return d | [
"def",
"asdict",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
"and",
"self",
".",
"_cached_asdict",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_cached_asdict",
"d",
"=",
"self",
".",
"_get_nosync",
"(",
")",
"if",
"self",
".",
"cache",
"... | Retrieve all attributes as a dictionary. | [
"Retrieve",
"all",
"attributes",
"as",
"a",
"dictionary",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/attrs.py#L49-L56 |
234,764 | zarr-developers/zarr | zarr/attrs.py | Attributes.update | def update(self, *args, **kwargs):
"""Update the values of several attributes in a single operation."""
self._write_op(self._update_nosync, *args, **kwargs) | python | def update(self, *args, **kwargs):
self._write_op(self._update_nosync, *args, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_write_op",
"(",
"self",
".",
"_update_nosync",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Update the values of several attributes in a single operation. | [
"Update",
"the",
"values",
"of",
"several",
"attributes",
"in",
"a",
"single",
"operation",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/attrs.py#L121-L123 |
234,765 | zarr-developers/zarr | zarr/util.py | json_dumps | def json_dumps(o):
"""Write JSON in a consistent, human-readable way."""
return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
separators=(',', ': ')).encode('ascii') | python | def json_dumps(o):
return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
separators=(',', ': ')).encode('ascii') | [
"def",
"json_dumps",
"(",
"o",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"o",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"ensure_ascii",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
".",
"encode",
... | Write JSON in a consistent, human-readable way. | [
"Write",
"JSON",
"in",
"a",
"consistent",
"human",
"-",
"readable",
"way",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L36-L39 |
234,766 | zarr-developers/zarr | zarr/util.py | normalize_shape | def normalize_shape(shape):
"""Convenience function to normalize the `shape` argument."""
if shape is None:
raise TypeError('shape is None')
# handle 1D convenience form
if isinstance(shape, numbers.Integral):
shape = (int(shape),)
# normalize
shape = tuple(int(s) for s in shape)
return shape | python | def normalize_shape(shape):
if shape is None:
raise TypeError('shape is None')
# handle 1D convenience form
if isinstance(shape, numbers.Integral):
shape = (int(shape),)
# normalize
shape = tuple(int(s) for s in shape)
return shape | [
"def",
"normalize_shape",
"(",
"shape",
")",
":",
"if",
"shape",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'shape is None'",
")",
"# handle 1D convenience form",
"if",
"isinstance",
"(",
"shape",
",",
"numbers",
".",
"Integral",
")",
":",
"shape",
"=",
... | Convenience function to normalize the `shape` argument. | [
"Convenience",
"function",
"to",
"normalize",
"the",
"shape",
"argument",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L47-L59 |
234,767 | zarr-developers/zarr | zarr/util.py | guess_chunks | def guess_chunks(shape, typesize):
"""
Guess an appropriate chunk layout for a dataset, given its shape and
the size of each element in bytes. Will allocate chunks only as large
as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of
each axis, slightly favoring bigger values for the last index.
Undocumented and subject to change without warning.
"""
ndims = len(shape)
# require chunks to have non-zero length for all dimensions
chunks = np.maximum(np.array(shape, dtype='=f8'), 1)
# Determine the optimal chunk size in bytes using a PyTables expression.
# This is kept as a float.
dset_size = np.product(chunks)*typesize
target_size = CHUNK_BASE * (2**np.log10(dset_size/(1024.*1024)))
if target_size > CHUNK_MAX:
target_size = CHUNK_MAX
elif target_size < CHUNK_MIN:
target_size = CHUNK_MIN
idx = 0
while True:
# Repeatedly loop over the axes, dividing them by 2. Stop when:
# 1a. We're smaller than the target chunk size, OR
# 1b. We're within 50% of the target chunk size, AND
# 2. The chunk is smaller than the maximum chunk size
chunk_bytes = np.product(chunks)*typesize
if (chunk_bytes < target_size or
abs(chunk_bytes-target_size)/target_size < 0.5) and \
chunk_bytes < CHUNK_MAX:
break
if np.product(chunks) == 1:
break # Element size larger than CHUNK_MAX
chunks[idx % ndims] = np.ceil(chunks[idx % ndims] / 2.0)
idx += 1
return tuple(int(x) for x in chunks) | python | def guess_chunks(shape, typesize):
ndims = len(shape)
# require chunks to have non-zero length for all dimensions
chunks = np.maximum(np.array(shape, dtype='=f8'), 1)
# Determine the optimal chunk size in bytes using a PyTables expression.
# This is kept as a float.
dset_size = np.product(chunks)*typesize
target_size = CHUNK_BASE * (2**np.log10(dset_size/(1024.*1024)))
if target_size > CHUNK_MAX:
target_size = CHUNK_MAX
elif target_size < CHUNK_MIN:
target_size = CHUNK_MIN
idx = 0
while True:
# Repeatedly loop over the axes, dividing them by 2. Stop when:
# 1a. We're smaller than the target chunk size, OR
# 1b. We're within 50% of the target chunk size, AND
# 2. The chunk is smaller than the maximum chunk size
chunk_bytes = np.product(chunks)*typesize
if (chunk_bytes < target_size or
abs(chunk_bytes-target_size)/target_size < 0.5) and \
chunk_bytes < CHUNK_MAX:
break
if np.product(chunks) == 1:
break # Element size larger than CHUNK_MAX
chunks[idx % ndims] = np.ceil(chunks[idx % ndims] / 2.0)
idx += 1
return tuple(int(x) for x in chunks) | [
"def",
"guess_chunks",
"(",
"shape",
",",
"typesize",
")",
":",
"ndims",
"=",
"len",
"(",
"shape",
")",
"# require chunks to have non-zero length for all dimensions",
"chunks",
"=",
"np",
".",
"maximum",
"(",
"np",
".",
"array",
"(",
"shape",
",",
"dtype",
"="... | Guess an appropriate chunk layout for a dataset, given its shape and
the size of each element in bytes. Will allocate chunks only as large
as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of
each axis, slightly favoring bigger values for the last index.
Undocumented and subject to change without warning. | [
"Guess",
"an",
"appropriate",
"chunk",
"layout",
"for",
"a",
"dataset",
"given",
"its",
"shape",
"and",
"the",
"size",
"of",
"each",
"element",
"in",
"bytes",
".",
"Will",
"allocate",
"chunks",
"only",
"as",
"large",
"as",
"MAX_SIZE",
".",
"Chunks",
"are",... | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L69-L112 |
234,768 | zarr-developers/zarr | zarr/util.py | normalize_chunks | def normalize_chunks(chunks, shape, typesize):
"""Convenience function to normalize the `chunks` argument for an array
with the given `shape`."""
# N.B., expect shape already normalized
# handle auto-chunking
if chunks is None or chunks is True:
return guess_chunks(shape, typesize)
# handle no chunking
if chunks is False:
return shape
# handle 1D convenience form
if isinstance(chunks, numbers.Integral):
chunks = (int(chunks),)
# handle bad dimensionality
if len(chunks) > len(shape):
raise ValueError('too many dimensions in chunks')
# handle underspecified chunks
if len(chunks) < len(shape):
# assume chunks across remaining dimensions
chunks += shape[len(chunks):]
# handle None in chunks
chunks = tuple(s if c is None else int(c)
for s, c in zip(shape, chunks))
return chunks | python | def normalize_chunks(chunks, shape, typesize):
# N.B., expect shape already normalized
# handle auto-chunking
if chunks is None or chunks is True:
return guess_chunks(shape, typesize)
# handle no chunking
if chunks is False:
return shape
# handle 1D convenience form
if isinstance(chunks, numbers.Integral):
chunks = (int(chunks),)
# handle bad dimensionality
if len(chunks) > len(shape):
raise ValueError('too many dimensions in chunks')
# handle underspecified chunks
if len(chunks) < len(shape):
# assume chunks across remaining dimensions
chunks += shape[len(chunks):]
# handle None in chunks
chunks = tuple(s if c is None else int(c)
for s, c in zip(shape, chunks))
return chunks | [
"def",
"normalize_chunks",
"(",
"chunks",
",",
"shape",
",",
"typesize",
")",
":",
"# N.B., expect shape already normalized",
"# handle auto-chunking",
"if",
"chunks",
"is",
"None",
"or",
"chunks",
"is",
"True",
":",
"return",
"guess_chunks",
"(",
"shape",
",",
"t... | Convenience function to normalize the `chunks` argument for an array
with the given `shape`. | [
"Convenience",
"function",
"to",
"normalize",
"the",
"chunks",
"argument",
"for",
"an",
"array",
"with",
"the",
"given",
"shape",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L115-L146 |
234,769 | zarr-developers/zarr | zarr/storage.py | contains_array | def contains_array(store, path=None):
"""Return True if the store contains an array at the given logical path."""
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = prefix + array_meta_key
return key in store | python | def contains_array(store, path=None):
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = prefix + array_meta_key
return key in store | [
"def",
"contains_array",
"(",
"store",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"prefix",
"=",
"_path_to_prefix",
"(",
"path",
")",
"key",
"=",
"prefix",
"+",
"array_meta_key",
"return",
"key",
"in",
"sto... | Return True if the store contains an array at the given logical path. | [
"Return",
"True",
"if",
"the",
"store",
"contains",
"an",
"array",
"at",
"the",
"given",
"logical",
"path",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L77-L82 |
234,770 | zarr-developers/zarr | zarr/storage.py | contains_group | def contains_group(store, path=None):
"""Return True if the store contains a group at the given logical path."""
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = prefix + group_meta_key
return key in store | python | def contains_group(store, path=None):
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = prefix + group_meta_key
return key in store | [
"def",
"contains_group",
"(",
"store",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"prefix",
"=",
"_path_to_prefix",
"(",
"path",
")",
"key",
"=",
"prefix",
"+",
"group_meta_key",
"return",
"key",
"in",
"sto... | Return True if the store contains a group at the given logical path. | [
"Return",
"True",
"if",
"the",
"store",
"contains",
"a",
"group",
"at",
"the",
"given",
"logical",
"path",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L85-L90 |
234,771 | zarr-developers/zarr | zarr/storage.py | rmdir | def rmdir(store, path=None):
"""Remove all items under the given path. If `store` provides a `rmdir` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
path = normalize_storage_path(path)
if hasattr(store, 'rmdir'):
# pass through
store.rmdir(path)
else:
# slow version, delete one key at a time
_rmdir_from_keys(store, path) | python | def rmdir(store, path=None):
path = normalize_storage_path(path)
if hasattr(store, 'rmdir'):
# pass through
store.rmdir(path)
else:
# slow version, delete one key at a time
_rmdir_from_keys(store, path) | [
"def",
"rmdir",
"(",
"store",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"if",
"hasattr",
"(",
"store",
",",
"'rmdir'",
")",
":",
"# pass through",
"store",
".",
"rmdir",
"(",
"path",
")",
"else",
":",
... | Remove all items under the given path. If `store` provides a `rmdir` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface. | [
"Remove",
"all",
"items",
"under",
"the",
"given",
"path",
".",
"If",
"store",
"provides",
"a",
"rmdir",
"method",
"this",
"will",
"be",
"called",
"otherwise",
"will",
"fall",
"back",
"to",
"implementation",
"via",
"the",
"MutableMapping",
"interface",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L101-L111 |
234,772 | zarr-developers/zarr | zarr/storage.py | rename | def rename(store, src_path, dst_path):
"""Rename all items under the given path. If `store` provides a `rename` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
if hasattr(store, 'rename'):
# pass through
store.rename(src_path, dst_path)
else:
# slow version, delete one key at a time
_rename_from_keys(store, src_path, dst_path) | python | def rename(store, src_path, dst_path):
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
if hasattr(store, 'rename'):
# pass through
store.rename(src_path, dst_path)
else:
# slow version, delete one key at a time
_rename_from_keys(store, src_path, dst_path) | [
"def",
"rename",
"(",
"store",
",",
"src_path",
",",
"dst_path",
")",
":",
"src_path",
"=",
"normalize_storage_path",
"(",
"src_path",
")",
"dst_path",
"=",
"normalize_storage_path",
"(",
"dst_path",
")",
"if",
"hasattr",
"(",
"store",
",",
"'rename'",
")",
... | Rename all items under the given path. If `store` provides a `rename` method,
this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface. | [
"Rename",
"all",
"items",
"under",
"the",
"given",
"path",
".",
"If",
"store",
"provides",
"a",
"rename",
"method",
"this",
"will",
"be",
"called",
"otherwise",
"will",
"fall",
"back",
"to",
"implementation",
"via",
"the",
"MutableMapping",
"interface",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L124-L135 |
234,773 | zarr-developers/zarr | zarr/storage.py | listdir | def listdir(store, path=None):
"""Obtain a directory listing for the given path. If `store` provides a `listdir`
method, this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
path = normalize_storage_path(path)
if hasattr(store, 'listdir'):
# pass through
return store.listdir(path)
else:
# slow version, iterate through all keys
return _listdir_from_keys(store, path) | python | def listdir(store, path=None):
path = normalize_storage_path(path)
if hasattr(store, 'listdir'):
# pass through
return store.listdir(path)
else:
# slow version, iterate through all keys
return _listdir_from_keys(store, path) | [
"def",
"listdir",
"(",
"store",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"if",
"hasattr",
"(",
"store",
",",
"'listdir'",
")",
":",
"# pass through",
"return",
"store",
".",
"listdir",
"(",
"path",
")",... | Obtain a directory listing for the given path. If `store` provides a `listdir`
method, this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface. | [
"Obtain",
"a",
"directory",
"listing",
"for",
"the",
"given",
"path",
".",
"If",
"store",
"provides",
"a",
"listdir",
"method",
"this",
"will",
"be",
"called",
"otherwise",
"will",
"fall",
"back",
"to",
"implementation",
"via",
"the",
"MutableMapping",
"interf... | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L150-L160 |
234,774 | zarr-developers/zarr | zarr/storage.py | getsize | def getsize(store, path=None):
"""Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif isinstance(store, dict):
# compute from size of values
if path in store:
v = store[path]
size = buffer_size(v)
else:
members = listdir(store, path)
prefix = _path_to_prefix(path)
size = 0
for k in members:
try:
v = store[prefix + k]
except KeyError:
pass
else:
try:
size += buffer_size(v)
except TypeError:
return -1
return size
else:
return -1 | python | def getsize(store, path=None):
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif isinstance(store, dict):
# compute from size of values
if path in store:
v = store[path]
size = buffer_size(v)
else:
members = listdir(store, path)
prefix = _path_to_prefix(path)
size = 0
for k in members:
try:
v = store[prefix + k]
except KeyError:
pass
else:
try:
size += buffer_size(v)
except TypeError:
return -1
return size
else:
return -1 | [
"def",
"getsize",
"(",
"store",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"if",
"hasattr",
"(",
"store",
",",
"'getsize'",
")",
":",
"# pass through",
"return",
"store",
".",
"getsize",
"(",
"path",
")",... | Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1. | [
"Compute",
"size",
"of",
"stored",
"items",
"for",
"a",
"given",
"path",
".",
"If",
"store",
"provides",
"a",
"getsize",
"method",
"this",
"will",
"be",
"called",
"otherwise",
"will",
"return",
"-",
"1",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L163-L191 |
234,775 | zarr-developers/zarr | zarr/storage.py | init_array | def init_array(store, shape, chunks=True, dtype=None, compressor='default',
fill_value=None, order='C', overwrite=False, path=None,
chunk_store=None, filters=None, object_codec=None):
"""Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and bytes-like values.
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape. If True, will be guessed from `shape` and `dtype`. If
False, will be set to `shape`, i.e., single chunk for the whole array.
dtype : string or dtype, optional
NumPy dtype.
compressor : Codec, optional
Primary compressor.
fill_value : object
Default value to use for uninitialized portions of the array.
order : {'C', 'F'}, optional
Memory layout to be used within each chunk.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to compression.
object_codec : Codec, optional
A codec to encode object arrays, only needed if dtype=object.
Examples
--------
Initialize an array store::
>>> from zarr.storage import init_array
>>> store = dict()
>>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000))
>>> sorted(store.keys())
['.zarray']
Array metadata is stored as JSON::
>>> print(store['.zarray'].decode())
{
"chunks": [
1000,
1000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f8",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
10000,
10000
],
"zarr_format": 2
}
Initialize an array using a storage path::
>>> store = dict()
>>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo')
>>> sorted(store.keys())
['.zgroup', 'foo/.zarray']
>>> print(store['foo/.zarray'].decode())
{
"chunks": [
1000000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "|i1",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
100000000
],
"zarr_format": 2
}
Notes
-----
The initialisation process involves normalising all array metadata, encoding
as JSON and storing under the '.zarray' key.
"""
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite)
_init_array_metadata(store, shape=shape, chunks=chunks, dtype=dtype,
compressor=compressor, fill_value=fill_value,
order=order, overwrite=overwrite, path=path,
chunk_store=chunk_store, filters=filters,
object_codec=object_codec) | python | def init_array(store, shape, chunks=True, dtype=None, compressor='default',
fill_value=None, order='C', overwrite=False, path=None,
chunk_store=None, filters=None, object_codec=None):
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite)
_init_array_metadata(store, shape=shape, chunks=chunks, dtype=dtype,
compressor=compressor, fill_value=fill_value,
order=order, overwrite=overwrite, path=path,
chunk_store=chunk_store, filters=filters,
object_codec=object_codec) | [
"def",
"init_array",
"(",
"store",
",",
"shape",
",",
"chunks",
"=",
"True",
",",
"dtype",
"=",
"None",
",",
"compressor",
"=",
"'default'",
",",
"fill_value",
"=",
"None",
",",
"order",
"=",
"'C'",
",",
"overwrite",
"=",
"False",
",",
"path",
"=",
"... | Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and bytes-like values.
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape. If True, will be guessed from `shape` and `dtype`. If
False, will be set to `shape`, i.e., single chunk for the whole array.
dtype : string or dtype, optional
NumPy dtype.
compressor : Codec, optional
Primary compressor.
fill_value : object
Default value to use for uninitialized portions of the array.
order : {'C', 'F'}, optional
Memory layout to be used within each chunk.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to compression.
object_codec : Codec, optional
A codec to encode object arrays, only needed if dtype=object.
Examples
--------
Initialize an array store::
>>> from zarr.storage import init_array
>>> store = dict()
>>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000))
>>> sorted(store.keys())
['.zarray']
Array metadata is stored as JSON::
>>> print(store['.zarray'].decode())
{
"chunks": [
1000,
1000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f8",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
10000,
10000
],
"zarr_format": 2
}
Initialize an array using a storage path::
>>> store = dict()
>>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo')
>>> sorted(store.keys())
['.zgroup', 'foo/.zarray']
>>> print(store['foo/.zarray'].decode())
{
"chunks": [
1000000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "|i1",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
100000000
],
"zarr_format": 2
}
Notes
-----
The initialisation process involves normalising all array metadata, encoding
as JSON and storing under the '.zarray' key. | [
"Initialize",
"an",
"array",
"store",
"with",
"the",
"given",
"configuration",
".",
"Note",
"that",
"this",
"is",
"a",
"low",
"-",
"level",
"function",
"and",
"there",
"should",
"be",
"no",
"need",
"to",
"call",
"this",
"directly",
"from",
"user",
"code",
... | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L207-L323 |
234,776 | zarr-developers/zarr | zarr/storage.py | init_group | def init_group(store, overwrite=False, path=None, chunk_store=None):
"""Initialize a group store. Note that this is a low-level function and there should be no
need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and byte sequence values.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
"""
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store,
overwrite=overwrite)
# initialise metadata
_init_group_metadata(store=store, overwrite=overwrite, path=path,
chunk_store=chunk_store) | python | def init_group(store, overwrite=False, path=None, chunk_store=None):
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store,
overwrite=overwrite)
# initialise metadata
_init_group_metadata(store=store, overwrite=overwrite, path=path,
chunk_store=chunk_store) | [
"def",
"init_group",
"(",
"store",
",",
"overwrite",
"=",
"False",
",",
"path",
"=",
"None",
",",
"chunk_store",
"=",
"None",
")",
":",
"# normalize path",
"path",
"=",
"normalize_storage_path",
"(",
"path",
")",
"# ensure parent group initialized",
"_require_pare... | Initialize a group store. Note that this is a low-level function and there should be no
need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and byte sequence values.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata. | [
"Initialize",
"a",
"group",
"store",
".",
"Note",
"that",
"this",
"is",
"a",
"low",
"-",
"level",
"function",
"and",
"there",
"should",
"be",
"no",
"need",
"to",
"call",
"this",
"directly",
"from",
"user",
"code",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L405-L432 |
234,777 | zarr-developers/zarr | zarr/storage.py | atexit_rmtree | def atexit_rmtree(path,
isdir=os.path.isdir,
rmtree=shutil.rmtree): # pragma: no cover
"""Ensure directory removal at interpreter exit."""
if isdir(path):
rmtree(path) | python | def atexit_rmtree(path,
isdir=os.path.isdir,
rmtree=shutil.rmtree): # pragma: no cover
if isdir(path):
rmtree(path) | [
"def",
"atexit_rmtree",
"(",
"path",
",",
"isdir",
"=",
"os",
".",
"path",
".",
"isdir",
",",
"rmtree",
"=",
"shutil",
".",
"rmtree",
")",
":",
"# pragma: no cover",
"if",
"isdir",
"(",
"path",
")",
":",
"rmtree",
"(",
"path",
")"
] | Ensure directory removal at interpreter exit. | [
"Ensure",
"directory",
"removal",
"at",
"interpreter",
"exit",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L863-L868 |
234,778 | zarr-developers/zarr | zarr/storage.py | atexit_rmglob | def atexit_rmglob(path,
glob=glob.glob,
isdir=os.path.isdir,
isfile=os.path.isfile,
remove=os.remove,
rmtree=shutil.rmtree): # pragma: no cover
"""Ensure removal of multiple files at interpreter exit."""
for p in glob(path):
if isfile(p):
remove(p)
elif isdir(p):
rmtree(p) | python | def atexit_rmglob(path,
glob=glob.glob,
isdir=os.path.isdir,
isfile=os.path.isfile,
remove=os.remove,
rmtree=shutil.rmtree): # pragma: no cover
for p in glob(path):
if isfile(p):
remove(p)
elif isdir(p):
rmtree(p) | [
"def",
"atexit_rmglob",
"(",
"path",
",",
"glob",
"=",
"glob",
".",
"glob",
",",
"isdir",
"=",
"os",
".",
"path",
".",
"isdir",
",",
"isfile",
"=",
"os",
".",
"path",
".",
"isfile",
",",
"remove",
"=",
"os",
".",
"remove",
",",
"rmtree",
"=",
"sh... | Ensure removal of multiple files at interpreter exit. | [
"Ensure",
"removal",
"of",
"multiple",
"files",
"at",
"interpreter",
"exit",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L872-L883 |
234,779 | zarr-developers/zarr | zarr/storage.py | migrate_1to2 | def migrate_1to2(store):
"""Migrate array metadata in `store` from Zarr format version 1 to
version 2.
Parameters
----------
store : MutableMapping
Store to be migrated.
Notes
-----
Version 1 did not support hierarchies, so this migration function will
look for a single array in `store` and migrate the array metadata to
version 2.
"""
# migrate metadata
from zarr import meta_v1
meta = meta_v1.decode_metadata(store['meta'])
del store['meta']
# add empty filters
meta['filters'] = None
# migration compression metadata
compression = meta['compression']
if compression is None or compression == 'none':
compressor_config = None
else:
compression_opts = meta['compression_opts']
codec_cls = codec_registry[compression]
if isinstance(compression_opts, dict):
compressor = codec_cls(**compression_opts)
else:
compressor = codec_cls(compression_opts)
compressor_config = compressor.get_config()
meta['compressor'] = compressor_config
del meta['compression']
del meta['compression_opts']
# store migrated metadata
store[array_meta_key] = encode_array_metadata(meta)
# migrate user attributes
store[attrs_key] = store['attrs']
del store['attrs'] | python | def migrate_1to2(store):
# migrate metadata
from zarr import meta_v1
meta = meta_v1.decode_metadata(store['meta'])
del store['meta']
# add empty filters
meta['filters'] = None
# migration compression metadata
compression = meta['compression']
if compression is None or compression == 'none':
compressor_config = None
else:
compression_opts = meta['compression_opts']
codec_cls = codec_registry[compression]
if isinstance(compression_opts, dict):
compressor = codec_cls(**compression_opts)
else:
compressor = codec_cls(compression_opts)
compressor_config = compressor.get_config()
meta['compressor'] = compressor_config
del meta['compression']
del meta['compression_opts']
# store migrated metadata
store[array_meta_key] = encode_array_metadata(meta)
# migrate user attributes
store[attrs_key] = store['attrs']
del store['attrs'] | [
"def",
"migrate_1to2",
"(",
"store",
")",
":",
"# migrate metadata",
"from",
"zarr",
"import",
"meta_v1",
"meta",
"=",
"meta_v1",
".",
"decode_metadata",
"(",
"store",
"[",
"'meta'",
"]",
")",
"del",
"store",
"[",
"'meta'",
"]",
"# add empty filters",
"meta",
... | Migrate array metadata in `store` from Zarr format version 1 to
version 2.
Parameters
----------
store : MutableMapping
Store to be migrated.
Notes
-----
Version 1 did not support hierarchies, so this migration function will
look for a single array in `store` and migrate the array metadata to
version 2. | [
"Migrate",
"array",
"metadata",
"in",
"store",
"from",
"Zarr",
"format",
"version",
"1",
"to",
"version",
"2",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1260-L1306 |
234,780 | zarr-developers/zarr | zarr/storage.py | ZipStore.flush | def flush(self):
"""Closes the underlying zip file, ensuring all records are written,
then re-opens the file for further modifications."""
if self.mode != 'r':
with self.mutex:
self.zf.close()
# N.B., re-open with mode 'a' regardless of initial mode so we don't wipe
# what's been written
self.zf = zipfile.ZipFile(self.path, mode='a',
compression=self.compression,
allowZip64=self.allowZip64) | python | def flush(self):
if self.mode != 'r':
with self.mutex:
self.zf.close()
# N.B., re-open with mode 'a' regardless of initial mode so we don't wipe
# what's been written
self.zf = zipfile.ZipFile(self.path, mode='a',
compression=self.compression,
allowZip64=self.allowZip64) | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"!=",
"'r'",
":",
"with",
"self",
".",
"mutex",
":",
"self",
".",
"zf",
".",
"close",
"(",
")",
"# N.B., re-open with mode 'a' regardless of initial mode so we don't wipe",
"# what's been written",
... | Closes the underlying zip file, ensuring all records are written,
then re-opens the file for further modifications. | [
"Closes",
"the",
"underlying",
"zip",
"file",
"ensuring",
"all",
"records",
"are",
"written",
"then",
"re",
"-",
"opens",
"the",
"file",
"for",
"further",
"modifications",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1154-L1164 |
234,781 | zarr-developers/zarr | zarr/storage.py | DBMStore.close | def close(self):
"""Closes the underlying database file."""
if hasattr(self.db, 'close'):
with self.write_mutex:
self.db.close() | python | def close(self):
if hasattr(self.db, 'close'):
with self.write_mutex:
self.db.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"db",
",",
"'close'",
")",
":",
"with",
"self",
".",
"write_mutex",
":",
"self",
".",
"db",
".",
"close",
"(",
")"
] | Closes the underlying database file. | [
"Closes",
"the",
"underlying",
"database",
"file",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1442-L1446 |
234,782 | zarr-developers/zarr | zarr/storage.py | DBMStore.flush | def flush(self):
"""Synchronizes data to the underlying database file."""
if self.flag[0] != 'r':
with self.write_mutex:
if hasattr(self.db, 'sync'):
self.db.sync()
else:
# fall-back, close and re-open, needed for ndbm
flag = self.flag
if flag[0] == 'n':
flag = 'c' + flag[1:] # don't clobber an existing database
self.db.close()
# noinspection PyArgumentList
self.db = self.open(self.path, flag, self.mode, **self.open_kwargs) | python | def flush(self):
if self.flag[0] != 'r':
with self.write_mutex:
if hasattr(self.db, 'sync'):
self.db.sync()
else:
# fall-back, close and re-open, needed for ndbm
flag = self.flag
if flag[0] == 'n':
flag = 'c' + flag[1:] # don't clobber an existing database
self.db.close()
# noinspection PyArgumentList
self.db = self.open(self.path, flag, self.mode, **self.open_kwargs) | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"flag",
"[",
"0",
"]",
"!=",
"'r'",
":",
"with",
"self",
".",
"write_mutex",
":",
"if",
"hasattr",
"(",
"self",
".",
"db",
",",
"'sync'",
")",
":",
"self",
".",
"db",
".",
"sync",
"(",
... | Synchronizes data to the underlying database file. | [
"Synchronizes",
"data",
"to",
"the",
"underlying",
"database",
"file",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1448-L1461 |
234,783 | zarr-developers/zarr | zarr/indexing.py | oindex | def oindex(a, selection):
"""Implementation of orthogonal indexing with slices and ints."""
selection = replace_ellipsis(selection, a.shape)
drop_axes = tuple([i for i, s in enumerate(selection) if is_integer(s)])
selection = ix_(selection, a.shape)
result = a[selection]
if drop_axes:
result = result.squeeze(axis=drop_axes)
return result | python | def oindex(a, selection):
selection = replace_ellipsis(selection, a.shape)
drop_axes = tuple([i for i, s in enumerate(selection) if is_integer(s)])
selection = ix_(selection, a.shape)
result = a[selection]
if drop_axes:
result = result.squeeze(axis=drop_axes)
return result | [
"def",
"oindex",
"(",
"a",
",",
"selection",
")",
":",
"selection",
"=",
"replace_ellipsis",
"(",
"selection",
",",
"a",
".",
"shape",
")",
"drop_axes",
"=",
"tuple",
"(",
"[",
"i",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"selection",
")",
"if"... | Implementation of orthogonal indexing with slices and ints. | [
"Implementation",
"of",
"orthogonal",
"indexing",
"with",
"slices",
"and",
"ints",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/indexing.py#L496-L504 |
234,784 | zarr-developers/zarr | zarr/n5.py | array_metadata_to_n5 | def array_metadata_to_n5(array_metadata):
'''Convert array metadata from zarr to N5 format.'''
for f, t in zarr_to_n5_keys:
array_metadata[t] = array_metadata[f]
del array_metadata[f]
del array_metadata['zarr_format']
try:
dtype = np.dtype(array_metadata['dataType'])
except TypeError: # pragma: no cover
raise TypeError(
"data type %s not supported by N5" % array_metadata['dataType'])
array_metadata['dataType'] = dtype.name
array_metadata['dimensions'] = array_metadata['dimensions'][::-1]
array_metadata['blockSize'] = array_metadata['blockSize'][::-1]
if 'fill_value' in array_metadata:
if array_metadata['fill_value'] != 0 and array_metadata['fill_value'] is not None:
raise ValueError("N5 only supports fill_value == 0 (for now)")
del array_metadata['fill_value']
if 'order' in array_metadata:
if array_metadata['order'] != 'C':
raise ValueError("zarr N5 storage only stores arrays in C order (for now)")
del array_metadata['order']
if 'filters' in array_metadata:
if array_metadata['filters'] != [] and array_metadata['filters'] is not None:
raise ValueError("N5 storage does not support zarr filters")
del array_metadata['filters']
assert 'compression' in array_metadata
compressor_config = array_metadata['compression']
compressor_config = compressor_config_to_n5(compressor_config)
array_metadata['compression'] = compressor_config
return array_metadata | python | def array_metadata_to_n5(array_metadata):
'''Convert array metadata from zarr to N5 format.'''
for f, t in zarr_to_n5_keys:
array_metadata[t] = array_metadata[f]
del array_metadata[f]
del array_metadata['zarr_format']
try:
dtype = np.dtype(array_metadata['dataType'])
except TypeError: # pragma: no cover
raise TypeError(
"data type %s not supported by N5" % array_metadata['dataType'])
array_metadata['dataType'] = dtype.name
array_metadata['dimensions'] = array_metadata['dimensions'][::-1]
array_metadata['blockSize'] = array_metadata['blockSize'][::-1]
if 'fill_value' in array_metadata:
if array_metadata['fill_value'] != 0 and array_metadata['fill_value'] is not None:
raise ValueError("N5 only supports fill_value == 0 (for now)")
del array_metadata['fill_value']
if 'order' in array_metadata:
if array_metadata['order'] != 'C':
raise ValueError("zarr N5 storage only stores arrays in C order (for now)")
del array_metadata['order']
if 'filters' in array_metadata:
if array_metadata['filters'] != [] and array_metadata['filters'] is not None:
raise ValueError("N5 storage does not support zarr filters")
del array_metadata['filters']
assert 'compression' in array_metadata
compressor_config = array_metadata['compression']
compressor_config = compressor_config_to_n5(compressor_config)
array_metadata['compression'] = compressor_config
return array_metadata | [
"def",
"array_metadata_to_n5",
"(",
"array_metadata",
")",
":",
"for",
"f",
",",
"t",
"in",
"zarr_to_n5_keys",
":",
"array_metadata",
"[",
"t",
"]",
"=",
"array_metadata",
"[",
"f",
"]",
"del",
"array_metadata",
"[",
"f",
"]",
"del",
"array_metadata",
"[",
... | Convert array metadata from zarr to N5 format. | [
"Convert",
"array",
"metadata",
"from",
"zarr",
"to",
"N5",
"format",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/n5.py#L316-L354 |
234,785 | zarr-developers/zarr | zarr/n5.py | array_metadata_to_zarr | def array_metadata_to_zarr(array_metadata):
'''Convert array metadata from N5 to zarr format.'''
for t, f in zarr_to_n5_keys:
array_metadata[t] = array_metadata[f]
del array_metadata[f]
array_metadata['zarr_format'] = ZARR_FORMAT
array_metadata['shape'] = array_metadata['shape'][::-1]
array_metadata['chunks'] = array_metadata['chunks'][::-1]
array_metadata['fill_value'] = 0 # also if None was requested
array_metadata['order'] = 'C'
array_metadata['filters'] = []
compressor_config = array_metadata['compressor']
compressor_config = compressor_config_to_zarr(compressor_config)
array_metadata['compressor'] = {
'id': N5ChunkWrapper.codec_id,
'compressor_config': compressor_config,
'dtype': array_metadata['dtype'],
'chunk_shape': array_metadata['chunks']
}
return array_metadata | python | def array_metadata_to_zarr(array_metadata):
'''Convert array metadata from N5 to zarr format.'''
for t, f in zarr_to_n5_keys:
array_metadata[t] = array_metadata[f]
del array_metadata[f]
array_metadata['zarr_format'] = ZARR_FORMAT
array_metadata['shape'] = array_metadata['shape'][::-1]
array_metadata['chunks'] = array_metadata['chunks'][::-1]
array_metadata['fill_value'] = 0 # also if None was requested
array_metadata['order'] = 'C'
array_metadata['filters'] = []
compressor_config = array_metadata['compressor']
compressor_config = compressor_config_to_zarr(compressor_config)
array_metadata['compressor'] = {
'id': N5ChunkWrapper.codec_id,
'compressor_config': compressor_config,
'dtype': array_metadata['dtype'],
'chunk_shape': array_metadata['chunks']
}
return array_metadata | [
"def",
"array_metadata_to_zarr",
"(",
"array_metadata",
")",
":",
"for",
"t",
",",
"f",
"in",
"zarr_to_n5_keys",
":",
"array_metadata",
"[",
"t",
"]",
"=",
"array_metadata",
"[",
"f",
"]",
"del",
"array_metadata",
"[",
"f",
"]",
"array_metadata",
"[",
"'zarr... | Convert array metadata from N5 to zarr format. | [
"Convert",
"array",
"metadata",
"from",
"N5",
"to",
"zarr",
"format",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/n5.py#L357-L379 |
234,786 | zarr-developers/zarr | zarr/core.py | Array.name | def name(self):
"""Array name following h5py convention."""
if self.path:
# follow h5py convention: add leading slash
name = self.path
if name[0] != '/':
name = '/' + name
return name
return None | python | def name(self):
if self.path:
# follow h5py convention: add leading slash
name = self.path
if name[0] != '/':
name = '/' + name
return name
return None | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
":",
"# follow h5py convention: add leading slash",
"name",
"=",
"self",
".",
"path",
"if",
"name",
"[",
"0",
"]",
"!=",
"'/'",
":",
"name",
"=",
"'/'",
"+",
"name",
"return",
"name",
"re... | Array name following h5py convention. | [
"Array",
"name",
"following",
"h5py",
"convention",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L214-L222 |
234,787 | zarr-developers/zarr | zarr/core.py | Array.nbytes_stored | def nbytes_stored(self):
"""The total number of stored bytes of data for the array. This
includes storage required for configuration metadata and user
attributes."""
m = getsize(self._store, self._path)
if self._chunk_store is None:
return m
else:
n = getsize(self._chunk_store, self._path)
if m < 0 or n < 0:
return -1
else:
return m + n | python | def nbytes_stored(self):
m = getsize(self._store, self._path)
if self._chunk_store is None:
return m
else:
n = getsize(self._chunk_store, self._path)
if m < 0 or n < 0:
return -1
else:
return m + n | [
"def",
"nbytes_stored",
"(",
"self",
")",
":",
"m",
"=",
"getsize",
"(",
"self",
".",
"_store",
",",
"self",
".",
"_path",
")",
"if",
"self",
".",
"_chunk_store",
"is",
"None",
":",
"return",
"m",
"else",
":",
"n",
"=",
"getsize",
"(",
"self",
".",... | The total number of stored bytes of data for the array. This
includes storage required for configuration metadata and user
attributes. | [
"The",
"total",
"number",
"of",
"stored",
"bytes",
"of",
"data",
"for",
"the",
"array",
".",
"This",
"includes",
"storage",
"required",
"for",
"configuration",
"metadata",
"and",
"user",
"attributes",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L340-L352 |
234,788 | zarr-developers/zarr | zarr/core.py | Array.nchunks_initialized | def nchunks_initialized(self):
"""The number of chunks that have been initialized with some data."""
# key pattern for chunk keys
prog = re.compile(r'\.'.join([r'\d+'] * min(1, self.ndim)))
# count chunk keys
return sum(1 for k in listdir(self.chunk_store, self._path) if prog.match(k)) | python | def nchunks_initialized(self):
# key pattern for chunk keys
prog = re.compile(r'\.'.join([r'\d+'] * min(1, self.ndim)))
# count chunk keys
return sum(1 for k in listdir(self.chunk_store, self._path) if prog.match(k)) | [
"def",
"nchunks_initialized",
"(",
"self",
")",
":",
"# key pattern for chunk keys",
"prog",
"=",
"re",
".",
"compile",
"(",
"r'\\.'",
".",
"join",
"(",
"[",
"r'\\d+'",
"]",
"*",
"min",
"(",
"1",
",",
"self",
".",
"ndim",
")",
")",
")",
"# count chunk ke... | The number of chunks that have been initialized with some data. | [
"The",
"number",
"of",
"chunks",
"that",
"have",
"been",
"initialized",
"with",
"some",
"data",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L380-L387 |
234,789 | zarr-developers/zarr | zarr/core.py | Array.get_basic_selection | def get_basic_selection(self, selection=Ellipsis, out=None, fields=None):
"""Retrieve data for an item or region of the array.
Parameters
----------
selection : tuple
A tuple specifying the requested item or region for each dimension of the
array. May be any combination of int and/or slice for multidimensional arrays.
out : ndarray, optional
If given, load the selected data directly into this array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to
extract data for.
Returns
-------
out : ndarray
A NumPy array containing the data for the requested region.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100))
Retrieve a single item::
>>> z.get_basic_selection(5)
5
Retrieve a region via slicing::
>>> z.get_basic_selection(slice(5))
array([0, 1, 2, 3, 4])
>>> z.get_basic_selection(slice(-5, None))
array([95, 96, 97, 98, 99])
>>> z.get_basic_selection(slice(5, 10))
array([5, 6, 7, 8, 9])
>>> z.get_basic_selection(slice(5, 10, 2))
array([5, 7, 9])
>>> z.get_basic_selection(slice(None, None, 2))
array([ 0, 2, 4, ..., 94, 96, 98])
Setup a 2-dimensional array::
>>> z = zarr.array(np.arange(100).reshape(10, 10))
Retrieve an item::
>>> z.get_basic_selection((2, 2))
22
Retrieve a region via slicing::
>>> z.get_basic_selection((slice(1, 3), slice(1, 3)))
array([[11, 12],
[21, 22]])
>>> z.get_basic_selection((slice(1, 3), slice(None)))
array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])
>>> z.get_basic_selection((slice(None), slice(1, 3)))
array([[ 1, 2],
[11, 12],
[21, 22],
[31, 32],
[41, 42],
[51, 52],
[61, 62],
[71, 72],
[81, 82],
[91, 92]])
>>> z.get_basic_selection((slice(0, 5, 2), slice(0, 5, 2)))
array([[ 0, 2, 4],
[20, 22, 24],
[40, 42, 44]])
>>> z.get_basic_selection((slice(None, None, 2), slice(None, None, 2)))
array([[ 0, 2, 4, 6, 8],
[20, 22, 24, 26, 28],
[40, 42, 44, 46, 48],
[60, 62, 64, 66, 68],
[80, 82, 84, 86, 88]])
For arrays with a structured dtype, specific fields can be retrieved, e.g.::
>>> a = np.array([(b'aaa', 1, 4.2),
... (b'bbb', 2, 8.4),
... (b'ccc', 3, 12.6)],
... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
>>> z = zarr.array(a)
>>> z.get_basic_selection(slice(2), fields='foo')
array([b'aaa', b'bbb'],
dtype='|S3')
Notes
-----
Slices with step > 1 are supported, but slices with negative step are not.
Currently this method provides the implementation for accessing data via the
square bracket notation (__getitem__). See :func:`__getitem__` for examples
using the alternative notation.
See Also
--------
set_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__
"""
# refresh metadata
if not self._cache_metadata:
self._load_metadata()
# check args
check_fields(fields, self._dtype)
# handle zero-dimensional arrays
if self._shape == ():
return self._get_basic_selection_zd(selection=selection, out=out,
fields=fields)
else:
return self._get_basic_selection_nd(selection=selection, out=out,
fields=fields) | python | def get_basic_selection(self, selection=Ellipsis, out=None, fields=None):
# refresh metadata
if not self._cache_metadata:
self._load_metadata()
# check args
check_fields(fields, self._dtype)
# handle zero-dimensional arrays
if self._shape == ():
return self._get_basic_selection_zd(selection=selection, out=out,
fields=fields)
else:
return self._get_basic_selection_nd(selection=selection, out=out,
fields=fields) | [
"def",
"get_basic_selection",
"(",
"self",
",",
"selection",
"=",
"Ellipsis",
",",
"out",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"# refresh metadata",
"if",
"not",
"self",
".",
"_cache_metadata",
":",
"self",
".",
"_load_metadata",
"(",
")",
"#... | Retrieve data for an item or region of the array.
Parameters
----------
selection : tuple
A tuple specifying the requested item or region for each dimension of the
array. May be any combination of int and/or slice for multidimensional arrays.
out : ndarray, optional
If given, load the selected data directly into this array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to
extract data for.
Returns
-------
out : ndarray
A NumPy array containing the data for the requested region.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100))
Retrieve a single item::
>>> z.get_basic_selection(5)
5
Retrieve a region via slicing::
>>> z.get_basic_selection(slice(5))
array([0, 1, 2, 3, 4])
>>> z.get_basic_selection(slice(-5, None))
array([95, 96, 97, 98, 99])
>>> z.get_basic_selection(slice(5, 10))
array([5, 6, 7, 8, 9])
>>> z.get_basic_selection(slice(5, 10, 2))
array([5, 7, 9])
>>> z.get_basic_selection(slice(None, None, 2))
array([ 0, 2, 4, ..., 94, 96, 98])
Setup a 2-dimensional array::
>>> z = zarr.array(np.arange(100).reshape(10, 10))
Retrieve an item::
>>> z.get_basic_selection((2, 2))
22
Retrieve a region via slicing::
>>> z.get_basic_selection((slice(1, 3), slice(1, 3)))
array([[11, 12],
[21, 22]])
>>> z.get_basic_selection((slice(1, 3), slice(None)))
array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])
>>> z.get_basic_selection((slice(None), slice(1, 3)))
array([[ 1, 2],
[11, 12],
[21, 22],
[31, 32],
[41, 42],
[51, 52],
[61, 62],
[71, 72],
[81, 82],
[91, 92]])
>>> z.get_basic_selection((slice(0, 5, 2), slice(0, 5, 2)))
array([[ 0, 2, 4],
[20, 22, 24],
[40, 42, 44]])
>>> z.get_basic_selection((slice(None, None, 2), slice(None, None, 2)))
array([[ 0, 2, 4, 6, 8],
[20, 22, 24, 26, 28],
[40, 42, 44, 46, 48],
[60, 62, 64, 66, 68],
[80, 82, 84, 86, 88]])
For arrays with a structured dtype, specific fields can be retrieved, e.g.::
>>> a = np.array([(b'aaa', 1, 4.2),
... (b'bbb', 2, 8.4),
... (b'ccc', 3, 12.6)],
... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
>>> z = zarr.array(a)
>>> z.get_basic_selection(slice(2), fields='foo')
array([b'aaa', b'bbb'],
dtype='|S3')
Notes
-----
Slices with step > 1 are supported, but slices with negative step are not.
Currently this method provides the implementation for accessing data via the
square bracket notation (__getitem__). See :func:`__getitem__` for examples
using the alternative notation.
See Also
--------
set_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__ | [
"Retrieve",
"data",
"for",
"an",
"item",
"or",
"region",
"of",
"the",
"array",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L574-L698 |
234,790 | zarr-developers/zarr | zarr/core.py | Array.get_mask_selection | def get_mask_selection(self, selection, out=None, fields=None):
"""Retrieve a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
selection : ndarray, bool
A Boolean array of the same shape as the array against which the selection is
being made.
out : ndarray, optional
If given, load the selected data directly into this array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to
extract data for.
Returns
-------
out : ndarray
A NumPy array containing the data for the requested selection.
Examples
--------
Setup a 2-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100).reshape(10, 10))
Retrieve items by specifying a maks::
>>> sel = np.zeros_like(z, dtype=bool)
>>> sel[1, 1] = True
>>> sel[4, 4] = True
>>> z.get_mask_selection(sel)
array([11, 44])
For convenience, the mask selection functionality is also available via the
`vindex` property, e.g.::
>>> z.vindex[sel]
array([11, 44])
Notes
-----
Mask indexing is a form of vectorized or inner indexing, and is equivalent to
coordinate indexing. Internally the mask array is converted to coordinate
arrays by calling `np.nonzero`.
See Also
--------
get_basic_selection, set_basic_selection, set_mask_selection,
get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,
set_coordinate_selection, vindex, oindex, __getitem__, __setitem__
"""
# refresh metadata
if not self._cache_metadata:
self._load_metadata()
# check args
check_fields(fields, self._dtype)
# setup indexer
indexer = MaskIndexer(selection, self)
return self._get_selection(indexer=indexer, out=out, fields=fields) | python | def get_mask_selection(self, selection, out=None, fields=None):
# refresh metadata
if not self._cache_metadata:
self._load_metadata()
# check args
check_fields(fields, self._dtype)
# setup indexer
indexer = MaskIndexer(selection, self)
return self._get_selection(indexer=indexer, out=out, fields=fields) | [
"def",
"get_mask_selection",
"(",
"self",
",",
"selection",
",",
"out",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"# refresh metadata",
"if",
"not",
"self",
".",
"_cache_metadata",
":",
"self",
".",
"_load_metadata",
"(",
")",
"# check args",
"check... | Retrieve a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
selection : ndarray, bool
A Boolean array of the same shape as the array against which the selection is
being made.
out : ndarray, optional
If given, load the selected data directly into this array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to
extract data for.
Returns
-------
out : ndarray
A NumPy array containing the data for the requested selection.
Examples
--------
Setup a 2-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100).reshape(10, 10))
Retrieve items by specifying a maks::
>>> sel = np.zeros_like(z, dtype=bool)
>>> sel[1, 1] = True
>>> sel[4, 4] = True
>>> z.get_mask_selection(sel)
array([11, 44])
For convenience, the mask selection functionality is also available via the
`vindex` property, e.g.::
>>> z.vindex[sel]
array([11, 44])
Notes
-----
Mask indexing is a form of vectorized or inner indexing, and is equivalent to
coordinate indexing. Internally the mask array is converted to coordinate
arrays by calling `np.nonzero`.
See Also
--------
get_basic_selection, set_basic_selection, set_mask_selection,
get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,
set_coordinate_selection, vindex, oindex, __getitem__, __setitem__ | [
"Retrieve",
"a",
"selection",
"of",
"individual",
"items",
"by",
"providing",
"a",
"Boolean",
"array",
"of",
"the",
"same",
"shape",
"as",
"the",
"array",
"against",
"which",
"the",
"selection",
"is",
"being",
"made",
"where",
"True",
"values",
"indicate",
"... | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L933-L1000 |
234,791 | zarr-developers/zarr | zarr/core.py | Array.set_basic_selection | def set_basic_selection(self, selection, value, fields=None):
"""Modify data for an item or region of the array.
Parameters
----------
selection : tuple
An integer index or slice or tuple of int/slice specifying the requested
region for each dimension of the array.
value : scalar or array-like
Value to be stored into the array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to set
data for.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.zeros(100, dtype=int)
Set all array elements to the same scalar value::
>>> z.set_basic_selection(..., 42)
>>> z[...]
array([42, 42, 42, ..., 42, 42, 42])
Set a portion of the array::
>>> z.set_basic_selection(slice(10), np.arange(10))
>>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1])
>>> z[...]
array([ 0, 1, 2, ..., 2, 1, 0])
Setup a 2-dimensional array::
>>> z = zarr.zeros((5, 5), dtype=int)
Set all array elements to the same scalar value::
>>> z.set_basic_selection(..., 42)
Set a portion of the array::
>>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1]))
>>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0]))
>>> z[...]
array([[ 0, 1, 2, 3, 4],
[ 1, 42, 42, 42, 42],
[ 2, 42, 42, 42, 42],
[ 3, 42, 42, 42, 42],
[ 4, 42, 42, 42, 42]])
For arrays with a structured dtype, the `fields` parameter can be used to set
data for a specific field, e.g.::
>>> a = np.array([(b'aaa', 1, 4.2),
... (b'bbb', 2, 8.4),
... (b'ccc', 3, 12.6)],
... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
>>> z = zarr.array(a)
>>> z.set_basic_selection(slice(0, 2), b'zzz', fields='foo')
>>> z[:]
array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'ccc', 3, 12.6)],
dtype=[('foo', 'S3'), ('bar', '<i4'), ('baz', '<f8')])
Notes
-----
This method provides the underlying implementation for modifying data via square
bracket notation, see :func:`__setitem__` for equivalent examples using the
alternative notation.
See Also
--------
get_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__
"""
# guard conditions
if self._read_only:
err_read_only()
# refresh metadata
if not self._cache_metadata:
self._load_metadata_nosync()
# handle zero-dimensional arrays
if self._shape == ():
return self._set_basic_selection_zd(selection, value, fields=fields)
else:
return self._set_basic_selection_nd(selection, value, fields=fields) | python | def set_basic_selection(self, selection, value, fields=None):
# guard conditions
if self._read_only:
err_read_only()
# refresh metadata
if not self._cache_metadata:
self._load_metadata_nosync()
# handle zero-dimensional arrays
if self._shape == ():
return self._set_basic_selection_zd(selection, value, fields=fields)
else:
return self._set_basic_selection_nd(selection, value, fields=fields) | [
"def",
"set_basic_selection",
"(",
"self",
",",
"selection",
",",
"value",
",",
"fields",
"=",
"None",
")",
":",
"# guard conditions",
"if",
"self",
".",
"_read_only",
":",
"err_read_only",
"(",
")",
"# refresh metadata",
"if",
"not",
"self",
".",
"_cache_meta... | Modify data for an item or region of the array.
Parameters
----------
selection : tuple
An integer index or slice or tuple of int/slice specifying the requested
region for each dimension of the array.
value : scalar or array-like
Value to be stored into the array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to set
data for.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.zeros(100, dtype=int)
Set all array elements to the same scalar value::
>>> z.set_basic_selection(..., 42)
>>> z[...]
array([42, 42, 42, ..., 42, 42, 42])
Set a portion of the array::
>>> z.set_basic_selection(slice(10), np.arange(10))
>>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1])
>>> z[...]
array([ 0, 1, 2, ..., 2, 1, 0])
Setup a 2-dimensional array::
>>> z = zarr.zeros((5, 5), dtype=int)
Set all array elements to the same scalar value::
>>> z.set_basic_selection(..., 42)
Set a portion of the array::
>>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1]))
>>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0]))
>>> z[...]
array([[ 0, 1, 2, 3, 4],
[ 1, 42, 42, 42, 42],
[ 2, 42, 42, 42, 42],
[ 3, 42, 42, 42, 42],
[ 4, 42, 42, 42, 42]])
For arrays with a structured dtype, the `fields` parameter can be used to set
data for a specific field, e.g.::
>>> a = np.array([(b'aaa', 1, 4.2),
... (b'bbb', 2, 8.4),
... (b'ccc', 3, 12.6)],
... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
>>> z = zarr.array(a)
>>> z.set_basic_selection(slice(0, 2), b'zzz', fields='foo')
>>> z[:]
array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'ccc', 3, 12.6)],
dtype=[('foo', 'S3'), ('bar', '<i4'), ('baz', '<f8')])
Notes
-----
This method provides the underlying implementation for modifying data via square
bracket notation, see :func:`__setitem__` for equivalent examples using the
alternative notation.
See Also
--------
get_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__ | [
"Modify",
"data",
"for",
"an",
"item",
"or",
"region",
"of",
"the",
"array",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1117-L1210 |
234,792 | zarr-developers/zarr | zarr/core.py | Array.set_orthogonal_selection | def set_orthogonal_selection(self, selection, value, fields=None):
"""Modify data via a selection for each dimension of the array.
Parameters
----------
selection : tuple
A selection for each dimension of the array. May be any combination of int,
slice, integer array or Boolean array.
value : scalar or array-like
Value to be stored into the array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to set
data for.
Examples
--------
Setup a 2-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.zeros((5, 5), dtype=int)
Set data for a selection of rows::
>>> z.set_orthogonal_selection(([1, 4], slice(None)), 1)
>>> z[...]
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1]])
Set data for a selection of columns::
>>> z.set_orthogonal_selection((slice(None), [1, 4]), 2)
>>> z[...]
array([[0, 2, 0, 0, 2],
[1, 2, 1, 1, 2],
[0, 2, 0, 0, 2],
[0, 2, 0, 0, 2],
[1, 2, 1, 1, 2]])
Set data for a selection of rows and columns::
>>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3)
>>> z[...]
array([[0, 2, 0, 0, 2],
[1, 3, 1, 1, 3],
[0, 2, 0, 0, 2],
[0, 2, 0, 0, 2],
[1, 3, 1, 1, 3]])
For convenience, this functionality is also available via the `oindex` property.
E.g.::
>>> z.oindex[[1, 4], [1, 4]] = 4
>>> z[...]
array([[0, 2, 0, 0, 2],
[1, 4, 1, 1, 4],
[0, 2, 0, 0, 2],
[0, 2, 0, 0, 2],
[1, 4, 1, 1, 4]])
Notes
-----
Orthogonal indexing is also known as outer indexing.
Slices with step > 1 are supported, but slices with negative step are not.
See Also
--------
get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
vindex, oindex, __getitem__, __setitem__
"""
# guard conditions
if self._read_only:
err_read_only()
# refresh metadata
if not self._cache_metadata:
self._load_metadata_nosync()
# setup indexer
indexer = OrthogonalIndexer(selection, self)
self._set_selection(indexer, value, fields=fields) | python | def set_orthogonal_selection(self, selection, value, fields=None):
# guard conditions
if self._read_only:
err_read_only()
# refresh metadata
if not self._cache_metadata:
self._load_metadata_nosync()
# setup indexer
indexer = OrthogonalIndexer(selection, self)
self._set_selection(indexer, value, fields=fields) | [
"def",
"set_orthogonal_selection",
"(",
"self",
",",
"selection",
",",
"value",
",",
"fields",
"=",
"None",
")",
":",
"# guard conditions",
"if",
"self",
".",
"_read_only",
":",
"err_read_only",
"(",
")",
"# refresh metadata",
"if",
"not",
"self",
".",
"_cache... | Modify data via a selection for each dimension of the array.
Parameters
----------
selection : tuple
A selection for each dimension of the array. May be any combination of int,
slice, integer array or Boolean array.
value : scalar or array-like
Value to be stored into the array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to set
data for.
Examples
--------
Setup a 2-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.zeros((5, 5), dtype=int)
Set data for a selection of rows::
>>> z.set_orthogonal_selection(([1, 4], slice(None)), 1)
>>> z[...]
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1]])
Set data for a selection of columns::
>>> z.set_orthogonal_selection((slice(None), [1, 4]), 2)
>>> z[...]
array([[0, 2, 0, 0, 2],
[1, 2, 1, 1, 2],
[0, 2, 0, 0, 2],
[0, 2, 0, 0, 2],
[1, 2, 1, 1, 2]])
Set data for a selection of rows and columns::
>>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3)
>>> z[...]
array([[0, 2, 0, 0, 2],
[1, 3, 1, 1, 3],
[0, 2, 0, 0, 2],
[0, 2, 0, 0, 2],
[1, 3, 1, 1, 3]])
For convenience, this functionality is also available via the `oindex` property.
E.g.::
>>> z.oindex[[1, 4], [1, 4]] = 4
>>> z[...]
array([[0, 2, 0, 0, 2],
[1, 4, 1, 1, 4],
[0, 2, 0, 0, 2],
[0, 2, 0, 0, 2],
[1, 4, 1, 1, 4]])
Notes
-----
Orthogonal indexing is also known as outer indexing.
Slices with step > 1 are supported, but slices with negative step are not.
See Also
--------
get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
vindex, oindex, __getitem__, __setitem__ | [
"Modify",
"data",
"via",
"a",
"selection",
"for",
"each",
"dimension",
"of",
"the",
"array",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1212-L1300 |
234,793 | zarr-developers/zarr | zarr/core.py | Array.set_mask_selection | def set_mask_selection(self, selection, value, fields=None):
"""Modify a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
selection : ndarray, bool
A Boolean array of the same shape as the array against which the selection is
being made.
value : scalar or array-like
Value to be stored into the array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to set
data for.
Examples
--------
Setup a 2-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.zeros((5, 5), dtype=int)
Set data for a selection of items::
>>> sel = np.zeros_like(z, dtype=bool)
>>> sel[1, 1] = True
>>> sel[4, 4] = True
>>> z.set_mask_selection(sel, 1)
>>> z[...]
array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]])
For convenience, this functionality is also available via the `vindex` property.
E.g.::
>>> z.vindex[sel] = 2
>>> z[...]
array([[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 2]])
Notes
-----
Mask indexing is a form of vectorized or inner indexing, and is equivalent to
coordinate indexing. Internally the mask array is converted to coordinate
arrays by calling `np.nonzero`.
See Also
--------
get_basic_selection, set_basic_selection, get_mask_selection,
get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,
set_coordinate_selection, vindex, oindex, __getitem__, __setitem__
"""
# guard conditions
if self._read_only:
err_read_only()
# refresh metadata
if not self._cache_metadata:
self._load_metadata_nosync()
# setup indexer
indexer = MaskIndexer(selection, self)
self._set_selection(indexer, value, fields=fields) | python | def set_mask_selection(self, selection, value, fields=None):
# guard conditions
if self._read_only:
err_read_only()
# refresh metadata
if not self._cache_metadata:
self._load_metadata_nosync()
# setup indexer
indexer = MaskIndexer(selection, self)
self._set_selection(indexer, value, fields=fields) | [
"def",
"set_mask_selection",
"(",
"self",
",",
"selection",
",",
"value",
",",
"fields",
"=",
"None",
")",
":",
"# guard conditions",
"if",
"self",
".",
"_read_only",
":",
"err_read_only",
"(",
")",
"# refresh metadata",
"if",
"not",
"self",
".",
"_cache_metad... | Modify a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
selection : ndarray, bool
A Boolean array of the same shape as the array against which the selection is
being made.
value : scalar or array-like
Value to be stored into the array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to set
data for.
Examples
--------
Setup a 2-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.zeros((5, 5), dtype=int)
Set data for a selection of items::
>>> sel = np.zeros_like(z, dtype=bool)
>>> sel[1, 1] = True
>>> sel[4, 4] = True
>>> z.set_mask_selection(sel, 1)
>>> z[...]
array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]])
For convenience, this functionality is also available via the `vindex` property.
E.g.::
>>> z.vindex[sel] = 2
>>> z[...]
array([[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 2]])
Notes
-----
Mask indexing is a form of vectorized or inner indexing, and is equivalent to
coordinate indexing. Internally the mask array is converted to coordinate
arrays by calling `np.nonzero`.
See Also
--------
get_basic_selection, set_basic_selection, get_mask_selection,
get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,
set_coordinate_selection, vindex, oindex, __getitem__, __setitem__ | [
"Modify",
"a",
"selection",
"of",
"individual",
"items",
"by",
"providing",
"a",
"Boolean",
"array",
"of",
"the",
"same",
"shape",
"as",
"the",
"array",
"against",
"which",
"the",
"selection",
"is",
"being",
"made",
"where",
"True",
"values",
"indicate",
"a"... | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1380-L1453 |
234,794 | zarr-developers/zarr | zarr/core.py | Array._chunk_getitem | def _chunk_getitem(self, chunk_coords, chunk_selection, out, out_selection,
drop_axes=None, fields=None):
"""Obtain part or whole of a chunk.
Parameters
----------
chunk_coords : tuple of ints
Indices of the chunk.
chunk_selection : selection
Location of region within the chunk to extract.
out : ndarray
Array to store result in.
out_selection : selection
Location of region within output array to store results in.
drop_axes : tuple of ints
Axes to squeeze out of the chunk.
fields
TODO
"""
assert len(chunk_coords) == len(self._cdata_shape)
# obtain key for chunk
ckey = self._chunk_key(chunk_coords)
try:
# obtain compressed data for chunk
cdata = self.chunk_store[ckey]
except KeyError:
# chunk not initialized
if self._fill_value is not None:
if fields:
fill_value = self._fill_value[fields]
else:
fill_value = self._fill_value
out[out_selection] = fill_value
else:
if (isinstance(out, np.ndarray) and
not fields and
is_contiguous_selection(out_selection) and
is_total_slice(chunk_selection, self._chunks) and
not self._filters and
self._dtype != object):
dest = out[out_selection]
write_direct = (
dest.flags.writeable and (
(self._order == 'C' and dest.flags.c_contiguous) or
(self._order == 'F' and dest.flags.f_contiguous)
)
)
if write_direct:
# optimization: we want the whole chunk, and the destination is
# contiguous, so we can decompress directly from the chunk
# into the destination array
if self._compressor:
self._compressor.decode(cdata, dest)
else:
chunk = ensure_ndarray(cdata).view(self._dtype)
chunk = chunk.reshape(self._chunks, order=self._order)
np.copyto(dest, chunk)
return
# decode chunk
chunk = self._decode_chunk(cdata)
# select data from chunk
if fields:
chunk = chunk[fields]
tmp = chunk[chunk_selection]
if drop_axes:
tmp = np.squeeze(tmp, axis=drop_axes)
# store selected data in output
out[out_selection] = tmp | python | def _chunk_getitem(self, chunk_coords, chunk_selection, out, out_selection,
drop_axes=None, fields=None):
assert len(chunk_coords) == len(self._cdata_shape)
# obtain key for chunk
ckey = self._chunk_key(chunk_coords)
try:
# obtain compressed data for chunk
cdata = self.chunk_store[ckey]
except KeyError:
# chunk not initialized
if self._fill_value is not None:
if fields:
fill_value = self._fill_value[fields]
else:
fill_value = self._fill_value
out[out_selection] = fill_value
else:
if (isinstance(out, np.ndarray) and
not fields and
is_contiguous_selection(out_selection) and
is_total_slice(chunk_selection, self._chunks) and
not self._filters and
self._dtype != object):
dest = out[out_selection]
write_direct = (
dest.flags.writeable and (
(self._order == 'C' and dest.flags.c_contiguous) or
(self._order == 'F' and dest.flags.f_contiguous)
)
)
if write_direct:
# optimization: we want the whole chunk, and the destination is
# contiguous, so we can decompress directly from the chunk
# into the destination array
if self._compressor:
self._compressor.decode(cdata, dest)
else:
chunk = ensure_ndarray(cdata).view(self._dtype)
chunk = chunk.reshape(self._chunks, order=self._order)
np.copyto(dest, chunk)
return
# decode chunk
chunk = self._decode_chunk(cdata)
# select data from chunk
if fields:
chunk = chunk[fields]
tmp = chunk[chunk_selection]
if drop_axes:
tmp = np.squeeze(tmp, axis=drop_axes)
# store selected data in output
out[out_selection] = tmp | [
"def",
"_chunk_getitem",
"(",
"self",
",",
"chunk_coords",
",",
"chunk_selection",
",",
"out",
",",
"out_selection",
",",
"drop_axes",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"chunk_coords",
")",
"==",
"len",
"(",
"self",
... | Obtain part or whole of a chunk.
Parameters
----------
chunk_coords : tuple of ints
Indices of the chunk.
chunk_selection : selection
Location of region within the chunk to extract.
out : ndarray
Array to store result in.
out_selection : selection
Location of region within output array to store results in.
drop_axes : tuple of ints
Axes to squeeze out of the chunk.
fields
TODO | [
"Obtain",
"part",
"or",
"whole",
"of",
"a",
"chunk",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1552-L1633 |
234,795 | zarr-developers/zarr | zarr/core.py | Array._chunk_setitem | def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None):
"""Replace part or whole of a chunk.
Parameters
----------
chunk_coords : tuple of ints
Indices of the chunk.
chunk_selection : tuple of slices
Location of region within the chunk.
value : scalar or ndarray
Value to set.
"""
if self._synchronizer is None:
# no synchronization
lock = nolock
else:
# synchronize on the chunk
ckey = self._chunk_key(chunk_coords)
lock = self._synchronizer[ckey]
with lock:
self._chunk_setitem_nosync(chunk_coords, chunk_selection, value,
fields=fields) | python | def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None):
if self._synchronizer is None:
# no synchronization
lock = nolock
else:
# synchronize on the chunk
ckey = self._chunk_key(chunk_coords)
lock = self._synchronizer[ckey]
with lock:
self._chunk_setitem_nosync(chunk_coords, chunk_selection, value,
fields=fields) | [
"def",
"_chunk_setitem",
"(",
"self",
",",
"chunk_coords",
",",
"chunk_selection",
",",
"value",
",",
"fields",
"=",
"None",
")",
":",
"if",
"self",
".",
"_synchronizer",
"is",
"None",
":",
"# no synchronization",
"lock",
"=",
"nolock",
"else",
":",
"# synch... | Replace part or whole of a chunk.
Parameters
----------
chunk_coords : tuple of ints
Indices of the chunk.
chunk_selection : tuple of slices
Location of region within the chunk.
value : scalar or ndarray
Value to set. | [
"Replace",
"part",
"or",
"whole",
"of",
"a",
"chunk",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1635-L1659 |
234,796 | zarr-developers/zarr | zarr/core.py | Array.append | def append(self, data, axis=0):
"""Append `data` to `axis`.
Parameters
----------
data : array_like
Data to be appended.
axis : int
Axis along which to append.
Returns
-------
new_shape : tuple
Notes
-----
The size of all dimensions other than `axis` must match between this
array and `data`.
Examples
--------
>>> import numpy as np
>>> import zarr
>>> a = np.arange(10000000, dtype='i4').reshape(10000, 1000)
>>> z = zarr.array(a, chunks=(1000, 100))
>>> z.shape
(10000, 1000)
>>> z.append(a)
(20000, 1000)
>>> z.append(np.vstack([a, a]), axis=1)
(20000, 2000)
>>> z.shape
(20000, 2000)
"""
return self._write_op(self._append_nosync, data, axis=axis) | python | def append(self, data, axis=0):
return self._write_op(self._append_nosync, data, axis=axis) | [
"def",
"append",
"(",
"self",
",",
"data",
",",
"axis",
"=",
"0",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_append_nosync",
",",
"data",
",",
"axis",
"=",
"axis",
")"
] | Append `data` to `axis`.
Parameters
----------
data : array_like
Data to be appended.
axis : int
Axis along which to append.
Returns
-------
new_shape : tuple
Notes
-----
The size of all dimensions other than `axis` must match between this
array and `data`.
Examples
--------
>>> import numpy as np
>>> import zarr
>>> a = np.arange(10000000, dtype='i4').reshape(10000, 1000)
>>> z = zarr.array(a, chunks=(1000, 100))
>>> z.shape
(10000, 1000)
>>> z.append(a)
(20000, 1000)
>>> z.append(np.vstack([a, a]), axis=1)
(20000, 2000)
>>> z.shape
(20000, 2000) | [
"Append",
"data",
"to",
"axis",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2027-L2062 |
234,797 | zarr-developers/zarr | zarr/core.py | Array.view | def view(self, shape=None, chunks=None, dtype=None,
fill_value=None, filters=None, read_only=None,
synchronizer=None):
"""Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optional
NumPy dtype.
fill_value : object
Default value to use for uninitialized portions of the array.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to
compression.
read_only : bool, optional
True if array should be protected against modification.
synchronizer : object, optional
Array synchronizer.
Notes
-----
WARNING: This is an experimental feature and should be used with care.
There are plenty of ways to generate errors and/or cause data
corruption.
Examples
--------
Bypass filters:
>>> import zarr
>>> import numpy as np
>>> np.random.seed(42)
>>> labels = ['female', 'male']
>>> data = np.random.choice(labels, size=10000)
>>> filters = [zarr.Categorize(labels=labels,
... dtype=data.dtype,
... astype='u1')]
>>> a = zarr.array(data, chunks=1000, filters=filters)
>>> a[:]
array(['female', 'male', 'female', ..., 'male', 'male', 'female'],
dtype='<U6')
>>> v = a.view(dtype='u1', filters=[])
>>> v.is_view
True
>>> v[:]
array([1, 2, 1, ..., 2, 2, 1], dtype=uint8)
Views can be used to modify data:
>>> x = v[:]
>>> x.sort()
>>> v[:] = x
>>> v[:]
array([1, 1, 1, ..., 2, 2, 2], dtype=uint8)
>>> a[:]
array(['female', 'female', 'female', ..., 'male', 'male', 'male'],
dtype='<U6')
View as a different dtype with the same item size:
>>> data = np.random.randint(0, 2, size=10000, dtype='u1')
>>> a = zarr.array(data, chunks=1000)
>>> a[:]
array([0, 0, 1, ..., 1, 0, 0], dtype=uint8)
>>> v = a.view(dtype=bool)
>>> v[:]
array([False, False, True, ..., True, False, False])
>>> np.all(a[:].view(dtype=bool) == v[:])
True
An array can be viewed with a dtype with a different item size, however
some care is needed to adjust the shape and chunk shape so that chunk
data is interpreted correctly:
>>> data = np.arange(10000, dtype='u2')
>>> a = zarr.array(data, chunks=1000)
>>> a[:10]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
>>> v = a.view(dtype='u1', shape=20000, chunks=2000)
>>> v[:10]
array([0, 0, 1, 0, 2, 0, 3, 0, 4, 0], dtype=uint8)
>>> np.all(a[:].view('u1') == v[:])
True
Change fill value for uninitialized chunks:
>>> a = zarr.full(10000, chunks=1000, fill_value=-1, dtype='i1')
>>> a[:]
array([-1, -1, -1, ..., -1, -1, -1], dtype=int8)
>>> v = a.view(fill_value=42)
>>> v[:]
array([42, 42, 42, ..., 42, 42, 42], dtype=int8)
Note that resizing or appending to views is not permitted:
>>> a = zarr.empty(10000)
>>> v = a.view()
>>> try:
... v.resize(20000)
... except PermissionError as e:
... print(e)
operation not permitted for views
"""
store = self._store
chunk_store = self._chunk_store
path = self._path
if read_only is None:
read_only = self._read_only
if synchronizer is None:
synchronizer = self._synchronizer
a = Array(store=store, path=path, chunk_store=chunk_store, read_only=read_only,
synchronizer=synchronizer, cache_metadata=True)
a._is_view = True
# allow override of some properties
if dtype is None:
dtype = self._dtype
else:
dtype = np.dtype(dtype)
a._dtype = dtype
if shape is None:
shape = self._shape
else:
shape = normalize_shape(shape)
a._shape = shape
if chunks is not None:
chunks = normalize_chunks(chunks, shape, dtype.itemsize)
a._chunks = chunks
if fill_value is not None:
a._fill_value = fill_value
if filters is not None:
a._filters = filters
return a | python | def view(self, shape=None, chunks=None, dtype=None,
fill_value=None, filters=None, read_only=None,
synchronizer=None):
store = self._store
chunk_store = self._chunk_store
path = self._path
if read_only is None:
read_only = self._read_only
if synchronizer is None:
synchronizer = self._synchronizer
a = Array(store=store, path=path, chunk_store=chunk_store, read_only=read_only,
synchronizer=synchronizer, cache_metadata=True)
a._is_view = True
# allow override of some properties
if dtype is None:
dtype = self._dtype
else:
dtype = np.dtype(dtype)
a._dtype = dtype
if shape is None:
shape = self._shape
else:
shape = normalize_shape(shape)
a._shape = shape
if chunks is not None:
chunks = normalize_chunks(chunks, shape, dtype.itemsize)
a._chunks = chunks
if fill_value is not None:
a._fill_value = fill_value
if filters is not None:
a._filters = filters
return a | [
"def",
"view",
"(",
"self",
",",
"shape",
"=",
"None",
",",
"chunks",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"fill_value",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"read_only",
"=",
"None",
",",
"synchronizer",
"=",
"None",
")",
":",
"s... | Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optional
NumPy dtype.
fill_value : object
Default value to use for uninitialized portions of the array.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to
compression.
read_only : bool, optional
True if array should be protected against modification.
synchronizer : object, optional
Array synchronizer.
Notes
-----
WARNING: This is an experimental feature and should be used with care.
There are plenty of ways to generate errors and/or cause data
corruption.
Examples
--------
Bypass filters:
>>> import zarr
>>> import numpy as np
>>> np.random.seed(42)
>>> labels = ['female', 'male']
>>> data = np.random.choice(labels, size=10000)
>>> filters = [zarr.Categorize(labels=labels,
... dtype=data.dtype,
... astype='u1')]
>>> a = zarr.array(data, chunks=1000, filters=filters)
>>> a[:]
array(['female', 'male', 'female', ..., 'male', 'male', 'female'],
dtype='<U6')
>>> v = a.view(dtype='u1', filters=[])
>>> v.is_view
True
>>> v[:]
array([1, 2, 1, ..., 2, 2, 1], dtype=uint8)
Views can be used to modify data:
>>> x = v[:]
>>> x.sort()
>>> v[:] = x
>>> v[:]
array([1, 1, 1, ..., 2, 2, 2], dtype=uint8)
>>> a[:]
array(['female', 'female', 'female', ..., 'male', 'male', 'male'],
dtype='<U6')
View as a different dtype with the same item size:
>>> data = np.random.randint(0, 2, size=10000, dtype='u1')
>>> a = zarr.array(data, chunks=1000)
>>> a[:]
array([0, 0, 1, ..., 1, 0, 0], dtype=uint8)
>>> v = a.view(dtype=bool)
>>> v[:]
array([False, False, True, ..., True, False, False])
>>> np.all(a[:].view(dtype=bool) == v[:])
True
An array can be viewed with a dtype with a different item size, however
some care is needed to adjust the shape and chunk shape so that chunk
data is interpreted correctly:
>>> data = np.arange(10000, dtype='u2')
>>> a = zarr.array(data, chunks=1000)
>>> a[:10]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
>>> v = a.view(dtype='u1', shape=20000, chunks=2000)
>>> v[:10]
array([0, 0, 1, 0, 2, 0, 3, 0, 4, 0], dtype=uint8)
>>> np.all(a[:].view('u1') == v[:])
True
Change fill value for uninitialized chunks:
>>> a = zarr.full(10000, chunks=1000, fill_value=-1, dtype='i1')
>>> a[:]
array([-1, -1, -1, ..., -1, -1, -1], dtype=int8)
>>> v = a.view(fill_value=42)
>>> v[:]
array([42, 42, 42, ..., 42, 42, 42], dtype=int8)
Note that resizing or appending to views is not permitted:
>>> a = zarr.empty(10000)
>>> v = a.view()
>>> try:
... v.resize(20000)
... except PermissionError as e:
... print(e)
operation not permitted for views | [
"Return",
"an",
"array",
"sharing",
"the",
"same",
"data",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2102-L2242 |
234,798 | zarr-developers/zarr | zarr/core.py | Array.astype | def astype(self, dtype):
"""Returns a view that does on the fly type conversion of the underlying data.
Parameters
----------
dtype : string or dtype
NumPy dtype.
Notes
-----
This method returns a new Array object which is a view on the same
underlying chunk data. Modifying any data via the view is currently
not permitted and will result in an error. This is an experimental
feature and its behavior is subject to change in the future.
See Also
--------
Array.view
Examples
--------
>>> import zarr
>>> import numpy as np
>>> data = np.arange(100, dtype=np.uint8)
>>> a = zarr.array(data, chunks=10)
>>> a[:]
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99], dtype=uint8)
>>> v = a.astype(np.float32)
>>> v.is_view
True
>>> v[:]
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,
30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,
40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,
50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,
60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,
70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,
80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,
90., 91., 92., 93., 94., 95., 96., 97., 98., 99.],
dtype=float32)
"""
dtype = np.dtype(dtype)
filters = []
if self._filters:
filters.extend(self._filters)
filters.insert(0, AsType(encode_dtype=self._dtype, decode_dtype=dtype))
return self.view(filters=filters, dtype=dtype, read_only=True) | python | def astype(self, dtype):
dtype = np.dtype(dtype)
filters = []
if self._filters:
filters.extend(self._filters)
filters.insert(0, AsType(encode_dtype=self._dtype, decode_dtype=dtype))
return self.view(filters=filters, dtype=dtype, read_only=True) | [
"def",
"astype",
"(",
"self",
",",
"dtype",
")",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"filters",
"=",
"[",
"]",
"if",
"self",
".",
"_filters",
":",
"filters",
".",
"extend",
"(",
"self",
".",
"_filters",
")",
"filters",
".",
... | Returns a view that does on the fly type conversion of the underlying data.
Parameters
----------
dtype : string or dtype
NumPy dtype.
Notes
-----
This method returns a new Array object which is a view on the same
underlying chunk data. Modifying any data via the view is currently
not permitted and will result in an error. This is an experimental
feature and its behavior is subject to change in the future.
See Also
--------
Array.view
Examples
--------
>>> import zarr
>>> import numpy as np
>>> data = np.arange(100, dtype=np.uint8)
>>> a = zarr.array(data, chunks=10)
>>> a[:]
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99], dtype=uint8)
>>> v = a.astype(np.float32)
>>> v.is_view
True
>>> v[:]
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,
30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,
40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,
50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,
60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,
70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,
80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,
90., 91., 92., 93., 94., 95., 96., 97., 98., 99.],
dtype=float32) | [
"Returns",
"a",
"view",
"that",
"does",
"on",
"the",
"fly",
"type",
"conversion",
"of",
"the",
"underlying",
"data",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2244-L2302 |
234,799 | zarr-developers/zarr | zarr/creation.py | full | def full(shape, fill_value, **kwargs):
"""Create an array, with `fill_value` being used as the default value for
uninitialized portions of the array.
For parameter definitions see :func:`zarr.creation.create`.
Examples
--------
>>> import zarr
>>> z = zarr.full((10000, 10000), chunks=(1000, 1000), fill_value=42)
>>> z
<zarr.core.Array (10000, 10000) float64>
>>> z[:2, :2]
array([[42., 42.],
[42., 42.]])
"""
return create(shape=shape, fill_value=fill_value, **kwargs) | python | def full(shape, fill_value, **kwargs):
return create(shape=shape, fill_value=fill_value, **kwargs) | [
"def",
"full",
"(",
"shape",
",",
"fill_value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create",
"(",
"shape",
"=",
"shape",
",",
"fill_value",
"=",
"fill_value",
",",
"*",
"*",
"kwargs",
")"
] | Create an array, with `fill_value` being used as the default value for
uninitialized portions of the array.
For parameter definitions see :func:`zarr.creation.create`.
Examples
--------
>>> import zarr
>>> z = zarr.full((10000, 10000), chunks=(1000, 1000), fill_value=42)
>>> z
<zarr.core.Array (10000, 10000) float64>
>>> z[:2, :2]
array([[42., 42.],
[42., 42.]]) | [
"Create",
"an",
"array",
"with",
"fill_value",
"being",
"used",
"as",
"the",
"default",
"value",
"for",
"uninitialized",
"portions",
"of",
"the",
"array",
"."
] | fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5 | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L259-L277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.