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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
14,200
yt-project/unyt
unyt/array.py
ucross
def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None): """Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details. """ v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axisc, axis=axis) units = arr1.units * arr2.units arr = unyt_array(v, units, registry=registry) return arr
python
def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None): """Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details. """ v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axisc, axis=axis) units = arr1.units * arr2.units arr = unyt_array(v, units, registry=registry) return arr
[ "def", "ucross", "(", "arr1", ",", "arr2", ",", "registry", "=", "None", ",", "axisa", "=", "-", "1", ",", "axisb", "=", "-", "1", ",", "axisc", "=", "-", "1", ",", "axis", "=", "None", ")", ":", "v", "=", "np", ".", "cross", "(", "arr1", ",", "arr2", ",", "axisa", "=", "axisa", ",", "axisb", "=", "axisb", ",", "axisc", "=", "axisc", ",", "axis", "=", "axis", ")", "units", "=", "arr1", ".", "units", "*", "arr2", ".", "units", "arr", "=", "unyt_array", "(", "v", ",", "units", ",", "registry", "=", "registry", ")", "return", "arr" ]
Applies the cross product to two YT arrays. This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details.
[ "Applies", "the", "cross", "product", "to", "two", "YT", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1966-L1976
14,201
yt-project/unyt
unyt/array.py
uintersect1d
def uintersect1d(arr1, arr2, assume_unique=False): """Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm') """ v = np.intersect1d(arr1, arr2, assume_unique=assume_unique) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
python
def uintersect1d(arr1, arr2, assume_unique=False): """Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm') """ v = np.intersect1d(arr1, arr2, assume_unique=assume_unique) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
[ "def", "uintersect1d", "(", "arr1", ",", "arr2", ",", "assume_unique", "=", "False", ")", ":", "v", "=", "np", ".", "intersect1d", "(", "arr1", ",", "arr2", ",", "assume_unique", "=", "assume_unique", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "[", "arr1", ",", "arr2", "]", ")", "return", "v" ]
Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uintersect1d(A, B) unyt_array([2, 3], 'cm')
[ "Find", "the", "sorted", "unique", "elements", "of", "the", "two", "input", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1979-L1997
14,202
yt-project/unyt
unyt/array.py
uunion1d
def uunion1d(arr1, arr2): """Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm') """ v = np.union1d(arr1, arr2) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
python
def uunion1d(arr1, arr2): """Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm') """ v = np.union1d(arr1, arr2) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
[ "def", "uunion1d", "(", "arr1", ",", "arr2", ")", ":", "v", "=", "np", ".", "union1d", "(", "arr1", ",", "arr2", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "[", "arr1", ",", "arr2", "]", ")", "return", "v" ]
Find the union of two arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>> B = [2, 3, 4]*cm >>> uunion1d(A, B) unyt_array([1, 2, 3, 4], 'cm')
[ "Find", "the", "union", "of", "two", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2000-L2018
14,203
yt-project/unyt
unyt/array.py
unorm
def unorm(data, ord=None, axis=None, keepdims=False): """Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km >>> data = [1, 2, 3]*km >>> print(unorm(data)) 3.7416573867739413 km """ norm = np.linalg.norm(data, ord=ord, axis=axis, keepdims=keepdims) if norm.shape == (): return unyt_quantity(norm, data.units) return unyt_array(norm, data.units)
python
def unorm(data, ord=None, axis=None, keepdims=False): """Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km >>> data = [1, 2, 3]*km >>> print(unorm(data)) 3.7416573867739413 km """ norm = np.linalg.norm(data, ord=ord, axis=axis, keepdims=keepdims) if norm.shape == (): return unyt_quantity(norm, data.units) return unyt_array(norm, data.units)
[ "def", "unorm", "(", "data", ",", "ord", "=", "None", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "norm", "=", "np", ".", "linalg", ".", "norm", "(", "data", ",", "ord", "=", "ord", ",", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")", "if", "norm", ".", "shape", "==", "(", ")", ":", "return", "unyt_quantity", "(", "norm", ",", "data", ".", "units", ")", "return", "unyt_array", "(", "norm", ",", "data", ".", "units", ")" ]
Matrix or vector norm that preserves units This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments. Examples -------- >>> from unyt import km >>> data = [1, 2, 3]*km >>> print(unorm(data)) 3.7416573867739413 km
[ "Matrix", "or", "vector", "norm", "that", "preserves", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2021-L2038
14,204
yt-project/unyt
unyt/array.py
udot
def udot(op1, op2): """Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units. Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s """ dot = np.dot(op1.d, op2.d) units = op1.units * op2.units if dot.shape == (): return unyt_quantity(dot, units) return unyt_array(dot, units)
python
def udot(op1, op2): """Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units. Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s """ dot = np.dot(op1.d, op2.d) units = op1.units * op2.units if dot.shape == (): return unyt_quantity(dot, units) return unyt_array(dot, units)
[ "def", "udot", "(", "op1", ",", "op2", ")", ":", "dot", "=", "np", ".", "dot", "(", "op1", ".", "d", ",", "op2", ".", "d", ")", "units", "=", "op1", ".", "units", "*", "op2", ".", "units", "if", "dot", ".", "shape", "==", "(", ")", ":", "return", "unyt_quantity", "(", "dot", ",", "units", ")", "return", "unyt_array", "(", "dot", ",", "units", ")" ]
Matrix or vector dot product that preserves units This is a wrapper around np.dot that preserves units. Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(udot(a, b)) [[2. 2.] [2. 2.]] km*s
[ "Matrix", "or", "vector", "dot", "product", "that", "preserves", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2041-L2059
14,205
yt-project/unyt
unyt/array.py
uhstack
def uhstack(arrs): """Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a = [[1],[2],[3]]*km >>> b = [[2],[3],[4]]*km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km """ v = np.hstack(arrs) v = _validate_numpy_wrapper_units(v, arrs) return v
python
def uhstack(arrs): """Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a = [[1],[2],[3]]*km >>> b = [[2],[3],[4]]*km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km """ v = np.hstack(arrs) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "def", "uhstack", "(", "arrs", ")", ":", "v", "=", "np", ".", "hstack", "(", "arrs", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "arrs", ")", "return", "v" ]
Stack arrays in sequence horizontally while preserving units This is a wrapper around np.hstack that preserves units. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(uhstack([a, b])) [1 2 3 2 3 4] km >>> a = [[1],[2],[3]]*km >>> b = [[2],[3],[4]]*km >>> print(uhstack([a, b])) [[1 2] [2 3] [3 4]] km
[ "Stack", "arrays", "in", "sequence", "horizontally", "while", "preserving", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2081-L2102
14,206
yt-project/unyt
unyt/array.py
ustack
def ustack(arrs, axis=0): """Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km """ v = np.stack(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
python
def ustack(arrs, axis=0): """Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km """ v = np.stack(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "def", "ustack", "(", "arrs", ",", "axis", "=", "0", ")", ":", "v", "=", "np", ".", "stack", "(", "arrs", ",", "axis", "=", "axis", ")", "v", "=", "_validate_numpy_wrapper_units", "(", "v", ",", "arrs", ")", "return", "v" ]
Join a sequence of arrays along a new axis while preserving units The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details. Examples -------- >>> from unyt import km >>> a = [1, 2, 3]*km >>> b = [2, 3, 4]*km >>> print(ustack([a, b])) [[1 2 3] [2 3 4]] km
[ "Join", "a", "sequence", "of", "arrays", "along", "a", "new", "axis", "while", "preserving", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2105-L2126
14,207
yt-project/unyt
unyt/array.py
loadtxt
def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"): r""" Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : str Filename to read. dtype : data-type, optional Data-type of the resulting array; default: float. delimiter : str, optional The string used to separate values. By default, this is any whitespace. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. comments : str, optional The character used to indicate the start of a comment; default: '#'. Examples -------- >>> temp, velx = loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP """ f = open(fname, "r") next_one = False units = [] num_cols = -1 for line in f.readlines(): words = line.strip().split() if len(words) == 0: continue if line[0] == comments: if next_one: units = words[1:] if len(words) == 2 and words[1] == "Units": next_one = True else: # Here we catch the first line of numbers col_words = line.strip().split(delimiter) for word in col_words: float(word) num_cols = len(col_words) break f.close() if len(units) != num_cols: units = ["dimensionless"] * num_cols arrays = np.loadtxt( fname, dtype=dtype, comments=comments, delimiter=delimiter, converters=None, unpack=True, usecols=usecols, ndmin=0, ) if len(arrays.shape) < 2: arrays = [arrays] if usecols is not None: units = [units[col] for col in usecols] ret = tuple([unyt_array(arr, unit) for arr, unit in zip(arrays, units)]) if len(ret) == 1: return ret[0] return ret
python
def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"): r""" Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : str Filename to read. dtype : data-type, optional Data-type of the resulting array; default: float. delimiter : str, optional The string used to separate values. By default, this is any whitespace. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. comments : str, optional The character used to indicate the start of a comment; default: '#'. Examples -------- >>> temp, velx = loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP """ f = open(fname, "r") next_one = False units = [] num_cols = -1 for line in f.readlines(): words = line.strip().split() if len(words) == 0: continue if line[0] == comments: if next_one: units = words[1:] if len(words) == 2 and words[1] == "Units": next_one = True else: # Here we catch the first line of numbers col_words = line.strip().split(delimiter) for word in col_words: float(word) num_cols = len(col_words) break f.close() if len(units) != num_cols: units = ["dimensionless"] * num_cols arrays = np.loadtxt( fname, dtype=dtype, comments=comments, delimiter=delimiter, converters=None, unpack=True, usecols=usecols, ndmin=0, ) if len(arrays.shape) < 2: arrays = [arrays] if usecols is not None: units = [units[col] for col in usecols] ret = tuple([unyt_array(arr, unit) for arr, unit in zip(arrays, units)]) if len(ret) == 1: return ret[0] return ret
[ "def", "loadtxt", "(", "fname", ",", "dtype", "=", "\"float\"", ",", "delimiter", "=", "\"\\t\"", ",", "usecols", "=", "None", ",", "comments", "=", "\"#\"", ")", ":", "f", "=", "open", "(", "fname", ",", "\"r\"", ")", "next_one", "=", "False", "units", "=", "[", "]", "num_cols", "=", "-", "1", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "words", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "if", "len", "(", "words", ")", "==", "0", ":", "continue", "if", "line", "[", "0", "]", "==", "comments", ":", "if", "next_one", ":", "units", "=", "words", "[", "1", ":", "]", "if", "len", "(", "words", ")", "==", "2", "and", "words", "[", "1", "]", "==", "\"Units\"", ":", "next_one", "=", "True", "else", ":", "# Here we catch the first line of numbers", "col_words", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "delimiter", ")", "for", "word", "in", "col_words", ":", "float", "(", "word", ")", "num_cols", "=", "len", "(", "col_words", ")", "break", "f", ".", "close", "(", ")", "if", "len", "(", "units", ")", "!=", "num_cols", ":", "units", "=", "[", "\"dimensionless\"", "]", "*", "num_cols", "arrays", "=", "np", ".", "loadtxt", "(", "fname", ",", "dtype", "=", "dtype", ",", "comments", "=", "comments", ",", "delimiter", "=", "delimiter", ",", "converters", "=", "None", ",", "unpack", "=", "True", ",", "usecols", "=", "usecols", ",", "ndmin", "=", "0", ",", ")", "if", "len", "(", "arrays", ".", "shape", ")", "<", "2", ":", "arrays", "=", "[", "arrays", "]", "if", "usecols", "is", "not", "None", ":", "units", "=", "[", "units", "[", "col", "]", "for", "col", "in", "usecols", "]", "ret", "=", "tuple", "(", "[", "unyt_array", "(", "arr", ",", "unit", ")", "for", "arr", ",", "unit", "in", "zip", "(", "arrays", ",", "units", ")", "]", ")", "if", "len", "(", "ret", ")", "==", "1", ":", "return", "ret", "[", "0", "]", "return", "ret" ]
r""" Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : str Filename to read. dtype : data-type, optional Data-type of the resulting array; default: float. delimiter : str, optional The string used to separate values. By default, this is any whitespace. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. comments : str, optional The character used to indicate the start of a comment; default: '#'. Examples -------- >>> temp, velx = loadtxt( ... "sphere.dat", usecols=(1,2), delimiter="\t") # doctest: +SKIP
[ "r", "Load", "unyt_arrays", "with", "unit", "information", "from", "a", "text", "file", ".", "Each", "row", "in", "the", "text", "file", "must", "have", "the", "same", "number", "of", "values", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2155-L2222
14,208
yt-project/unyt
unyt/array.py
savetxt
def savetxt( fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#" ): r""" Write unyt_arrays with unit information to a text file. Parameters ---------- fname : str The file to write the unyt_arrays to. arrays : list of unyt_arrays or single unyt_array The array(s) to write to the file. fmt : str or sequence of strs, optional A single format (%10.5f), or a sequence of formats. delimiter : str, optional String or character separating columns. header : str, optional String that will be written at the beginning of the file, before the unit header. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``unyt.loadtxt``. Examples -------- >>> import unyt as u >>> a = [1, 2, 3]*u.cm >>> b = [8, 10, 12]*u.cm/u.s >>> c = [2, 85, 9]*u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP """ if not isinstance(arrays, list): arrays = [arrays] units = [] for array in arrays: if hasattr(array, "units"): units.append(str(array.units)) else: units.append("dimensionless") if header != "" and not header.endswith("\n"): header += "\n" header += " Units\n " + "\t".join(units) np.savetxt( fname, np.transpose(arrays), header=header, fmt=fmt, delimiter=delimiter, footer=footer, newline="\n", comments=comments, )
python
def savetxt( fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#" ): r""" Write unyt_arrays with unit information to a text file. Parameters ---------- fname : str The file to write the unyt_arrays to. arrays : list of unyt_arrays or single unyt_array The array(s) to write to the file. fmt : str or sequence of strs, optional A single format (%10.5f), or a sequence of formats. delimiter : str, optional String or character separating columns. header : str, optional String that will be written at the beginning of the file, before the unit header. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``unyt.loadtxt``. Examples -------- >>> import unyt as u >>> a = [1, 2, 3]*u.cm >>> b = [8, 10, 12]*u.cm/u.s >>> c = [2, 85, 9]*u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP """ if not isinstance(arrays, list): arrays = [arrays] units = [] for array in arrays: if hasattr(array, "units"): units.append(str(array.units)) else: units.append("dimensionless") if header != "" and not header.endswith("\n"): header += "\n" header += " Units\n " + "\t".join(units) np.savetxt( fname, np.transpose(arrays), header=header, fmt=fmt, delimiter=delimiter, footer=footer, newline="\n", comments=comments, )
[ "def", "savetxt", "(", "fname", ",", "arrays", ",", "fmt", "=", "\"%.18e\"", ",", "delimiter", "=", "\"\\t\"", ",", "header", "=", "\"\"", ",", "footer", "=", "\"\"", ",", "comments", "=", "\"#\"", ")", ":", "if", "not", "isinstance", "(", "arrays", ",", "list", ")", ":", "arrays", "=", "[", "arrays", "]", "units", "=", "[", "]", "for", "array", "in", "arrays", ":", "if", "hasattr", "(", "array", ",", "\"units\"", ")", ":", "units", ".", "append", "(", "str", "(", "array", ".", "units", ")", ")", "else", ":", "units", ".", "append", "(", "\"dimensionless\"", ")", "if", "header", "!=", "\"\"", "and", "not", "header", ".", "endswith", "(", "\"\\n\"", ")", ":", "header", "+=", "\"\\n\"", "header", "+=", "\" Units\\n \"", "+", "\"\\t\"", ".", "join", "(", "units", ")", "np", ".", "savetxt", "(", "fname", ",", "np", ".", "transpose", "(", "arrays", ")", ",", "header", "=", "header", ",", "fmt", "=", "fmt", ",", "delimiter", "=", "delimiter", ",", "footer", "=", "footer", ",", "newline", "=", "\"\\n\"", ",", "comments", "=", "comments", ",", ")" ]
r""" Write unyt_arrays with unit information to a text file. Parameters ---------- fname : str The file to write the unyt_arrays to. arrays : list of unyt_arrays or single unyt_array The array(s) to write to the file. fmt : str or sequence of strs, optional A single format (%10.5f), or a sequence of formats. delimiter : str, optional String or character separating columns. header : str, optional String that will be written at the beginning of the file, before the unit header. footer : str, optional String that will be written at the end of the file. comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``unyt.loadtxt``. Examples -------- >>> import unyt as u >>> a = [1, 2, 3]*u.cm >>> b = [8, 10, 12]*u.cm/u.s >>> c = [2, 85, 9]*u.g >>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff', ... delimiter="\t") # doctest: +SKIP
[ "r", "Write", "unyt_arrays", "with", "unit", "information", "to", "a", "text", "file", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2225-L2280
14,209
yt-project/unyt
unyt/array.py
unyt_array.convert_to_units
def convert_to_units(self, units, equivalence=None, **kwargs): """ Convert the array to the given units in-place. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- units : Unit object or string The units you want to convert to. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import cm, km >>> length = [3000, 2000, 1000]*cm >>> length.convert_to_units('m') >>> print(length) [30. 20. 10.] m """ units = _sanitize_units_convert(units, self.units.registry) if equivalence is None: conv_data = _check_em_conversion( self.units, units, registry=self.units.registry ) if any(conv_data): new_units, (conv_factor, offset) = _em_conversion( self.units, conv_data, units ) else: new_units = units (conv_factor, offset) = self.units.get_conversion_factor( new_units, self.dtype ) self.units = new_units values = self.d # if our dtype is an integer do the following somewhat awkward # dance to change the dtype in-place. We can't use astype # directly because that will create a copy and not update self if self.dtype.kind in ("u", "i"): # create a copy of the original data in floating point # form, it's possible this may lose precision for very # large integers dsize = values.dtype.itemsize new_dtype = "f" + str(dsize) large = LARGE_INPUT.get(dsize, 0) if large and np.any(np.abs(values) > large): warnings.warn( "Overflow encountered while converting to units '%s'" % new_units, RuntimeWarning, stacklevel=2, ) float_values = values.astype(new_dtype) # change the dtypes in-place, this does not change the # underlying memory buffer values.dtype = new_dtype self.dtype = new_dtype # actually fill in the new float values now that our # dtype is correct np.copyto(values, float_values) values *= conv_factor if offset: np.subtract(values, offset, values) else: self.convert_to_equivalent(units, equivalence, **kwargs)
python
def convert_to_units(self, units, equivalence=None, **kwargs): """ Convert the array to the given units in-place. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- units : Unit object or string The units you want to convert to. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import cm, km >>> length = [3000, 2000, 1000]*cm >>> length.convert_to_units('m') >>> print(length) [30. 20. 10.] m """ units = _sanitize_units_convert(units, self.units.registry) if equivalence is None: conv_data = _check_em_conversion( self.units, units, registry=self.units.registry ) if any(conv_data): new_units, (conv_factor, offset) = _em_conversion( self.units, conv_data, units ) else: new_units = units (conv_factor, offset) = self.units.get_conversion_factor( new_units, self.dtype ) self.units = new_units values = self.d # if our dtype is an integer do the following somewhat awkward # dance to change the dtype in-place. We can't use astype # directly because that will create a copy and not update self if self.dtype.kind in ("u", "i"): # create a copy of the original data in floating point # form, it's possible this may lose precision for very # large integers dsize = values.dtype.itemsize new_dtype = "f" + str(dsize) large = LARGE_INPUT.get(dsize, 0) if large and np.any(np.abs(values) > large): warnings.warn( "Overflow encountered while converting to units '%s'" % new_units, RuntimeWarning, stacklevel=2, ) float_values = values.astype(new_dtype) # change the dtypes in-place, this does not change the # underlying memory buffer values.dtype = new_dtype self.dtype = new_dtype # actually fill in the new float values now that our # dtype is correct np.copyto(values, float_values) values *= conv_factor if offset: np.subtract(values, offset, values) else: self.convert_to_equivalent(units, equivalence, **kwargs)
[ "def", "convert_to_units", "(", "self", ",", "units", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "units", "=", "_sanitize_units_convert", "(", "units", ",", "self", ".", "units", ".", "registry", ")", "if", "equivalence", "is", "None", ":", "conv_data", "=", "_check_em_conversion", "(", "self", ".", "units", ",", "units", ",", "registry", "=", "self", ".", "units", ".", "registry", ")", "if", "any", "(", "conv_data", ")", ":", "new_units", ",", "(", "conv_factor", ",", "offset", ")", "=", "_em_conversion", "(", "self", ".", "units", ",", "conv_data", ",", "units", ")", "else", ":", "new_units", "=", "units", "(", "conv_factor", ",", "offset", ")", "=", "self", ".", "units", ".", "get_conversion_factor", "(", "new_units", ",", "self", ".", "dtype", ")", "self", ".", "units", "=", "new_units", "values", "=", "self", ".", "d", "# if our dtype is an integer do the following somewhat awkward", "# dance to change the dtype in-place. We can't use astype", "# directly because that will create a copy and not update self", "if", "self", ".", "dtype", ".", "kind", "in", "(", "\"u\"", ",", "\"i\"", ")", ":", "# create a copy of the original data in floating point", "# form, it's possible this may lose precision for very", "# large integers", "dsize", "=", "values", ".", "dtype", ".", "itemsize", "new_dtype", "=", "\"f\"", "+", "str", "(", "dsize", ")", "large", "=", "LARGE_INPUT", ".", "get", "(", "dsize", ",", "0", ")", "if", "large", "and", "np", ".", "any", "(", "np", ".", "abs", "(", "values", ")", ">", "large", ")", ":", "warnings", ".", "warn", "(", "\"Overflow encountered while converting to units '%s'\"", "%", "new_units", ",", "RuntimeWarning", ",", "stacklevel", "=", "2", ",", ")", "float_values", "=", "values", ".", "astype", "(", "new_dtype", ")", "# change the dtypes in-place, this does not change the", "# underlying memory buffer", "values", ".", "dtype", "=", "new_dtype", "self", ".", "dtype", "=", "new_dtype", "# actually fill in the new float values now that our", "# dtype is correct", "np", ".", "copyto", "(", "values", ",", "float_values", ")", "values", "*=", "conv_factor", "if", "offset", ":", "np", ".", "subtract", "(", "values", ",", "offset", ",", "values", ")", "else", ":", "self", ".", "convert_to_equivalent", "(", "units", ",", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array to the given units in-place. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- units : Unit object or string The units you want to convert to. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import cm, km >>> length = [3000, 2000, 1000]*cm >>> length.convert_to_units('m') >>> print(length) [30. 20. 10.] m
[ "Convert", "the", "array", "to", "the", "given", "units", "in", "-", "place", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L552-L631
14,210
yt-project/unyt
unyt/array.py
unyt_array.convert_to_base
def convert_to_base(self, unit_system=None, equivalence=None, **kwargs): """ Convert the array in-place to the equivalent base units in the specified unit system. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS). equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> E.convert_to_base("mks") >>> E unyt_quantity(2.5e-07, 'W') """ self.convert_to_units( self.units.get_base_equivalent(unit_system), equivalence=equivalence, **kwargs )
python
def convert_to_base(self, unit_system=None, equivalence=None, **kwargs): """ Convert the array in-place to the equivalent base units in the specified unit system. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS). equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> E.convert_to_base("mks") >>> E unyt_quantity(2.5e-07, 'W') """ self.convert_to_units( self.units.get_base_equivalent(unit_system), equivalence=equivalence, **kwargs )
[ "def", "convert_to_base", "(", "self", ",", "unit_system", "=", "None", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_base_equivalent", "(", "unit_system", ")", ",", "equivalence", "=", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array in-place to the equivalent base units in the specified unit system. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS). equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> E.convert_to_base("mks") >>> E unyt_quantity(2.5e-07, 'W')
[ "Convert", "the", "array", "in", "-", "place", "to", "the", "equivalent", "base", "units", "in", "the", "specified", "unit", "system", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L633-L670
14,211
yt-project/unyt
unyt/array.py
unyt_array.convert_to_cgs
def convert_to_cgs(self, equivalence=None, **kwargs): """ Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import Newton >>> data = [1., 2., 3.]*Newton >>> data.convert_to_cgs() >>> data unyt_array([100000., 200000., 300000.], 'dyn') """ self.convert_to_units( self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs )
python
def convert_to_cgs(self, equivalence=None, **kwargs): """ Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import Newton >>> data = [1., 2., 3.]*Newton >>> data.convert_to_cgs() >>> data unyt_array([100000., 200000., 300000.], 'dyn') """ self.convert_to_units( self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs )
[ "def", "convert_to_cgs", "(", "self", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_cgs_equivalent", "(", ")", ",", "equivalence", "=", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import Newton >>> data = [1., 2., 3.]*Newton >>> data.convert_to_cgs() >>> data unyt_array([100000., 200000., 300000.], 'dyn')
[ "Convert", "the", "array", "and", "in", "-", "place", "to", "the", "equivalent", "cgs", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L672-L704
14,212
yt-project/unyt
unyt/array.py
unyt_array.convert_to_mks
def convert_to_mks(self, equivalence=None, **kwargs): """ Convert the array and units to the equivalent mks units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import dyne, erg >>> data = [1., 2., 3.]*erg >>> data unyt_array([1., 2., 3.], 'erg') >>> data.convert_to_mks() >>> data unyt_array([1.e-07, 2.e-07, 3.e-07], 'J') """ self.convert_to_units(self.units.get_mks_equivalent(), equivalence, **kwargs)
python
def convert_to_mks(self, equivalence=None, **kwargs): """ Convert the array and units to the equivalent mks units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import dyne, erg >>> data = [1., 2., 3.]*erg >>> data unyt_array([1., 2., 3.], 'erg') >>> data.convert_to_mks() >>> data unyt_array([1.e-07, 2.e-07, 3.e-07], 'J') """ self.convert_to_units(self.units.get_mks_equivalent(), equivalence, **kwargs)
[ "def", "convert_to_mks", "(", "self", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_mks_equivalent", "(", ")", ",", "equivalence", ",", "*", "*", "kwargs", ")" ]
Convert the array and units to the equivalent mks units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this object, try the ``list_equivalencies`` method. Default: None kwargs: optional Any additional keyword arguments are supplied to the equivalence Raises ------ If the provided unit does not have the same dimensions as the array this will raise a UnitConversionError Examples -------- >>> from unyt import dyne, erg >>> data = [1., 2., 3.]*erg >>> data unyt_array([1., 2., 3.], 'erg') >>> data.convert_to_mks() >>> data unyt_array([1.e-07, 2.e-07, 3.e-07], 'J')
[ "Convert", "the", "array", "and", "units", "to", "the", "equivalent", "mks", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L706-L737
14,213
yt-project/unyt
unyt/array.py
unyt_array.to_value
def to_value(self, units=None, equivalence=None, **kwargs): """ Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. .. note:: All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them. Parameters ---------- units : Unit object or string, optional The units you want to get the bare quantity in. If not specified, the value will be returned in the current units. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the :meth:`list_equivalencies` method. Default: None Examples -------- >>> from unyt import km >>> a = [3, 4, 5]*km >>> print(a.to_value('cm')) [300000. 400000. 500000.] """ if units is None: v = self.value else: v = self.in_units(units, equivalence=equivalence, **kwargs).value if isinstance(self, unyt_quantity): return float(v) else: return v
python
def to_value(self, units=None, equivalence=None, **kwargs): """ Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. .. note:: All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them. Parameters ---------- units : Unit object or string, optional The units you want to get the bare quantity in. If not specified, the value will be returned in the current units. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the :meth:`list_equivalencies` method. Default: None Examples -------- >>> from unyt import km >>> a = [3, 4, 5]*km >>> print(a.to_value('cm')) [300000. 400000. 500000.] """ if units is None: v = self.value else: v = self.in_units(units, equivalence=equivalence, **kwargs).value if isinstance(self, unyt_quantity): return float(v) else: return v
[ "def", "to_value", "(", "self", ",", "units", "=", "None", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "units", "is", "None", ":", "v", "=", "self", ".", "value", "else", ":", "v", "=", "self", ".", "in_units", "(", "units", ",", "equivalence", "=", "equivalence", ",", "*", "*", "kwargs", ")", ".", "value", "if", "isinstance", "(", "self", ",", "unyt_quantity", ")", ":", "return", "float", "(", "v", ")", "else", ":", "return", "v" ]
Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. .. note:: All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them. Parameters ---------- units : Unit object or string, optional The units you want to get the bare quantity in. If not specified, the value will be returned in the current units. equivalence : string, optional The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the :meth:`list_equivalencies` method. Default: None Examples -------- >>> from unyt import km >>> a = [3, 4, 5]*km >>> print(a.to_value('cm')) [300000. 400000. 500000.]
[ "Creates", "a", "copy", "of", "this", "array", "with", "the", "data", "in", "the", "supplied", "units", "and", "returns", "it", "without", "units", ".", "Output", "is", "therefore", "a", "bare", "NumPy", "array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L855-L896
14,214
yt-project/unyt
unyt/array.py
unyt_array.in_base
def in_base(self, unit_system=None): """ Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS). Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W """ us = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, unit_system=us, registry=self.units.registry ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, us) if any(conv_data): to_units, (conv, offset) = _em_conversion( self.units, conv_data, unit_system=us ) else: to_units = self.units.get_base_equivalent(unit_system) conv, offset = self.units.get_conversion_factor(to_units, self.dtype) new_dtype = np.dtype("f" + str(self.dtype.itemsize)) conv = new_dtype.type(conv) ret = self.v * conv if offset: ret = ret - offset return type(self)(ret, to_units)
python
def in_base(self, unit_system=None): """ Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS). Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W """ us = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, unit_system=us, registry=self.units.registry ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, us) if any(conv_data): to_units, (conv, offset) = _em_conversion( self.units, conv_data, unit_system=us ) else: to_units = self.units.get_base_equivalent(unit_system) conv, offset = self.units.get_conversion_factor(to_units, self.dtype) new_dtype = np.dtype("f" + str(self.dtype.itemsize)) conv = new_dtype.type(conv) ret = self.v * conv if offset: ret = ret - offset return type(self)(ret, to_units)
[ "def", "in_base", "(", "self", ",", "unit_system", "=", "None", ")", ":", "us", "=", "_sanitize_unit_system", "(", "unit_system", ",", "self", ")", "try", ":", "conv_data", "=", "_check_em_conversion", "(", "self", ".", "units", ",", "unit_system", "=", "us", ",", "registry", "=", "self", ".", "units", ".", "registry", ")", "except", "MKSCGSConversionError", ":", "raise", "UnitsNotReducible", "(", "self", ".", "units", ",", "us", ")", "if", "any", "(", "conv_data", ")", ":", "to_units", ",", "(", "conv", ",", "offset", ")", "=", "_em_conversion", "(", "self", ".", "units", ",", "conv_data", ",", "unit_system", "=", "us", ")", "else", ":", "to_units", "=", "self", ".", "units", ".", "get_base_equivalent", "(", "unit_system", ")", "conv", ",", "offset", "=", "self", ".", "units", ".", "get_conversion_factor", "(", "to_units", ",", "self", ".", "dtype", ")", "new_dtype", "=", "np", ".", "dtype", "(", "\"f\"", "+", "str", "(", "self", ".", "dtype", ".", "itemsize", ")", ")", "conv", "=", "new_dtype", ".", "type", "(", "conv", ")", "ret", "=", "self", ".", "v", "*", "conv", "if", "offset", ":", "ret", "=", "ret", "-", "offset", "return", "type", "(", "self", ")", "(", "ret", ",", "to_units", ")" ]
Creates a copy of this array with the data in the specified unit system, and returns it in that system's base units. Parameters ---------- unit_system : string, optional The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS). Examples -------- >>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W
[ "Creates", "a", "copy", "of", "this", "array", "with", "the", "data", "in", "the", "specified", "unit", "system", "and", "returns", "it", "in", "that", "system", "s", "base", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L898-L935
14,215
yt-project/unyt
unyt/array.py
unyt_array.argsort
def argsort(self, axis=-1, kind="quicksort", order=None): """ Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1] """ return self.view(np.ndarray).argsort(axis, kind, order)
python
def argsort(self, axis=-1, kind="quicksort", order=None): """ Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1] """ return self.view(np.ndarray).argsort(axis, kind, order)
[ "def", "argsort", "(", "self", ",", "axis", "=", "-", "1", ",", "kind", "=", "\"quicksort\"", ",", "order", "=", "None", ")", ":", "return", "self", ".", "view", "(", "np", ".", "ndarray", ")", ".", "argsort", "(", "axis", ",", "kind", ",", "order", ")" ]
Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km >>> print(np.argsort(data)) [0 2 1] >>> print(data.argsort()) [0 2 1]
[ "Returns", "the", "indices", "that", "would", "sort", "the", "array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1126-L1142
14,216
yt-project/unyt
unyt/array.py
unyt_array.from_astropy
def from_astropy(cls, arr, unit_registry=None): """ Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : AstroPy Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Example ------- >>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a = [1, 2, 3]*km >>> a <Quantity [1., 2., 3.] km> >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km') """ # Converting from AstroPy Quantity try: u = arr.unit _arr = arr except AttributeError: u = arr _arr = 1.0 * u ap_units = [] for base, exponent in zip(u.bases, u.powers): unit_str = base.to_string() # we have to do this because AstroPy is silly and defines # hour as "h" if unit_str == "h": unit_str = "hr" ap_units.append("%s**(%s)" % (unit_str, Rational(exponent))) ap_units = "*".join(ap_units) if isinstance(_arr.value, np.ndarray) and _arr.shape != (): return unyt_array(_arr.value, ap_units, registry=unit_registry) else: return unyt_quantity(_arr.value, ap_units, registry=unit_registry)
python
def from_astropy(cls, arr, unit_registry=None): """ Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : AstroPy Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Example ------- >>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a = [1, 2, 3]*km >>> a <Quantity [1., 2., 3.] km> >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km') """ # Converting from AstroPy Quantity try: u = arr.unit _arr = arr except AttributeError: u = arr _arr = 1.0 * u ap_units = [] for base, exponent in zip(u.bases, u.powers): unit_str = base.to_string() # we have to do this because AstroPy is silly and defines # hour as "h" if unit_str == "h": unit_str = "hr" ap_units.append("%s**(%s)" % (unit_str, Rational(exponent))) ap_units = "*".join(ap_units) if isinstance(_arr.value, np.ndarray) and _arr.shape != (): return unyt_array(_arr.value, ap_units, registry=unit_registry) else: return unyt_quantity(_arr.value, ap_units, registry=unit_registry)
[ "def", "from_astropy", "(", "cls", ",", "arr", ",", "unit_registry", "=", "None", ")", ":", "# Converting from AstroPy Quantity", "try", ":", "u", "=", "arr", ".", "unit", "_arr", "=", "arr", "except", "AttributeError", ":", "u", "=", "arr", "_arr", "=", "1.0", "*", "u", "ap_units", "=", "[", "]", "for", "base", ",", "exponent", "in", "zip", "(", "u", ".", "bases", ",", "u", ".", "powers", ")", ":", "unit_str", "=", "base", ".", "to_string", "(", ")", "# we have to do this because AstroPy is silly and defines", "# hour as \"h\"", "if", "unit_str", "==", "\"h\"", ":", "unit_str", "=", "\"hr\"", "ap_units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "unit_str", ",", "Rational", "(", "exponent", ")", ")", ")", "ap_units", "=", "\"*\"", ".", "join", "(", "ap_units", ")", "if", "isinstance", "(", "_arr", ".", "value", ",", "np", ".", "ndarray", ")", "and", "_arr", ".", "shape", "!=", "(", ")", ":", "return", "unyt_array", "(", "_arr", ".", "value", ",", "ap_units", ",", "registry", "=", "unit_registry", ")", "else", ":", "return", "unyt_quantity", "(", "_arr", ".", "value", ",", "ap_units", ",", "registry", "=", "unit_registry", ")" ]
Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : AstroPy Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Example ------- >>> from astropy.units import km >>> unyt_quantity.from_astropy(km) unyt_quantity(1., 'km') >>> a = [1, 2, 3]*km >>> a <Quantity [1., 2., 3.] km> >>> unyt_array.from_astropy(a) unyt_array([1., 2., 3.], 'km')
[ "Convert", "an", "AstroPy", "Quantity", "to", "a", "unyt_array", "or", "unyt_quantity", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1145-L1187
14,217
yt-project/unyt
unyt/array.py
unyt_array.to_astropy
def to_astropy(self, **kwargs): """ Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3> """ return self.value * _astropy.units.Unit(str(self.units), **kwargs)
python
def to_astropy(self, **kwargs): """ Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3> """ return self.value * _astropy.units.Unit(str(self.units), **kwargs)
[ "def", "to_astropy", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "value", "*", "_astropy", ".", "units", ".", "Unit", "(", "str", "(", "self", ".", "units", ")", ",", "*", "*", "kwargs", ")" ]
Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3>
[ "Creates", "a", "new", "AstroPy", "quantity", "with", "the", "same", "unit", "information", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1189-L1200
14,218
yt-project/unyt
unyt/array.py
unyt_array.from_pint
def from_pint(cls, arr, unit_registry=None): """ Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Examples -------- >>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3') """ p_units = [] for base, exponent in arr._units.items(): bs = convert_pint_units(base) p_units.append("%s**(%s)" % (bs, Rational(exponent))) p_units = "*".join(p_units) if isinstance(arr.magnitude, np.ndarray): return unyt_array(arr.magnitude, p_units, registry=unit_registry) else: return unyt_quantity(arr.magnitude, p_units, registry=unit_registry)
python
def from_pint(cls, arr, unit_registry=None): """ Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Examples -------- >>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3') """ p_units = [] for base, exponent in arr._units.items(): bs = convert_pint_units(base) p_units.append("%s**(%s)" % (bs, Rational(exponent))) p_units = "*".join(p_units) if isinstance(arr.magnitude, np.ndarray): return unyt_array(arr.magnitude, p_units, registry=unit_registry) else: return unyt_quantity(arr.magnitude, p_units, registry=unit_registry)
[ "def", "from_pint", "(", "cls", ",", "arr", ",", "unit_registry", "=", "None", ")", ":", "p_units", "=", "[", "]", "for", "base", ",", "exponent", "in", "arr", ".", "_units", ".", "items", "(", ")", ":", "bs", "=", "convert_pint_units", "(", "base", ")", "p_units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "bs", ",", "Rational", "(", "exponent", ")", ")", ")", "p_units", "=", "\"*\"", ".", "join", "(", "p_units", ")", "if", "isinstance", "(", "arr", ".", "magnitude", ",", "np", ".", "ndarray", ")", ":", "return", "unyt_array", "(", "arr", ".", "magnitude", ",", "p_units", ",", "registry", "=", "unit_registry", ")", "else", ":", "return", "unyt_quantity", "(", "arr", ".", "magnitude", ",", "p_units", ",", "registry", "=", "unit_registry", ")" ]
Convert a Pint "Quantity" to a unyt_array or unyt_quantity. Parameters ---------- arr : Pint Quantity The Quantity to convert from. unit_registry : yt UnitRegistry, optional A yt unit registry to use in the conversion. If one is not supplied, the default one will be used. Examples -------- >>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = unyt_array.from_pint(b) >>> c unyt_array([0, 1, 2, 3], 'erg/cm**3')
[ "Convert", "a", "Pint", "Quantity", "to", "a", "unyt_array", "or", "unyt_quantity", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1203-L1236
14,219
yt-project/unyt
unyt/array.py
unyt_array.to_pint
def to_pint(self, unit_registry=None): """ Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters ---------- arr : unyt_array or unyt_quantity The unitful quantity to convert from. unit_registry : Pint UnitRegistry, optional The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object. Examples -------- >>> from unyt import cm, s >>> a = 4*cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint() <Quantity(4, 'centimeter ** 2 / second')> """ if unit_registry is None: unit_registry = _pint.UnitRegistry() powers_dict = self.units.expr.as_powers_dict() units = [] for unit, pow in powers_dict.items(): # we have to do this because Pint doesn't recognize # "yr" as "year" if str(unit).endswith("yr") and len(str(unit)) in [2, 3]: unit = str(unit).replace("yr", "year") units.append("%s**(%s)" % (unit, Rational(pow))) units = "*".join(units) return unit_registry.Quantity(self.value, units)
python
def to_pint(self, unit_registry=None): """ Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters ---------- arr : unyt_array or unyt_quantity The unitful quantity to convert from. unit_registry : Pint UnitRegistry, optional The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object. Examples -------- >>> from unyt import cm, s >>> a = 4*cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint() <Quantity(4, 'centimeter ** 2 / second')> """ if unit_registry is None: unit_registry = _pint.UnitRegistry() powers_dict = self.units.expr.as_powers_dict() units = [] for unit, pow in powers_dict.items(): # we have to do this because Pint doesn't recognize # "yr" as "year" if str(unit).endswith("yr") and len(str(unit)) in [2, 3]: unit = str(unit).replace("yr", "year") units.append("%s**(%s)" % (unit, Rational(pow))) units = "*".join(units) return unit_registry.Quantity(self.value, units)
[ "def", "to_pint", "(", "self", ",", "unit_registry", "=", "None", ")", ":", "if", "unit_registry", "is", "None", ":", "unit_registry", "=", "_pint", ".", "UnitRegistry", "(", ")", "powers_dict", "=", "self", ".", "units", ".", "expr", ".", "as_powers_dict", "(", ")", "units", "=", "[", "]", "for", "unit", ",", "pow", "in", "powers_dict", ".", "items", "(", ")", ":", "# we have to do this because Pint doesn't recognize", "# \"yr\" as \"year\"", "if", "str", "(", "unit", ")", ".", "endswith", "(", "\"yr\"", ")", "and", "len", "(", "str", "(", "unit", ")", ")", "in", "[", "2", ",", "3", "]", ":", "unit", "=", "str", "(", "unit", ")", ".", "replace", "(", "\"yr\"", ",", "\"year\"", ")", "units", ".", "append", "(", "\"%s**(%s)\"", "%", "(", "unit", ",", "Rational", "(", "pow", ")", ")", ")", "units", "=", "\"*\"", ".", "join", "(", "units", ")", "return", "unit_registry", ".", "Quantity", "(", "self", ".", "value", ",", "units", ")" ]
Convert a unyt_array or unyt_quantity to a Pint Quantity. Parameters ---------- arr : unyt_array or unyt_quantity The unitful quantity to convert from. unit_registry : Pint UnitRegistry, optional The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a yt UnitRegistry object. Examples -------- >>> from unyt import cm, s >>> a = 4*cm**2/s >>> print(a) 4 cm**2/s >>> a.to_pint() <Quantity(4, 'centimeter ** 2 / second')>
[ "Convert", "a", "unyt_array", "or", "unyt_quantity", "to", "a", "Pint", "Quantity", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1238-L1271
14,220
yt-project/unyt
unyt/array.py
unyt_array.write_hdf5
def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None): r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to create in the file. info: dictionary A dictionary of supplementary info to write to append as attributes to the dataset. group_name: string An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default. Examples -------- >>> from unyt import cm >>> a = [1,2,3]*cm >>> myinfo = {'field':'dinosaurs', 'type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP """ from unyt._on_demand_imports import _h5py as h5py import pickle if info is None: info = {} info["units"] = str(self.units) info["unit_registry"] = np.void(pickle.dumps(self.units.registry.lut)) if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: if group_name in f: g = f[group_name] else: g = f.create_group(group_name) else: g = f if dataset_name in g.keys(): d = g[dataset_name] # Overwrite without deleting if we can get away with it. if d.shape == self.shape and d.dtype == self.dtype: d[...] = self for k in d.attrs.keys(): del d.attrs[k] else: del f[dataset_name] d = g.create_dataset(dataset_name, data=self) else: d = g.create_dataset(dataset_name, data=self) for k, v in info.items(): d.attrs[k] = v f.close()
python
def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None): r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to create in the file. info: dictionary A dictionary of supplementary info to write to append as attributes to the dataset. group_name: string An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default. Examples -------- >>> from unyt import cm >>> a = [1,2,3]*cm >>> myinfo = {'field':'dinosaurs', 'type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP """ from unyt._on_demand_imports import _h5py as h5py import pickle if info is None: info = {} info["units"] = str(self.units) info["unit_registry"] = np.void(pickle.dumps(self.units.registry.lut)) if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: if group_name in f: g = f[group_name] else: g = f.create_group(group_name) else: g = f if dataset_name in g.keys(): d = g[dataset_name] # Overwrite without deleting if we can get away with it. if d.shape == self.shape and d.dtype == self.dtype: d[...] = self for k in d.attrs.keys(): del d.attrs[k] else: del f[dataset_name] d = g.create_dataset(dataset_name, data=self) else: d = g.create_dataset(dataset_name, data=self) for k, v in info.items(): d.attrs[k] = v f.close()
[ "def", "write_hdf5", "(", "self", ",", "filename", ",", "dataset_name", "=", "None", ",", "info", "=", "None", ",", "group_name", "=", "None", ")", ":", "from", "unyt", ".", "_on_demand_imports", "import", "_h5py", "as", "h5py", "import", "pickle", "if", "info", "is", "None", ":", "info", "=", "{", "}", "info", "[", "\"units\"", "]", "=", "str", "(", "self", ".", "units", ")", "info", "[", "\"unit_registry\"", "]", "=", "np", ".", "void", "(", "pickle", ".", "dumps", "(", "self", ".", "units", ".", "registry", ".", "lut", ")", ")", "if", "dataset_name", "is", "None", ":", "dataset_name", "=", "\"array_data\"", "f", "=", "h5py", ".", "File", "(", "filename", ")", "if", "group_name", "is", "not", "None", ":", "if", "group_name", "in", "f", ":", "g", "=", "f", "[", "group_name", "]", "else", ":", "g", "=", "f", ".", "create_group", "(", "group_name", ")", "else", ":", "g", "=", "f", "if", "dataset_name", "in", "g", ".", "keys", "(", ")", ":", "d", "=", "g", "[", "dataset_name", "]", "# Overwrite without deleting if we can get away with it.", "if", "d", ".", "shape", "==", "self", ".", "shape", "and", "d", ".", "dtype", "==", "self", ".", "dtype", ":", "d", "[", "...", "]", "=", "self", "for", "k", "in", "d", ".", "attrs", ".", "keys", "(", ")", ":", "del", "d", ".", "attrs", "[", "k", "]", "else", ":", "del", "f", "[", "dataset_name", "]", "d", "=", "g", ".", "create_dataset", "(", "dataset_name", ",", "data", "=", "self", ")", "else", ":", "d", "=", "g", ".", "create_dataset", "(", "dataset_name", ",", "data", "=", "self", ")", "for", "k", ",", "v", "in", "info", ".", "items", "(", ")", ":", "d", ".", "attrs", "[", "k", "]", "=", "v", "f", ".", "close", "(", ")" ]
r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to create in the file. info: dictionary A dictionary of supplementary info to write to append as attributes to the dataset. group_name: string An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default. Examples -------- >>> from unyt import cm >>> a = [1,2,3]*cm >>> myinfo = {'field':'dinosaurs', 'type':'field_data'} >>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs', ... info=myinfo) # doctest: +SKIP
[ "r", "Writes", "a", "unyt_array", "to", "hdf5", "file", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1277-L1339
14,221
yt-project/unyt
unyt/array.py
unyt_array.from_hdf5
def from_hdf5(cls, filename, dataset_name=None, group_name=None): r"""Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters ---------- filename: string The filename to of the hdf5 file. dataset_name: string The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. group_name: string An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default. """ from unyt._on_demand_imports import _h5py as h5py import pickle if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: g = f[group_name] else: g = f dataset = g[dataset_name] data = dataset[:] units = dataset.attrs.get("units", "") unit_lut = pickle.loads(dataset.attrs["unit_registry"].tostring()) f.close() registry = UnitRegistry(lut=unit_lut, add_default_symbols=False) return cls(data, units, registry=registry)
python
def from_hdf5(cls, filename, dataset_name=None, group_name=None): r"""Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters ---------- filename: string The filename to of the hdf5 file. dataset_name: string The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. group_name: string An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default. """ from unyt._on_demand_imports import _h5py as h5py import pickle if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if group_name is not None: g = f[group_name] else: g = f dataset = g[dataset_name] data = dataset[:] units = dataset.attrs.get("units", "") unit_lut = pickle.loads(dataset.attrs["unit_registry"].tostring()) f.close() registry = UnitRegistry(lut=unit_lut, add_default_symbols=False) return cls(data, units, registry=registry)
[ "def", "from_hdf5", "(", "cls", ",", "filename", ",", "dataset_name", "=", "None", ",", "group_name", "=", "None", ")", ":", "from", "unyt", ".", "_on_demand_imports", "import", "_h5py", "as", "h5py", "import", "pickle", "if", "dataset_name", "is", "None", ":", "dataset_name", "=", "\"array_data\"", "f", "=", "h5py", ".", "File", "(", "filename", ")", "if", "group_name", "is", "not", "None", ":", "g", "=", "f", "[", "group_name", "]", "else", ":", "g", "=", "f", "dataset", "=", "g", "[", "dataset_name", "]", "data", "=", "dataset", "[", ":", "]", "units", "=", "dataset", ".", "attrs", ".", "get", "(", "\"units\"", ",", "\"\"", ")", "unit_lut", "=", "pickle", ".", "loads", "(", "dataset", ".", "attrs", "[", "\"unit_registry\"", "]", ".", "tostring", "(", ")", ")", "f", ".", "close", "(", ")", "registry", "=", "UnitRegistry", "(", "lut", "=", "unit_lut", ",", "add_default_symbols", "=", "False", ")", "return", "cls", "(", "data", ",", "units", ",", "registry", "=", "registry", ")" ]
r"""Attempts read in and convert a dataset in an hdf5 file into a unyt_array. Parameters ---------- filename: string The filename to of the hdf5 file. dataset_name: string The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well. group_name: string An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default.
[ "r", "Attempts", "read", "in", "and", "convert", "a", "dataset", "in", "an", "hdf5", "file", "into", "a", "unyt_array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1342-L1377
14,222
yt-project/unyt
unyt/array.py
unyt_array.copy
def copy(self, order="C"): """ Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:`numpy.copy` are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km >>> print(y) [[1 2 3] [4 5 6]] km """ return type(self)(np.copy(np.asarray(self)), self.units)
python
def copy(self, order="C"): """ Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:`numpy.copy` are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km >>> print(y) [[1 2 3] [4 5 6]] km """ return type(self)(np.copy(np.asarray(self)), self.units)
[ "def", "copy", "(", "self", ",", "order", "=", "\"C\"", ")", ":", "return", "type", "(", "self", ")", "(", "np", ".", "copy", "(", "np", ".", "asarray", "(", "self", ")", ")", ",", "self", ".", "units", ")" ]
Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:`numpy.copy` are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km >>> print(y) [[1 2 3] [4 5 6]] km
[ "Return", "a", "copy", "of", "the", "array", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1738-L1772
14,223
yt-project/unyt
unyt/array.py
unyt_array.dot
def dot(self, b, out=None): """dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s This array method can be conveniently chained: >>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2 """ res_units = self.units * getattr(b, "units", NULL_UNIT) ret = self.view(np.ndarray).dot(np.asarray(b), out=out) * res_units if out is not None: out.units = res_units return ret
python
def dot(self, b, out=None): """dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s This array method can be conveniently chained: >>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2 """ res_units = self.units * getattr(b, "units", NULL_UNIT) ret = self.view(np.ndarray).dot(np.asarray(b), out=out) * res_units if out is not None: out.units = res_units return ret
[ "def", "dot", "(", "self", ",", "b", ",", "out", "=", "None", ")", ":", "res_units", "=", "self", ".", "units", "*", "getattr", "(", "b", ",", "\"units\"", ",", "NULL_UNIT", ")", "ret", "=", "self", ".", "view", "(", "np", ".", "ndarray", ")", ".", "dot", "(", "np", ".", "asarray", "(", "b", ")", ",", "out", "=", "out", ")", "*", "res_units", "if", "out", "is", "not", "None", ":", "out", ".", "units", "=", "res_units", "return", "ret" ]
dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> from unyt import km, s >>> a = np.eye(2)*km >>> b = (np.ones((2, 2)) * 2)*s >>> print(a.dot(b)) [[2. 2.] [2. 2.]] km*s This array method can be conveniently chained: >>> print(a.dot(b).dot(b)) [[8. 8.] [8. 8.]] km*s**2
[ "dot", "product", "of", "two", "arrays", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1783-L1811
14,224
yt-project/unyt
unyt/__init__.py
import_units
def import_units(module, namespace): """Import Unit objects from a module into a namespace""" for key, value in module.__dict__.items(): if isinstance(value, (unyt_quantity, Unit)): namespace[key] = value
python
def import_units(module, namespace): """Import Unit objects from a module into a namespace""" for key, value in module.__dict__.items(): if isinstance(value, (unyt_quantity, Unit)): namespace[key] = value
[ "def", "import_units", "(", "module", ",", "namespace", ")", ":", "for", "key", ",", "value", "in", "module", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "unyt_quantity", ",", "Unit", ")", ")", ":", "namespace", "[", "key", "]", "=", "value" ]
Import Unit objects from a module into a namespace
[ "Import", "Unit", "objects", "from", "a", "module", "into", "a", "namespace" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/__init__.py#L98-L102
14,225
yt-project/unyt
unyt/unit_registry.py
_lookup_unit_symbol
def _lookup_unit_symbol(symbol_str, unit_symbol_lut): """ Searches for the unit data tuple corresponding to the given symbol. Parameters ---------- symbol_str : str The unit symbol to look up. unit_symbol_lut : dict Dictionary with symbols as keys and unit data tuples as values. """ if symbol_str in unit_symbol_lut: # lookup successful, return the tuple directly return unit_symbol_lut[symbol_str] # could still be a known symbol with a prefix prefix, symbol_wo_prefix = _split_prefix(symbol_str, unit_symbol_lut) if prefix: # lookup successful, it's a symbol with a prefix unit_data = unit_symbol_lut[symbol_wo_prefix] prefix_value = unit_prefixes[prefix][0] # Need to add some special handling for comoving units # this is fine for now, but it wouldn't work for a general # unit that has an arbitrary LaTeX representation if symbol_wo_prefix != "cm" and symbol_wo_prefix.endswith("cm"): sub_symbol_wo_prefix = symbol_wo_prefix[:-2] sub_symbol_str = symbol_str[:-2] else: sub_symbol_wo_prefix = symbol_wo_prefix sub_symbol_str = symbol_str latex_repr = unit_data[3].replace( "{" + sub_symbol_wo_prefix + "}", "{" + sub_symbol_str + "}" ) # Leave offset and dimensions the same, but adjust scale factor and # LaTeX representation ret = ( unit_data[0] * prefix_value, unit_data[1], unit_data[2], latex_repr, False, ) unit_symbol_lut[symbol_str] = ret return ret # no dice raise UnitParseError( "Could not find unit symbol '%s' in the provided " "symbols." % symbol_str )
python
def _lookup_unit_symbol(symbol_str, unit_symbol_lut): """ Searches for the unit data tuple corresponding to the given symbol. Parameters ---------- symbol_str : str The unit symbol to look up. unit_symbol_lut : dict Dictionary with symbols as keys and unit data tuples as values. """ if symbol_str in unit_symbol_lut: # lookup successful, return the tuple directly return unit_symbol_lut[symbol_str] # could still be a known symbol with a prefix prefix, symbol_wo_prefix = _split_prefix(symbol_str, unit_symbol_lut) if prefix: # lookup successful, it's a symbol with a prefix unit_data = unit_symbol_lut[symbol_wo_prefix] prefix_value = unit_prefixes[prefix][0] # Need to add some special handling for comoving units # this is fine for now, but it wouldn't work for a general # unit that has an arbitrary LaTeX representation if symbol_wo_prefix != "cm" and symbol_wo_prefix.endswith("cm"): sub_symbol_wo_prefix = symbol_wo_prefix[:-2] sub_symbol_str = symbol_str[:-2] else: sub_symbol_wo_prefix = symbol_wo_prefix sub_symbol_str = symbol_str latex_repr = unit_data[3].replace( "{" + sub_symbol_wo_prefix + "}", "{" + sub_symbol_str + "}" ) # Leave offset and dimensions the same, but adjust scale factor and # LaTeX representation ret = ( unit_data[0] * prefix_value, unit_data[1], unit_data[2], latex_repr, False, ) unit_symbol_lut[symbol_str] = ret return ret # no dice raise UnitParseError( "Could not find unit symbol '%s' in the provided " "symbols." % symbol_str )
[ "def", "_lookup_unit_symbol", "(", "symbol_str", ",", "unit_symbol_lut", ")", ":", "if", "symbol_str", "in", "unit_symbol_lut", ":", "# lookup successful, return the tuple directly", "return", "unit_symbol_lut", "[", "symbol_str", "]", "# could still be a known symbol with a prefix", "prefix", ",", "symbol_wo_prefix", "=", "_split_prefix", "(", "symbol_str", ",", "unit_symbol_lut", ")", "if", "prefix", ":", "# lookup successful, it's a symbol with a prefix", "unit_data", "=", "unit_symbol_lut", "[", "symbol_wo_prefix", "]", "prefix_value", "=", "unit_prefixes", "[", "prefix", "]", "[", "0", "]", "# Need to add some special handling for comoving units", "# this is fine for now, but it wouldn't work for a general", "# unit that has an arbitrary LaTeX representation", "if", "symbol_wo_prefix", "!=", "\"cm\"", "and", "symbol_wo_prefix", ".", "endswith", "(", "\"cm\"", ")", ":", "sub_symbol_wo_prefix", "=", "symbol_wo_prefix", "[", ":", "-", "2", "]", "sub_symbol_str", "=", "symbol_str", "[", ":", "-", "2", "]", "else", ":", "sub_symbol_wo_prefix", "=", "symbol_wo_prefix", "sub_symbol_str", "=", "symbol_str", "latex_repr", "=", "unit_data", "[", "3", "]", ".", "replace", "(", "\"{\"", "+", "sub_symbol_wo_prefix", "+", "\"}\"", ",", "\"{\"", "+", "sub_symbol_str", "+", "\"}\"", ")", "# Leave offset and dimensions the same, but adjust scale factor and", "# LaTeX representation", "ret", "=", "(", "unit_data", "[", "0", "]", "*", "prefix_value", ",", "unit_data", "[", "1", "]", ",", "unit_data", "[", "2", "]", ",", "latex_repr", ",", "False", ",", ")", "unit_symbol_lut", "[", "symbol_str", "]", "=", "ret", "return", "ret", "# no dice", "raise", "UnitParseError", "(", "\"Could not find unit symbol '%s' in the provided \"", "\"symbols.\"", "%", "symbol_str", ")" ]
Searches for the unit data tuple corresponding to the given symbol. Parameters ---------- symbol_str : str The unit symbol to look up. unit_symbol_lut : dict Dictionary with symbols as keys and unit data tuples as values.
[ "Searches", "for", "the", "unit", "data", "tuple", "corresponding", "to", "the", "given", "symbol", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L272-L326
14,226
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.unit_system_id
def unit_system_id(self): """ This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset's code unit system in the unit system registry. """ if self._unit_system_id is None: hash_data = bytearray() for k, v in sorted(self.lut.items()): hash_data.extend(k.encode("utf8")) hash_data.extend(repr(v).encode("utf8")) m = md5() m.update(hash_data) self._unit_system_id = str(m.hexdigest()) return self._unit_system_id
python
def unit_system_id(self): """ This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset's code unit system in the unit system registry. """ if self._unit_system_id is None: hash_data = bytearray() for k, v in sorted(self.lut.items()): hash_data.extend(k.encode("utf8")) hash_data.extend(repr(v).encode("utf8")) m = md5() m.update(hash_data) self._unit_system_id = str(m.hexdigest()) return self._unit_system_id
[ "def", "unit_system_id", "(", "self", ")", ":", "if", "self", ".", "_unit_system_id", "is", "None", ":", "hash_data", "=", "bytearray", "(", ")", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "lut", ".", "items", "(", ")", ")", ":", "hash_data", ".", "extend", "(", "k", ".", "encode", "(", "\"utf8\"", ")", ")", "hash_data", ".", "extend", "(", "repr", "(", "v", ")", ".", "encode", "(", "\"utf8\"", ")", ")", "m", "=", "md5", "(", ")", "m", ".", "update", "(", "hash_data", ")", "self", ".", "_unit_system_id", "=", "str", "(", "m", ".", "hexdigest", "(", ")", ")", "return", "self", ".", "_unit_system_id" ]
This is a unique identifier for the unit registry created from a FNV hash. It is needed to register a dataset's code unit system in the unit system registry.
[ "This", "is", "a", "unique", "identifier", "for", "the", "unit", "registry", "created", "from", "a", "FNV", "hash", ".", "It", "is", "needed", "to", "register", "a", "dataset", "s", "code", "unit", "system", "in", "the", "unit", "system", "registry", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L82-L96
14,227
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.add
def add( self, symbol, base_value, dimensions, tex_repr=None, offset=None, prefixable=False, ): """ Add a symbol to this registry. Parameters ---------- symbol : str The name of the unit base_value : float The scaling from the units value to the equivalent SI unit with the same dimensions dimensions : expr The dimensions of the unit tex_repr : str, optional The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. offset : float, optional If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. prefixable : bool If True, then SI-prefix versions of the unit will be created along with the unit itself. """ from unyt.unit_object import _validate_dimensions self._unit_system_id = None # Validate if not isinstance(base_value, float): raise UnitParseError( "base_value (%s) must be a float, got a %s." % (base_value, type(base_value)) ) if offset is not None: if not isinstance(offset, float): raise UnitParseError( "offset value (%s) must be a float, got a %s." % (offset, type(offset)) ) else: offset = 0.0 _validate_dimensions(dimensions) if tex_repr is None: # make educated guess that will look nice in most cases tex_repr = r"\rm{" + symbol.replace("_", r"\ ") + "}" # Add to lut self.lut[symbol] = (base_value, dimensions, offset, tex_repr, prefixable)
python
def add( self, symbol, base_value, dimensions, tex_repr=None, offset=None, prefixable=False, ): """ Add a symbol to this registry. Parameters ---------- symbol : str The name of the unit base_value : float The scaling from the units value to the equivalent SI unit with the same dimensions dimensions : expr The dimensions of the unit tex_repr : str, optional The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. offset : float, optional If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. prefixable : bool If True, then SI-prefix versions of the unit will be created along with the unit itself. """ from unyt.unit_object import _validate_dimensions self._unit_system_id = None # Validate if not isinstance(base_value, float): raise UnitParseError( "base_value (%s) must be a float, got a %s." % (base_value, type(base_value)) ) if offset is not None: if not isinstance(offset, float): raise UnitParseError( "offset value (%s) must be a float, got a %s." % (offset, type(offset)) ) else: offset = 0.0 _validate_dimensions(dimensions) if tex_repr is None: # make educated guess that will look nice in most cases tex_repr = r"\rm{" + symbol.replace("_", r"\ ") + "}" # Add to lut self.lut[symbol] = (base_value, dimensions, offset, tex_repr, prefixable)
[ "def", "add", "(", "self", ",", "symbol", ",", "base_value", ",", "dimensions", ",", "tex_repr", "=", "None", ",", "offset", "=", "None", ",", "prefixable", "=", "False", ",", ")", ":", "from", "unyt", ".", "unit_object", "import", "_validate_dimensions", "self", ".", "_unit_system_id", "=", "None", "# Validate", "if", "not", "isinstance", "(", "base_value", ",", "float", ")", ":", "raise", "UnitParseError", "(", "\"base_value (%s) must be a float, got a %s.\"", "%", "(", "base_value", ",", "type", "(", "base_value", ")", ")", ")", "if", "offset", "is", "not", "None", ":", "if", "not", "isinstance", "(", "offset", ",", "float", ")", ":", "raise", "UnitParseError", "(", "\"offset value (%s) must be a float, got a %s.\"", "%", "(", "offset", ",", "type", "(", "offset", ")", ")", ")", "else", ":", "offset", "=", "0.0", "_validate_dimensions", "(", "dimensions", ")", "if", "tex_repr", "is", "None", ":", "# make educated guess that will look nice in most cases", "tex_repr", "=", "r\"\\rm{\"", "+", "symbol", ".", "replace", "(", "\"_\"", ",", "r\"\\ \"", ")", "+", "\"}\"", "# Add to lut", "self", ".", "lut", "[", "symbol", "]", "=", "(", "base_value", ",", "dimensions", ",", "offset", ",", "tex_repr", ",", "prefixable", ")" ]
Add a symbol to this registry. Parameters ---------- symbol : str The name of the unit base_value : float The scaling from the units value to the equivalent SI unit with the same dimensions dimensions : expr The dimensions of the unit tex_repr : str, optional The LaTeX representation of the unit. If not provided a LaTeX representation is automatically generated from the name of the unit. offset : float, optional If set, the zero-point offset to apply to the unit to convert to SI. This is mostly used for units like Farhenheit and Celcius that are not defined on an absolute scale. prefixable : bool If True, then SI-prefix versions of the unit will be created along with the unit itself.
[ "Add", "a", "symbol", "to", "this", "registry", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L102-L164
14,228
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.remove
def remove(self, symbol): """ Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ) del self.lut[symbol]
python
def remove(self, symbol): """ Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ) del self.lut[symbol]
[ "def", "remove", "(", "self", ",", "symbol", ")", ":", "self", ".", "_unit_system_id", "=", "None", "if", "symbol", "not", "in", "self", ".", "lut", ":", "raise", "SymbolNotFoundError", "(", "\"Tried to remove the symbol '%s', but it does not exist \"", "\"in this registry.\"", "%", "symbol", ")", "del", "self", ".", "lut", "[", "symbol", "]" ]
Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry.
[ "Remove", "the", "entry", "for", "the", "unit", "matching", "symbol", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L166-L185
14,229
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.modify
def modify(self, symbol, base_value): """ Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters ---------- symbol : str The name of the symbol to modify base_value : float The new base_value for the symbol. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to modify the symbol '%s', but it does not exist " "in this registry." % symbol ) if hasattr(base_value, "in_base"): new_dimensions = base_value.units.dimensions base_value = base_value.in_base("mks") base_value = base_value.value else: new_dimensions = self.lut[symbol][1] self.lut[symbol] = (float(base_value), new_dimensions) + self.lut[symbol][2:]
python
def modify(self, symbol, base_value): """ Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters ---------- symbol : str The name of the symbol to modify base_value : float The new base_value for the symbol. """ self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to modify the symbol '%s', but it does not exist " "in this registry." % symbol ) if hasattr(base_value, "in_base"): new_dimensions = base_value.units.dimensions base_value = base_value.in_base("mks") base_value = base_value.value else: new_dimensions = self.lut[symbol][1] self.lut[symbol] = (float(base_value), new_dimensions) + self.lut[symbol][2:]
[ "def", "modify", "(", "self", ",", "symbol", ",", "base_value", ")", ":", "self", ".", "_unit_system_id", "=", "None", "if", "symbol", "not", "in", "self", ".", "lut", ":", "raise", "SymbolNotFoundError", "(", "\"Tried to modify the symbol '%s', but it does not exist \"", "\"in this registry.\"", "%", "symbol", ")", "if", "hasattr", "(", "base_value", ",", "\"in_base\"", ")", ":", "new_dimensions", "=", "base_value", ".", "units", ".", "dimensions", "base_value", "=", "base_value", ".", "in_base", "(", "\"mks\"", ")", "base_value", "=", "base_value", ".", "value", "else", ":", "new_dimensions", "=", "self", ".", "lut", "[", "symbol", "]", "[", "1", "]", "self", ".", "lut", "[", "symbol", "]", "=", "(", "float", "(", "base_value", ")", ",", "new_dimensions", ")", "+", "self", ".", "lut", "[", "symbol", "]", "[", "2", ":", "]" ]
Change the base value of a unit symbol. Useful for adjusting code units after parsing parameters. Parameters ---------- symbol : str The name of the symbol to modify base_value : float The new base_value for the symbol.
[ "Change", "the", "base", "value", "of", "a", "unit", "symbol", ".", "Useful", "for", "adjusting", "code", "units", "after", "parsing", "parameters", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L187-L216
14,230
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.to_json
def to_json(self): """ Returns a json-serialized version of the unit registry """ sanitized_lut = {} for k, v in self.lut.items(): san_v = list(v) repr_dims = str(v[1]) san_v[1] = repr_dims sanitized_lut[k] = tuple(san_v) return json.dumps(sanitized_lut)
python
def to_json(self): """ Returns a json-serialized version of the unit registry """ sanitized_lut = {} for k, v in self.lut.items(): san_v = list(v) repr_dims = str(v[1]) san_v[1] = repr_dims sanitized_lut[k] = tuple(san_v) return json.dumps(sanitized_lut)
[ "def", "to_json", "(", "self", ")", ":", "sanitized_lut", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "lut", ".", "items", "(", ")", ":", "san_v", "=", "list", "(", "v", ")", "repr_dims", "=", "str", "(", "v", "[", "1", "]", ")", "san_v", "[", "1", "]", "=", "repr_dims", "sanitized_lut", "[", "k", "]", "=", "tuple", "(", "san_v", ")", "return", "json", ".", "dumps", "(", "sanitized_lut", ")" ]
Returns a json-serialized version of the unit registry
[ "Returns", "a", "json", "-", "serialized", "version", "of", "the", "unit", "registry" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L225-L236
14,231
yt-project/unyt
unyt/unit_registry.py
UnitRegistry.from_json
def from_json(cls, json_text): """ Returns a UnitRegistry object from a json-serialized unit registry Parameters ---------- json_text : str A string containing a json represention of a UnitRegistry """ data = json.loads(json_text) lut = {} for k, v in data.items(): unsan_v = list(v) unsan_v[1] = sympify(v[1], locals=vars(unyt_dims)) lut[k] = tuple(unsan_v) return cls(lut=lut, add_default_symbols=False)
python
def from_json(cls, json_text): """ Returns a UnitRegistry object from a json-serialized unit registry Parameters ---------- json_text : str A string containing a json represention of a UnitRegistry """ data = json.loads(json_text) lut = {} for k, v in data.items(): unsan_v = list(v) unsan_v[1] = sympify(v[1], locals=vars(unyt_dims)) lut[k] = tuple(unsan_v) return cls(lut=lut, add_default_symbols=False)
[ "def", "from_json", "(", "cls", ",", "json_text", ")", ":", "data", "=", "json", ".", "loads", "(", "json_text", ")", "lut", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "unsan_v", "=", "list", "(", "v", ")", "unsan_v", "[", "1", "]", "=", "sympify", "(", "v", "[", "1", "]", ",", "locals", "=", "vars", "(", "unyt_dims", ")", ")", "lut", "[", "k", "]", "=", "tuple", "(", "unsan_v", ")", "return", "cls", "(", "lut", "=", "lut", ",", "add_default_symbols", "=", "False", ")" ]
Returns a UnitRegistry object from a json-serialized unit registry Parameters ---------- json_text : str A string containing a json represention of a UnitRegistry
[ "Returns", "a", "UnitRegistry", "object", "from", "a", "json", "-", "serialized", "unit", "registry" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L239-L256
14,232
yt-project/unyt
unyt/unit_object.py
_em_conversion
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None): """Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression of the original unit with the new one in the unit expression and multiplying by the scale factor. """ conv_unit, canonical_unit, scale = conv_data if conv_unit is None: conv_unit = canonical_unit new_expr = scale * canonical_unit.expr if unit_system is not None: # we don't know the to_units, so we get it directly from the # conv_data to_units = Unit(conv_unit.expr, registry=orig_units.registry) new_units = Unit(new_expr, registry=orig_units.registry) conv = new_units.get_conversion_factor(to_units) return to_units, conv
python
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None): """Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression of the original unit with the new one in the unit expression and multiplying by the scale factor. """ conv_unit, canonical_unit, scale = conv_data if conv_unit is None: conv_unit = canonical_unit new_expr = scale * canonical_unit.expr if unit_system is not None: # we don't know the to_units, so we get it directly from the # conv_data to_units = Unit(conv_unit.expr, registry=orig_units.registry) new_units = Unit(new_expr, registry=orig_units.registry) conv = new_units.get_conversion_factor(to_units) return to_units, conv
[ "def", "_em_conversion", "(", "orig_units", ",", "conv_data", ",", "to_units", "=", "None", ",", "unit_system", "=", "None", ")", ":", "conv_unit", ",", "canonical_unit", ",", "scale", "=", "conv_data", "if", "conv_unit", "is", "None", ":", "conv_unit", "=", "canonical_unit", "new_expr", "=", "scale", "*", "canonical_unit", ".", "expr", "if", "unit_system", "is", "not", "None", ":", "# we don't know the to_units, so we get it directly from the", "# conv_data", "to_units", "=", "Unit", "(", "conv_unit", ".", "expr", ",", "registry", "=", "orig_units", ".", "registry", ")", "new_units", "=", "Unit", "(", "new_expr", ",", "registry", "=", "orig_units", ".", "registry", ")", "conv", "=", "new_units", ".", "get_conversion_factor", "(", "to_units", ")", "return", "to_units", ",", "conv" ]
Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression of the original unit with the new one in the unit expression and multiplying by the scale factor.
[ "Convert", "between", "E&M", "&", "MKS", "base", "units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L786-L805
14,233
yt-project/unyt
unyt/unit_object.py
_check_em_conversion
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None): """Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readily converted. This function tries to see if the unit is an atomic base unit that is present in the em_conversions dict. If it does not contain E&M units, the function returns an empty tuple. If it does contain an atomic E&M unit in the em_conversions dict, it returns a tuple containing the unit to convert to and scale factor. If it contains a more complicated E&M unit and we are trying to convert between CGS & MKS E&M units, it raises an error. """ em_map = () if unit == to_unit or unit.dimensions not in em_conversion_dims: return em_map if unit.is_atomic: prefix, unit_wo_prefix = _split_prefix(str(unit), unit.registry.lut) else: prefix, unit_wo_prefix = "", str(unit) if (unit_wo_prefix, unit.dimensions) in em_conversions: em_info = em_conversions[unit_wo_prefix, unit.dimensions] em_unit = Unit(prefix + em_info[1], registry=registry) if to_unit is None: cmks_in_unit = current_mks in unit.dimensions.atoms() cmks_in_unit_system = unit_system.units_map[current_mks] cmks_in_unit_system = cmks_in_unit_system is not None if cmks_in_unit and cmks_in_unit_system: em_map = (unit_system[unit.dimensions], unit, 1.0) else: em_map = (None, em_unit, em_info[2]) elif to_unit.dimensions == em_unit.dimensions: em_map = (to_unit, em_unit, em_info[2]) if em_map: return em_map if unit_system is None: from unyt.unit_systems import unit_system_registry unit_system = unit_system_registry["mks"] for unit_atom in unit.expr.atoms(): if unit_atom.is_Number: continue bu = str(unit_atom) budims = Unit(bu, registry=registry).dimensions try: if str(unit_system[budims]) == bu: continue except MissingMKSCurrent: raise MKSCGSConversionError(unit) return em_map
python
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None): """Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readily converted. This function tries to see if the unit is an atomic base unit that is present in the em_conversions dict. If it does not contain E&M units, the function returns an empty tuple. If it does contain an atomic E&M unit in the em_conversions dict, it returns a tuple containing the unit to convert to and scale factor. If it contains a more complicated E&M unit and we are trying to convert between CGS & MKS E&M units, it raises an error. """ em_map = () if unit == to_unit or unit.dimensions not in em_conversion_dims: return em_map if unit.is_atomic: prefix, unit_wo_prefix = _split_prefix(str(unit), unit.registry.lut) else: prefix, unit_wo_prefix = "", str(unit) if (unit_wo_prefix, unit.dimensions) in em_conversions: em_info = em_conversions[unit_wo_prefix, unit.dimensions] em_unit = Unit(prefix + em_info[1], registry=registry) if to_unit is None: cmks_in_unit = current_mks in unit.dimensions.atoms() cmks_in_unit_system = unit_system.units_map[current_mks] cmks_in_unit_system = cmks_in_unit_system is not None if cmks_in_unit and cmks_in_unit_system: em_map = (unit_system[unit.dimensions], unit, 1.0) else: em_map = (None, em_unit, em_info[2]) elif to_unit.dimensions == em_unit.dimensions: em_map = (to_unit, em_unit, em_info[2]) if em_map: return em_map if unit_system is None: from unyt.unit_systems import unit_system_registry unit_system = unit_system_registry["mks"] for unit_atom in unit.expr.atoms(): if unit_atom.is_Number: continue bu = str(unit_atom) budims = Unit(bu, registry=registry).dimensions try: if str(unit_system[budims]) == bu: continue except MissingMKSCurrent: raise MKSCGSConversionError(unit) return em_map
[ "def", "_check_em_conversion", "(", "unit", ",", "to_unit", "=", "None", ",", "unit_system", "=", "None", ",", "registry", "=", "None", ")", ":", "em_map", "=", "(", ")", "if", "unit", "==", "to_unit", "or", "unit", ".", "dimensions", "not", "in", "em_conversion_dims", ":", "return", "em_map", "if", "unit", ".", "is_atomic", ":", "prefix", ",", "unit_wo_prefix", "=", "_split_prefix", "(", "str", "(", "unit", ")", ",", "unit", ".", "registry", ".", "lut", ")", "else", ":", "prefix", ",", "unit_wo_prefix", "=", "\"\"", ",", "str", "(", "unit", ")", "if", "(", "unit_wo_prefix", ",", "unit", ".", "dimensions", ")", "in", "em_conversions", ":", "em_info", "=", "em_conversions", "[", "unit_wo_prefix", ",", "unit", ".", "dimensions", "]", "em_unit", "=", "Unit", "(", "prefix", "+", "em_info", "[", "1", "]", ",", "registry", "=", "registry", ")", "if", "to_unit", "is", "None", ":", "cmks_in_unit", "=", "current_mks", "in", "unit", ".", "dimensions", ".", "atoms", "(", ")", "cmks_in_unit_system", "=", "unit_system", ".", "units_map", "[", "current_mks", "]", "cmks_in_unit_system", "=", "cmks_in_unit_system", "is", "not", "None", "if", "cmks_in_unit", "and", "cmks_in_unit_system", ":", "em_map", "=", "(", "unit_system", "[", "unit", ".", "dimensions", "]", ",", "unit", ",", "1.0", ")", "else", ":", "em_map", "=", "(", "None", ",", "em_unit", ",", "em_info", "[", "2", "]", ")", "elif", "to_unit", ".", "dimensions", "==", "em_unit", ".", "dimensions", ":", "em_map", "=", "(", "to_unit", ",", "em_unit", ",", "em_info", "[", "2", "]", ")", "if", "em_map", ":", "return", "em_map", "if", "unit_system", "is", "None", ":", "from", "unyt", ".", "unit_systems", "import", "unit_system_registry", "unit_system", "=", "unit_system_registry", "[", "\"mks\"", "]", "for", "unit_atom", "in", "unit", ".", "expr", ".", "atoms", "(", ")", ":", "if", "unit_atom", ".", "is_Number", ":", "continue", "bu", "=", "str", "(", "unit_atom", ")", "budims", "=", "Unit", "(", "bu", ",", "registry", "=", "registry", ")", ".", "dimensions", "try", ":", "if", "str", "(", "unit_system", "[", "budims", "]", ")", "==", "bu", ":", "continue", "except", "MissingMKSCurrent", ":", "raise", "MKSCGSConversionError", "(", "unit", ")", "return", "em_map" ]
Check to see if the units contain E&M units This function supports unyt's ability to convert data to and from E&M electromagnetic units. However, this support is limited and only very simple unit expressions can be readily converted. This function tries to see if the unit is an atomic base unit that is present in the em_conversions dict. If it does not contain E&M units, the function returns an empty tuple. If it does contain an atomic E&M unit in the em_conversions dict, it returns a tuple containing the unit to convert to and scale factor. If it contains a more complicated E&M unit and we are trying to convert between CGS & MKS E&M units, it raises an error.
[ "Check", "to", "see", "if", "the", "units", "contain", "E&M", "units" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L809-L858
14,234
yt-project/unyt
unyt/unit_object.py
_get_conversion_factor
def _get_conversion_factor(old_units, new_units, dtype): """ Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object The current units. new_units : str or Unit object The units we want. dtype: NumPy dtype The dtype of the conversion factor Returns ------- conversion_factor : float `old_units / new_units` offset : float or None Offset between the old unit and new unit. """ if old_units.dimensions != new_units.dimensions: raise UnitConversionError( old_units, old_units.dimensions, new_units, new_units.dimensions ) ratio = old_units.base_value / new_units.base_value if old_units.base_offset == 0 and new_units.base_offset == 0: return (ratio, None) else: # the dimensions are the same, so both are temperatures, where # it's legal to convert units so no need to do error checking return ratio, ratio * old_units.base_offset - new_units.base_offset
python
def _get_conversion_factor(old_units, new_units, dtype): """ Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object The current units. new_units : str or Unit object The units we want. dtype: NumPy dtype The dtype of the conversion factor Returns ------- conversion_factor : float `old_units / new_units` offset : float or None Offset between the old unit and new unit. """ if old_units.dimensions != new_units.dimensions: raise UnitConversionError( old_units, old_units.dimensions, new_units, new_units.dimensions ) ratio = old_units.base_value / new_units.base_value if old_units.base_offset == 0 and new_units.base_offset == 0: return (ratio, None) else: # the dimensions are the same, so both are temperatures, where # it's legal to convert units so no need to do error checking return ratio, ratio * old_units.base_offset - new_units.base_offset
[ "def", "_get_conversion_factor", "(", "old_units", ",", "new_units", ",", "dtype", ")", ":", "if", "old_units", ".", "dimensions", "!=", "new_units", ".", "dimensions", ":", "raise", "UnitConversionError", "(", "old_units", ",", "old_units", ".", "dimensions", ",", "new_units", ",", "new_units", ".", "dimensions", ")", "ratio", "=", "old_units", ".", "base_value", "/", "new_units", ".", "base_value", "if", "old_units", ".", "base_offset", "==", "0", "and", "new_units", ".", "base_offset", "==", "0", ":", "return", "(", "ratio", ",", "None", ")", "else", ":", "# the dimensions are the same, so both are temperatures, where", "# it's legal to convert units so no need to do error checking", "return", "ratio", ",", "ratio", "*", "old_units", ".", "base_offset", "-", "new_units", ".", "base_offset" ]
Get the conversion factor between two units of equivalent dimensions. This is the number you multiply data by to convert from values in `old_units` to values in `new_units`. Parameters ---------- old_units: str or Unit object The current units. new_units : str or Unit object The units we want. dtype: NumPy dtype The dtype of the conversion factor Returns ------- conversion_factor : float `old_units / new_units` offset : float or None Offset between the old unit and new unit.
[ "Get", "the", "conversion", "factor", "between", "two", "units", "of", "equivalent", "dimensions", ".", "This", "is", "the", "number", "you", "multiply", "data", "by", "to", "convert", "from", "values", "in", "old_units", "to", "values", "in", "new_units", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L861-L894
14,235
yt-project/unyt
unyt/unit_object.py
_get_unit_data_from_expr
def _get_unit_data_from_expr(unit_expr, unit_symbol_lut): """ Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the unit data for each valid unit symbol. """ # Now for the sympy possibilities if isinstance(unit_expr, Number): if unit_expr is sympy_one: return (1.0, sympy_one) return (float(unit_expr), sympy_one) if isinstance(unit_expr, Symbol): return _lookup_unit_symbol(unit_expr.name, unit_symbol_lut) if isinstance(unit_expr, Pow): unit_data = _get_unit_data_from_expr(unit_expr.args[0], unit_symbol_lut) power = unit_expr.args[1] if isinstance(power, Symbol): raise UnitParseError("Invalid unit expression '%s'." % unit_expr) conv = float(unit_data[0] ** power) unit = unit_data[1] ** power return (conv, unit) if isinstance(unit_expr, Mul): base_value = 1.0 dimensions = 1 for expr in unit_expr.args: unit_data = _get_unit_data_from_expr(expr, unit_symbol_lut) base_value *= unit_data[0] dimensions *= unit_data[1] return (float(base_value), dimensions) raise UnitParseError( "Cannot parse for unit data from '%s'. Please supply" " an expression of only Unit, Symbol, Pow, and Mul" "objects." % str(unit_expr) )
python
def _get_unit_data_from_expr(unit_expr, unit_symbol_lut): """ Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the unit data for each valid unit symbol. """ # Now for the sympy possibilities if isinstance(unit_expr, Number): if unit_expr is sympy_one: return (1.0, sympy_one) return (float(unit_expr), sympy_one) if isinstance(unit_expr, Symbol): return _lookup_unit_symbol(unit_expr.name, unit_symbol_lut) if isinstance(unit_expr, Pow): unit_data = _get_unit_data_from_expr(unit_expr.args[0], unit_symbol_lut) power = unit_expr.args[1] if isinstance(power, Symbol): raise UnitParseError("Invalid unit expression '%s'." % unit_expr) conv = float(unit_data[0] ** power) unit = unit_data[1] ** power return (conv, unit) if isinstance(unit_expr, Mul): base_value = 1.0 dimensions = 1 for expr in unit_expr.args: unit_data = _get_unit_data_from_expr(expr, unit_symbol_lut) base_value *= unit_data[0] dimensions *= unit_data[1] return (float(base_value), dimensions) raise UnitParseError( "Cannot parse for unit data from '%s'. Please supply" " an expression of only Unit, Symbol, Pow, and Mul" "objects." % str(unit_expr) )
[ "def", "_get_unit_data_from_expr", "(", "unit_expr", ",", "unit_symbol_lut", ")", ":", "# Now for the sympy possibilities", "if", "isinstance", "(", "unit_expr", ",", "Number", ")", ":", "if", "unit_expr", "is", "sympy_one", ":", "return", "(", "1.0", ",", "sympy_one", ")", "return", "(", "float", "(", "unit_expr", ")", ",", "sympy_one", ")", "if", "isinstance", "(", "unit_expr", ",", "Symbol", ")", ":", "return", "_lookup_unit_symbol", "(", "unit_expr", ".", "name", ",", "unit_symbol_lut", ")", "if", "isinstance", "(", "unit_expr", ",", "Pow", ")", ":", "unit_data", "=", "_get_unit_data_from_expr", "(", "unit_expr", ".", "args", "[", "0", "]", ",", "unit_symbol_lut", ")", "power", "=", "unit_expr", ".", "args", "[", "1", "]", "if", "isinstance", "(", "power", ",", "Symbol", ")", ":", "raise", "UnitParseError", "(", "\"Invalid unit expression '%s'.\"", "%", "unit_expr", ")", "conv", "=", "float", "(", "unit_data", "[", "0", "]", "**", "power", ")", "unit", "=", "unit_data", "[", "1", "]", "**", "power", "return", "(", "conv", ",", "unit", ")", "if", "isinstance", "(", "unit_expr", ",", "Mul", ")", ":", "base_value", "=", "1.0", "dimensions", "=", "1", "for", "expr", "in", "unit_expr", ".", "args", ":", "unit_data", "=", "_get_unit_data_from_expr", "(", "expr", ",", "unit_symbol_lut", ")", "base_value", "*=", "unit_data", "[", "0", "]", "dimensions", "*=", "unit_data", "[", "1", "]", "return", "(", "float", "(", "base_value", ")", ",", "dimensions", ")", "raise", "UnitParseError", "(", "\"Cannot parse for unit data from '%s'. Please supply\"", "\" an expression of only Unit, Symbol, Pow, and Mul\"", "\"objects.\"", "%", "str", "(", "unit_expr", ")", ")" ]
Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the unit data for each valid unit symbol.
[ "Grabs", "the", "total", "base_value", "and", "dimensions", "from", "a", "valid", "unit", "expression", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L902-L946
14,236
yt-project/unyt
unyt/unit_object.py
define_unit
def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): """ Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mph" unit with ``(1.0, "mile/hr")`` or with ``1.0*unyt.mile/unyt.hr`` tex_repr : string, optional The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. offset : float, optional The default offset for the unit. If not set, an offset of 0 is assumed. prefixable : boolean, optional Whether or not the new unit can use SI prefixes. Default: False registry : :class:`unyt.unit_registry.UnitRegistry` or None The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level :mod:`unyt` namespace to ease working with the newly defined unit. See the example below. Examples -------- >>> from unyt import day >>> two_weeks = 14.0*day >>> one_day = 1.0*day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless """ from unyt.array import unyt_quantity, _iterable import unyt if registry is None: registry = default_unit_registry if symbol in registry: raise RuntimeError( "Unit symbol '%s' already exists in the provided " "registry" % symbol ) if not isinstance(value, unyt_quantity): if _iterable(value) and len(value) == 2: value = unyt_quantity(value[0], value[1], registry=registry) else: raise RuntimeError( '"value" needs to be a quantity or ' "(value, unit) tuple!" ) base_value = float(value.in_base(unit_system="mks")) dimensions = value.units.dimensions registry.add( symbol, base_value, dimensions, prefixable=prefixable, tex_repr=tex_repr, offset=offset, ) if registry is default_unit_registry: u = Unit(symbol, registry=registry) setattr(unyt, symbol, u)
python
def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): """ Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mph" unit with ``(1.0, "mile/hr")`` or with ``1.0*unyt.mile/unyt.hr`` tex_repr : string, optional The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. offset : float, optional The default offset for the unit. If not set, an offset of 0 is assumed. prefixable : boolean, optional Whether or not the new unit can use SI prefixes. Default: False registry : :class:`unyt.unit_registry.UnitRegistry` or None The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level :mod:`unyt` namespace to ease working with the newly defined unit. See the example below. Examples -------- >>> from unyt import day >>> two_weeks = 14.0*day >>> one_day = 1.0*day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless """ from unyt.array import unyt_quantity, _iterable import unyt if registry is None: registry = default_unit_registry if symbol in registry: raise RuntimeError( "Unit symbol '%s' already exists in the provided " "registry" % symbol ) if not isinstance(value, unyt_quantity): if _iterable(value) and len(value) == 2: value = unyt_quantity(value[0], value[1], registry=registry) else: raise RuntimeError( '"value" needs to be a quantity or ' "(value, unit) tuple!" ) base_value = float(value.in_base(unit_system="mks")) dimensions = value.units.dimensions registry.add( symbol, base_value, dimensions, prefixable=prefixable, tex_repr=tex_repr, offset=offset, ) if registry is default_unit_registry: u = Unit(symbol, registry=registry) setattr(unyt, symbol, u)
[ "def", "define_unit", "(", "symbol", ",", "value", ",", "tex_repr", "=", "None", ",", "offset", "=", "None", ",", "prefixable", "=", "False", ",", "registry", "=", "None", ")", ":", "from", "unyt", ".", "array", "import", "unyt_quantity", ",", "_iterable", "import", "unyt", "if", "registry", "is", "None", ":", "registry", "=", "default_unit_registry", "if", "symbol", "in", "registry", ":", "raise", "RuntimeError", "(", "\"Unit symbol '%s' already exists in the provided \"", "\"registry\"", "%", "symbol", ")", "if", "not", "isinstance", "(", "value", ",", "unyt_quantity", ")", ":", "if", "_iterable", "(", "value", ")", "and", "len", "(", "value", ")", "==", "2", ":", "value", "=", "unyt_quantity", "(", "value", "[", "0", "]", ",", "value", "[", "1", "]", ",", "registry", "=", "registry", ")", "else", ":", "raise", "RuntimeError", "(", "'\"value\" needs to be a quantity or '", "\"(value, unit) tuple!\"", ")", "base_value", "=", "float", "(", "value", ".", "in_base", "(", "unit_system", "=", "\"mks\"", ")", ")", "dimensions", "=", "value", ".", "units", ".", "dimensions", "registry", ".", "add", "(", "symbol", ",", "base_value", ",", "dimensions", ",", "prefixable", "=", "prefixable", ",", "tex_repr", "=", "tex_repr", ",", "offset", "=", "offset", ",", ")", "if", "registry", "is", "default_unit_registry", ":", "u", "=", "Unit", "(", "symbol", ",", "registry", "=", "registry", ")", "setattr", "(", "unyt", ",", "symbol", ",", "u", ")" ]
Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mph" unit with ``(1.0, "mile/hr")`` or with ``1.0*unyt.mile/unyt.hr`` tex_repr : string, optional The LaTeX representation of the new unit. If one is not supplied, it will be generated automatically based on the symbol string. offset : float, optional The default offset for the unit. If not set, an offset of 0 is assumed. prefixable : boolean, optional Whether or not the new unit can use SI prefixes. Default: False registry : :class:`unyt.unit_registry.UnitRegistry` or None The unit registry to add the unit to. If None, then defaults to the global default unit registry. If registry is set to None then the unit object will be added as an attribute to the top-level :mod:`unyt` namespace to ease working with the newly defined unit. See the example below. Examples -------- >>> from unyt import day >>> two_weeks = 14.0*day >>> one_day = 1.0*day >>> define_unit("two_weeks", two_weeks) >>> from unyt import two_weeks >>> print((3*two_weeks)/one_day) 42.0 dimensionless
[ "Define", "a", "new", "unit", "and", "add", "it", "to", "the", "specified", "unit", "registry", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L976-L1042
14,237
yt-project/unyt
unyt/unit_object.py
Unit.latex_repr
def latex_repr(self): """A LaTeX representation for the unit Examples -------- >>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}' """ if self._latex_repr is not None: return self._latex_repr if self.expr.is_Atom: expr = self.expr else: expr = self.expr.copy() self._latex_repr = _get_latex_representation(expr, self.registry) return self._latex_repr
python
def latex_repr(self): """A LaTeX representation for the unit Examples -------- >>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}' """ if self._latex_repr is not None: return self._latex_repr if self.expr.is_Atom: expr = self.expr else: expr = self.expr.copy() self._latex_repr = _get_latex_representation(expr, self.registry) return self._latex_repr
[ "def", "latex_repr", "(", "self", ")", ":", "if", "self", ".", "_latex_repr", "is", "not", "None", ":", "return", "self", ".", "_latex_repr", "if", "self", ".", "expr", ".", "is_Atom", ":", "expr", "=", "self", ".", "expr", "else", ":", "expr", "=", "self", ".", "expr", ".", "copy", "(", ")", "self", ".", "_latex_repr", "=", "_get_latex_representation", "(", "expr", ",", "self", ".", "registry", ")", "return", "self", ".", "_latex_repr" ]
A LaTeX representation for the unit Examples -------- >>> from unyt import g, cm >>> (g/cm**3).units.latex_repr '\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}'
[ "A", "LaTeX", "representation", "for", "the", "unit" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L261-L277
14,238
yt-project/unyt
unyt/unit_object.py
Unit.is_code_unit
def is_code_unit(self): """Is this a "code" unit? Returns ------- True if the unit consists of atom units that being with "code". False otherwise """ for atom in self.expr.atoms(): if not (str(atom).startswith("code") or atom.is_Number): return False return True
python
def is_code_unit(self): """Is this a "code" unit? Returns ------- True if the unit consists of atom units that being with "code". False otherwise """ for atom in self.expr.atoms(): if not (str(atom).startswith("code") or atom.is_Number): return False return True
[ "def", "is_code_unit", "(", "self", ")", ":", "for", "atom", "in", "self", ".", "expr", ".", "atoms", "(", ")", ":", "if", "not", "(", "str", "(", "atom", ")", ".", "startswith", "(", "\"code\"", ")", "or", "atom", ".", "is_Number", ")", ":", "return", "False", "return", "True" ]
Is this a "code" unit? Returns ------- True if the unit consists of atom units that being with "code". False otherwise
[ "Is", "this", "a", "code", "unit?" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L514-L526
14,239
yt-project/unyt
unyt/unit_object.py
Unit.list_equivalencies
def list_equivalencies(self): """Lists the possible equivalencies associated with this unit object Examples -------- >>> from unyt import km >>> km.units.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length """ from unyt.equivalencies import equivalence_registry for k, v in equivalence_registry.items(): if self.has_equivalent(k): print(v())
python
def list_equivalencies(self): """Lists the possible equivalencies associated with this unit object Examples -------- >>> from unyt import km >>> km.units.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length """ from unyt.equivalencies import equivalence_registry for k, v in equivalence_registry.items(): if self.has_equivalent(k): print(v())
[ "def", "list_equivalencies", "(", "self", ")", ":", "from", "unyt", ".", "equivalencies", "import", "equivalence_registry", "for", "k", ",", "v", "in", "equivalence_registry", ".", "items", "(", ")", ":", "if", "self", ".", "has_equivalent", "(", "k", ")", ":", "print", "(", "v", "(", ")", ")" ]
Lists the possible equivalencies associated with this unit object Examples -------- >>> from unyt import km >>> km.units.list_equivalencies() spectral: length <-> spatial_frequency <-> frequency <-> energy schwarzschild: mass <-> length compton: mass <-> length
[ "Lists", "the", "possible", "equivalencies", "associated", "with", "this", "unit", "object" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L528-L543
14,240
yt-project/unyt
unyt/unit_object.py
Unit.get_base_equivalent
def get_base_equivalent(self, unit_system=None): """Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3 """ from unyt.unit_registry import _sanitize_unit_system unit_system = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, registry=self.registry, unit_system=unit_system ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, unit_system) if any(conv_data): new_units, _ = _em_conversion(self, conv_data, unit_system=unit_system) else: try: new_units = unit_system[self.dimensions] except MissingMKSCurrent: raise UnitsNotReducible(self.units, unit_system) return Unit(new_units, registry=self.registry)
python
def get_base_equivalent(self, unit_system=None): """Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3 """ from unyt.unit_registry import _sanitize_unit_system unit_system = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, registry=self.registry, unit_system=unit_system ) except MKSCGSConversionError: raise UnitsNotReducible(self.units, unit_system) if any(conv_data): new_units, _ = _em_conversion(self, conv_data, unit_system=unit_system) else: try: new_units = unit_system[self.dimensions] except MissingMKSCurrent: raise UnitsNotReducible(self.units, unit_system) return Unit(new_units, registry=self.registry)
[ "def", "get_base_equivalent", "(", "self", ",", "unit_system", "=", "None", ")", ":", "from", "unyt", ".", "unit_registry", "import", "_sanitize_unit_system", "unit_system", "=", "_sanitize_unit_system", "(", "unit_system", ",", "self", ")", "try", ":", "conv_data", "=", "_check_em_conversion", "(", "self", ".", "units", ",", "registry", "=", "self", ".", "registry", ",", "unit_system", "=", "unit_system", ")", "except", "MKSCGSConversionError", ":", "raise", "UnitsNotReducible", "(", "self", ".", "units", ",", "unit_system", ")", "if", "any", "(", "conv_data", ")", ":", "new_units", ",", "_", "=", "_em_conversion", "(", "self", ",", "conv_data", ",", "unit_system", "=", "unit_system", ")", "else", ":", "try", ":", "new_units", "=", "unit_system", "[", "self", ".", "dimensions", "]", "except", "MissingMKSCurrent", ":", "raise", "UnitsNotReducible", "(", "self", ".", "units", ",", "unit_system", ")", "return", "Unit", "(", "new_units", ",", "registry", "=", "self", ".", "registry", ")" ]
Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3
[ "Create", "and", "return", "dimensionally", "-", "equivalent", "units", "in", "a", "specified", "base", "." ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L564-L589
14,241
yt-project/unyt
unyt/unit_object.py
Unit.as_coeff_unit
def as_coeff_unit(self): """Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m) """ coeff, mul = self.expr.as_coeff_Mul() coeff = float(coeff) ret = Unit( mul, self.base_value / coeff, self.base_offset, self.dimensions, self.registry, ) return coeff, ret
python
def as_coeff_unit(self): """Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m) """ coeff, mul = self.expr.as_coeff_Mul() coeff = float(coeff) ret = Unit( mul, self.base_value / coeff, self.base_offset, self.dimensions, self.registry, ) return coeff, ret
[ "def", "as_coeff_unit", "(", "self", ")", ":", "coeff", ",", "mul", "=", "self", ".", "expr", ".", "as_coeff_Mul", "(", ")", "coeff", "=", "float", "(", "coeff", ")", "ret", "=", "Unit", "(", "mul", ",", "self", ".", "base_value", "/", "coeff", ",", "self", ".", "base_offset", ",", "self", ".", "dimensions", ",", "self", ".", "registry", ",", ")", "return", "coeff", ",", "ret" ]
Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m >>> unit.as_coeff_unit() (100.0, m)
[ "Factor", "the", "coefficient", "multiplying", "a", "unit" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L653-L679
14,242
yt-project/unyt
unyt/unit_object.py
Unit.simplify
def simplify(self): """Return a new equivalent unit object with a simplified unit expression >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m """ expr = self.expr self.expr = _cancel_mul(expr, self.registry) return self
python
def simplify(self): """Return a new equivalent unit object with a simplified unit expression >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m """ expr = self.expr self.expr = _cancel_mul(expr, self.registry) return self
[ "def", "simplify", "(", "self", ")", ":", "expr", "=", "self", ".", "expr", "self", ".", "expr", "=", "_cancel_mul", "(", "expr", ",", "self", ".", "registry", ")", "return", "self" ]
Return a new equivalent unit object with a simplified unit expression >>> import unyt as u >>> unit = (u.m**2/u.cm).simplify() >>> unit 100*m
[ "Return", "a", "new", "equivalent", "unit", "object", "with", "a", "simplified", "unit", "expression" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L681-L691
14,243
yt-project/unyt
unyt/_parsing.py
_auto_positive_symbol
def _auto_positive_symbol(tokens, local_dict, global_dict): """ Inserts calls to ``Symbol`` for undefined variables. Passes in positive=True as a keyword argument. Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol """ result = [] tokens.append((None, None)) # so zip traverses all tokens for tok, nextTok in zip(tokens, tokens[1:]): tokNum, tokVal = tok nextTokNum, nextTokVal = nextTok if tokNum == token.NAME: name = tokVal if name in global_dict: obj = global_dict[name] if isinstance(obj, (Basic, type)) or callable(obj): result.append((token.NAME, name)) continue # try to resolve known alternative unit name try: used_name = inv_name_alternatives[str(name)] except KeyError: # if we don't know this name it's a user-defined unit name # so we should create a new symbol for it used_name = str(name) result.extend( [ (token.NAME, "Symbol"), (token.OP, "("), (token.NAME, repr(used_name)), (token.OP, ","), (token.NAME, "positive"), (token.OP, "="), (token.NAME, "True"), (token.OP, ")"), ] ) else: result.append((tokNum, tokVal)) return result
python
def _auto_positive_symbol(tokens, local_dict, global_dict): """ Inserts calls to ``Symbol`` for undefined variables. Passes in positive=True as a keyword argument. Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol """ result = [] tokens.append((None, None)) # so zip traverses all tokens for tok, nextTok in zip(tokens, tokens[1:]): tokNum, tokVal = tok nextTokNum, nextTokVal = nextTok if tokNum == token.NAME: name = tokVal if name in global_dict: obj = global_dict[name] if isinstance(obj, (Basic, type)) or callable(obj): result.append((token.NAME, name)) continue # try to resolve known alternative unit name try: used_name = inv_name_alternatives[str(name)] except KeyError: # if we don't know this name it's a user-defined unit name # so we should create a new symbol for it used_name = str(name) result.extend( [ (token.NAME, "Symbol"), (token.OP, "("), (token.NAME, repr(used_name)), (token.OP, ","), (token.NAME, "positive"), (token.OP, "="), (token.NAME, "True"), (token.OP, ")"), ] ) else: result.append((tokNum, tokVal)) return result
[ "def", "_auto_positive_symbol", "(", "tokens", ",", "local_dict", ",", "global_dict", ")", ":", "result", "=", "[", "]", "tokens", ".", "append", "(", "(", "None", ",", "None", ")", ")", "# so zip traverses all tokens", "for", "tok", ",", "nextTok", "in", "zip", "(", "tokens", ",", "tokens", "[", "1", ":", "]", ")", ":", "tokNum", ",", "tokVal", "=", "tok", "nextTokNum", ",", "nextTokVal", "=", "nextTok", "if", "tokNum", "==", "token", ".", "NAME", ":", "name", "=", "tokVal", "if", "name", "in", "global_dict", ":", "obj", "=", "global_dict", "[", "name", "]", "if", "isinstance", "(", "obj", ",", "(", "Basic", ",", "type", ")", ")", "or", "callable", "(", "obj", ")", ":", "result", ".", "append", "(", "(", "token", ".", "NAME", ",", "name", ")", ")", "continue", "# try to resolve known alternative unit name", "try", ":", "used_name", "=", "inv_name_alternatives", "[", "str", "(", "name", ")", "]", "except", "KeyError", ":", "# if we don't know this name it's a user-defined unit name", "# so we should create a new symbol for it", "used_name", "=", "str", "(", "name", ")", "result", ".", "extend", "(", "[", "(", "token", ".", "NAME", ",", "\"Symbol\"", ")", ",", "(", "token", ".", "OP", ",", "\"(\"", ")", ",", "(", "token", ".", "NAME", ",", "repr", "(", "used_name", ")", ")", ",", "(", "token", ".", "OP", ",", "\",\"", ")", ",", "(", "token", ".", "NAME", ",", "\"positive\"", ")", ",", "(", "token", ".", "OP", ",", "\"=\"", ")", ",", "(", "token", ".", "NAME", ",", "\"True\"", ")", ",", "(", "token", ".", "OP", ",", "\")\"", ")", ",", "]", ")", "else", ":", "result", ".", "append", "(", "(", "tokNum", ",", "tokVal", ")", ")", "return", "result" ]
Inserts calls to ``Symbol`` for undefined variables. Passes in positive=True as a keyword argument. Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol
[ "Inserts", "calls", "to", "Symbol", "for", "undefined", "variables", ".", "Passes", "in", "positive", "=", "True", "as", "a", "keyword", "argument", ".", "Adapted", "from", "sympy", ".", "sympy", ".", "parsing", ".", "sympy_parser", ".", "auto_symbol" ]
7a4eafc229f83784f4c63d639aee554f9a6b1ca0
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/_parsing.py#L25-L68
14,244
kz26/PyExcelerate
pyexcelerate/Range.py
Range.intersection
def intersection(self, range): """ Calculates the intersection with another range object """ if self.worksheet != range.worksheet: # Different worksheet return None start = (max(self._start[0], range._start[0]), max(self._start[1], range._start[1])) end = (min(self._end[0], range._end[0]), min(self._end[1], range._end[1])) if end[0] < start[0] or end[1] < start[1]: return None return Range(start, end, self.worksheet, validate=False)
python
def intersection(self, range): """ Calculates the intersection with another range object """ if self.worksheet != range.worksheet: # Different worksheet return None start = (max(self._start[0], range._start[0]), max(self._start[1], range._start[1])) end = (min(self._end[0], range._end[0]), min(self._end[1], range._end[1])) if end[0] < start[0] or end[1] < start[1]: return None return Range(start, end, self.worksheet, validate=False)
[ "def", "intersection", "(", "self", ",", "range", ")", ":", "if", "self", ".", "worksheet", "!=", "range", ".", "worksheet", ":", "# Different worksheet", "return", "None", "start", "=", "(", "max", "(", "self", ".", "_start", "[", "0", "]", ",", "range", ".", "_start", "[", "0", "]", ")", ",", "max", "(", "self", ".", "_start", "[", "1", "]", ",", "range", ".", "_start", "[", "1", "]", ")", ")", "end", "=", "(", "min", "(", "self", ".", "_end", "[", "0", "]", ",", "range", ".", "_end", "[", "0", "]", ")", ",", "min", "(", "self", ".", "_end", "[", "1", "]", ",", "range", ".", "_end", "[", "1", "]", ")", ")", "if", "end", "[", "0", "]", "<", "start", "[", "0", "]", "or", "end", "[", "1", "]", "<", "start", "[", "1", "]", ":", "return", "None", "return", "Range", "(", "start", ",", "end", ",", "self", ".", "worksheet", ",", "validate", "=", "False", ")" ]
Calculates the intersection with another range object
[ "Calculates", "the", "intersection", "with", "another", "range", "object" ]
247406dc41adc7e94542bcbf04589f1e5fdf8c51
https://github.com/kz26/PyExcelerate/blob/247406dc41adc7e94542bcbf04589f1e5fdf8c51/pyexcelerate/Range.py#L140-L153
14,245
harlowja/fasteners
fasteners/process_lock.py
interprocess_locked
def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) return wrapper return decorator
python
def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) return wrapper return decorator
[ "def", "interprocess_locked", "(", "path", ")", ":", "lock", "=", "InterProcessLock", "(", "path", ")", "def", "decorator", "(", "f", ")", ":", "@", "six", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "lock", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
Acquires & releases a interprocess lock around call into decorated function.
[ "Acquires", "&", "releases", "a", "interprocess", "lock", "around", "call", "into", "decorated", "function", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/process_lock.py#L265-L280
14,246
harlowja/fasteners
fasteners/process_lock.py
_InterProcessLock.acquire
def acquire(self, blocking=True, delay=DELAY_INCREMENT, max_delay=MAX_DELAY, timeout=None): """Attempt to acquire the given lock. :param blocking: whether to wait forever to try to acquire the lock :type blocking: bool :param delay: when blocking this is the delay time in seconds that will be added after each failed acquisition :type delay: int/float :param max_delay: the maximum delay to have (this limits the accumulated delay(s) added after each failed acquisition) :type max_delay: int/float :param timeout: an optional timeout (limits how long blocking will occur for) :type timeout: int/float :returns: whether or not the acquisition succeeded :rtype: bool """ if delay < 0: raise ValueError("Delay must be greater than or equal to zero") if timeout is not None and timeout < 0: raise ValueError("Timeout must be greater than or equal to zero") if delay >= max_delay: max_delay = delay self._do_open() watch = _utils.StopWatch(duration=timeout) r = _utils.Retry(delay, max_delay, sleep_func=self.sleep_func, watch=watch) with watch: gotten = r(self._try_acquire, blocking, watch) if not gotten: self.acquired = False return False else: self.acquired = True self.logger.log(_utils.BLATHER, "Acquired file lock `%s` after waiting %0.3fs [%s" " attempts were required]", self.path, watch.elapsed(), r.attempts) return True
python
def acquire(self, blocking=True, delay=DELAY_INCREMENT, max_delay=MAX_DELAY, timeout=None): """Attempt to acquire the given lock. :param blocking: whether to wait forever to try to acquire the lock :type blocking: bool :param delay: when blocking this is the delay time in seconds that will be added after each failed acquisition :type delay: int/float :param max_delay: the maximum delay to have (this limits the accumulated delay(s) added after each failed acquisition) :type max_delay: int/float :param timeout: an optional timeout (limits how long blocking will occur for) :type timeout: int/float :returns: whether or not the acquisition succeeded :rtype: bool """ if delay < 0: raise ValueError("Delay must be greater than or equal to zero") if timeout is not None and timeout < 0: raise ValueError("Timeout must be greater than or equal to zero") if delay >= max_delay: max_delay = delay self._do_open() watch = _utils.StopWatch(duration=timeout) r = _utils.Retry(delay, max_delay, sleep_func=self.sleep_func, watch=watch) with watch: gotten = r(self._try_acquire, blocking, watch) if not gotten: self.acquired = False return False else: self.acquired = True self.logger.log(_utils.BLATHER, "Acquired file lock `%s` after waiting %0.3fs [%s" " attempts were required]", self.path, watch.elapsed(), r.attempts) return True
[ "def", "acquire", "(", "self", ",", "blocking", "=", "True", ",", "delay", "=", "DELAY_INCREMENT", ",", "max_delay", "=", "MAX_DELAY", ",", "timeout", "=", "None", ")", ":", "if", "delay", "<", "0", ":", "raise", "ValueError", "(", "\"Delay must be greater than or equal to zero\"", ")", "if", "timeout", "is", "not", "None", "and", "timeout", "<", "0", ":", "raise", "ValueError", "(", "\"Timeout must be greater than or equal to zero\"", ")", "if", "delay", ">=", "max_delay", ":", "max_delay", "=", "delay", "self", ".", "_do_open", "(", ")", "watch", "=", "_utils", ".", "StopWatch", "(", "duration", "=", "timeout", ")", "r", "=", "_utils", ".", "Retry", "(", "delay", ",", "max_delay", ",", "sleep_func", "=", "self", ".", "sleep_func", ",", "watch", "=", "watch", ")", "with", "watch", ":", "gotten", "=", "r", "(", "self", ".", "_try_acquire", ",", "blocking", ",", "watch", ")", "if", "not", "gotten", ":", "self", ".", "acquired", "=", "False", "return", "False", "else", ":", "self", ".", "acquired", "=", "True", "self", ".", "logger", ".", "log", "(", "_utils", ".", "BLATHER", ",", "\"Acquired file lock `%s` after waiting %0.3fs [%s\"", "\" attempts were required]\"", ",", "self", ".", "path", ",", "watch", ".", "elapsed", "(", ")", ",", "r", ".", "attempts", ")", "return", "True" ]
Attempt to acquire the given lock. :param blocking: whether to wait forever to try to acquire the lock :type blocking: bool :param delay: when blocking this is the delay time in seconds that will be added after each failed acquisition :type delay: int/float :param max_delay: the maximum delay to have (this limits the accumulated delay(s) added after each failed acquisition) :type max_delay: int/float :param timeout: an optional timeout (limits how long blocking will occur for) :type timeout: int/float :returns: whether or not the acquisition succeeded :rtype: bool
[ "Attempt", "to", "acquire", "the", "given", "lock", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/process_lock.py#L130-L171
14,247
harlowja/fasteners
fasteners/process_lock.py
_InterProcessLock.release
def release(self): """Release the previously acquired lock.""" if not self.acquired: raise threading.ThreadError("Unable to release an unacquired" " lock") try: self.unlock() except IOError: self.logger.exception("Could not unlock the acquired lock opened" " on `%s`", self.path) else: self.acquired = False try: self._do_close() except IOError: self.logger.exception("Could not close the file handle" " opened on `%s`", self.path) else: self.logger.log(_utils.BLATHER, "Unlocked and closed file lock open on" " `%s`", self.path)
python
def release(self): """Release the previously acquired lock.""" if not self.acquired: raise threading.ThreadError("Unable to release an unacquired" " lock") try: self.unlock() except IOError: self.logger.exception("Could not unlock the acquired lock opened" " on `%s`", self.path) else: self.acquired = False try: self._do_close() except IOError: self.logger.exception("Could not close the file handle" " opened on `%s`", self.path) else: self.logger.log(_utils.BLATHER, "Unlocked and closed file lock open on" " `%s`", self.path)
[ "def", "release", "(", "self", ")", ":", "if", "not", "self", ".", "acquired", ":", "raise", "threading", ".", "ThreadError", "(", "\"Unable to release an unacquired\"", "\" lock\"", ")", "try", ":", "self", ".", "unlock", "(", ")", "except", "IOError", ":", "self", ".", "logger", ".", "exception", "(", "\"Could not unlock the acquired lock opened\"", "\" on `%s`\"", ",", "self", ".", "path", ")", "else", ":", "self", ".", "acquired", "=", "False", "try", ":", "self", ".", "_do_close", "(", ")", "except", "IOError", ":", "self", ".", "logger", ".", "exception", "(", "\"Could not close the file handle\"", "\" opened on `%s`\"", ",", "self", ".", "path", ")", "else", ":", "self", ".", "logger", ".", "log", "(", "_utils", ".", "BLATHER", ",", "\"Unlocked and closed file lock open on\"", "\" `%s`\"", ",", "self", ".", "path", ")" ]
Release the previously acquired lock.
[ "Release", "the", "previously", "acquired", "lock", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/process_lock.py#L187-L207
14,248
harlowja/fasteners
fasteners/_utils.py
canonicalize_path
def canonicalize_path(path): """Canonicalizes a potential path. Returns a binary string encoded into filesystem encoding. """ if isinstance(path, six.binary_type): return path if isinstance(path, six.text_type): return _fsencode(path) else: return canonicalize_path(str(path))
python
def canonicalize_path(path): """Canonicalizes a potential path. Returns a binary string encoded into filesystem encoding. """ if isinstance(path, six.binary_type): return path if isinstance(path, six.text_type): return _fsencode(path) else: return canonicalize_path(str(path))
[ "def", "canonicalize_path", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "six", ".", "binary_type", ")", ":", "return", "path", "if", "isinstance", "(", "path", ",", "six", ".", "text_type", ")", ":", "return", "_fsencode", "(", "path", ")", "else", ":", "return", "canonicalize_path", "(", "str", "(", "path", ")", ")" ]
Canonicalizes a potential path. Returns a binary string encoded into filesystem encoding.
[ "Canonicalizes", "a", "potential", "path", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/_utils.py#L47-L57
14,249
harlowja/fasteners
fasteners/lock.py
read_locked
def read_locked(*args, **kwargs): """Acquires & releases a read lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock`) in the instance object this decorator is attached to. """ def decorator(f): attr_name = kwargs.get('lock', '_lock') @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.read_lock(): return f(self, *args, **kwargs) return wrapper # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args: return decorator else: if len(args) == 1: return decorator(args[0]) else: return decorator
python
def read_locked(*args, **kwargs): """Acquires & releases a read lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock`) in the instance object this decorator is attached to. """ def decorator(f): attr_name = kwargs.get('lock', '_lock') @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.read_lock(): return f(self, *args, **kwargs) return wrapper # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args: return decorator else: if len(args) == 1: return decorator(args[0]) else: return decorator
[ "def", "read_locked", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "attr_name", "=", "kwargs", ".", "get", "(", "'lock'", ",", "'_lock'", ")", "@", "six", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rw_lock", "=", "getattr", "(", "self", ",", "attr_name", ")", "with", "rw_lock", ".", "read_lock", "(", ")", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "# This is needed to handle when the decorator has args or the decorator", "# doesn't have args, python is rather weird here...", "if", "kwargs", "or", "not", "args", ":", "return", "decorator", "else", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "decorator", "(", "args", "[", "0", "]", ")", "else", ":", "return", "decorator" ]
Acquires & releases a read lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock`) in the instance object this decorator is attached to.
[ "Acquires", "&", "releases", "a", "read", "lock", "around", "call", "into", "decorated", "method", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L38-L66
14,250
harlowja/fasteners
fasteners/lock.py
write_locked
def write_locked(*args, **kwargs): """Acquires & releases a write lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock` object) in the instance object this decorator is attached to. """ def decorator(f): attr_name = kwargs.get('lock', '_lock') @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.write_lock(): return f(self, *args, **kwargs) return wrapper # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args: return decorator else: if len(args) == 1: return decorator(args[0]) else: return decorator
python
def write_locked(*args, **kwargs): """Acquires & releases a write lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock` object) in the instance object this decorator is attached to. """ def decorator(f): attr_name = kwargs.get('lock', '_lock') @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.write_lock(): return f(self, *args, **kwargs) return wrapper # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args: return decorator else: if len(args) == 1: return decorator(args[0]) else: return decorator
[ "def", "write_locked", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "attr_name", "=", "kwargs", ".", "get", "(", "'lock'", ",", "'_lock'", ")", "@", "six", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rw_lock", "=", "getattr", "(", "self", ",", "attr_name", ")", "with", "rw_lock", ".", "write_lock", "(", ")", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "# This is needed to handle when the decorator has args or the decorator", "# doesn't have args, python is rather weird here...", "if", "kwargs", "or", "not", "args", ":", "return", "decorator", "else", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "decorator", "(", "args", "[", "0", "]", ")", "else", ":", "return", "decorator" ]
Acquires & releases a write lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock` object) in the instance object this decorator is attached to.
[ "Acquires", "&", "releases", "a", "write", "lock", "around", "call", "into", "decorated", "method", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L69-L97
14,251
harlowja/fasteners
fasteners/lock.py
ReaderWriterLock.is_writer
def is_writer(self, check_pending=True): """Returns if the caller is the active writer or a pending writer.""" me = self._current_thread() if self._writer == me: return True if check_pending: return me in self._pending_writers else: return False
python
def is_writer(self, check_pending=True): """Returns if the caller is the active writer or a pending writer.""" me = self._current_thread() if self._writer == me: return True if check_pending: return me in self._pending_writers else: return False
[ "def", "is_writer", "(", "self", ",", "check_pending", "=", "True", ")", ":", "me", "=", "self", ".", "_current_thread", "(", ")", "if", "self", ".", "_writer", "==", "me", ":", "return", "True", "if", "check_pending", ":", "return", "me", "in", "self", ".", "_pending_writers", "else", ":", "return", "False" ]
Returns if the caller is the active writer or a pending writer.
[ "Returns", "if", "the", "caller", "is", "the", "active", "writer", "or", "a", "pending", "writer", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L136-L144
14,252
harlowja/fasteners
fasteners/lock.py
ReaderWriterLock.owner
def owner(self): """Returns whether the lock is locked by a writer or reader.""" if self._writer is not None: return self.WRITER if self._readers: return self.READER return None
python
def owner(self): """Returns whether the lock is locked by a writer or reader.""" if self._writer is not None: return self.WRITER if self._readers: return self.READER return None
[ "def", "owner", "(", "self", ")", ":", "if", "self", ".", "_writer", "is", "not", "None", ":", "return", "self", ".", "WRITER", "if", "self", ".", "_readers", ":", "return", "self", ".", "READER", "return", "None" ]
Returns whether the lock is locked by a writer or reader.
[ "Returns", "whether", "the", "lock", "is", "locked", "by", "a", "writer", "or", "reader", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L147-L153
14,253
harlowja/fasteners
fasteners/lock.py
ReaderWriterLock.read_lock
def read_lock(self): """Context manager that grants a read lock. Will wait until no active or pending writers. Raises a ``RuntimeError`` if a pending writer tries to acquire a read lock. """ me = self._current_thread() if me in self._pending_writers: raise RuntimeError("Writer %s can not acquire a read lock" " while waiting for the write lock" % me) with self._cond: while True: # No active writer, or we are the writer; # we are good to become a reader. if self._writer is None or self._writer == me: try: self._readers[me] = self._readers[me] + 1 except KeyError: self._readers[me] = 1 break # An active writer; guess we have to wait. self._cond.wait() try: yield self finally: # I am no longer a reader, remove *one* occurrence of myself. # If the current thread acquired two read locks, then it will # still have to remove that other read lock; this allows for # basic reentrancy to be possible. with self._cond: try: me_instances = self._readers[me] if me_instances > 1: self._readers[me] = me_instances - 1 else: self._readers.pop(me) except KeyError: pass self._cond.notify_all()
python
def read_lock(self): """Context manager that grants a read lock. Will wait until no active or pending writers. Raises a ``RuntimeError`` if a pending writer tries to acquire a read lock. """ me = self._current_thread() if me in self._pending_writers: raise RuntimeError("Writer %s can not acquire a read lock" " while waiting for the write lock" % me) with self._cond: while True: # No active writer, or we are the writer; # we are good to become a reader. if self._writer is None or self._writer == me: try: self._readers[me] = self._readers[me] + 1 except KeyError: self._readers[me] = 1 break # An active writer; guess we have to wait. self._cond.wait() try: yield self finally: # I am no longer a reader, remove *one* occurrence of myself. # If the current thread acquired two read locks, then it will # still have to remove that other read lock; this allows for # basic reentrancy to be possible. with self._cond: try: me_instances = self._readers[me] if me_instances > 1: self._readers[me] = me_instances - 1 else: self._readers.pop(me) except KeyError: pass self._cond.notify_all()
[ "def", "read_lock", "(", "self", ")", ":", "me", "=", "self", ".", "_current_thread", "(", ")", "if", "me", "in", "self", ".", "_pending_writers", ":", "raise", "RuntimeError", "(", "\"Writer %s can not acquire a read lock\"", "\" while waiting for the write lock\"", "%", "me", ")", "with", "self", ".", "_cond", ":", "while", "True", ":", "# No active writer, or we are the writer;", "# we are good to become a reader.", "if", "self", ".", "_writer", "is", "None", "or", "self", ".", "_writer", "==", "me", ":", "try", ":", "self", ".", "_readers", "[", "me", "]", "=", "self", ".", "_readers", "[", "me", "]", "+", "1", "except", "KeyError", ":", "self", ".", "_readers", "[", "me", "]", "=", "1", "break", "# An active writer; guess we have to wait.", "self", ".", "_cond", ".", "wait", "(", ")", "try", ":", "yield", "self", "finally", ":", "# I am no longer a reader, remove *one* occurrence of myself.", "# If the current thread acquired two read locks, then it will", "# still have to remove that other read lock; this allows for", "# basic reentrancy to be possible.", "with", "self", ".", "_cond", ":", "try", ":", "me_instances", "=", "self", ".", "_readers", "[", "me", "]", "if", "me_instances", ">", "1", ":", "self", ".", "_readers", "[", "me", "]", "=", "me_instances", "-", "1", "else", ":", "self", ".", "_readers", ".", "pop", "(", "me", ")", "except", "KeyError", ":", "pass", "self", ".", "_cond", ".", "notify_all", "(", ")" ]
Context manager that grants a read lock. Will wait until no active or pending writers. Raises a ``RuntimeError`` if a pending writer tries to acquire a read lock.
[ "Context", "manager", "that", "grants", "a", "read", "lock", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L161-L202
14,254
harlowja/fasteners
fasteners/lock.py
ReaderWriterLock.write_lock
def write_lock(self): """Context manager that grants a write lock. Will wait until no active readers. Blocks readers after acquiring. Guaranteed for locks to be processed in fair order (FIFO). Raises a ``RuntimeError`` if an active reader attempts to acquire a lock. """ me = self._current_thread() i_am_writer = self.is_writer(check_pending=False) if self.is_reader() and not i_am_writer: raise RuntimeError("Reader %s to writer privilege" " escalation not allowed" % me) if i_am_writer: # Already the writer; this allows for basic reentrancy. yield self else: with self._cond: self._pending_writers.append(me) while True: # No readers, and no active writer, am I next?? if len(self._readers) == 0 and self._writer is None: if self._pending_writers[0] == me: self._writer = self._pending_writers.popleft() break self._cond.wait() try: yield self finally: with self._cond: self._writer = None self._cond.notify_all()
python
def write_lock(self): """Context manager that grants a write lock. Will wait until no active readers. Blocks readers after acquiring. Guaranteed for locks to be processed in fair order (FIFO). Raises a ``RuntimeError`` if an active reader attempts to acquire a lock. """ me = self._current_thread() i_am_writer = self.is_writer(check_pending=False) if self.is_reader() and not i_am_writer: raise RuntimeError("Reader %s to writer privilege" " escalation not allowed" % me) if i_am_writer: # Already the writer; this allows for basic reentrancy. yield self else: with self._cond: self._pending_writers.append(me) while True: # No readers, and no active writer, am I next?? if len(self._readers) == 0 and self._writer is None: if self._pending_writers[0] == me: self._writer = self._pending_writers.popleft() break self._cond.wait() try: yield self finally: with self._cond: self._writer = None self._cond.notify_all()
[ "def", "write_lock", "(", "self", ")", ":", "me", "=", "self", ".", "_current_thread", "(", ")", "i_am_writer", "=", "self", ".", "is_writer", "(", "check_pending", "=", "False", ")", "if", "self", ".", "is_reader", "(", ")", "and", "not", "i_am_writer", ":", "raise", "RuntimeError", "(", "\"Reader %s to writer privilege\"", "\" escalation not allowed\"", "%", "me", ")", "if", "i_am_writer", ":", "# Already the writer; this allows for basic reentrancy.", "yield", "self", "else", ":", "with", "self", ".", "_cond", ":", "self", ".", "_pending_writers", ".", "append", "(", "me", ")", "while", "True", ":", "# No readers, and no active writer, am I next??", "if", "len", "(", "self", ".", "_readers", ")", "==", "0", "and", "self", ".", "_writer", "is", "None", ":", "if", "self", ".", "_pending_writers", "[", "0", "]", "==", "me", ":", "self", ".", "_writer", "=", "self", ".", "_pending_writers", ".", "popleft", "(", ")", "break", "self", ".", "_cond", ".", "wait", "(", ")", "try", ":", "yield", "self", "finally", ":", "with", "self", ".", "_cond", ":", "self", ".", "_writer", "=", "None", "self", ".", "_cond", ".", "notify_all", "(", ")" ]
Context manager that grants a write lock. Will wait until no active readers. Blocks readers after acquiring. Guaranteed for locks to be processed in fair order (FIFO). Raises a ``RuntimeError`` if an active reader attempts to acquire a lock.
[ "Context", "manager", "that", "grants", "a", "write", "lock", "." ]
8f3bbab0204a50037448a8fad7a6bf12eb1a2695
https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L205-L238
14,255
bfontaine/freesms
freesms/__init__.py
FreeClient.send_sms
def send_sms(self, text, **kw): """ Send an SMS. Since Free only allows us to send SMSes to ourselves you don't have to provide your phone number. """ params = { 'user': self._user, 'pass': self._passwd, 'msg': text } kw.setdefault("verify", False) if not kw["verify"]: # remove SSL warning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) res = requests.get(FreeClient.BASE_URL, params=params, **kw) return FreeResponse(res.status_code)
python
def send_sms(self, text, **kw): """ Send an SMS. Since Free only allows us to send SMSes to ourselves you don't have to provide your phone number. """ params = { 'user': self._user, 'pass': self._passwd, 'msg': text } kw.setdefault("verify", False) if not kw["verify"]: # remove SSL warning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) res = requests.get(FreeClient.BASE_URL, params=params, **kw) return FreeResponse(res.status_code)
[ "def", "send_sms", "(", "self", ",", "text", ",", "*", "*", "kw", ")", ":", "params", "=", "{", "'user'", ":", "self", ".", "_user", ",", "'pass'", ":", "self", ".", "_passwd", ",", "'msg'", ":", "text", "}", "kw", ".", "setdefault", "(", "\"verify\"", ",", "False", ")", "if", "not", "kw", "[", "\"verify\"", "]", ":", "# remove SSL warning", "requests", ".", "packages", ".", "urllib3", ".", "disable_warnings", "(", "InsecureRequestWarning", ")", "res", "=", "requests", ".", "get", "(", "FreeClient", ".", "BASE_URL", ",", "params", "=", "params", ",", "*", "*", "kw", ")", "return", "FreeResponse", "(", "res", ".", "status_code", ")" ]
Send an SMS. Since Free only allows us to send SMSes to ourselves you don't have to provide your phone number.
[ "Send", "an", "SMS", ".", "Since", "Free", "only", "allows", "us", "to", "send", "SMSes", "to", "ourselves", "you", "don", "t", "have", "to", "provide", "your", "phone", "number", "." ]
64b3df222a852f313bd80afd9a7280b584fe31e1
https://github.com/bfontaine/freesms/blob/64b3df222a852f313bd80afd9a7280b584fe31e1/freesms/__init__.py#L63-L82
14,256
scrapinghub/exporters
exporters/writers/filebase_base_writer.py
FilebaseBaseWriter.create_filebase_name
def create_filebase_name(self, group_info, extension='gz', file_name=None): """ Return tuple of resolved destination folder name and file name """ dirname = self.filebase.formatted_dirname(groups=group_info) if not file_name: file_name = self.filebase.prefix_template + '.' + extension return dirname, file_name
python
def create_filebase_name(self, group_info, extension='gz', file_name=None): """ Return tuple of resolved destination folder name and file name """ dirname = self.filebase.formatted_dirname(groups=group_info) if not file_name: file_name = self.filebase.prefix_template + '.' + extension return dirname, file_name
[ "def", "create_filebase_name", "(", "self", ",", "group_info", ",", "extension", "=", "'gz'", ",", "file_name", "=", "None", ")", ":", "dirname", "=", "self", ".", "filebase", ".", "formatted_dirname", "(", "groups", "=", "group_info", ")", "if", "not", "file_name", ":", "file_name", "=", "self", ".", "filebase", ".", "prefix_template", "+", "'.'", "+", "extension", "return", "dirname", ",", "file_name" ]
Return tuple of resolved destination folder name and file name
[ "Return", "tuple", "of", "resolved", "destination", "folder", "name", "and", "file", "name" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/filebase_base_writer.py#L145-L152
14,257
scrapinghub/exporters
exporters/writers/aggregation_stats_writer.py
AggregationStatsWriter.write_batch
def write_batch(self, batch): """ Receives the batch and writes it. This method is usually called from a manager. """ for item in batch: for key in item: self.aggregated_info['occurrences'][key] += 1 self.increment_written_items() if self.items_limit and self.items_limit == self.get_metadata('items_count'): raise ItemsLimitReached('Finishing job after items_limit reached: {} items written.' .format(self.get_metadata('items_count'))) self.logger.debug('Wrote items')
python
def write_batch(self, batch): """ Receives the batch and writes it. This method is usually called from a manager. """ for item in batch: for key in item: self.aggregated_info['occurrences'][key] += 1 self.increment_written_items() if self.items_limit and self.items_limit == self.get_metadata('items_count'): raise ItemsLimitReached('Finishing job after items_limit reached: {} items written.' .format(self.get_metadata('items_count'))) self.logger.debug('Wrote items')
[ "def", "write_batch", "(", "self", ",", "batch", ")", ":", "for", "item", "in", "batch", ":", "for", "key", "in", "item", ":", "self", ".", "aggregated_info", "[", "'occurrences'", "]", "[", "key", "]", "+=", "1", "self", ".", "increment_written_items", "(", ")", "if", "self", ".", "items_limit", "and", "self", ".", "items_limit", "==", "self", ".", "get_metadata", "(", "'items_count'", ")", ":", "raise", "ItemsLimitReached", "(", "'Finishing job after items_limit reached: {} items written.'", ".", "format", "(", "self", ".", "get_metadata", "(", "'items_count'", ")", ")", ")", "self", ".", "logger", ".", "debug", "(", "'Wrote items'", ")" ]
Receives the batch and writes it. This method is usually called from a manager.
[ "Receives", "the", "batch", "and", "writes", "it", ".", "This", "method", "is", "usually", "called", "from", "a", "manager", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/aggregation_stats_writer.py#L18-L29
14,258
scrapinghub/exporters
exporters/writers/aggregation_stats_writer.py
AggregationStatsWriter._get_aggregated_info
def _get_aggregated_info(self): """ Keeps track of aggregated info in a dictionary called self.aggregated_info """ agg_results = {} for key in self.aggregated_info['occurrences']: agg_results[key] = { 'occurrences': self.aggregated_info['occurrences'].get(key), 'coverage': (float(self.aggregated_info['occurrences'] .get(key))/float(self.get_metadata('items_count')))*100 } return agg_results
python
def _get_aggregated_info(self): """ Keeps track of aggregated info in a dictionary called self.aggregated_info """ agg_results = {} for key in self.aggregated_info['occurrences']: agg_results[key] = { 'occurrences': self.aggregated_info['occurrences'].get(key), 'coverage': (float(self.aggregated_info['occurrences'] .get(key))/float(self.get_metadata('items_count')))*100 } return agg_results
[ "def", "_get_aggregated_info", "(", "self", ")", ":", "agg_results", "=", "{", "}", "for", "key", "in", "self", ".", "aggregated_info", "[", "'occurrences'", "]", ":", "agg_results", "[", "key", "]", "=", "{", "'occurrences'", ":", "self", ".", "aggregated_info", "[", "'occurrences'", "]", ".", "get", "(", "key", ")", ",", "'coverage'", ":", "(", "float", "(", "self", ".", "aggregated_info", "[", "'occurrences'", "]", ".", "get", "(", "key", ")", ")", "/", "float", "(", "self", ".", "get_metadata", "(", "'items_count'", ")", ")", ")", "*", "100", "}", "return", "agg_results" ]
Keeps track of aggregated info in a dictionary called self.aggregated_info
[ "Keeps", "track", "of", "aggregated", "info", "in", "a", "dictionary", "called", "self", ".", "aggregated_info" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/aggregation_stats_writer.py#L31-L42
14,259
scrapinghub/exporters
exporters/writers/cloudsearch_writer.py
create_document_batches
def create_document_batches(jsonlines, id_field, max_batch_size=CLOUDSEARCH_MAX_BATCH_SIZE): """Create batches in expected AWS Cloudsearch format, limiting the byte size per batch according to given max_batch_size See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html """ batch = [] fixed_initial_size = 2 def create_entry(line): try: record = json.loads(line) except: raise ValueError('Could not parse JSON from: %s' % line) key = record[id_field] return '{"type":"add","id":%s,"fields":%s}' % (json.dumps(key), line) current_size = fixed_initial_size for line in jsonlines: entry = create_entry(line) entry_size = len(entry) + 1 if max_batch_size > (current_size + entry_size): current_size += entry_size batch.append(entry) else: yield '[' + ','.join(batch) + ']' batch = [entry] current_size = fixed_initial_size + entry_size if batch: yield '[' + ','.join(batch) + ']'
python
def create_document_batches(jsonlines, id_field, max_batch_size=CLOUDSEARCH_MAX_BATCH_SIZE): """Create batches in expected AWS Cloudsearch format, limiting the byte size per batch according to given max_batch_size See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html """ batch = [] fixed_initial_size = 2 def create_entry(line): try: record = json.loads(line) except: raise ValueError('Could not parse JSON from: %s' % line) key = record[id_field] return '{"type":"add","id":%s,"fields":%s}' % (json.dumps(key), line) current_size = fixed_initial_size for line in jsonlines: entry = create_entry(line) entry_size = len(entry) + 1 if max_batch_size > (current_size + entry_size): current_size += entry_size batch.append(entry) else: yield '[' + ','.join(batch) + ']' batch = [entry] current_size = fixed_initial_size + entry_size if batch: yield '[' + ','.join(batch) + ']'
[ "def", "create_document_batches", "(", "jsonlines", ",", "id_field", ",", "max_batch_size", "=", "CLOUDSEARCH_MAX_BATCH_SIZE", ")", ":", "batch", "=", "[", "]", "fixed_initial_size", "=", "2", "def", "create_entry", "(", "line", ")", ":", "try", ":", "record", "=", "json", ".", "loads", "(", "line", ")", "except", ":", "raise", "ValueError", "(", "'Could not parse JSON from: %s'", "%", "line", ")", "key", "=", "record", "[", "id_field", "]", "return", "'{\"type\":\"add\",\"id\":%s,\"fields\":%s}'", "%", "(", "json", ".", "dumps", "(", "key", ")", ",", "line", ")", "current_size", "=", "fixed_initial_size", "for", "line", "in", "jsonlines", ":", "entry", "=", "create_entry", "(", "line", ")", "entry_size", "=", "len", "(", "entry", ")", "+", "1", "if", "max_batch_size", ">", "(", "current_size", "+", "entry_size", ")", ":", "current_size", "+=", "entry_size", "batch", ".", "append", "(", "entry", ")", "else", ":", "yield", "'['", "+", "','", ".", "join", "(", "batch", ")", "+", "']'", "batch", "=", "[", "entry", "]", "current_size", "=", "fixed_initial_size", "+", "entry_size", "if", "batch", ":", "yield", "'['", "+", "','", ".", "join", "(", "batch", ")", "+", "']'" ]
Create batches in expected AWS Cloudsearch format, limiting the byte size per batch according to given max_batch_size See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html
[ "Create", "batches", "in", "expected", "AWS", "Cloudsearch", "format", "limiting", "the", "byte", "size", "per", "batch", "according", "to", "given", "max_batch_size" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/cloudsearch_writer.py#L14-L45
14,260
scrapinghub/exporters
exporters/writers/cloudsearch_writer.py
CloudSearchWriter._post_document_batch
def _post_document_batch(self, batch): """ Send a batch to Cloudsearch endpoint See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html """ # noqa target_batch = '/2013-01-01/documents/batch' url = self.endpoint_url + target_batch return requests.post(url, data=batch, headers={'Content-type': 'application/json'})
python
def _post_document_batch(self, batch): """ Send a batch to Cloudsearch endpoint See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html """ # noqa target_batch = '/2013-01-01/documents/batch' url = self.endpoint_url + target_batch return requests.post(url, data=batch, headers={'Content-type': 'application/json'})
[ "def", "_post_document_batch", "(", "self", ",", "batch", ")", ":", "# noqa", "target_batch", "=", "'/2013-01-01/documents/batch'", "url", "=", "self", ".", "endpoint_url", "+", "target_batch", "return", "requests", ".", "post", "(", "url", ",", "data", "=", "batch", ",", "headers", "=", "{", "'Content-type'", ":", "'application/json'", "}", ")" ]
Send a batch to Cloudsearch endpoint See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html
[ "Send", "a", "batch", "to", "Cloudsearch", "endpoint" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/cloudsearch_writer.py#L97-L105
14,261
scrapinghub/exporters
exporters/writers/fs_writer.py
FSWriter._create_path_if_not_exist
def _create_path_if_not_exist(self, path): """ Creates a folders path if it doesn't exist """ if path and not os.path.exists(path): os.makedirs(path)
python
def _create_path_if_not_exist(self, path): """ Creates a folders path if it doesn't exist """ if path and not os.path.exists(path): os.makedirs(path)
[ "def", "_create_path_if_not_exist", "(", "self", ",", "path", ")", ":", "if", "path", "and", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")" ]
Creates a folders path if it doesn't exist
[ "Creates", "a", "folders", "path", "if", "it", "doesn", "t", "exist" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/fs_writer.py#L26-L31
14,262
scrapinghub/exporters
exporters/writers/s3_writer.py
S3Writer.close
def close(self): """ Called to clean all possible tmp files created during the process. """ if self.read_option('save_pointer'): self._update_last_pointer() super(S3Writer, self).close()
python
def close(self): """ Called to clean all possible tmp files created during the process. """ if self.read_option('save_pointer'): self._update_last_pointer() super(S3Writer, self).close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "read_option", "(", "'save_pointer'", ")", ":", "self", ".", "_update_last_pointer", "(", ")", "super", "(", "S3Writer", ",", "self", ")", ".", "close", "(", ")" ]
Called to clean all possible tmp files created during the process.
[ "Called", "to", "clean", "all", "possible", "tmp", "files", "created", "during", "the", "process", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/s3_writer.py#L207-L213
14,263
scrapinghub/exporters
exporters/utils.py
get_boto_connection
def get_boto_connection(aws_access_key_id, aws_secret_access_key, region=None, bucketname=None, host=None): """ Conection parameters must be different only if bucket name has a period """ m = _AWS_ACCESS_KEY_ID_RE.match(aws_access_key_id) if m is None or m.group() != aws_access_key_id: logging.error('The provided aws_access_key_id is not in the correct format. It must \ be alphanumeric and contain between 16 and 32 characters.') if len(aws_access_key_id) > len(aws_secret_access_key): logging.warn("The AWS credential keys aren't in the usual size," " are you using the correct ones?") import boto from boto.s3.connection import OrdinaryCallingFormat extra_args = {} if host is not None: extra_args['host'] = host if bucketname is not None and '.' in bucketname: extra_args['calling_format'] = OrdinaryCallingFormat() if region is None: return boto.connect_s3(aws_access_key_id, aws_secret_access_key, **extra_args) return boto.s3.connect_to_region(region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **extra_args)
python
def get_boto_connection(aws_access_key_id, aws_secret_access_key, region=None, bucketname=None, host=None): """ Conection parameters must be different only if bucket name has a period """ m = _AWS_ACCESS_KEY_ID_RE.match(aws_access_key_id) if m is None or m.group() != aws_access_key_id: logging.error('The provided aws_access_key_id is not in the correct format. It must \ be alphanumeric and contain between 16 and 32 characters.') if len(aws_access_key_id) > len(aws_secret_access_key): logging.warn("The AWS credential keys aren't in the usual size," " are you using the correct ones?") import boto from boto.s3.connection import OrdinaryCallingFormat extra_args = {} if host is not None: extra_args['host'] = host if bucketname is not None and '.' in bucketname: extra_args['calling_format'] = OrdinaryCallingFormat() if region is None: return boto.connect_s3(aws_access_key_id, aws_secret_access_key, **extra_args) return boto.s3.connect_to_region(region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **extra_args)
[ "def", "get_boto_connection", "(", "aws_access_key_id", ",", "aws_secret_access_key", ",", "region", "=", "None", ",", "bucketname", "=", "None", ",", "host", "=", "None", ")", ":", "m", "=", "_AWS_ACCESS_KEY_ID_RE", ".", "match", "(", "aws_access_key_id", ")", "if", "m", "is", "None", "or", "m", ".", "group", "(", ")", "!=", "aws_access_key_id", ":", "logging", ".", "error", "(", "'The provided aws_access_key_id is not in the correct format. It must \\\n be alphanumeric and contain between 16 and 32 characters.'", ")", "if", "len", "(", "aws_access_key_id", ")", ">", "len", "(", "aws_secret_access_key", ")", ":", "logging", ".", "warn", "(", "\"The AWS credential keys aren't in the usual size,\"", "\" are you using the correct ones?\"", ")", "import", "boto", "from", "boto", ".", "s3", ".", "connection", "import", "OrdinaryCallingFormat", "extra_args", "=", "{", "}", "if", "host", "is", "not", "None", ":", "extra_args", "[", "'host'", "]", "=", "host", "if", "bucketname", "is", "not", "None", "and", "'.'", "in", "bucketname", ":", "extra_args", "[", "'calling_format'", "]", "=", "OrdinaryCallingFormat", "(", ")", "if", "region", "is", "None", ":", "return", "boto", ".", "connect_s3", "(", "aws_access_key_id", ",", "aws_secret_access_key", ",", "*", "*", "extra_args", ")", "return", "boto", ".", "s3", ".", "connect_to_region", "(", "region", ",", "aws_access_key_id", "=", "aws_access_key_id", ",", "aws_secret_access_key", "=", "aws_secret_access_key", ",", "*", "*", "extra_args", ")" ]
Conection parameters must be different only if bucket name has a period
[ "Conection", "parameters", "must", "be", "different", "only", "if", "bucket", "name", "has", "a", "period" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/utils.py#L115-L140
14,264
scrapinghub/exporters
exporters/utils.py
maybe_cast_list
def maybe_cast_list(value, types): """ Try to coerce list values into more specific list subclasses in types. """ if not isinstance(value, list): return value if type(types) not in (list, tuple): types = (types,) for list_type in types: if issubclass(list_type, list): try: return list_type(value) except (TypeError, ValueError): pass return value
python
def maybe_cast_list(value, types): """ Try to coerce list values into more specific list subclasses in types. """ if not isinstance(value, list): return value if type(types) not in (list, tuple): types = (types,) for list_type in types: if issubclass(list_type, list): try: return list_type(value) except (TypeError, ValueError): pass return value
[ "def", "maybe_cast_list", "(", "value", ",", "types", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "return", "value", "if", "type", "(", "types", ")", "not", "in", "(", "list", ",", "tuple", ")", ":", "types", "=", "(", "types", ",", ")", "for", "list_type", "in", "types", ":", "if", "issubclass", "(", "list_type", ",", "list", ")", ":", "try", ":", "return", "list_type", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "return", "value" ]
Try to coerce list values into more specific list subclasses in types.
[ "Try", "to", "coerce", "list", "values", "into", "more", "specific", "list", "subclasses", "in", "types", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/utils.py#L143-L159
14,265
scrapinghub/exporters
exporters/iterio.py
iterate_chunks
def iterate_chunks(file, chunk_size): """ Iterate chunks of size chunk_size from a file-like object """ chunk = file.read(chunk_size) while chunk: yield chunk chunk = file.read(chunk_size)
python
def iterate_chunks(file, chunk_size): """ Iterate chunks of size chunk_size from a file-like object """ chunk = file.read(chunk_size) while chunk: yield chunk chunk = file.read(chunk_size)
[ "def", "iterate_chunks", "(", "file", ",", "chunk_size", ")", ":", "chunk", "=", "file", ".", "read", "(", "chunk_size", ")", "while", "chunk", ":", "yield", "chunk", "chunk", "=", "file", ".", "read", "(", "chunk_size", ")" ]
Iterate chunks of size chunk_size from a file-like object
[ "Iterate", "chunks", "of", "size", "chunk_size", "from", "a", "file", "-", "like", "object" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L15-L22
14,266
scrapinghub/exporters
exporters/iterio.py
IterIO.unshift
def unshift(self, chunk): """ Pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party. """ if chunk: self._pos -= len(chunk) self._unconsumed.append(chunk)
python
def unshift(self, chunk): """ Pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party. """ if chunk: self._pos -= len(chunk) self._unconsumed.append(chunk)
[ "def", "unshift", "(", "self", ",", "chunk", ")", ":", "if", "chunk", ":", "self", ".", "_pos", "-=", "len", "(", "chunk", ")", "self", ".", "_unconsumed", ".", "append", "(", "chunk", ")" ]
Pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.
[ "Pushes", "a", "chunk", "of", "data", "back", "into", "the", "internal", "buffer", ".", "This", "is", "useful", "in", "certain", "situations", "where", "a", "stream", "is", "being", "consumed", "by", "code", "that", "needs", "to", "un", "-", "consume", "some", "amount", "of", "data", "that", "it", "has", "optimistically", "pulled", "out", "of", "the", "source", "so", "that", "the", "data", "can", "be", "passed", "on", "to", "some", "other", "party", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L46-L56
14,267
scrapinghub/exporters
exporters/iterio.py
IterIO.readline
def readline(self): """ Read until a new-line character is encountered """ line = "" n_pos = -1 try: while n_pos < 0: line += self.next_chunk() n_pos = line.find('\n') except StopIteration: pass if n_pos >= 0: line, extra = line[:n_pos+1], line[n_pos+1:] self.unshift(extra) return line
python
def readline(self): """ Read until a new-line character is encountered """ line = "" n_pos = -1 try: while n_pos < 0: line += self.next_chunk() n_pos = line.find('\n') except StopIteration: pass if n_pos >= 0: line, extra = line[:n_pos+1], line[n_pos+1:] self.unshift(extra) return line
[ "def", "readline", "(", "self", ")", ":", "line", "=", "\"\"", "n_pos", "=", "-", "1", "try", ":", "while", "n_pos", "<", "0", ":", "line", "+=", "self", ".", "next_chunk", "(", ")", "n_pos", "=", "line", ".", "find", "(", "'\\n'", ")", "except", "StopIteration", ":", "pass", "if", "n_pos", ">=", "0", ":", "line", ",", "extra", "=", "line", "[", ":", "n_pos", "+", "1", "]", ",", "line", "[", "n_pos", "+", "1", ":", "]", "self", ".", "unshift", "(", "extra", ")", "return", "line" ]
Read until a new-line character is encountered
[ "Read", "until", "a", "new", "-", "line", "character", "is", "encountered" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L110-L126
14,268
scrapinghub/exporters
exporters/iterio.py
IterIO.close
def close(self): """ Disable al operations and close the underlying file-like object, if any """ if callable(getattr(self._file, 'close', None)): self._iterator.close() self._iterator = None self._unconsumed = None self.closed = True
python
def close(self): """ Disable al operations and close the underlying file-like object, if any """ if callable(getattr(self._file, 'close', None)): self._iterator.close() self._iterator = None self._unconsumed = None self.closed = True
[ "def", "close", "(", "self", ")", ":", "if", "callable", "(", "getattr", "(", "self", ".", "_file", ",", "'close'", ",", "None", ")", ")", ":", "self", ".", "_iterator", ".", "close", "(", ")", "self", ".", "_iterator", "=", "None", "self", ".", "_unconsumed", "=", "None", "self", ".", "closed", "=", "True" ]
Disable al operations and close the underlying file-like object, if any
[ "Disable", "al", "operations", "and", "close", "the", "underlying", "file", "-", "like", "object", "if", "any" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L148-L156
14,269
scrapinghub/exporters
exporters/persistence/pickle_persistence.py
PicklePersistence.configuration_from_uri
def configuration_from_uri(uri, uri_regex): """ returns a configuration object. """ file_path = re.match(uri_regex, uri).groups()[0] with open(file_path) as f: configuration = pickle.load(f)['configuration'] configuration = yaml.safe_load(configuration) configuration['exporter_options']['resume'] = True persistence_state_id = file_path.split(os.path.sep)[-1] configuration['exporter_options']['persistence_state_id'] = persistence_state_id return configuration
python
def configuration_from_uri(uri, uri_regex): """ returns a configuration object. """ file_path = re.match(uri_regex, uri).groups()[0] with open(file_path) as f: configuration = pickle.load(f)['configuration'] configuration = yaml.safe_load(configuration) configuration['exporter_options']['resume'] = True persistence_state_id = file_path.split(os.path.sep)[-1] configuration['exporter_options']['persistence_state_id'] = persistence_state_id return configuration
[ "def", "configuration_from_uri", "(", "uri", ",", "uri_regex", ")", ":", "file_path", "=", "re", ".", "match", "(", "uri_regex", ",", "uri", ")", ".", "groups", "(", ")", "[", "0", "]", "with", "open", "(", "file_path", ")", "as", "f", ":", "configuration", "=", "pickle", ".", "load", "(", "f", ")", "[", "'configuration'", "]", "configuration", "=", "yaml", ".", "safe_load", "(", "configuration", ")", "configuration", "[", "'exporter_options'", "]", "[", "'resume'", "]", "=", "True", "persistence_state_id", "=", "file_path", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "-", "1", "]", "configuration", "[", "'exporter_options'", "]", "[", "'persistence_state_id'", "]", "=", "persistence_state_id", "return", "configuration" ]
returns a configuration object.
[ "returns", "a", "configuration", "object", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/persistence/pickle_persistence.py#L77-L88
14,270
scrapinghub/exporters
exporters/write_buffers/base.py
WriteBuffer.buffer
def buffer(self, item): """ Receive an item and write it. """ key = self.get_key_from_item(item) if not self.grouping_info.is_first_file_item(key): self.items_group_files.add_item_separator_to_file(key) self.grouping_info.ensure_group_info(key) self.items_group_files.add_item_to_file(item, key)
python
def buffer(self, item): """ Receive an item and write it. """ key = self.get_key_from_item(item) if not self.grouping_info.is_first_file_item(key): self.items_group_files.add_item_separator_to_file(key) self.grouping_info.ensure_group_info(key) self.items_group_files.add_item_to_file(item, key)
[ "def", "buffer", "(", "self", ",", "item", ")", ":", "key", "=", "self", ".", "get_key_from_item", "(", "item", ")", "if", "not", "self", ".", "grouping_info", ".", "is_first_file_item", "(", "key", ")", ":", "self", ".", "items_group_files", ".", "add_item_separator_to_file", "(", "key", ")", "self", ".", "grouping_info", ".", "ensure_group_info", "(", "key", ")", "self", ".", "items_group_files", ".", "add_item_to_file", "(", "item", ",", "key", ")" ]
Receive an item and write it.
[ "Receive", "an", "item", "and", "write", "it", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/write_buffers/base.py#L29-L37
14,271
scrapinghub/exporters
exporters/persistence/alchemy_persistence.py
BaseAlchemyPersistence.parse_persistence_uri
def parse_persistence_uri(cls, persistence_uri): """Parse a database URI and the persistence state ID from the given persistence URI """ regex = cls.persistence_uri_re match = re.match(regex, persistence_uri) if not match: raise ValueError("Couldn't parse persistence URI: %s -- regex: %s)" % (persistence_uri, regex)) conn_params = match.groupdict() missing = {'proto', 'job_id', 'database'} - set(conn_params) if missing: raise ValueError('Missing required parameters: %s (given params: %s)' % (tuple(missing), conn_params)) persistence_state_id = int(conn_params.pop('job_id')) db_uri = cls.build_db_conn_uri(**conn_params) return db_uri, persistence_state_id
python
def parse_persistence_uri(cls, persistence_uri): """Parse a database URI and the persistence state ID from the given persistence URI """ regex = cls.persistence_uri_re match = re.match(regex, persistence_uri) if not match: raise ValueError("Couldn't parse persistence URI: %s -- regex: %s)" % (persistence_uri, regex)) conn_params = match.groupdict() missing = {'proto', 'job_id', 'database'} - set(conn_params) if missing: raise ValueError('Missing required parameters: %s (given params: %s)' % (tuple(missing), conn_params)) persistence_state_id = int(conn_params.pop('job_id')) db_uri = cls.build_db_conn_uri(**conn_params) return db_uri, persistence_state_id
[ "def", "parse_persistence_uri", "(", "cls", ",", "persistence_uri", ")", ":", "regex", "=", "cls", ".", "persistence_uri_re", "match", "=", "re", ".", "match", "(", "regex", ",", "persistence_uri", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"Couldn't parse persistence URI: %s -- regex: %s)\"", "%", "(", "persistence_uri", ",", "regex", ")", ")", "conn_params", "=", "match", ".", "groupdict", "(", ")", "missing", "=", "{", "'proto'", ",", "'job_id'", ",", "'database'", "}", "-", "set", "(", "conn_params", ")", "if", "missing", ":", "raise", "ValueError", "(", "'Missing required parameters: %s (given params: %s)'", "%", "(", "tuple", "(", "missing", ")", ",", "conn_params", ")", ")", "persistence_state_id", "=", "int", "(", "conn_params", ".", "pop", "(", "'job_id'", ")", ")", "db_uri", "=", "cls", ".", "build_db_conn_uri", "(", "*", "*", "conn_params", ")", "return", "db_uri", ",", "persistence_state_id" ]
Parse a database URI and the persistence state ID from the given persistence URI
[ "Parse", "a", "database", "URI", "and", "the", "persistence", "state", "ID", "from", "the", "given", "persistence", "URI" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/persistence/alchemy_persistence.py#L104-L122
14,272
scrapinghub/exporters
exporters/persistence/alchemy_persistence.py
BaseAlchemyPersistence.configuration_from_uri
def configuration_from_uri(cls, persistence_uri): """ Return a configuration object. """ db_uri, persistence_state_id = cls.parse_persistence_uri(persistence_uri) engine = create_engine(db_uri) Base.metadata.create_all(engine) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() job = session.query(Job).filter(Job.id == persistence_state_id).first() configuration = job.configuration configuration = yaml.safe_load(configuration) configuration['exporter_options']['resume'] = True configuration['exporter_options']['persistence_state_id'] = persistence_state_id return configuration
python
def configuration_from_uri(cls, persistence_uri): """ Return a configuration object. """ db_uri, persistence_state_id = cls.parse_persistence_uri(persistence_uri) engine = create_engine(db_uri) Base.metadata.create_all(engine) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() job = session.query(Job).filter(Job.id == persistence_state_id).first() configuration = job.configuration configuration = yaml.safe_load(configuration) configuration['exporter_options']['resume'] = True configuration['exporter_options']['persistence_state_id'] = persistence_state_id return configuration
[ "def", "configuration_from_uri", "(", "cls", ",", "persistence_uri", ")", ":", "db_uri", ",", "persistence_state_id", "=", "cls", ".", "parse_persistence_uri", "(", "persistence_uri", ")", "engine", "=", "create_engine", "(", "db_uri", ")", "Base", ".", "metadata", ".", "create_all", "(", "engine", ")", "Base", ".", "metadata", ".", "bind", "=", "engine", "DBSession", "=", "sessionmaker", "(", "bind", "=", "engine", ")", "session", "=", "DBSession", "(", ")", "job", "=", "session", ".", "query", "(", "Job", ")", ".", "filter", "(", "Job", ".", "id", "==", "persistence_state_id", ")", ".", "first", "(", ")", "configuration", "=", "job", ".", "configuration", "configuration", "=", "yaml", ".", "safe_load", "(", "configuration", ")", "configuration", "[", "'exporter_options'", "]", "[", "'resume'", "]", "=", "True", "configuration", "[", "'exporter_options'", "]", "[", "'persistence_state_id'", "]", "=", "persistence_state_id", "return", "configuration" ]
Return a configuration object.
[ "Return", "a", "configuration", "object", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/persistence/alchemy_persistence.py#L125-L140
14,273
scrapinghub/exporters
exporters/readers/fs_reader.py
FSReader._get_input_files
def _get_input_files(cls, input_specification): """Get list of input files according to input definition. Input definition can be: - str: specifying a filename - list of str: specifying list a of filenames - dict with "dir" and optional "pattern" parameters: specifying the toplevel directory under which input files will be sought and an optional filepath pattern """ if isinstance(input_specification, (basestring, dict)): input_specification = [input_specification] elif not isinstance(input_specification, list): raise ConfigurationError("Input specification must be string, list or dict.") out = [] for input_unit in input_specification: if isinstance(input_unit, basestring): out.append(input_unit) elif isinstance(input_unit, dict): missing = object() directory = input_unit.get('dir', missing) dir_pointer = input_unit.get('dir_pointer', missing) if directory is missing and dir_pointer is missing: raise ConfigurationError( 'Input directory dict must contain' ' "dir" or "dir_pointer" element (but not both)') if directory is not missing and dir_pointer is not missing: raise ConfigurationError( 'Input directory dict must not contain' ' both "dir" and "dir_pointer" elements') if dir_pointer is not missing: directory = cls._get_pointer(dir_pointer) out.extend(cls._get_directory_files( directory=directory, pattern=input_unit.get('pattern'), include_dot_files=input_unit.get('include_dot_files', False))) else: raise ConfigurationError('Input must only contain strings or dicts') return out
python
def _get_input_files(cls, input_specification): """Get list of input files according to input definition. Input definition can be: - str: specifying a filename - list of str: specifying list a of filenames - dict with "dir" and optional "pattern" parameters: specifying the toplevel directory under which input files will be sought and an optional filepath pattern """ if isinstance(input_specification, (basestring, dict)): input_specification = [input_specification] elif not isinstance(input_specification, list): raise ConfigurationError("Input specification must be string, list or dict.") out = [] for input_unit in input_specification: if isinstance(input_unit, basestring): out.append(input_unit) elif isinstance(input_unit, dict): missing = object() directory = input_unit.get('dir', missing) dir_pointer = input_unit.get('dir_pointer', missing) if directory is missing and dir_pointer is missing: raise ConfigurationError( 'Input directory dict must contain' ' "dir" or "dir_pointer" element (but not both)') if directory is not missing and dir_pointer is not missing: raise ConfigurationError( 'Input directory dict must not contain' ' both "dir" and "dir_pointer" elements') if dir_pointer is not missing: directory = cls._get_pointer(dir_pointer) out.extend(cls._get_directory_files( directory=directory, pattern=input_unit.get('pattern'), include_dot_files=input_unit.get('include_dot_files', False))) else: raise ConfigurationError('Input must only contain strings or dicts') return out
[ "def", "_get_input_files", "(", "cls", ",", "input_specification", ")", ":", "if", "isinstance", "(", "input_specification", ",", "(", "basestring", ",", "dict", ")", ")", ":", "input_specification", "=", "[", "input_specification", "]", "elif", "not", "isinstance", "(", "input_specification", ",", "list", ")", ":", "raise", "ConfigurationError", "(", "\"Input specification must be string, list or dict.\"", ")", "out", "=", "[", "]", "for", "input_unit", "in", "input_specification", ":", "if", "isinstance", "(", "input_unit", ",", "basestring", ")", ":", "out", ".", "append", "(", "input_unit", ")", "elif", "isinstance", "(", "input_unit", ",", "dict", ")", ":", "missing", "=", "object", "(", ")", "directory", "=", "input_unit", ".", "get", "(", "'dir'", ",", "missing", ")", "dir_pointer", "=", "input_unit", ".", "get", "(", "'dir_pointer'", ",", "missing", ")", "if", "directory", "is", "missing", "and", "dir_pointer", "is", "missing", ":", "raise", "ConfigurationError", "(", "'Input directory dict must contain'", "' \"dir\" or \"dir_pointer\" element (but not both)'", ")", "if", "directory", "is", "not", "missing", "and", "dir_pointer", "is", "not", "missing", ":", "raise", "ConfigurationError", "(", "'Input directory dict must not contain'", "' both \"dir\" and \"dir_pointer\" elements'", ")", "if", "dir_pointer", "is", "not", "missing", ":", "directory", "=", "cls", ".", "_get_pointer", "(", "dir_pointer", ")", "out", ".", "extend", "(", "cls", ".", "_get_directory_files", "(", "directory", "=", "directory", ",", "pattern", "=", "input_unit", ".", "get", "(", "'pattern'", ")", ",", "include_dot_files", "=", "input_unit", ".", "get", "(", "'include_dot_files'", ",", "False", ")", ")", ")", "else", ":", "raise", "ConfigurationError", "(", "'Input must only contain strings or dicts'", ")", "return", "out" ]
Get list of input files according to input definition. Input definition can be: - str: specifying a filename - list of str: specifying list a of filenames - dict with "dir" and optional "pattern" parameters: specifying the toplevel directory under which input files will be sought and an optional filepath pattern
[ "Get", "list", "of", "input", "files", "according", "to", "input", "definition", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/fs_reader.py#L59-L103
14,274
scrapinghub/exporters
exporters/readers/kafka_random_reader.py
KafkaRandomReader.consume_messages
def consume_messages(self, batchsize): """ Get messages batch from the reservoir """ if not self._reservoir: self.finished = True return for msg in self._reservoir[:batchsize]: yield msg self._reservoir = self._reservoir[batchsize:]
python
def consume_messages(self, batchsize): """ Get messages batch from the reservoir """ if not self._reservoir: self.finished = True return for msg in self._reservoir[:batchsize]: yield msg self._reservoir = self._reservoir[batchsize:]
[ "def", "consume_messages", "(", "self", ",", "batchsize", ")", ":", "if", "not", "self", ".", "_reservoir", ":", "self", ".", "finished", "=", "True", "return", "for", "msg", "in", "self", ".", "_reservoir", "[", ":", "batchsize", "]", ":", "yield", "msg", "self", ".", "_reservoir", "=", "self", ".", "_reservoir", "[", "batchsize", ":", "]" ]
Get messages batch from the reservoir
[ "Get", "messages", "batch", "from", "the", "reservoir" ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/kafka_random_reader.py#L127-L134
14,275
scrapinghub/exporters
exporters/readers/kafka_random_reader.py
KafkaRandomReader.decompress_messages
def decompress_messages(self, offmsgs): """ Decompress pre-defined compressed fields for each message. Msgs should be unpacked before this step. """ for offmsg in offmsgs: yield offmsg.message.key, self.decompress_fun(offmsg.message.value)
python
def decompress_messages(self, offmsgs): """ Decompress pre-defined compressed fields for each message. Msgs should be unpacked before this step. """ for offmsg in offmsgs: yield offmsg.message.key, self.decompress_fun(offmsg.message.value)
[ "def", "decompress_messages", "(", "self", ",", "offmsgs", ")", ":", "for", "offmsg", "in", "offmsgs", ":", "yield", "offmsg", ".", "message", ".", "key", ",", "self", ".", "decompress_fun", "(", "offmsg", ".", "message", ".", "value", ")" ]
Decompress pre-defined compressed fields for each message. Msgs should be unpacked before this step.
[ "Decompress", "pre", "-", "defined", "compressed", "fields", "for", "each", "message", ".", "Msgs", "should", "be", "unpacked", "before", "this", "step", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/kafka_random_reader.py#L136-L141
14,276
scrapinghub/exporters
exporters/filters/base_filter.py
BaseFilter.filter_batch
def filter_batch(self, batch): """ Receives the batch, filters it, and returns it. """ for item in batch: if self.filter(item): yield item else: self.set_metadata('filtered_out', self.get_metadata('filtered_out') + 1) self.total += 1 self._log_progress()
python
def filter_batch(self, batch): """ Receives the batch, filters it, and returns it. """ for item in batch: if self.filter(item): yield item else: self.set_metadata('filtered_out', self.get_metadata('filtered_out') + 1) self.total += 1 self._log_progress()
[ "def", "filter_batch", "(", "self", ",", "batch", ")", ":", "for", "item", "in", "batch", ":", "if", "self", ".", "filter", "(", "item", ")", ":", "yield", "item", "else", ":", "self", ".", "set_metadata", "(", "'filtered_out'", ",", "self", ".", "get_metadata", "(", "'filtered_out'", ")", "+", "1", ")", "self", ".", "total", "+=", "1", "self", ".", "_log_progress", "(", ")" ]
Receives the batch, filters it, and returns it.
[ "Receives", "the", "batch", "filters", "it", "and", "returns", "it", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/filters/base_filter.py#L24-L36
14,277
scrapinghub/exporters
exporters/writers/base_writer.py
BaseWriter.write_batch
def write_batch(self, batch): """ Buffer a batch of items to be written and update internal counters. Calling this method doesn't guarantee that all items have been written. To ensure everything has been written you need to call flush(). """ for item in batch: self.write_buffer.buffer(item) key = self.write_buffer.get_key_from_item(item) if self.write_buffer.should_write_buffer(key): self._write_current_buffer_for_group_key(key) self.increment_written_items() self._check_items_limit()
python
def write_batch(self, batch): """ Buffer a batch of items to be written and update internal counters. Calling this method doesn't guarantee that all items have been written. To ensure everything has been written you need to call flush(). """ for item in batch: self.write_buffer.buffer(item) key = self.write_buffer.get_key_from_item(item) if self.write_buffer.should_write_buffer(key): self._write_current_buffer_for_group_key(key) self.increment_written_items() self._check_items_limit()
[ "def", "write_batch", "(", "self", ",", "batch", ")", ":", "for", "item", "in", "batch", ":", "self", ".", "write_buffer", ".", "buffer", "(", "item", ")", "key", "=", "self", ".", "write_buffer", ".", "get_key_from_item", "(", "item", ")", "if", "self", ".", "write_buffer", ".", "should_write_buffer", "(", "key", ")", ":", "self", ".", "_write_current_buffer_for_group_key", "(", "key", ")", "self", ".", "increment_written_items", "(", ")", "self", ".", "_check_items_limit", "(", ")" ]
Buffer a batch of items to be written and update internal counters. Calling this method doesn't guarantee that all items have been written. To ensure everything has been written you need to call flush().
[ "Buffer", "a", "batch", "of", "items", "to", "be", "written", "and", "update", "internal", "counters", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L103-L116
14,278
scrapinghub/exporters
exporters/writers/base_writer.py
BaseWriter._check_items_limit
def _check_items_limit(self): """ Raise ItemsLimitReached if the writer reached the configured items limit. """ if self.items_limit and self.items_limit == self.get_metadata('items_count'): raise ItemsLimitReached('Finishing job after items_limit reached:' ' {} items written.'.format(self.get_metadata('items_count')))
python
def _check_items_limit(self): """ Raise ItemsLimitReached if the writer reached the configured items limit. """ if self.items_limit and self.items_limit == self.get_metadata('items_count'): raise ItemsLimitReached('Finishing job after items_limit reached:' ' {} items written.'.format(self.get_metadata('items_count')))
[ "def", "_check_items_limit", "(", "self", ")", ":", "if", "self", ".", "items_limit", "and", "self", ".", "items_limit", "==", "self", ".", "get_metadata", "(", "'items_count'", ")", ":", "raise", "ItemsLimitReached", "(", "'Finishing job after items_limit reached:'", "' {} items written.'", ".", "format", "(", "self", ".", "get_metadata", "(", "'items_count'", ")", ")", ")" ]
Raise ItemsLimitReached if the writer reached the configured items limit.
[ "Raise", "ItemsLimitReached", "if", "the", "writer", "reached", "the", "configured", "items", "limit", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L118-L124
14,279
scrapinghub/exporters
exporters/writers/base_writer.py
BaseWriter.flush
def flush(self): """ Ensure all remaining buffers are written. """ for key in self.grouping_info.keys(): if self._should_flush(key): self._write_current_buffer_for_group_key(key)
python
def flush(self): """ Ensure all remaining buffers are written. """ for key in self.grouping_info.keys(): if self._should_flush(key): self._write_current_buffer_for_group_key(key)
[ "def", "flush", "(", "self", ")", ":", "for", "key", "in", "self", ".", "grouping_info", ".", "keys", "(", ")", ":", "if", "self", ".", "_should_flush", "(", "key", ")", ":", "self", ".", "_write_current_buffer_for_group_key", "(", "key", ")" ]
Ensure all remaining buffers are written.
[ "Ensure", "all", "remaining", "buffers", "are", "written", "." ]
c9fb01db1771ada4672bbffd67cb46e1f7802ab9
https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L129-L135
14,280
opendatateam/udata
udata/assets.py
has_manifest
def has_manifest(app, filename='manifest.json'): '''Verify the existance of a JSON assets manifest''' try: return pkg_resources.resource_exists(app, filename) except ImportError: return os.path.isabs(filename) and os.path.exists(filename)
python
def has_manifest(app, filename='manifest.json'): '''Verify the existance of a JSON assets manifest''' try: return pkg_resources.resource_exists(app, filename) except ImportError: return os.path.isabs(filename) and os.path.exists(filename)
[ "def", "has_manifest", "(", "app", ",", "filename", "=", "'manifest.json'", ")", ":", "try", ":", "return", "pkg_resources", ".", "resource_exists", "(", "app", ",", "filename", ")", "except", "ImportError", ":", "return", "os", ".", "path", ".", "isabs", "(", "filename", ")", "and", "os", ".", "path", ".", "exists", "(", "filename", ")" ]
Verify the existance of a JSON assets manifest
[ "Verify", "the", "existance", "of", "a", "JSON", "assets", "manifest" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L19-L24
14,281
opendatateam/udata
udata/assets.py
register_manifest
def register_manifest(app, filename='manifest.json'): '''Register an assets json manifest''' if current_app.config.get('TESTING'): return # Do not spend time here when testing if not has_manifest(app, filename): msg = '{filename} not found for {app}'.format(**locals()) raise ValueError(msg) manifest = _manifests.get(app, {}) manifest.update(load_manifest(app, filename)) _manifests[app] = manifest
python
def register_manifest(app, filename='manifest.json'): '''Register an assets json manifest''' if current_app.config.get('TESTING'): return # Do not spend time here when testing if not has_manifest(app, filename): msg = '{filename} not found for {app}'.format(**locals()) raise ValueError(msg) manifest = _manifests.get(app, {}) manifest.update(load_manifest(app, filename)) _manifests[app] = manifest
[ "def", "register_manifest", "(", "app", ",", "filename", "=", "'manifest.json'", ")", ":", "if", "current_app", ".", "config", ".", "get", "(", "'TESTING'", ")", ":", "return", "# Do not spend time here when testing", "if", "not", "has_manifest", "(", "app", ",", "filename", ")", ":", "msg", "=", "'{filename} not found for {app}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "raise", "ValueError", "(", "msg", ")", "manifest", "=", "_manifests", ".", "get", "(", "app", ",", "{", "}", ")", "manifest", ".", "update", "(", "load_manifest", "(", "app", ",", "filename", ")", ")", "_manifests", "[", "app", "]", "=", "manifest" ]
Register an assets json manifest
[ "Register", "an", "assets", "json", "manifest" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L27-L36
14,282
opendatateam/udata
udata/assets.py
load_manifest
def load_manifest(app, filename='manifest.json'): '''Load an assets json manifest''' if os.path.isabs(filename): path = filename else: path = pkg_resources.resource_filename(app, filename) with io.open(path, mode='r', encoding='utf8') as stream: data = json.load(stream) _registered_manifests[app] = path return data
python
def load_manifest(app, filename='manifest.json'): '''Load an assets json manifest''' if os.path.isabs(filename): path = filename else: path = pkg_resources.resource_filename(app, filename) with io.open(path, mode='r', encoding='utf8') as stream: data = json.load(stream) _registered_manifests[app] = path return data
[ "def", "load_manifest", "(", "app", ",", "filename", "=", "'manifest.json'", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "filename", ")", ":", "path", "=", "filename", "else", ":", "path", "=", "pkg_resources", ".", "resource_filename", "(", "app", ",", "filename", ")", "with", "io", ".", "open", "(", "path", ",", "mode", "=", "'r'", ",", "encoding", "=", "'utf8'", ")", "as", "stream", ":", "data", "=", "json", ".", "load", "(", "stream", ")", "_registered_manifests", "[", "app", "]", "=", "path", "return", "data" ]
Load an assets json manifest
[ "Load", "an", "assets", "json", "manifest" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L39-L48
14,283
opendatateam/udata
udata/assets.py
from_manifest
def from_manifest(app, filename, raw=False, **kwargs): ''' Get the path to a static file for a given app entry of a given type. :param str app: The application key to which is tied this manifest :param str filename: the original filename (without hash) :param bool raw: if True, doesn't add prefix to the manifest :return: the resolved file path from manifest :rtype: str ''' cfg = current_app.config if current_app.config.get('TESTING'): return # Do not spend time here when testing path = _manifests[app][filename] if not raw and cfg.get('CDN_DOMAIN') and not cfg.get('CDN_DEBUG'): scheme = 'https' if cfg.get('CDN_HTTPS') else request.scheme prefix = '{}://'.format(scheme) if not path.startswith('/'): # CDN_DOMAIN has no trailing slash path = '/' + path return ''.join((prefix, cfg['CDN_DOMAIN'], path)) elif not raw and kwargs.get('external', False): if path.startswith('/'): # request.host_url has a trailing slash path = path[1:] return ''.join((request.host_url, path)) return path
python
def from_manifest(app, filename, raw=False, **kwargs): ''' Get the path to a static file for a given app entry of a given type. :param str app: The application key to which is tied this manifest :param str filename: the original filename (without hash) :param bool raw: if True, doesn't add prefix to the manifest :return: the resolved file path from manifest :rtype: str ''' cfg = current_app.config if current_app.config.get('TESTING'): return # Do not spend time here when testing path = _manifests[app][filename] if not raw and cfg.get('CDN_DOMAIN') and not cfg.get('CDN_DEBUG'): scheme = 'https' if cfg.get('CDN_HTTPS') else request.scheme prefix = '{}://'.format(scheme) if not path.startswith('/'): # CDN_DOMAIN has no trailing slash path = '/' + path return ''.join((prefix, cfg['CDN_DOMAIN'], path)) elif not raw and kwargs.get('external', False): if path.startswith('/'): # request.host_url has a trailing slash path = path[1:] return ''.join((request.host_url, path)) return path
[ "def", "from_manifest", "(", "app", ",", "filename", ",", "raw", "=", "False", ",", "*", "*", "kwargs", ")", ":", "cfg", "=", "current_app", ".", "config", "if", "current_app", ".", "config", ".", "get", "(", "'TESTING'", ")", ":", "return", "# Do not spend time here when testing", "path", "=", "_manifests", "[", "app", "]", "[", "filename", "]", "if", "not", "raw", "and", "cfg", ".", "get", "(", "'CDN_DOMAIN'", ")", "and", "not", "cfg", ".", "get", "(", "'CDN_DEBUG'", ")", ":", "scheme", "=", "'https'", "if", "cfg", ".", "get", "(", "'CDN_HTTPS'", ")", "else", "request", ".", "scheme", "prefix", "=", "'{}://'", ".", "format", "(", "scheme", ")", "if", "not", "path", ".", "startswith", "(", "'/'", ")", ":", "# CDN_DOMAIN has no trailing slash", "path", "=", "'/'", "+", "path", "return", "''", ".", "join", "(", "(", "prefix", ",", "cfg", "[", "'CDN_DOMAIN'", "]", ",", "path", ")", ")", "elif", "not", "raw", "and", "kwargs", ".", "get", "(", "'external'", ",", "False", ")", ":", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "# request.host_url has a trailing slash", "path", "=", "path", "[", "1", ":", "]", "return", "''", ".", "join", "(", "(", "request", ".", "host_url", ",", "path", ")", ")", "return", "path" ]
Get the path to a static file for a given app entry of a given type. :param str app: The application key to which is tied this manifest :param str filename: the original filename (without hash) :param bool raw: if True, doesn't add prefix to the manifest :return: the resolved file path from manifest :rtype: str
[ "Get", "the", "path", "to", "a", "static", "file", "for", "a", "given", "app", "entry", "of", "a", "given", "type", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L58-L85
14,284
opendatateam/udata
udata/assets.py
cdn_for
def cdn_for(endpoint, **kwargs): ''' Get a CDN URL for a static assets. Do not use a replacement for all flask.url_for calls as it is only meant for CDN assets URLS. (There is some extra round trip which cost is justified by the CDN assets prformance improvements) ''' if current_app.config['CDN_DOMAIN']: if not current_app.config.get('CDN_DEBUG'): kwargs.pop('_external', None) # Avoid the _external parameter in URL return cdn_url_for(endpoint, **kwargs) return url_for(endpoint, **kwargs)
python
def cdn_for(endpoint, **kwargs): ''' Get a CDN URL for a static assets. Do not use a replacement for all flask.url_for calls as it is only meant for CDN assets URLS. (There is some extra round trip which cost is justified by the CDN assets prformance improvements) ''' if current_app.config['CDN_DOMAIN']: if not current_app.config.get('CDN_DEBUG'): kwargs.pop('_external', None) # Avoid the _external parameter in URL return cdn_url_for(endpoint, **kwargs) return url_for(endpoint, **kwargs)
[ "def", "cdn_for", "(", "endpoint", ",", "*", "*", "kwargs", ")", ":", "if", "current_app", ".", "config", "[", "'CDN_DOMAIN'", "]", ":", "if", "not", "current_app", ".", "config", ".", "get", "(", "'CDN_DEBUG'", ")", ":", "kwargs", ".", "pop", "(", "'_external'", ",", "None", ")", "# Avoid the _external parameter in URL", "return", "cdn_url_for", "(", "endpoint", ",", "*", "*", "kwargs", ")", "return", "url_for", "(", "endpoint", ",", "*", "*", "kwargs", ")" ]
Get a CDN URL for a static assets. Do not use a replacement for all flask.url_for calls as it is only meant for CDN assets URLS. (There is some extra round trip which cost is justified by the CDN assets prformance improvements)
[ "Get", "a", "CDN", "URL", "for", "a", "static", "assets", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L92-L105
14,285
opendatateam/udata
udata/models/queryset.py
UDataQuerySet.get_or_create
def get_or_create(self, write_concern=None, auto_save=True, *q_objs, **query): """Retrieve unique object or create, if it doesn't exist. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or created object and ``created`` is a boolean specifying whether a new object was created. Taken back from: https://github.com/MongoEngine/mongoengine/ pull/1029/files#diff-05c70acbd0634d6d05e4a6e3a9b7d66b """ defaults = query.pop('defaults', {}) try: doc = self.get(*q_objs, **query) return doc, False except self._document.DoesNotExist: query.update(defaults) doc = self._document(**query) if auto_save: doc.save(write_concern=write_concern) return doc, True
python
def get_or_create(self, write_concern=None, auto_save=True, *q_objs, **query): """Retrieve unique object or create, if it doesn't exist. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or created object and ``created`` is a boolean specifying whether a new object was created. Taken back from: https://github.com/MongoEngine/mongoengine/ pull/1029/files#diff-05c70acbd0634d6d05e4a6e3a9b7d66b """ defaults = query.pop('defaults', {}) try: doc = self.get(*q_objs, **query) return doc, False except self._document.DoesNotExist: query.update(defaults) doc = self._document(**query) if auto_save: doc.save(write_concern=write_concern) return doc, True
[ "def", "get_or_create", "(", "self", ",", "write_concern", "=", "None", ",", "auto_save", "=", "True", ",", "*", "q_objs", ",", "*", "*", "query", ")", ":", "defaults", "=", "query", ".", "pop", "(", "'defaults'", ",", "{", "}", ")", "try", ":", "doc", "=", "self", ".", "get", "(", "*", "q_objs", ",", "*", "*", "query", ")", "return", "doc", ",", "False", "except", "self", ".", "_document", ".", "DoesNotExist", ":", "query", ".", "update", "(", "defaults", ")", "doc", "=", "self", ".", "_document", "(", "*", "*", "query", ")", "if", "auto_save", ":", "doc", ".", "save", "(", "write_concern", "=", "write_concern", ")", "return", "doc", ",", "True" ]
Retrieve unique object or create, if it doesn't exist. Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or created object and ``created`` is a boolean specifying whether a new object was created. Taken back from: https://github.com/MongoEngine/mongoengine/ pull/1029/files#diff-05c70acbd0634d6d05e4a6e3a9b7d66b
[ "Retrieve", "unique", "object", "or", "create", "if", "it", "doesn", "t", "exist", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/queryset.py#L50-L73
14,286
opendatateam/udata
udata/models/queryset.py
UDataQuerySet.generic_in
def generic_in(self, **kwargs): '''Bypass buggy GenericReferenceField querying issue''' query = {} for key, value in kwargs.items(): if not value: continue # Optimize query for when there is only one value if isinstance(value, (list, tuple)) and len(value) == 1: value = value[0] if isinstance(value, (list, tuple)): if all(isinstance(v, basestring) for v in value): ids = [ObjectId(v) for v in value] query['{0}._ref.$id'.format(key)] = {'$in': ids} elif all(isinstance(v, DBRef) for v in value): query['{0}._ref'.format(key)] = {'$in': value} elif all(isinstance(v, ObjectId) for v in value): query['{0}._ref.$id'.format(key)] = {'$in': value} elif isinstance(value, ObjectId): query['{0}._ref.$id'.format(key)] = value elif isinstance(value, basestring): query['{0}._ref.$id'.format(key)] = ObjectId(value) else: self.error('expect a list of string, ObjectId or DBRef') return self(__raw__=query)
python
def generic_in(self, **kwargs): '''Bypass buggy GenericReferenceField querying issue''' query = {} for key, value in kwargs.items(): if not value: continue # Optimize query for when there is only one value if isinstance(value, (list, tuple)) and len(value) == 1: value = value[0] if isinstance(value, (list, tuple)): if all(isinstance(v, basestring) for v in value): ids = [ObjectId(v) for v in value] query['{0}._ref.$id'.format(key)] = {'$in': ids} elif all(isinstance(v, DBRef) for v in value): query['{0}._ref'.format(key)] = {'$in': value} elif all(isinstance(v, ObjectId) for v in value): query['{0}._ref.$id'.format(key)] = {'$in': value} elif isinstance(value, ObjectId): query['{0}._ref.$id'.format(key)] = value elif isinstance(value, basestring): query['{0}._ref.$id'.format(key)] = ObjectId(value) else: self.error('expect a list of string, ObjectId or DBRef') return self(__raw__=query)
[ "def", "generic_in", "(", "self", ",", "*", "*", "kwargs", ")", ":", "query", "=", "{", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "value", ":", "continue", "# Optimize query for when there is only one value", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "value", ")", "==", "1", ":", "value", "=", "value", "[", "0", "]", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "all", "(", "isinstance", "(", "v", ",", "basestring", ")", "for", "v", "in", "value", ")", ":", "ids", "=", "[", "ObjectId", "(", "v", ")", "for", "v", "in", "value", "]", "query", "[", "'{0}._ref.$id'", ".", "format", "(", "key", ")", "]", "=", "{", "'$in'", ":", "ids", "}", "elif", "all", "(", "isinstance", "(", "v", ",", "DBRef", ")", "for", "v", "in", "value", ")", ":", "query", "[", "'{0}._ref'", ".", "format", "(", "key", ")", "]", "=", "{", "'$in'", ":", "value", "}", "elif", "all", "(", "isinstance", "(", "v", ",", "ObjectId", ")", "for", "v", "in", "value", ")", ":", "query", "[", "'{0}._ref.$id'", ".", "format", "(", "key", ")", "]", "=", "{", "'$in'", ":", "value", "}", "elif", "isinstance", "(", "value", ",", "ObjectId", ")", ":", "query", "[", "'{0}._ref.$id'", ".", "format", "(", "key", ")", "]", "=", "value", "elif", "isinstance", "(", "value", ",", "basestring", ")", ":", "query", "[", "'{0}._ref.$id'", ".", "format", "(", "key", ")", "]", "=", "ObjectId", "(", "value", ")", "else", ":", "self", ".", "error", "(", "'expect a list of string, ObjectId or DBRef'", ")", "return", "self", "(", "__raw__", "=", "query", ")" ]
Bypass buggy GenericReferenceField querying issue
[ "Bypass", "buggy", "GenericReferenceField", "querying", "issue" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/queryset.py#L75-L98
14,287
opendatateam/udata
udata/core/issues/notifications.py
issues_notifications
def issues_notifications(user): '''Notify user about open issues''' notifications = [] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = issues_for(user).only('id', 'title', 'created', 'subject') # Do not dereference subject (so it's a DBRef) # Also improve performances and memory usage for issue in qs.no_dereference(): notifications.append((issue.created, { 'id': issue.id, 'title': issue.title, 'subject': { 'id': issue.subject['_ref'].id, 'type': issue.subject['_cls'].lower(), } })) return notifications
python
def issues_notifications(user): '''Notify user about open issues''' notifications = [] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = issues_for(user).only('id', 'title', 'created', 'subject') # Do not dereference subject (so it's a DBRef) # Also improve performances and memory usage for issue in qs.no_dereference(): notifications.append((issue.created, { 'id': issue.id, 'title': issue.title, 'subject': { 'id': issue.subject['_ref'].id, 'type': issue.subject['_cls'].lower(), } })) return notifications
[ "def", "issues_notifications", "(", "user", ")", ":", "notifications", "=", "[", "]", "# Only fetch required fields for notification serialization", "# Greatly improve performances and memory usage", "qs", "=", "issues_for", "(", "user", ")", ".", "only", "(", "'id'", ",", "'title'", ",", "'created'", ",", "'subject'", ")", "# Do not dereference subject (so it's a DBRef)", "# Also improve performances and memory usage", "for", "issue", "in", "qs", ".", "no_dereference", "(", ")", ":", "notifications", ".", "append", "(", "(", "issue", ".", "created", ",", "{", "'id'", ":", "issue", ".", "id", ",", "'title'", ":", "issue", ".", "title", ",", "'subject'", ":", "{", "'id'", ":", "issue", ".", "subject", "[", "'_ref'", "]", ".", "id", ",", "'type'", ":", "issue", ".", "subject", "[", "'_cls'", "]", ".", "lower", "(", ")", ",", "}", "}", ")", ")", "return", "notifications" ]
Notify user about open issues
[ "Notify", "user", "about", "open", "issues" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/issues/notifications.py#L15-L35
14,288
opendatateam/udata
udata/features/identicon/backends.py
get_config
def get_config(key): ''' Get an identicon configuration parameter. Precedance order is: - application config (`udata.cfg`) - theme config - default ''' key = 'AVATAR_{0}'.format(key.upper()) local_config = current_app.config.get(key) return local_config or getattr(theme.current, key, DEFAULTS[key])
python
def get_config(key): ''' Get an identicon configuration parameter. Precedance order is: - application config (`udata.cfg`) - theme config - default ''' key = 'AVATAR_{0}'.format(key.upper()) local_config = current_app.config.get(key) return local_config or getattr(theme.current, key, DEFAULTS[key])
[ "def", "get_config", "(", "key", ")", ":", "key", "=", "'AVATAR_{0}'", ".", "format", "(", "key", ".", "upper", "(", ")", ")", "local_config", "=", "current_app", ".", "config", ".", "get", "(", "key", ")", "return", "local_config", "or", "getattr", "(", "theme", ".", "current", ",", "key", ",", "DEFAULTS", "[", "key", "]", ")" ]
Get an identicon configuration parameter. Precedance order is: - application config (`udata.cfg`) - theme config - default
[ "Get", "an", "identicon", "configuration", "parameter", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L41-L52
14,289
opendatateam/udata
udata/features/identicon/backends.py
get_provider
def get_provider(): '''Get the current provider from config''' name = get_config('provider') available = entrypoints.get_all('udata.avatars') if name not in available: raise ValueError('Unknown avatar provider: {0}'.format(name)) return available[name]
python
def get_provider(): '''Get the current provider from config''' name = get_config('provider') available = entrypoints.get_all('udata.avatars') if name not in available: raise ValueError('Unknown avatar provider: {0}'.format(name)) return available[name]
[ "def", "get_provider", "(", ")", ":", "name", "=", "get_config", "(", "'provider'", ")", "available", "=", "entrypoints", ".", "get_all", "(", "'udata.avatars'", ")", "if", "name", "not", "in", "available", ":", "raise", "ValueError", "(", "'Unknown avatar provider: {0}'", ".", "format", "(", "name", ")", ")", "return", "available", "[", "name", "]" ]
Get the current provider from config
[ "Get", "the", "current", "provider", "from", "config" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L59-L65
14,290
opendatateam/udata
udata/features/identicon/backends.py
generate_pydenticon
def generate_pydenticon(identifier, size): ''' Use pydenticon to generate an identicon image. All parameters are extracted from configuration. ''' blocks_size = get_internal_config('size') foreground = get_internal_config('foreground') background = get_internal_config('background') generator = pydenticon.Generator(blocks_size, blocks_size, digest=hashlib.sha1, foreground=foreground, background=background) # Pydenticon adds padding to the size and as a consequence # we need to compute the size without the padding padding = int(round(get_internal_config('padding') * size / 100.)) size = size - 2 * padding padding = (padding, ) * 4 return generator.generate(identifier, size, size, padding=padding, output_format='png')
python
def generate_pydenticon(identifier, size): ''' Use pydenticon to generate an identicon image. All parameters are extracted from configuration. ''' blocks_size = get_internal_config('size') foreground = get_internal_config('foreground') background = get_internal_config('background') generator = pydenticon.Generator(blocks_size, blocks_size, digest=hashlib.sha1, foreground=foreground, background=background) # Pydenticon adds padding to the size and as a consequence # we need to compute the size without the padding padding = int(round(get_internal_config('padding') * size / 100.)) size = size - 2 * padding padding = (padding, ) * 4 return generator.generate(identifier, size, size, padding=padding, output_format='png')
[ "def", "generate_pydenticon", "(", "identifier", ",", "size", ")", ":", "blocks_size", "=", "get_internal_config", "(", "'size'", ")", "foreground", "=", "get_internal_config", "(", "'foreground'", ")", "background", "=", "get_internal_config", "(", "'background'", ")", "generator", "=", "pydenticon", ".", "Generator", "(", "blocks_size", ",", "blocks_size", ",", "digest", "=", "hashlib", ".", "sha1", ",", "foreground", "=", "foreground", ",", "background", "=", "background", ")", "# Pydenticon adds padding to the size and as a consequence", "# we need to compute the size without the padding", "padding", "=", "int", "(", "round", "(", "get_internal_config", "(", "'padding'", ")", "*", "size", "/", "100.", ")", ")", "size", "=", "size", "-", "2", "*", "padding", "padding", "=", "(", "padding", ",", ")", "*", "4", "return", "generator", ".", "generate", "(", "identifier", ",", "size", ",", "size", ",", "padding", "=", "padding", ",", "output_format", "=", "'png'", ")" ]
Use pydenticon to generate an identicon image. All parameters are extracted from configuration.
[ "Use", "pydenticon", "to", "generate", "an", "identicon", "image", ".", "All", "parameters", "are", "extracted", "from", "configuration", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L80-L100
14,291
opendatateam/udata
udata/features/identicon/backends.py
adorable
def adorable(identifier, size): ''' Adorable Avatars provider Simply redirect to the external API. See: http://avatars.adorable.io/ ''' url = ADORABLE_AVATARS_URL.format(identifier=identifier, size=size) return redirect(url)
python
def adorable(identifier, size): ''' Adorable Avatars provider Simply redirect to the external API. See: http://avatars.adorable.io/ ''' url = ADORABLE_AVATARS_URL.format(identifier=identifier, size=size) return redirect(url)
[ "def", "adorable", "(", "identifier", ",", "size", ")", ":", "url", "=", "ADORABLE_AVATARS_URL", ".", "format", "(", "identifier", "=", "identifier", ",", "size", "=", "size", ")", "return", "redirect", "(", "url", ")" ]
Adorable Avatars provider Simply redirect to the external API. See: http://avatars.adorable.io/
[ "Adorable", "Avatars", "provider" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L116-L125
14,292
opendatateam/udata
udata/core/dataset/commands.py
licenses
def licenses(source=DEFAULT_LICENSE_FILE): '''Feed the licenses from a JSON file''' if source.startswith('http'): json_licenses = requests.get(source).json() else: with open(source) as fp: json_licenses = json.load(fp) if len(json_licenses): log.info('Dropping existing licenses') License.drop_collection() for json_license in json_licenses: flags = [] for field, flag in FLAGS_MAP.items(): if json_license.get(field, False): flags.append(flag) license = License.objects.create( id=json_license['id'], title=json_license['title'], url=json_license['url'] or None, maintainer=json_license['maintainer'] or None, flags=flags, active=json_license.get('active', False), alternate_urls=json_license.get('alternate_urls', []), alternate_titles=json_license.get('alternate_titles', []), ) log.info('Added license "%s"', license.title) try: License.objects.get(id=DEFAULT_LICENSE['id']) except License.DoesNotExist: License.objects.create(**DEFAULT_LICENSE) log.info('Added license "%s"', DEFAULT_LICENSE['title']) success('Done')
python
def licenses(source=DEFAULT_LICENSE_FILE): '''Feed the licenses from a JSON file''' if source.startswith('http'): json_licenses = requests.get(source).json() else: with open(source) as fp: json_licenses = json.load(fp) if len(json_licenses): log.info('Dropping existing licenses') License.drop_collection() for json_license in json_licenses: flags = [] for field, flag in FLAGS_MAP.items(): if json_license.get(field, False): flags.append(flag) license = License.objects.create( id=json_license['id'], title=json_license['title'], url=json_license['url'] or None, maintainer=json_license['maintainer'] or None, flags=flags, active=json_license.get('active', False), alternate_urls=json_license.get('alternate_urls', []), alternate_titles=json_license.get('alternate_titles', []), ) log.info('Added license "%s"', license.title) try: License.objects.get(id=DEFAULT_LICENSE['id']) except License.DoesNotExist: License.objects.create(**DEFAULT_LICENSE) log.info('Added license "%s"', DEFAULT_LICENSE['title']) success('Done')
[ "def", "licenses", "(", "source", "=", "DEFAULT_LICENSE_FILE", ")", ":", "if", "source", ".", "startswith", "(", "'http'", ")", ":", "json_licenses", "=", "requests", ".", "get", "(", "source", ")", ".", "json", "(", ")", "else", ":", "with", "open", "(", "source", ")", "as", "fp", ":", "json_licenses", "=", "json", ".", "load", "(", "fp", ")", "if", "len", "(", "json_licenses", ")", ":", "log", ".", "info", "(", "'Dropping existing licenses'", ")", "License", ".", "drop_collection", "(", ")", "for", "json_license", "in", "json_licenses", ":", "flags", "=", "[", "]", "for", "field", ",", "flag", "in", "FLAGS_MAP", ".", "items", "(", ")", ":", "if", "json_license", ".", "get", "(", "field", ",", "False", ")", ":", "flags", ".", "append", "(", "flag", ")", "license", "=", "License", ".", "objects", ".", "create", "(", "id", "=", "json_license", "[", "'id'", "]", ",", "title", "=", "json_license", "[", "'title'", "]", ",", "url", "=", "json_license", "[", "'url'", "]", "or", "None", ",", "maintainer", "=", "json_license", "[", "'maintainer'", "]", "or", "None", ",", "flags", "=", "flags", ",", "active", "=", "json_license", ".", "get", "(", "'active'", ",", "False", ")", ",", "alternate_urls", "=", "json_license", ".", "get", "(", "'alternate_urls'", ",", "[", "]", ")", ",", "alternate_titles", "=", "json_license", ".", "get", "(", "'alternate_titles'", ",", "[", "]", ")", ",", ")", "log", ".", "info", "(", "'Added license \"%s\"'", ",", "license", ".", "title", ")", "try", ":", "License", ".", "objects", ".", "get", "(", "id", "=", "DEFAULT_LICENSE", "[", "'id'", "]", ")", "except", "License", ".", "DoesNotExist", ":", "License", ".", "objects", ".", "create", "(", "*", "*", "DEFAULT_LICENSE", ")", "log", ".", "info", "(", "'Added license \"%s\"'", ",", "DEFAULT_LICENSE", "[", "'title'", "]", ")", "success", "(", "'Done'", ")" ]
Feed the licenses from a JSON file
[ "Feed", "the", "licenses", "from", "a", "JSON", "file" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/commands.py#L30-L64
14,293
opendatateam/udata
udata/core/spatial/forms.py
ZonesField.fetch_objects
def fetch_objects(self, geoids): ''' Custom object retrieval. Zones are resolved from their identifier instead of the default bulk fetch by ID. ''' zones = [] no_match = [] for geoid in geoids: zone = GeoZone.objects.resolve(geoid) if zone: zones.append(zone) else: no_match.append(geoid) if no_match: msg = _('Unknown geoid(s): {identifiers}').format( identifiers=', '.join(str(id) for id in no_match)) raise validators.ValidationError(msg) return zones
python
def fetch_objects(self, geoids): ''' Custom object retrieval. Zones are resolved from their identifier instead of the default bulk fetch by ID. ''' zones = [] no_match = [] for geoid in geoids: zone = GeoZone.objects.resolve(geoid) if zone: zones.append(zone) else: no_match.append(geoid) if no_match: msg = _('Unknown geoid(s): {identifiers}').format( identifiers=', '.join(str(id) for id in no_match)) raise validators.ValidationError(msg) return zones
[ "def", "fetch_objects", "(", "self", ",", "geoids", ")", ":", "zones", "=", "[", "]", "no_match", "=", "[", "]", "for", "geoid", "in", "geoids", ":", "zone", "=", "GeoZone", ".", "objects", ".", "resolve", "(", "geoid", ")", "if", "zone", ":", "zones", ".", "append", "(", "zone", ")", "else", ":", "no_match", ".", "append", "(", "geoid", ")", "if", "no_match", ":", "msg", "=", "_", "(", "'Unknown geoid(s): {identifiers}'", ")", ".", "format", "(", "identifiers", "=", "', '", ".", "join", "(", "str", "(", "id", ")", "for", "id", "in", "no_match", ")", ")", "raise", "validators", ".", "ValidationError", "(", "msg", ")", "return", "zones" ]
Custom object retrieval. Zones are resolved from their identifier instead of the default bulk fetch by ID.
[ "Custom", "object", "retrieval", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/forms.py#L34-L55
14,294
opendatateam/udata
tasks_helpers.py
lrun
def lrun(command, *args, **kwargs): '''Run a local command from project root''' return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs)
python
def lrun(command, *args, **kwargs): '''Run a local command from project root''' return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs)
[ "def", "lrun", "(", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "run", "(", "'cd {0} && {1}'", ".", "format", "(", "ROOT", ",", "command", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Run a local command from project root
[ "Run", "a", "local", "command", "from", "project", "root" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks_helpers.py#L37-L39
14,295
opendatateam/udata
udata/harvest/backends/dcat.py
DcatBackend.initialize
def initialize(self): '''List all datasets for a given ...''' fmt = guess_format(self.source.url) # if format can't be guessed from the url # we fallback on the declared Content-Type if not fmt: response = requests.head(self.source.url) mime_type = response.headers.get('Content-Type', '').split(';', 1)[0] if not mime_type: msg = 'Unable to detect format from extension or mime type' raise ValueError(msg) fmt = guess_format(mime_type) if not fmt: msg = 'Unsupported mime type "{0}"'.format(mime_type) raise ValueError(msg) graph = self.parse_graph(self.source.url, fmt) self.job.data = {'graph': graph.serialize(format='json-ld', indent=None)}
python
def initialize(self): '''List all datasets for a given ...''' fmt = guess_format(self.source.url) # if format can't be guessed from the url # we fallback on the declared Content-Type if not fmt: response = requests.head(self.source.url) mime_type = response.headers.get('Content-Type', '').split(';', 1)[0] if not mime_type: msg = 'Unable to detect format from extension or mime type' raise ValueError(msg) fmt = guess_format(mime_type) if not fmt: msg = 'Unsupported mime type "{0}"'.format(mime_type) raise ValueError(msg) graph = self.parse_graph(self.source.url, fmt) self.job.data = {'graph': graph.serialize(format='json-ld', indent=None)}
[ "def", "initialize", "(", "self", ")", ":", "fmt", "=", "guess_format", "(", "self", ".", "source", ".", "url", ")", "# if format can't be guessed from the url", "# we fallback on the declared Content-Type", "if", "not", "fmt", ":", "response", "=", "requests", ".", "head", "(", "self", ".", "source", ".", "url", ")", "mime_type", "=", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "''", ")", ".", "split", "(", "';'", ",", "1", ")", "[", "0", "]", "if", "not", "mime_type", ":", "msg", "=", "'Unable to detect format from extension or mime type'", "raise", "ValueError", "(", "msg", ")", "fmt", "=", "guess_format", "(", "mime_type", ")", "if", "not", "fmt", ":", "msg", "=", "'Unsupported mime type \"{0}\"'", ".", "format", "(", "mime_type", ")", "raise", "ValueError", "(", "msg", ")", "graph", "=", "self", ".", "parse_graph", "(", "self", ".", "source", ".", "url", ",", "fmt", ")", "self", ".", "job", ".", "data", "=", "{", "'graph'", ":", "graph", ".", "serialize", "(", "format", "=", "'json-ld'", ",", "indent", "=", "None", ")", "}" ]
List all datasets for a given ...
[ "List", "all", "datasets", "for", "a", "given", "..." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/dcat.py#L51-L67
14,296
opendatateam/udata
udata/commands/worker.py
get_tasks
def get_tasks(): '''Get a list of known tasks with their routing queue''' return { name: get_task_queue(name, cls) for name, cls in celery.tasks.items() # Exclude celery internal tasks if not name.startswith('celery.') # Exclude udata test tasks and not name.startswith('test-') }
python
def get_tasks(): '''Get a list of known tasks with their routing queue''' return { name: get_task_queue(name, cls) for name, cls in celery.tasks.items() # Exclude celery internal tasks if not name.startswith('celery.') # Exclude udata test tasks and not name.startswith('test-') }
[ "def", "get_tasks", "(", ")", ":", "return", "{", "name", ":", "get_task_queue", "(", "name", ",", "cls", ")", "for", "name", ",", "cls", "in", "celery", ".", "tasks", ".", "items", "(", ")", "# Exclude celery internal tasks", "if", "not", "name", ".", "startswith", "(", "'celery.'", ")", "# Exclude udata test tasks", "and", "not", "name", ".", "startswith", "(", "'test-'", ")", "}" ]
Get a list of known tasks with their routing queue
[ "Get", "a", "list", "of", "known", "tasks", "with", "their", "routing", "queue" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/worker.py#L97-L106
14,297
opendatateam/udata
udata/commands/worker.py
tasks
def tasks(): '''Display registered tasks with their queue''' tasks = get_tasks() longest = max(tasks.keys(), key=len) size = len(longest) for name, queue in sorted(tasks.items()): print('* {0}: {1}'.format(name.ljust(size), queue))
python
def tasks(): '''Display registered tasks with their queue''' tasks = get_tasks() longest = max(tasks.keys(), key=len) size = len(longest) for name, queue in sorted(tasks.items()): print('* {0}: {1}'.format(name.ljust(size), queue))
[ "def", "tasks", "(", ")", ":", "tasks", "=", "get_tasks", "(", ")", "longest", "=", "max", "(", "tasks", ".", "keys", "(", ")", ",", "key", "=", "len", ")", "size", "=", "len", "(", "longest", ")", "for", "name", ",", "queue", "in", "sorted", "(", "tasks", ".", "items", "(", ")", ")", ":", "print", "(", "'* {0}: {1}'", ".", "format", "(", "name", ".", "ljust", "(", "size", ")", ",", "queue", ")", ")" ]
Display registered tasks with their queue
[ "Display", "registered", "tasks", "with", "their", "queue" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/worker.py#L110-L116
14,298
opendatateam/udata
udata/commands/worker.py
status
def status(queue, munin, munin_config): """List queued tasks aggregated by name""" if munin_config: return status_print_config(queue) queues = get_queues(queue) for queue in queues: status_print_queue(queue, munin=munin) if not munin: print('-' * 40)
python
def status(queue, munin, munin_config): """List queued tasks aggregated by name""" if munin_config: return status_print_config(queue) queues = get_queues(queue) for queue in queues: status_print_queue(queue, munin=munin) if not munin: print('-' * 40)
[ "def", "status", "(", "queue", ",", "munin", ",", "munin_config", ")", ":", "if", "munin_config", ":", "return", "status_print_config", "(", "queue", ")", "queues", "=", "get_queues", "(", "queue", ")", "for", "queue", "in", "queues", ":", "status_print_queue", "(", "queue", ",", "munin", "=", "munin", ")", "if", "not", "munin", ":", "print", "(", "'-'", "*", "40", ")" ]
List queued tasks aggregated by name
[ "List", "queued", "tasks", "aggregated", "by", "name" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/worker.py#L125-L133
14,299
opendatateam/udata
udata/forms/fields.py
FieldHelper.pre_validate
def pre_validate(self, form): '''Calls preprocessors before pre_validation''' for preprocessor in self._preprocessors: preprocessor(form, self) super(FieldHelper, self).pre_validate(form)
python
def pre_validate(self, form): '''Calls preprocessors before pre_validation''' for preprocessor in self._preprocessors: preprocessor(form, self) super(FieldHelper, self).pre_validate(form)
[ "def", "pre_validate", "(", "self", ",", "form", ")", ":", "for", "preprocessor", "in", "self", ".", "_preprocessors", ":", "preprocessor", "(", "form", ",", "self", ")", "super", "(", "FieldHelper", ",", "self", ")", ".", "pre_validate", "(", "form", ")" ]
Calls preprocessors before pre_validation
[ "Calls", "preprocessors", "before", "pre_validation" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/forms/fields.py#L55-L59