repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
zarr-developers/zarr
zarr/hierarchy.py
Group.move
def move(self, source, dest): """Move contents from one path to another relative to the Group. Parameters ---------- source : string Name or path to a Zarr object to move. dest : string New name or path of the Zarr object. """ source = se...
python
def move(self, source, dest): """Move contents from one path to another relative to the Group. Parameters ---------- source : string Name or path to a Zarr object to move. dest : string New name or path of the Zarr object. """ source = se...
[ "def", "move", "(", "self", ",", "source", ",", "dest", ")", ":", "source", "=", "self", ".", "_item_path", "(", "source", ")", "dest", "=", "self", ".", "_item_path", "(", "dest", ")", "# Check that source exists.", "if", "not", "(", "contains_array", "...
Move contents from one path to another relative to the Group. Parameters ---------- source : string Name or path to a Zarr object to move. dest : string New name or path of the Zarr object.
[ "Move", "contents", "from", "one", "path", "to", "another", "relative", "to", "the", "Group", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L970-L995
train
zarr-developers/zarr
zarr/attrs.py
Attributes.asdict
def asdict(self): """Retrieve all attributes as a dictionary.""" if self.cache and self._cached_asdict is not None: return self._cached_asdict d = self._get_nosync() if self.cache: self._cached_asdict = d return d
python
def asdict(self): """Retrieve all attributes as a dictionary.""" if self.cache and self._cached_asdict is not None: return self._cached_asdict d = self._get_nosync() if self.cache: self._cached_asdict = d return d
[ "def", "asdict", "(", "self", ")", ":", "if", "self", ".", "cache", "and", "self", ".", "_cached_asdict", "is", "not", "None", ":", "return", "self", ".", "_cached_asdict", "d", "=", "self", ".", "_get_nosync", "(", ")", "if", "self", ".", "cache", "...
Retrieve all attributes as a dictionary.
[ "Retrieve", "all", "attributes", "as", "a", "dictionary", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/attrs.py#L49-L56
train
zarr-developers/zarr
zarr/attrs.py
Attributes.update
def update(self, *args, **kwargs): """Update the values of several attributes in a single operation.""" self._write_op(self._update_nosync, *args, **kwargs)
python
def update(self, *args, **kwargs): """Update the values of several attributes in a single operation.""" self._write_op(self._update_nosync, *args, **kwargs)
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_write_op", "(", "self", ".", "_update_nosync", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Update the values of several attributes in a single operation.
[ "Update", "the", "values", "of", "several", "attributes", "in", "a", "single", "operation", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/attrs.py#L121-L123
train
zarr-developers/zarr
zarr/util.py
json_dumps
def json_dumps(o): """Write JSON in a consistent, human-readable way.""" return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True, separators=(',', ': ')).encode('ascii')
python
def json_dumps(o): """Write JSON in a consistent, human-readable way.""" return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True, separators=(',', ': ')).encode('ascii')
[ "def", "json_dumps", "(", "o", ")", ":", "return", "json", ".", "dumps", "(", "o", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ",", "ensure_ascii", "=", "True", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", ".", "encode", ...
Write JSON in a consistent, human-readable way.
[ "Write", "JSON", "in", "a", "consistent", "human", "-", "readable", "way", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L36-L39
train
zarr-developers/zarr
zarr/util.py
normalize_shape
def normalize_shape(shape): """Convenience function to normalize the `shape` argument.""" if shape is None: raise TypeError('shape is None') # handle 1D convenience form if isinstance(shape, numbers.Integral): shape = (int(shape),) # normalize shape = tuple(int(s) for s in sha...
python
def normalize_shape(shape): """Convenience function to normalize the `shape` argument.""" if shape is None: raise TypeError('shape is None') # handle 1D convenience form if isinstance(shape, numbers.Integral): shape = (int(shape),) # normalize shape = tuple(int(s) for s in sha...
[ "def", "normalize_shape", "(", "shape", ")", ":", "if", "shape", "is", "None", ":", "raise", "TypeError", "(", "'shape is None'", ")", "# handle 1D convenience form", "if", "isinstance", "(", "shape", ",", "numbers", ".", "Integral", ")", ":", "shape", "=", ...
Convenience function to normalize the `shape` argument.
[ "Convenience", "function", "to", "normalize", "the", "shape", "argument", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L47-L59
train
zarr-developers/zarr
zarr/util.py
guess_chunks
def guess_chunks(shape, typesize): """ Guess an appropriate chunk layout for a dataset, given its shape and the size of each element in bytes. Will allocate chunks only as large as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of each axis, slightly favoring bigger values for th...
python
def guess_chunks(shape, typesize): """ Guess an appropriate chunk layout for a dataset, given its shape and the size of each element in bytes. Will allocate chunks only as large as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of each axis, slightly favoring bigger values for th...
[ "def", "guess_chunks", "(", "shape", ",", "typesize", ")", ":", "ndims", "=", "len", "(", "shape", ")", "# require chunks to have non-zero length for all dimensions", "chunks", "=", "np", ".", "maximum", "(", "np", ".", "array", "(", "shape", ",", "dtype", "="...
Guess an appropriate chunk layout for a dataset, given its shape and the size of each element in bytes. Will allocate chunks only as large as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of each axis, slightly favoring bigger values for the last index. Undocumented and subject to c...
[ "Guess", "an", "appropriate", "chunk", "layout", "for", "a", "dataset", "given", "its", "shape", "and", "the", "size", "of", "each", "element", "in", "bytes", ".", "Will", "allocate", "chunks", "only", "as", "large", "as", "MAX_SIZE", ".", "Chunks", "are",...
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L69-L112
train
zarr-developers/zarr
zarr/util.py
normalize_chunks
def normalize_chunks(chunks, shape, typesize): """Convenience function to normalize the `chunks` argument for an array with the given `shape`.""" # N.B., expect shape already normalized # handle auto-chunking if chunks is None or chunks is True: return guess_chunks(shape, typesize) # ...
python
def normalize_chunks(chunks, shape, typesize): """Convenience function to normalize the `chunks` argument for an array with the given `shape`.""" # N.B., expect shape already normalized # handle auto-chunking if chunks is None or chunks is True: return guess_chunks(shape, typesize) # ...
[ "def", "normalize_chunks", "(", "chunks", ",", "shape", ",", "typesize", ")", ":", "# N.B., expect shape already normalized", "# handle auto-chunking", "if", "chunks", "is", "None", "or", "chunks", "is", "True", ":", "return", "guess_chunks", "(", "shape", ",", "t...
Convenience function to normalize the `chunks` argument for an array with the given `shape`.
[ "Convenience", "function", "to", "normalize", "the", "chunks", "argument", "for", "an", "array", "with", "the", "given", "shape", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/util.py#L115-L146
train
zarr-developers/zarr
zarr/storage.py
contains_array
def contains_array(store, path=None): """Return True if the store contains an array at the given logical path.""" path = normalize_storage_path(path) prefix = _path_to_prefix(path) key = prefix + array_meta_key return key in store
python
def contains_array(store, path=None): """Return True if the store contains an array at the given logical path.""" path = normalize_storage_path(path) prefix = _path_to_prefix(path) key = prefix + array_meta_key return key in store
[ "def", "contains_array", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "prefix", "=", "_path_to_prefix", "(", "path", ")", "key", "=", "prefix", "+", "array_meta_key", "return", "key", "in", "sto...
Return True if the store contains an array at the given logical path.
[ "Return", "True", "if", "the", "store", "contains", "an", "array", "at", "the", "given", "logical", "path", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L77-L82
train
zarr-developers/zarr
zarr/storage.py
contains_group
def contains_group(store, path=None): """Return True if the store contains a group at the given logical path.""" path = normalize_storage_path(path) prefix = _path_to_prefix(path) key = prefix + group_meta_key return key in store
python
def contains_group(store, path=None): """Return True if the store contains a group at the given logical path.""" path = normalize_storage_path(path) prefix = _path_to_prefix(path) key = prefix + group_meta_key return key in store
[ "def", "contains_group", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "prefix", "=", "_path_to_prefix", "(", "path", ")", "key", "=", "prefix", "+", "group_meta_key", "return", "key", "in", "sto...
Return True if the store contains a group at the given logical path.
[ "Return", "True", "if", "the", "store", "contains", "a", "group", "at", "the", "given", "logical", "path", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L85-L90
train
zarr-developers/zarr
zarr/storage.py
rmdir
def rmdir(store, path=None): """Remove all items under the given path. If `store` provides a `rmdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" path = normalize_storage_path(path) if hasattr(store, 'rmdir'): # pass through ...
python
def rmdir(store, path=None): """Remove all items under the given path. If `store` provides a `rmdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" path = normalize_storage_path(path) if hasattr(store, 'rmdir'): # pass through ...
[ "def", "rmdir", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "if", "hasattr", "(", "store", ",", "'rmdir'", ")", ":", "# pass through", "store", ".", "rmdir", "(", "path", ")", "else", ":", ...
Remove all items under the given path. If `store` provides a `rmdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.
[ "Remove", "all", "items", "under", "the", "given", "path", ".", "If", "store", "provides", "a", "rmdir", "method", "this", "will", "be", "called", "otherwise", "will", "fall", "back", "to", "implementation", "via", "the", "MutableMapping", "interface", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L101-L111
train
zarr-developers/zarr
zarr/storage.py
rename
def rename(store, src_path, dst_path): """Rename all items under the given path. If `store` provides a `rename` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" src_path = normalize_storage_path(src_path) dst_path = normalize_storage_path...
python
def rename(store, src_path, dst_path): """Rename all items under the given path. If `store` provides a `rename` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" src_path = normalize_storage_path(src_path) dst_path = normalize_storage_path...
[ "def", "rename", "(", "store", ",", "src_path", ",", "dst_path", ")", ":", "src_path", "=", "normalize_storage_path", "(", "src_path", ")", "dst_path", "=", "normalize_storage_path", "(", "dst_path", ")", "if", "hasattr", "(", "store", ",", "'rename'", ")", ...
Rename all items under the given path. If `store` provides a `rename` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.
[ "Rename", "all", "items", "under", "the", "given", "path", ".", "If", "store", "provides", "a", "rename", "method", "this", "will", "be", "called", "otherwise", "will", "fall", "back", "to", "implementation", "via", "the", "MutableMapping", "interface", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L124-L135
train
zarr-developers/zarr
zarr/storage.py
listdir
def listdir(store, path=None): """Obtain a directory listing for the given path. If `store` provides a `listdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" path = normalize_storage_path(path) if hasattr(store, 'listdir'): # ...
python
def listdir(store, path=None): """Obtain a directory listing for the given path. If `store` provides a `listdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" path = normalize_storage_path(path) if hasattr(store, 'listdir'): # ...
[ "def", "listdir", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "if", "hasattr", "(", "store", ",", "'listdir'", ")", ":", "# pass through", "return", "store", ".", "listdir", "(", "path", ")",...
Obtain a directory listing for the given path. If `store` provides a `listdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.
[ "Obtain", "a", "directory", "listing", "for", "the", "given", "path", ".", "If", "store", "provides", "a", "listdir", "method", "this", "will", "be", "called", "otherwise", "will", "fall", "back", "to", "implementation", "via", "the", "MutableMapping", "interf...
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L150-L160
train
zarr-developers/zarr
zarr/storage.py
getsize
def getsize(store, path=None): """Compute size of stored items for a given path. If `store` provides a `getsize` method, this will be called, otherwise will return -1.""" path = normalize_storage_path(path) if hasattr(store, 'getsize'): # pass through return store.getsize(path) elif ...
python
def getsize(store, path=None): """Compute size of stored items for a given path. If `store` provides a `getsize` method, this will be called, otherwise will return -1.""" path = normalize_storage_path(path) if hasattr(store, 'getsize'): # pass through return store.getsize(path) elif ...
[ "def", "getsize", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "if", "hasattr", "(", "store", ",", "'getsize'", ")", ":", "# pass through", "return", "store", ".", "getsize", "(", "path", ")",...
Compute size of stored items for a given path. If `store` provides a `getsize` method, this will be called, otherwise will return -1.
[ "Compute", "size", "of", "stored", "items", "for", "a", "given", "path", ".", "If", "store", "provides", "a", "getsize", "method", "this", "will", "be", "called", "otherwise", "will", "return", "-", "1", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L163-L191
train
zarr-developers/zarr
zarr/storage.py
init_array
def init_array(store, shape, chunks=True, dtype=None, compressor='default', fill_value=None, order='C', overwrite=False, path=None, chunk_store=None, filters=None, object_codec=None): """Initialize an array store with the given configuration. Note that this is a low-level function ...
python
def init_array(store, shape, chunks=True, dtype=None, compressor='default', fill_value=None, order='C', overwrite=False, path=None, chunk_store=None, filters=None, object_codec=None): """Initialize an array store with the given configuration. Note that this is a low-level function ...
[ "def", "init_array", "(", "store", ",", "shape", ",", "chunks", "=", "True", ",", "dtype", "=", "None", ",", "compressor", "=", "'default'", ",", "fill_value", "=", "None", ",", "order", "=", "'C'", ",", "overwrite", "=", "False", ",", "path", "=", "...
Initialize an array store with the given configuration. Note that this is a low-level function and there should be no need to call this directly from user code. Parameters ---------- store : MutableMapping A mapping that supports string keys and bytes-like values. shape : int or tuple of in...
[ "Initialize", "an", "array", "store", "with", "the", "given", "configuration", ".", "Note", "that", "this", "is", "a", "low", "-", "level", "function", "and", "there", "should", "be", "no", "need", "to", "call", "this", "directly", "from", "user", "code", ...
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L207-L323
train
zarr-developers/zarr
zarr/storage.py
init_group
def init_group(store, overwrite=False, path=None, chunk_store=None): """Initialize a group store. Note that this is a low-level function and there should be no need to call this directly from user code. Parameters ---------- store : MutableMapping A mapping that supports string keys and byt...
python
def init_group(store, overwrite=False, path=None, chunk_store=None): """Initialize a group store. Note that this is a low-level function and there should be no need to call this directly from user code. Parameters ---------- store : MutableMapping A mapping that supports string keys and byt...
[ "def", "init_group", "(", "store", ",", "overwrite", "=", "False", ",", "path", "=", "None", ",", "chunk_store", "=", "None", ")", ":", "# normalize path", "path", "=", "normalize_storage_path", "(", "path", ")", "# ensure parent group initialized", "_require_pare...
Initialize a group store. Note that this is a low-level function and there should be no need to call this directly from user code. Parameters ---------- store : MutableMapping A mapping that supports string keys and byte sequence values. overwrite : bool, optional If True, erase all...
[ "Initialize", "a", "group", "store", ".", "Note", "that", "this", "is", "a", "low", "-", "level", "function", "and", "there", "should", "be", "no", "need", "to", "call", "this", "directly", "from", "user", "code", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L405-L432
train
zarr-developers/zarr
zarr/storage.py
atexit_rmtree
def atexit_rmtree(path, isdir=os.path.isdir, rmtree=shutil.rmtree): # pragma: no cover """Ensure directory removal at interpreter exit.""" if isdir(path): rmtree(path)
python
def atexit_rmtree(path, isdir=os.path.isdir, rmtree=shutil.rmtree): # pragma: no cover """Ensure directory removal at interpreter exit.""" if isdir(path): rmtree(path)
[ "def", "atexit_rmtree", "(", "path", ",", "isdir", "=", "os", ".", "path", ".", "isdir", ",", "rmtree", "=", "shutil", ".", "rmtree", ")", ":", "# pragma: no cover", "if", "isdir", "(", "path", ")", ":", "rmtree", "(", "path", ")" ]
Ensure directory removal at interpreter exit.
[ "Ensure", "directory", "removal", "at", "interpreter", "exit", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L863-L868
train
zarr-developers/zarr
zarr/storage.py
atexit_rmglob
def atexit_rmglob(path, glob=glob.glob, isdir=os.path.isdir, isfile=os.path.isfile, remove=os.remove, rmtree=shutil.rmtree): # pragma: no cover """Ensure removal of multiple files at interpreter exit.""" for p in glob(pat...
python
def atexit_rmglob(path, glob=glob.glob, isdir=os.path.isdir, isfile=os.path.isfile, remove=os.remove, rmtree=shutil.rmtree): # pragma: no cover """Ensure removal of multiple files at interpreter exit.""" for p in glob(pat...
[ "def", "atexit_rmglob", "(", "path", ",", "glob", "=", "glob", ".", "glob", ",", "isdir", "=", "os", ".", "path", ".", "isdir", ",", "isfile", "=", "os", ".", "path", ".", "isfile", ",", "remove", "=", "os", ".", "remove", ",", "rmtree", "=", "sh...
Ensure removal of multiple files at interpreter exit.
[ "Ensure", "removal", "of", "multiple", "files", "at", "interpreter", "exit", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L872-L883
train
zarr-developers/zarr
zarr/storage.py
migrate_1to2
def migrate_1to2(store): """Migrate array metadata in `store` from Zarr format version 1 to version 2. Parameters ---------- store : MutableMapping Store to be migrated. Notes ----- Version 1 did not support hierarchies, so this migration function will look for a single arr...
python
def migrate_1to2(store): """Migrate array metadata in `store` from Zarr format version 1 to version 2. Parameters ---------- store : MutableMapping Store to be migrated. Notes ----- Version 1 did not support hierarchies, so this migration function will look for a single arr...
[ "def", "migrate_1to2", "(", "store", ")", ":", "# migrate metadata", "from", "zarr", "import", "meta_v1", "meta", "=", "meta_v1", ".", "decode_metadata", "(", "store", "[", "'meta'", "]", ")", "del", "store", "[", "'meta'", "]", "# add empty filters", "meta", ...
Migrate array metadata in `store` from Zarr format version 1 to version 2. Parameters ---------- store : MutableMapping Store to be migrated. Notes ----- Version 1 did not support hierarchies, so this migration function will look for a single array in `store` and migrate the ar...
[ "Migrate", "array", "metadata", "in", "store", "from", "Zarr", "format", "version", "1", "to", "version", "2", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1260-L1306
train
zarr-developers/zarr
zarr/storage.py
ZipStore.flush
def flush(self): """Closes the underlying zip file, ensuring all records are written, then re-opens the file for further modifications.""" if self.mode != 'r': with self.mutex: self.zf.close() # N.B., re-open with mode 'a' regardless of initial mode so...
python
def flush(self): """Closes the underlying zip file, ensuring all records are written, then re-opens the file for further modifications.""" if self.mode != 'r': with self.mutex: self.zf.close() # N.B., re-open with mode 'a' regardless of initial mode so...
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "mode", "!=", "'r'", ":", "with", "self", ".", "mutex", ":", "self", ".", "zf", ".", "close", "(", ")", "# N.B., re-open with mode 'a' regardless of initial mode so we don't wipe", "# what's been written", ...
Closes the underlying zip file, ensuring all records are written, then re-opens the file for further modifications.
[ "Closes", "the", "underlying", "zip", "file", "ensuring", "all", "records", "are", "written", "then", "re", "-", "opens", "the", "file", "for", "further", "modifications", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1154-L1164
train
zarr-developers/zarr
zarr/storage.py
DBMStore.close
def close(self): """Closes the underlying database file.""" if hasattr(self.db, 'close'): with self.write_mutex: self.db.close()
python
def close(self): """Closes the underlying database file.""" if hasattr(self.db, 'close'): with self.write_mutex: self.db.close()
[ "def", "close", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "db", ",", "'close'", ")", ":", "with", "self", ".", "write_mutex", ":", "self", ".", "db", ".", "close", "(", ")" ]
Closes the underlying database file.
[ "Closes", "the", "underlying", "database", "file", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1442-L1446
train
zarr-developers/zarr
zarr/storage.py
DBMStore.flush
def flush(self): """Synchronizes data to the underlying database file.""" if self.flag[0] != 'r': with self.write_mutex: if hasattr(self.db, 'sync'): self.db.sync() else: # fall-back, close and re-open, needed for ndbm ...
python
def flush(self): """Synchronizes data to the underlying database file.""" if self.flag[0] != 'r': with self.write_mutex: if hasattr(self.db, 'sync'): self.db.sync() else: # fall-back, close and re-open, needed for ndbm ...
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "flag", "[", "0", "]", "!=", "'r'", ":", "with", "self", ".", "write_mutex", ":", "if", "hasattr", "(", "self", ".", "db", ",", "'sync'", ")", ":", "self", ".", "db", ".", "sync", "(", ...
Synchronizes data to the underlying database file.
[ "Synchronizes", "data", "to", "the", "underlying", "database", "file", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/storage.py#L1448-L1461
train
zarr-developers/zarr
zarr/indexing.py
oindex
def oindex(a, selection): """Implementation of orthogonal indexing with slices and ints.""" selection = replace_ellipsis(selection, a.shape) drop_axes = tuple([i for i, s in enumerate(selection) if is_integer(s)]) selection = ix_(selection, a.shape) result = a[selection] if drop_axes: re...
python
def oindex(a, selection): """Implementation of orthogonal indexing with slices and ints.""" selection = replace_ellipsis(selection, a.shape) drop_axes = tuple([i for i, s in enumerate(selection) if is_integer(s)]) selection = ix_(selection, a.shape) result = a[selection] if drop_axes: re...
[ "def", "oindex", "(", "a", ",", "selection", ")", ":", "selection", "=", "replace_ellipsis", "(", "selection", ",", "a", ".", "shape", ")", "drop_axes", "=", "tuple", "(", "[", "i", "for", "i", ",", "s", "in", "enumerate", "(", "selection", ")", "if"...
Implementation of orthogonal indexing with slices and ints.
[ "Implementation", "of", "orthogonal", "indexing", "with", "slices", "and", "ints", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/indexing.py#L496-L504
train
zarr-developers/zarr
zarr/n5.py
array_metadata_to_n5
def array_metadata_to_n5(array_metadata): '''Convert array metadata from zarr to N5 format.''' for f, t in zarr_to_n5_keys: array_metadata[t] = array_metadata[f] del array_metadata[f] del array_metadata['zarr_format'] try: dtype = np.dtype(array_metadata['dataType']) except...
python
def array_metadata_to_n5(array_metadata): '''Convert array metadata from zarr to N5 format.''' for f, t in zarr_to_n5_keys: array_metadata[t] = array_metadata[f] del array_metadata[f] del array_metadata['zarr_format'] try: dtype = np.dtype(array_metadata['dataType']) except...
[ "def", "array_metadata_to_n5", "(", "array_metadata", ")", ":", "for", "f", ",", "t", "in", "zarr_to_n5_keys", ":", "array_metadata", "[", "t", "]", "=", "array_metadata", "[", "f", "]", "del", "array_metadata", "[", "f", "]", "del", "array_metadata", "[", ...
Convert array metadata from zarr to N5 format.
[ "Convert", "array", "metadata", "from", "zarr", "to", "N5", "format", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/n5.py#L316-L354
train
zarr-developers/zarr
zarr/n5.py
array_metadata_to_zarr
def array_metadata_to_zarr(array_metadata): '''Convert array metadata from N5 to zarr format.''' for t, f in zarr_to_n5_keys: array_metadata[t] = array_metadata[f] del array_metadata[f] array_metadata['zarr_format'] = ZARR_FORMAT array_metadata['shape'] = array_metadata['shape'][::-1] ...
python
def array_metadata_to_zarr(array_metadata): '''Convert array metadata from N5 to zarr format.''' for t, f in zarr_to_n5_keys: array_metadata[t] = array_metadata[f] del array_metadata[f] array_metadata['zarr_format'] = ZARR_FORMAT array_metadata['shape'] = array_metadata['shape'][::-1] ...
[ "def", "array_metadata_to_zarr", "(", "array_metadata", ")", ":", "for", "t", ",", "f", "in", "zarr_to_n5_keys", ":", "array_metadata", "[", "t", "]", "=", "array_metadata", "[", "f", "]", "del", "array_metadata", "[", "f", "]", "array_metadata", "[", "'zarr...
Convert array metadata from N5 to zarr format.
[ "Convert", "array", "metadata", "from", "N5", "to", "zarr", "format", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/n5.py#L357-L379
train
zarr-developers/zarr
zarr/core.py
Array.name
def name(self): """Array name following h5py convention.""" if self.path: # follow h5py convention: add leading slash name = self.path if name[0] != '/': name = '/' + name return name return None
python
def name(self): """Array name following h5py convention.""" if self.path: # follow h5py convention: add leading slash name = self.path if name[0] != '/': name = '/' + name return name return None
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "path", ":", "# follow h5py convention: add leading slash", "name", "=", "self", ".", "path", "if", "name", "[", "0", "]", "!=", "'/'", ":", "name", "=", "'/'", "+", "name", "return", "name", "re...
Array name following h5py convention.
[ "Array", "name", "following", "h5py", "convention", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L214-L222
train
zarr-developers/zarr
zarr/core.py
Array.nbytes_stored
def nbytes_stored(self): """The total number of stored bytes of data for the array. This includes storage required for configuration metadata and user attributes.""" m = getsize(self._store, self._path) if self._chunk_store is None: return m else: ...
python
def nbytes_stored(self): """The total number of stored bytes of data for the array. This includes storage required for configuration metadata and user attributes.""" m = getsize(self._store, self._path) if self._chunk_store is None: return m else: ...
[ "def", "nbytes_stored", "(", "self", ")", ":", "m", "=", "getsize", "(", "self", ".", "_store", ",", "self", ".", "_path", ")", "if", "self", ".", "_chunk_store", "is", "None", ":", "return", "m", "else", ":", "n", "=", "getsize", "(", "self", ".",...
The total number of stored bytes of data for the array. This includes storage required for configuration metadata and user attributes.
[ "The", "total", "number", "of", "stored", "bytes", "of", "data", "for", "the", "array", ".", "This", "includes", "storage", "required", "for", "configuration", "metadata", "and", "user", "attributes", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L340-L352
train
zarr-developers/zarr
zarr/core.py
Array.nchunks_initialized
def nchunks_initialized(self): """The number of chunks that have been initialized with some data.""" # key pattern for chunk keys prog = re.compile(r'\.'.join([r'\d+'] * min(1, self.ndim))) # count chunk keys return sum(1 for k in listdir(self.chunk_store, self._path) if prog.m...
python
def nchunks_initialized(self): """The number of chunks that have been initialized with some data.""" # key pattern for chunk keys prog = re.compile(r'\.'.join([r'\d+'] * min(1, self.ndim))) # count chunk keys return sum(1 for k in listdir(self.chunk_store, self._path) if prog.m...
[ "def", "nchunks_initialized", "(", "self", ")", ":", "# key pattern for chunk keys", "prog", "=", "re", ".", "compile", "(", "r'\\.'", ".", "join", "(", "[", "r'\\d+'", "]", "*", "min", "(", "1", ",", "self", ".", "ndim", ")", ")", ")", "# count chunk ke...
The number of chunks that have been initialized with some data.
[ "The", "number", "of", "chunks", "that", "have", "been", "initialized", "with", "some", "data", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L380-L387
train
zarr-developers/zarr
zarr/core.py
Array.get_basic_selection
def get_basic_selection(self, selection=Ellipsis, out=None, fields=None): """Retrieve data for an item or region of the array. Parameters ---------- selection : tuple A tuple specifying the requested item or region for each dimension of the array. May be any comb...
python
def get_basic_selection(self, selection=Ellipsis, out=None, fields=None): """Retrieve data for an item or region of the array. Parameters ---------- selection : tuple A tuple specifying the requested item or region for each dimension of the array. May be any comb...
[ "def", "get_basic_selection", "(", "self", ",", "selection", "=", "Ellipsis", ",", "out", "=", "None", ",", "fields", "=", "None", ")", ":", "# refresh metadata", "if", "not", "self", ".", "_cache_metadata", ":", "self", ".", "_load_metadata", "(", ")", "#...
Retrieve data for an item or region of the array. Parameters ---------- selection : tuple A tuple specifying the requested item or region for each dimension of the array. May be any combination of int and/or slice for multidimensional arrays. out : ndarray, optio...
[ "Retrieve", "data", "for", "an", "item", "or", "region", "of", "the", "array", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L574-L698
train
zarr-developers/zarr
zarr/core.py
Array.get_mask_selection
def get_mask_selection(self, selection, out=None, fields=None): """Retrieve a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- ...
python
def get_mask_selection(self, selection, out=None, fields=None): """Retrieve a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- ...
[ "def", "get_mask_selection", "(", "self", ",", "selection", ",", "out", "=", "None", ",", "fields", "=", "None", ")", ":", "# refresh metadata", "if", "not", "self", ".", "_cache_metadata", ":", "self", ".", "_load_metadata", "(", ")", "# check args", "check...
Retrieve a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- selection : ndarray, bool A Boolean array of the same sh...
[ "Retrieve", "a", "selection", "of", "individual", "items", "by", "providing", "a", "Boolean", "array", "of", "the", "same", "shape", "as", "the", "array", "against", "which", "the", "selection", "is", "being", "made", "where", "True", "values", "indicate", "...
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L933-L1000
train
zarr-developers/zarr
zarr/core.py
Array.set_basic_selection
def set_basic_selection(self, selection, value, fields=None): """Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the arra...
python
def set_basic_selection(self, selection, value, fields=None): """Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the arra...
[ "def", "set_basic_selection", "(", "self", ",", "selection", ",", "value", ",", "fields", "=", "None", ")", ":", "# guard conditions", "if", "self", ".", "_read_only", ":", "err_read_only", "(", ")", "# refresh metadata", "if", "not", "self", ".", "_cache_meta...
Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the array. value : scalar or array-like Value to be stored in...
[ "Modify", "data", "for", "an", "item", "or", "region", "of", "the", "array", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1117-L1210
train
zarr-developers/zarr
zarr/core.py
Array.set_orthogonal_selection
def set_orthogonal_selection(self, selection, value, fields=None): """Modify data via a selection for each dimension of the array. Parameters ---------- selection : tuple A selection for each dimension of the array. May be any combination of int, slice, integer a...
python
def set_orthogonal_selection(self, selection, value, fields=None): """Modify data via a selection for each dimension of the array. Parameters ---------- selection : tuple A selection for each dimension of the array. May be any combination of int, slice, integer a...
[ "def", "set_orthogonal_selection", "(", "self", ",", "selection", ",", "value", ",", "fields", "=", "None", ")", ":", "# guard conditions", "if", "self", ".", "_read_only", ":", "err_read_only", "(", ")", "# refresh metadata", "if", "not", "self", ".", "_cache...
Modify data via a selection for each dimension of the array. Parameters ---------- selection : tuple A selection for each dimension of the array. May be any combination of int, slice, integer array or Boolean array. value : scalar or array-like Value ...
[ "Modify", "data", "via", "a", "selection", "for", "each", "dimension", "of", "the", "array", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1212-L1300
train
zarr-developers/zarr
zarr/core.py
Array.set_mask_selection
def set_mask_selection(self, selection, value, fields=None): """Modify a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- ...
python
def set_mask_selection(self, selection, value, fields=None): """Modify a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- ...
[ "def", "set_mask_selection", "(", "self", ",", "selection", ",", "value", ",", "fields", "=", "None", ")", ":", "# guard conditions", "if", "self", ".", "_read_only", ":", "err_read_only", "(", ")", "# refresh metadata", "if", "not", "self", ".", "_cache_metad...
Modify a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- selection : ndarray, bool A Boolean array of the same shap...
[ "Modify", "a", "selection", "of", "individual", "items", "by", "providing", "a", "Boolean", "array", "of", "the", "same", "shape", "as", "the", "array", "against", "which", "the", "selection", "is", "being", "made", "where", "True", "values", "indicate", "a"...
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1380-L1453
train
zarr-developers/zarr
zarr/core.py
Array._chunk_getitem
def _chunk_getitem(self, chunk_coords, chunk_selection, out, out_selection, drop_axes=None, fields=None): """Obtain part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : selection ...
python
def _chunk_getitem(self, chunk_coords, chunk_selection, out, out_selection, drop_axes=None, fields=None): """Obtain part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : selection ...
[ "def", "_chunk_getitem", "(", "self", ",", "chunk_coords", ",", "chunk_selection", ",", "out", ",", "out_selection", ",", "drop_axes", "=", "None", ",", "fields", "=", "None", ")", ":", "assert", "len", "(", "chunk_coords", ")", "==", "len", "(", "self", ...
Obtain part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : selection Location of region within the chunk to extract. out : ndarray Array to store result in. out_selection...
[ "Obtain", "part", "or", "whole", "of", "a", "chunk", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1552-L1633
train
zarr-developers/zarr
zarr/core.py
Array._chunk_setitem
def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None): """Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chun...
python
def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None): """Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chun...
[ "def", "_chunk_setitem", "(", "self", ",", "chunk_coords", ",", "chunk_selection", ",", "value", ",", "fields", "=", "None", ")", ":", "if", "self", ".", "_synchronizer", "is", "None", ":", "# no synchronization", "lock", "=", "nolock", "else", ":", "# synch...
Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chunk. value : scalar or ndarray Value to set.
[ "Replace", "part", "or", "whole", "of", "a", "chunk", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1635-L1659
train
zarr-developers/zarr
zarr/core.py
Array.append
def append(self, data, axis=0): """Append `data` to `axis`. Parameters ---------- data : array_like Data to be appended. axis : int Axis along which to append. Returns ------- new_shape : tuple Notes ----- ...
python
def append(self, data, axis=0): """Append `data` to `axis`. Parameters ---------- data : array_like Data to be appended. axis : int Axis along which to append. Returns ------- new_shape : tuple Notes ----- ...
[ "def", "append", "(", "self", ",", "data", ",", "axis", "=", "0", ")", ":", "return", "self", ".", "_write_op", "(", "self", ".", "_append_nosync", ",", "data", ",", "axis", "=", "axis", ")" ]
Append `data` to `axis`. Parameters ---------- data : array_like Data to be appended. axis : int Axis along which to append. Returns ------- new_shape : tuple Notes ----- The size of all dimensions other than `axi...
[ "Append", "data", "to", "axis", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2027-L2062
train
zarr-developers/zarr
zarr/core.py
Array.view
def view(self, shape=None, chunks=None, dtype=None, fill_value=None, filters=None, read_only=None, synchronizer=None): """Return an array sharing the same data. Parameters ---------- shape : int or tuple of ints Array shape. chunks : int or ...
python
def view(self, shape=None, chunks=None, dtype=None, fill_value=None, filters=None, read_only=None, synchronizer=None): """Return an array sharing the same data. Parameters ---------- shape : int or tuple of ints Array shape. chunks : int or ...
[ "def", "view", "(", "self", ",", "shape", "=", "None", ",", "chunks", "=", "None", ",", "dtype", "=", "None", ",", "fill_value", "=", "None", ",", "filters", "=", "None", ",", "read_only", "=", "None", ",", "synchronizer", "=", "None", ")", ":", "s...
Return an array sharing the same data. Parameters ---------- shape : int or tuple of ints Array shape. chunks : int or tuple of ints, optional Chunk shape. dtype : string or dtype, optional NumPy dtype. fill_value : object ...
[ "Return", "an", "array", "sharing", "the", "same", "data", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2102-L2242
train
zarr-developers/zarr
zarr/core.py
Array.astype
def astype(self, dtype): """Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same ...
python
def astype(self, dtype): """Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same ...
[ "def", "astype", "(", "self", ",", "dtype", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "filters", "=", "[", "]", "if", "self", ".", "_filters", ":", "filters", ".", "extend", "(", "self", ".", "_filters", ")", "filters", ".", ...
Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same underlying chunk data. Modifying any...
[ "Returns", "a", "view", "that", "does", "on", "the", "fly", "type", "conversion", "of", "the", "underlying", "data", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2244-L2302
train
zarr-developers/zarr
zarr/creation.py
full
def full(shape, fill_value, **kwargs): """Create an array, with `fill_value` being used as the default value for uninitialized portions of the array. For parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import zarr >>> z = zarr.full((10000, 10000), chunks=(1000...
python
def full(shape, fill_value, **kwargs): """Create an array, with `fill_value` being used as the default value for uninitialized portions of the array. For parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import zarr >>> z = zarr.full((10000, 10000), chunks=(1000...
[ "def", "full", "(", "shape", ",", "fill_value", ",", "*", "*", "kwargs", ")", ":", "return", "create", "(", "shape", "=", "shape", ",", "fill_value", "=", "fill_value", ",", "*", "*", "kwargs", ")" ]
Create an array, with `fill_value` being used as the default value for uninitialized portions of the array. For parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import zarr >>> z = zarr.full((10000, 10000), chunks=(1000, 1000), fill_value=42) >>> z <zarr.co...
[ "Create", "an", "array", "with", "fill_value", "being", "used", "as", "the", "default", "value", "for", "uninitialized", "portions", "of", "the", "array", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L259-L277
train
zarr-developers/zarr
zarr/creation.py
array
def array(data, **kwargs): """Create an array filled with `data`. The `data` argument should be a NumPy array or array-like object. For other parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import numpy as np >>> import zarr >>> a = np.arange(100000000).re...
python
def array(data, **kwargs): """Create an array filled with `data`. The `data` argument should be a NumPy array or array-like object. For other parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import numpy as np >>> import zarr >>> a = np.arange(100000000).re...
[ "def", "array", "(", "data", ",", "*", "*", "kwargs", ")", ":", "# ensure data is array-like", "if", "not", "hasattr", "(", "data", ",", "'shape'", ")", "or", "not", "hasattr", "(", "data", ",", "'dtype'", ")", ":", "data", "=", "np", ".", "asanyarray"...
Create an array filled with `data`. The `data` argument should be a NumPy array or array-like object. For other parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import numpy as np >>> import zarr >>> a = np.arange(100000000).reshape(10000, 10000) >>> z = za...
[ "Create", "an", "array", "filled", "with", "data", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L300-L349
train
zarr-developers/zarr
zarr/creation.py
open_array
def open_array(store=None, mode='a', shape=None, chunks=True, dtype=None, compressor='default', fill_value=0, order='C', synchronizer=None, filters=None, cache_metadata=True, cache_attrs=True, path=None, object_codec=None, chunk_store=None, **kwargs): """Open an array us...
python
def open_array(store=None, mode='a', shape=None, chunks=True, dtype=None, compressor='default', fill_value=0, order='C', synchronizer=None, filters=None, cache_metadata=True, cache_attrs=True, path=None, object_codec=None, chunk_store=None, **kwargs): """Open an array us...
[ "def", "open_array", "(", "store", "=", "None", ",", "mode", "=", "'a'", ",", "shape", "=", "None", ",", "chunks", "=", "True", ",", "dtype", "=", "None", ",", "compressor", "=", "'default'", ",", "fill_value", "=", "0", ",", "order", "=", "'C'", "...
Open an array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means ...
[ "Open", "an", "array", "using", "file", "-", "mode", "-", "like", "semantics", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L352-L489
train
zarr-developers/zarr
zarr/creation.py
full_like
def full_like(a, **kwargs): """Create a filled array like `a`.""" _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return full(**kwargs)
python
def full_like(a, **kwargs): """Create a filled array like `a`.""" _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return full(**kwargs)
[ "def", "full_like", "(", "a", ",", "*", "*", "kwargs", ")", ":", "_like_args", "(", "a", ",", "kwargs", ")", "if", "isinstance", "(", "a", ",", "Array", ")", ":", "kwargs", ".", "setdefault", "(", "'fill_value'", ",", "a", ".", "fill_value", ")", "...
Create a filled array like `a`.
[ "Create", "a", "filled", "array", "like", "a", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L530-L535
train
zarr-developers/zarr
zarr/creation.py
open_like
def open_like(a, path, **kwargs): """Open a persistent array like `a`.""" _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return open_array(path, **kwargs)
python
def open_like(a, path, **kwargs): """Open a persistent array like `a`.""" _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return open_array(path, **kwargs)
[ "def", "open_like", "(", "a", ",", "path", ",", "*", "*", "kwargs", ")", ":", "_like_args", "(", "a", ",", "kwargs", ")", "if", "isinstance", "(", "a", ",", "Array", ")", ":", "kwargs", ".", "setdefault", "(", "'fill_value'", ",", "a", ".", "fill_v...
Open a persistent array like `a`.
[ "Open", "a", "persistent", "array", "like", "a", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L538-L543
train
zarr-developers/zarr
zarr/convenience.py
open
def open(store=None, mode='a', **kwargs): """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, opti...
python
def open(store=None, mode='a', **kwargs): """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, opti...
[ "def", "open", "(", "store", "=", "None", ",", "mode", "=", "'a'", ",", "*", "*", "kwargs", ")", ":", "path", "=", "kwargs", ".", "get", "(", "'path'", ",", "None", ")", "# handle polymorphic store arg", "clobber", "=", "mode", "==", "'w'", "store", ...
Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read onl...
[ "Convenience", "function", "to", "open", "a", "group", "or", "array", "using", "file", "-", "mode", "-", "like", "semantics", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L21-L102
train
zarr-developers/zarr
zarr/convenience.py
save
def save(store, *args, **kwargs): """Convenience function to save an array or group of arrays to the local file system. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. args : ndarray NumPy arrays with data to save...
python
def save(store, *args, **kwargs): """Convenience function to save an array or group of arrays to the local file system. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. args : ndarray NumPy arrays with data to save...
[ "def", "save", "(", "store", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "0", "and", "len", "(", "kwargs", ")", "==", "0", ":", "raise", "ValueError", "(", "'at least one array must be provided'", ")", "i...
Convenience function to save an array or group of arrays to the local file system. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. args : ndarray NumPy arrays with data to save. kwargs NumPy arrays with da...
[ "Convenience", "function", "to", "save", "an", "array", "or", "group", "of", "arrays", "to", "the", "local", "file", "system", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L222-L299
train
zarr-developers/zarr
zarr/convenience.py
load
def load(store): """Load data from an array or group into memory. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. Returns ------- out If the store contains an array, out will be a numpy array. If the stor...
python
def load(store): """Load data from an array or group into memory. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. Returns ------- out If the store contains an array, out will be a numpy array. If the stor...
[ "def", "load", "(", "store", ")", ":", "# handle polymorphic store arg", "store", "=", "normalize_store_arg", "(", "store", ")", "if", "contains_array", "(", "store", ",", "path", "=", "None", ")", ":", "return", "Array", "(", "store", "=", "store", ",", "...
Load data from an array or group into memory. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. Returns ------- out If the store contains an array, out will be a numpy array. If the store contains a gro...
[ "Load", "data", "from", "an", "array", "or", "group", "into", "memory", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L332-L363
train
zarr-developers/zarr
zarr/convenience.py
copy
def copy(source, dest, name=None, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or d...
python
def copy(source, dest, name=None, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or d...
[ "def", "copy", "(", "source", ",", "dest", ",", "name", "=", "None", ",", "shallow", "=", "False", ",", "without_attrs", "=", "False", ",", "log", "=", "None", ",", "if_exists", "=", "'raise'", ",", "dry_run", "=", "False", ",", "*", "*", "create_kws...
Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. name : str, optional Name to copy the object to. shallow : bool, optional ...
[ "Copy", "the", "source", "array", "or", "group", "into", "the", "dest", "group", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L664-L796
train
zarr-developers/zarr
zarr/convenience.py
copy_all
def copy_all(source, dest, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy all children of the `source` group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group ...
python
def copy_all(source, dest, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy all children of the `source` group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group ...
[ "def", "copy_all", "(", "source", ",", "dest", ",", "shallow", "=", "False", ",", "without_attrs", "=", "False", ",", "log", "=", "None", ",", "if_exists", "=", "'raise'", ",", "dry_run", "=", "False", ",", "*", "*", "create_kws", ")", ":", "# value ch...
Copy all children of the `source` group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. shallow : bool, optional If True, only copy immediate children of `sour...
[ "Copy", "all", "children", "of", "the", "source", "group", "into", "the", "dest", "group", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L976-L1077
train
zarr-developers/zarr
zarr/convenience.py
consolidate_metadata
def consolidate_metadata(store, metadata_key='.zmetadata'): """ Consolidate all metadata for groups and arrays within the given store into a single resource and put it under the given key. This produces a single object in the backend store, containing all the metadata read from all the zarr-related...
python
def consolidate_metadata(store, metadata_key='.zmetadata'): """ Consolidate all metadata for groups and arrays within the given store into a single resource and put it under the given key. This produces a single object in the backend store, containing all the metadata read from all the zarr-related...
[ "def", "consolidate_metadata", "(", "store", ",", "metadata_key", "=", "'.zmetadata'", ")", ":", "store", "=", "normalize_store_arg", "(", "store", ")", "def", "is_zarr_key", "(", "key", ")", ":", "return", "(", "key", ".", "endswith", "(", "'.zarray'", ")",...
Consolidate all metadata for groups and arrays within the given store into a single resource and put it under the given key. This produces a single object in the backend store, containing all the metadata read from all the zarr-related keys that can be found. After metadata have been consolidated, use ...
[ "Consolidate", "all", "metadata", "for", "groups", "and", "arrays", "within", "the", "given", "store", "into", "a", "single", "resource", "and", "put", "it", "under", "the", "given", "key", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L1080-L1128
train
zarr-developers/zarr
zarr/convenience.py
open_consolidated
def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs): """Open group using metadata previously consolidated into a single key. This is an optimised method for opening a Zarr group, where instead of traversing the group/array hierarchy by accessing the metadata keys at each level,...
python
def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs): """Open group using metadata previously consolidated into a single key. This is an optimised method for opening a Zarr group, where instead of traversing the group/array hierarchy by accessing the metadata keys at each level,...
[ "def", "open_consolidated", "(", "store", ",", "metadata_key", "=", "'.zmetadata'", ",", "mode", "=", "'r+'", ",", "*", "*", "kwargs", ")", ":", "from", ".", "storage", "import", "ConsolidatedMetadataStore", "# normalize parameters", "store", "=", "normalize_store...
Open group using metadata previously consolidated into a single key. This is an optimised method for opening a Zarr group, where instead of traversing the group/array hierarchy by accessing the metadata keys at each level, a single key contains all of the metadata for everything. For remote data source...
[ "Open", "group", "using", "metadata", "previously", "consolidated", "into", "a", "single", "key", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L1131-L1185
train
openstack/horizon
openstack_dashboard/api/cinder.py
volume_list_paged
def volume_list_paged(request, search_opts=None, marker=None, paginate=False, sort_dir="desc"): """List volumes with pagination. To see all volumes in the cloud as an admin you can pass in a special search option: {'all_tenants': 1} """ has_more_data = False has_prev_data ...
python
def volume_list_paged(request, search_opts=None, marker=None, paginate=False, sort_dir="desc"): """List volumes with pagination. To see all volumes in the cloud as an admin you can pass in a special search option: {'all_tenants': 1} """ has_more_data = False has_prev_data ...
[ "def", "volume_list_paged", "(", "request", ",", "search_opts", "=", "None", ",", "marker", "=", "None", ",", "paginate", "=", "False", ",", "sort_dir", "=", "\"desc\"", ")", ":", "has_more_data", "=", "False", "has_prev_data", "=", "False", "volumes", "=", ...
List volumes with pagination. To see all volumes in the cloud as an admin you can pass in a special search option: {'all_tenants': 1}
[ "List", "volumes", "with", "pagination", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/cinder.py#L341-L380
train
openstack/horizon
openstack_dashboard/api/cinder.py
extension_supported
def extension_supported(request, extension_name): """This method will determine if Cinder supports a given extension name.""" for extension in list_extensions(request): if extension.name == extension_name: return True return False
python
def extension_supported(request, extension_name): """This method will determine if Cinder supports a given extension name.""" for extension in list_extensions(request): if extension.name == extension_name: return True return False
[ "def", "extension_supported", "(", "request", ",", "extension_name", ")", ":", "for", "extension", "in", "list_extensions", "(", "request", ")", ":", "if", "extension", ".", "name", "==", "extension_name", ":", "return", "True", "return", "False" ]
This method will determine if Cinder supports a given extension name.
[ "This", "method", "will", "determine", "if", "Cinder", "supports", "a", "given", "extension", "name", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/cinder.py#L1069-L1074
train
openstack/horizon
openstack_dashboard/api/cinder.py
transfer_list
def transfer_list(request, detailed=True, search_opts=None): """List volume transfers. To see all volumes transfers as an admin pass in a special search option: {'all_tenants': 1} """ c_client = cinderclient(request) try: return [VolumeTransfer(v) for v in c_client.transfers.list( ...
python
def transfer_list(request, detailed=True, search_opts=None): """List volume transfers. To see all volumes transfers as an admin pass in a special search option: {'all_tenants': 1} """ c_client = cinderclient(request) try: return [VolumeTransfer(v) for v in c_client.transfers.list( ...
[ "def", "transfer_list", "(", "request", ",", "detailed", "=", "True", ",", "search_opts", "=", "None", ")", ":", "c_client", "=", "cinderclient", "(", "request", ")", "try", ":", "return", "[", "VolumeTransfer", "(", "v", ")", "for", "v", "in", "c_client...
List volume transfers. To see all volumes transfers as an admin pass in a special search option: {'all_tenants': 1}
[ "List", "volume", "transfers", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/cinder.py#L1078-L1090
train
openstack/horizon
openstack_dashboard/usage/quotas.py
tenant_quota_usages
def tenant_quota_usages(request, tenant_id=None, targets=None): """Get our quotas and construct our usage object. :param tenant_id: Target tenant ID. If no tenant_id is provided, a the request.user.project_id is assumed to be used. :param targets: A tuple of quota names to be retrieved. If ...
python
def tenant_quota_usages(request, tenant_id=None, targets=None): """Get our quotas and construct our usage object. :param tenant_id: Target tenant ID. If no tenant_id is provided, a the request.user.project_id is assumed to be used. :param targets: A tuple of quota names to be retrieved. If ...
[ "def", "tenant_quota_usages", "(", "request", ",", "tenant_id", "=", "None", ",", "targets", "=", "None", ")", ":", "if", "not", "tenant_id", ":", "tenant_id", "=", "request", ".", "user", ".", "project_id", "disabled_quotas", "=", "get_disabled_quotas", "(", ...
Get our quotas and construct our usage object. :param tenant_id: Target tenant ID. If no tenant_id is provided, a the request.user.project_id is assumed to be used. :param targets: A tuple of quota names to be retrieved. If unspecified, all quota and usage information is retrieved.
[ "Get", "our", "quotas", "and", "construct", "our", "usage", "object", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L413-L435
train
openstack/horizon
openstack_dashboard/usage/quotas.py
QuotaUsage.add_quota
def add_quota(self, quota): """Adds an internal tracking reference for the given quota.""" if quota.limit in (None, -1, float('inf')): # Handle "unlimited" quotas. self.usages[quota.name]['quota'] = float("inf") self.usages[quota.name]['available'] = float("inf") ...
python
def add_quota(self, quota): """Adds an internal tracking reference for the given quota.""" if quota.limit in (None, -1, float('inf')): # Handle "unlimited" quotas. self.usages[quota.name]['quota'] = float("inf") self.usages[quota.name]['available'] = float("inf") ...
[ "def", "add_quota", "(", "self", ",", "quota", ")", ":", "if", "quota", ".", "limit", "in", "(", "None", ",", "-", "1", ",", "float", "(", "'inf'", ")", ")", ":", "# Handle \"unlimited\" quotas.", "self", ".", "usages", "[", "quota", ".", "name", "]"...
Adds an internal tracking reference for the given quota.
[ "Adds", "an", "internal", "tracking", "reference", "for", "the", "given", "quota", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L141-L148
train
openstack/horizon
openstack_dashboard/usage/quotas.py
QuotaUsage.tally
def tally(self, name, value): """Adds to the "used" metric for the given quota.""" value = value or 0 # Protection against None. # Start at 0 if this is the first value. if 'used' not in self.usages[name]: self.usages[name]['used'] = 0 # Increment our usage and updat...
python
def tally(self, name, value): """Adds to the "used" metric for the given quota.""" value = value or 0 # Protection against None. # Start at 0 if this is the first value. if 'used' not in self.usages[name]: self.usages[name]['used'] = 0 # Increment our usage and updat...
[ "def", "tally", "(", "self", ",", "name", ",", "value", ")", ":", "value", "=", "value", "or", "0", "# Protection against None.", "# Start at 0 if this is the first value.", "if", "'used'", "not", "in", "self", ".", "usages", "[", "name", "]", ":", "self", "...
Adds to the "used" metric for the given quota.
[ "Adds", "to", "the", "used", "metric", "for", "the", "given", "quota", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L150-L158
train
openstack/horizon
openstack_dashboard/usage/quotas.py
QuotaUsage.update_available
def update_available(self, name): """Updates the "available" metric for the given quota.""" quota = self.usages.get(name, {}).get('quota', float('inf')) available = quota - self.usages[name]['used'] if available < 0: available = 0 self.usages[name]['available'] = avai...
python
def update_available(self, name): """Updates the "available" metric for the given quota.""" quota = self.usages.get(name, {}).get('quota', float('inf')) available = quota - self.usages[name]['used'] if available < 0: available = 0 self.usages[name]['available'] = avai...
[ "def", "update_available", "(", "self", ",", "name", ")", ":", "quota", "=", "self", ".", "usages", ".", "get", "(", "name", ",", "{", "}", ")", ".", "get", "(", "'quota'", ",", "float", "(", "'inf'", ")", ")", "available", "=", "quota", "-", "se...
Updates the "available" metric for the given quota.
[ "Updates", "the", "available", "metric", "for", "the", "given", "quota", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L160-L166
train
openstack/horizon
openstack_dashboard/dashboards/project/instances/views.py
process_non_api_filters
def process_non_api_filters(search_opts, non_api_filter_info): """Process filters by non-API fields There are cases where it is useful to provide a filter field which does not exist in a resource in a backend service. For example, nova server list provides 'image' field with image ID but 'image nam...
python
def process_non_api_filters(search_opts, non_api_filter_info): """Process filters by non-API fields There are cases where it is useful to provide a filter field which does not exist in a resource in a backend service. For example, nova server list provides 'image' field with image ID but 'image nam...
[ "def", "process_non_api_filters", "(", "search_opts", ",", "non_api_filter_info", ")", ":", "for", "fake_field", ",", "real_field", ",", "resources", "in", "non_api_filter_info", ":", "if", "not", "_swap_filter", "(", "resources", ",", "search_opts", ",", "fake_fiel...
Process filters by non-API fields There are cases where it is useful to provide a filter field which does not exist in a resource in a backend service. For example, nova server list provides 'image' field with image ID but 'image name' is more useful for GUI users. This function replaces fake field...
[ "Process", "filters", "by", "non", "-", "API", "fields" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/views.py#L202-L221
train
openstack/horizon
horizon/utils/validators.py
validate_port_or_colon_separated_port_range
def validate_port_or_colon_separated_port_range(port_range): """Accepts a port number or a single-colon separated range.""" if port_range.count(':') > 1: raise ValidationError(_("One colon allowed in port range")) ports = port_range.split(':') for port in ports: validate_port_range(port)
python
def validate_port_or_colon_separated_port_range(port_range): """Accepts a port number or a single-colon separated range.""" if port_range.count(':') > 1: raise ValidationError(_("One colon allowed in port range")) ports = port_range.split(':') for port in ports: validate_port_range(port)
[ "def", "validate_port_or_colon_separated_port_range", "(", "port_range", ")", ":", "if", "port_range", ".", "count", "(", "':'", ")", ">", "1", ":", "raise", "ValidationError", "(", "_", "(", "\"One colon allowed in port range\"", ")", ")", "ports", "=", "port_ran...
Accepts a port number or a single-colon separated range.
[ "Accepts", "a", "port", "number", "or", "a", "single", "-", "colon", "separated", "range", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/validators.py#L58-L64
train
openstack/horizon
openstack_dashboard/utils/settings.py
import_submodules
def import_submodules(module): """Import all submodules and make them available in a dict.""" submodules = {} for loader, name, ispkg in pkgutil.iter_modules(module.__path__, module.__name__ + '.'): try: submodule = import_module(name) ...
python
def import_submodules(module): """Import all submodules and make them available in a dict.""" submodules = {} for loader, name, ispkg in pkgutil.iter_modules(module.__path__, module.__name__ + '.'): try: submodule = import_module(name) ...
[ "def", "import_submodules", "(", "module", ")", ":", "submodules", "=", "{", "}", "for", "loader", ",", "name", ",", "ispkg", "in", "pkgutil", ".", "iter_modules", "(", "module", ".", "__path__", ",", "module", ".", "__name__", "+", "'.'", ")", ":", "t...
Import all submodules and make them available in a dict.
[ "Import", "all", "submodules", "and", "make", "them", "available", "in", "a", "dict", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L24-L38
train
openstack/horizon
openstack_dashboard/utils/settings.py
import_dashboard_config
def import_dashboard_config(modules): """Imports configuration from all the modules and merges it.""" config = collections.defaultdict(dict) for module in modules: for submodule in import_submodules(module).values(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodu...
python
def import_dashboard_config(modules): """Imports configuration from all the modules and merges it.""" config = collections.defaultdict(dict) for module in modules: for submodule in import_submodules(module).values(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodu...
[ "def", "import_dashboard_config", "(", "modules", ")", ":", "config", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "module", "in", "modules", ":", "for", "submodule", "in", "import_submodules", "(", "module", ")", ".", "values", "(", ")",...
Imports configuration from all the modules and merges it.
[ "Imports", "configuration", "from", "all", "the", "modules", "and", "merges", "it", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L41-L61
train
openstack/horizon
openstack_dashboard/utils/settings.py
get_xstatic_dirs
def get_xstatic_dirs(XSTATIC_MODULES, HORIZON_CONFIG): """Discover static file configuration of the xstatic modules. For each entry in the XSTATIC_MODULES list we determine the entry point files (which may come from the xstatic MAIN var) and then determine where in the Django static tree the xstatic pa...
python
def get_xstatic_dirs(XSTATIC_MODULES, HORIZON_CONFIG): """Discover static file configuration of the xstatic modules. For each entry in the XSTATIC_MODULES list we determine the entry point files (which may come from the xstatic MAIN var) and then determine where in the Django static tree the xstatic pa...
[ "def", "get_xstatic_dirs", "(", "XSTATIC_MODULES", ",", "HORIZON_CONFIG", ")", ":", "STATICFILES_DIRS", "=", "[", "]", "HORIZON_CONFIG", ".", "setdefault", "(", "'xstatic_lib_files'", ",", "[", "]", ")", "for", "module_name", ",", "files", "in", "XSTATIC_MODULES",...
Discover static file configuration of the xstatic modules. For each entry in the XSTATIC_MODULES list we determine the entry point files (which may come from the xstatic MAIN var) and then determine where in the Django static tree the xstatic package's contents should be placed. For jquery.bootstr...
[ "Discover", "static", "file", "configuration", "of", "the", "xstatic", "modules", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L242-L293
train
openstack/horizon
openstack_dashboard/api/nova.py
upgrade_api
def upgrade_api(request, client, version): """Ugrade the nova API to the specified version if possible.""" min_ver, max_ver = api_versions._get_server_version_range(client) if min_ver <= api_versions.APIVersion(version) <= max_ver: client = _nova.novaclient(request, version) return client
python
def upgrade_api(request, client, version): """Ugrade the nova API to the specified version if possible.""" min_ver, max_ver = api_versions._get_server_version_range(client) if min_ver <= api_versions.APIVersion(version) <= max_ver: client = _nova.novaclient(request, version) return client
[ "def", "upgrade_api", "(", "request", ",", "client", ",", "version", ")", ":", "min_ver", ",", "max_ver", "=", "api_versions", ".", "_get_server_version_range", "(", "client", ")", "if", "min_ver", "<=", "api_versions", ".", "APIVersion", "(", "version", ")", ...
Ugrade the nova API to the specified version if possible.
[ "Ugrade", "the", "nova", "API", "to", "the", "specified", "version", "if", "possible", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L192-L198
train
openstack/horizon
openstack_dashboard/api/nova.py
add_tenant_to_flavor
def add_tenant_to_flavor(request, flavor, tenant): """Add a tenant to the given flavor access list.""" return _nova.novaclient(request).flavor_access.add_tenant_access( flavor=flavor, tenant=tenant)
python
def add_tenant_to_flavor(request, flavor, tenant): """Add a tenant to the given flavor access list.""" return _nova.novaclient(request).flavor_access.add_tenant_access( flavor=flavor, tenant=tenant)
[ "def", "add_tenant_to_flavor", "(", "request", ",", "flavor", ",", "tenant", ")", ":", "return", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavor_access", ".", "add_tenant_access", "(", "flavor", "=", "flavor", ",", "tenant", "=", "tenant", ")" ...
Add a tenant to the given flavor access list.
[ "Add", "a", "tenant", "to", "the", "given", "flavor", "access", "list", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L336-L339
train
openstack/horizon
openstack_dashboard/api/nova.py
remove_tenant_from_flavor
def remove_tenant_from_flavor(request, flavor, tenant): """Remove a tenant from the given flavor access list.""" return _nova.novaclient(request).flavor_access.remove_tenant_access( flavor=flavor, tenant=tenant)
python
def remove_tenant_from_flavor(request, flavor, tenant): """Remove a tenant from the given flavor access list.""" return _nova.novaclient(request).flavor_access.remove_tenant_access( flavor=flavor, tenant=tenant)
[ "def", "remove_tenant_from_flavor", "(", "request", ",", "flavor", ",", "tenant", ")", ":", "return", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavor_access", ".", "remove_tenant_access", "(", "flavor", "=", "flavor", ",", "tenant", "=", "tenant"...
Remove a tenant from the given flavor access list.
[ "Remove", "a", "tenant", "from", "the", "given", "flavor", "access", "list", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L343-L346
train
openstack/horizon
openstack_dashboard/api/nova.py
flavor_get_extras
def flavor_get_extras(request, flavor_id, raw=False, flavor=None): """Get flavor extra specs.""" if flavor is None: flavor = _nova.novaclient(request).flavors.get(flavor_id) extras = flavor.get_keys() if raw: return extras return [FlavorExtraSpec(flavor_id, key, value) for ...
python
def flavor_get_extras(request, flavor_id, raw=False, flavor=None): """Get flavor extra specs.""" if flavor is None: flavor = _nova.novaclient(request).flavors.get(flavor_id) extras = flavor.get_keys() if raw: return extras return [FlavorExtraSpec(flavor_id, key, value) for ...
[ "def", "flavor_get_extras", "(", "request", ",", "flavor_id", ",", "raw", "=", "False", ",", "flavor", "=", "None", ")", ":", "if", "flavor", "is", "None", ":", "flavor", "=", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavors", ".", "get",...
Get flavor extra specs.
[ "Get", "flavor", "extra", "specs", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L350-L358
train
openstack/horizon
openstack_dashboard/api/nova.py
flavor_extra_delete
def flavor_extra_delete(request, flavor_id, keys): """Unset the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) return flavor.unset_keys(keys)
python
def flavor_extra_delete(request, flavor_id, keys): """Unset the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) return flavor.unset_keys(keys)
[ "def", "flavor_extra_delete", "(", "request", ",", "flavor_id", ",", "keys", ")", ":", "flavor", "=", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavors", ".", "get", "(", "flavor_id", ")", "return", "flavor", ".", "unset_keys", "(", "keys", ...
Unset the flavor extra spec keys.
[ "Unset", "the", "flavor", "extra", "spec", "keys", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L362-L365
train
openstack/horizon
openstack_dashboard/api/nova.py
flavor_extra_set
def flavor_extra_set(request, flavor_id, metadata): """Set the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): # not a way to delete keys return None return flavor.set_keys(metadata)
python
def flavor_extra_set(request, flavor_id, metadata): """Set the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): # not a way to delete keys return None return flavor.set_keys(metadata)
[ "def", "flavor_extra_set", "(", "request", ",", "flavor_id", ",", "metadata", ")", ":", "flavor", "=", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavors", ".", "get", "(", "flavor_id", ")", "if", "(", "not", "metadata", ")", ":", "# not a wa...
Set the flavor extra spec keys.
[ "Set", "the", "flavor", "extra", "spec", "keys", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L369-L374
train
openstack/horizon
openstack_dashboard/api/nova.py
server_console_output
def server_console_output(request, instance_id, tail_length=None): """Gets console output of an instance.""" nc = _nova.novaclient(request) return nc.servers.get_console_output(instance_id, length=tail_length)
python
def server_console_output(request, instance_id, tail_length=None): """Gets console output of an instance.""" nc = _nova.novaclient(request) return nc.servers.get_console_output(instance_id, length=tail_length)
[ "def", "server_console_output", "(", "request", ",", "instance_id", ",", "tail_length", "=", "None", ")", ":", "nc", "=", "_nova", ".", "novaclient", "(", "request", ")", "return", "nc", ".", "servers", ".", "get_console_output", "(", "instance_id", ",", "le...
Gets console output of an instance.
[ "Gets", "console", "output", "of", "an", "instance", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L533-L536
train
openstack/horizon
openstack_dashboard/api/nova.py
list_extensions
def list_extensions(request): """List all nova extensions, except the ones in the blacklist.""" blacklist = set(getattr(settings, 'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', [])) nova_api = _nova.novaclient(request) return tuple( extension for extension in nova_lis...
python
def list_extensions(request): """List all nova extensions, except the ones in the blacklist.""" blacklist = set(getattr(settings, 'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', [])) nova_api = _nova.novaclient(request) return tuple( extension for extension in nova_lis...
[ "def", "list_extensions", "(", "request", ")", ":", "blacklist", "=", "set", "(", "getattr", "(", "settings", ",", "'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST'", ",", "[", "]", ")", ")", "nova_api", "=", "_nova", ".", "novaclient", "(", "request", ")", "return", "...
List all nova extensions, except the ones in the blacklist.
[ "List", "all", "nova", "extensions", "except", "the", "ones", "in", "the", "blacklist", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L1012-L1021
train
openstack/horizon
openstack_dashboard/api/nova.py
extension_supported
def extension_supported(extension_name, request): """Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc. """ for ext in list_extensions(request): if ext.name == extension_name: return True return ...
python
def extension_supported(extension_name, request): """Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc. """ for ext in list_extensions(request): if ext.name == extension_name: return True return ...
[ "def", "extension_supported", "(", "extension_name", ",", "request", ")", ":", "for", "ext", "in", "list_extensions", "(", "request", ")", ":", "if", "ext", ".", "name", "==", "extension_name", ":", "return", "True", "return", "False" ]
Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc.
[ "Determine", "if", "nova", "supports", "a", "given", "extension", "name", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L1026-L1035
train
openstack/horizon
openstack_dashboard/utils/futurist_utils.py
call_functions_parallel
def call_functions_parallel(*worker_defs): """Call specified functions in parallel. :param *worker_defs: Each positional argument can be either of a function to be called or a tuple which consists of a function, a list of positional arguments) and keyword arguments (optional). If you ne...
python
def call_functions_parallel(*worker_defs): """Call specified functions in parallel. :param *worker_defs: Each positional argument can be either of a function to be called or a tuple which consists of a function, a list of positional arguments) and keyword arguments (optional). If you ne...
[ "def", "call_functions_parallel", "(", "*", "worker_defs", ")", ":", "# TODO(amotoki): Needs to figure out what max_workers can be specified.", "# According to e0ne, the apache default configuration in devstack allows", "# only 10 threads. What happens if max_worker=11 is specified?", "max_work...
Call specified functions in parallel. :param *worker_defs: Each positional argument can be either of a function to be called or a tuple which consists of a function, a list of positional arguments) and keyword arguments (optional). If you need to pass arguments, you need to pass a tuple. ...
[ "Call", "specified", "functions", "in", "parallel", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/futurist_utils.py#L18-L50
train
openstack/horizon
horizon/utils/secret_key.py
generate_key
def generate_key(key_length=64): """Secret key generator. The quality of randomness depends on operating system support, see http://docs.python.org/library/random.html#random.SystemRandom. """ if hasattr(random, 'SystemRandom'): logging.info('Generating a secure random key using SystemRando...
python
def generate_key(key_length=64): """Secret key generator. The quality of randomness depends on operating system support, see http://docs.python.org/library/random.html#random.SystemRandom. """ if hasattr(random, 'SystemRandom'): logging.info('Generating a secure random key using SystemRando...
[ "def", "generate_key", "(", "key_length", "=", "64", ")", ":", "if", "hasattr", "(", "random", ",", "'SystemRandom'", ")", ":", "logging", ".", "info", "(", "'Generating a secure random key using SystemRandom.'", ")", "choice", "=", "random", ".", "SystemRandom", ...
Secret key generator. The quality of randomness depends on operating system support, see http://docs.python.org/library/random.html#random.SystemRandom.
[ "Secret", "key", "generator", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/secret_key.py#L28-L43
train
openstack/horizon
horizon/utils/secret_key.py
generate_or_read_from_file
def generate_or_read_from_file(key_file='.secret_key', key_length=64): """Multiprocess-safe secret key file generator. Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py upon first start. Save to use, i.e. when multiple Python interpreters serve the dashboard Django application (...
python
def generate_or_read_from_file(key_file='.secret_key', key_length=64): """Multiprocess-safe secret key file generator. Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py upon first start. Save to use, i.e. when multiple Python interpreters serve the dashboard Django application (...
[ "def", "generate_or_read_from_file", "(", "key_file", "=", "'.secret_key'", ",", "key_length", "=", "64", ")", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "key_file", ")", "# check, if key_file already exists", "# if yes, then just read and return key",...
Multiprocess-safe secret key file generator. Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py upon first start. Save to use, i.e. when multiple Python interpreters serve the dashboard Django application (e.g. in a mod_wsgi + daemonized environment). Also checks if file permiss...
[ "Multiprocess", "-", "safe", "secret", "key", "file", "generator", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/secret_key.py#L56-L84
train
openstack/horizon
openstack_dashboard/api/rest/urls.py
register
def register(view): """Register API views to respond to a regex pattern. ``url_regex`` on a wrapped view class is used as the regex pattern. The view should be a standard Django class-based view implementing an as_view() method. The url_regex attribute of the view should be a standard Django URL re...
python
def register(view): """Register API views to respond to a regex pattern. ``url_regex`` on a wrapped view class is used as the regex pattern. The view should be a standard Django class-based view implementing an as_view() method. The url_regex attribute of the view should be a standard Django URL re...
[ "def", "register", "(", "view", ")", ":", "p", "=", "urls", ".", "url", "(", "view", ".", "url_regex", ",", "view", ".", "as_view", "(", ")", ")", "urlpatterns", ".", "append", "(", "p", ")", "return", "view" ]
Register API views to respond to a regex pattern. ``url_regex`` on a wrapped view class is used as the regex pattern. The view should be a standard Django class-based view implementing an as_view() method. The url_regex attribute of the view should be a standard Django URL regex pattern.
[ "Register", "API", "views", "to", "respond", "to", "a", "regex", "pattern", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/urls.py#L22-L32
train
openstack/horizon
horizon/templatetags/shellfilter.py
shellfilter
def shellfilter(value): """Replace HTML chars for shell usage.""" replacements = {'\\': '\\\\', '`': '\\`', "'": "\\'", '"': '\\"'} for search, repl in replacements.items(): value = value.replace(search, repl) return safestring.mark_saf...
python
def shellfilter(value): """Replace HTML chars for shell usage.""" replacements = {'\\': '\\\\', '`': '\\`', "'": "\\'", '"': '\\"'} for search, repl in replacements.items(): value = value.replace(search, repl) return safestring.mark_saf...
[ "def", "shellfilter", "(", "value", ")", ":", "replacements", "=", "{", "'\\\\'", ":", "'\\\\\\\\'", ",", "'`'", ":", "'\\\\`'", ",", "\"'\"", ":", "\"\\\\'\"", ",", "'\"'", ":", "'\\\\\"'", "}", "for", "search", ",", "repl", "in", "replacements", ".", ...
Replace HTML chars for shell usage.
[ "Replace", "HTML", "chars", "for", "shell", "usage", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/shellfilter.py#L22-L30
train
openstack/horizon
openstack_auth/views.py
websso
def websso(request): """Logs a user in using a token from Keystone's POST.""" referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL) auth_url = utils.clean_up_auth_url(referer) token = request.POST.get('token') try: request.user = auth.authenticate(request=request, auth_...
python
def websso(request): """Logs a user in using a token from Keystone's POST.""" referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL) auth_url = utils.clean_up_auth_url(referer) token = request.POST.get('token') try: request.user = auth.authenticate(request=request, auth_...
[ "def", "websso", "(", "request", ")", ":", "referer", "=", "request", ".", "META", ".", "get", "(", "'HTTP_REFERER'", ",", "settings", ".", "OPENSTACK_KEYSTONE_URL", ")", "auth_url", "=", "utils", ".", "clean_up_auth_url", "(", "referer", ")", "token", "=", ...
Logs a user in using a token from Keystone's POST.
[ "Logs", "a", "user", "in", "using", "a", "token", "from", "Keystone", "s", "POST", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L159-L180
train
openstack/horizon
openstack_auth/views.py
logout
def logout(request, login_url=None, **kwargs): """Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters. ...
python
def logout(request, login_url=None, **kwargs): """Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters. ...
[ "def", "logout", "(", "request", ",", "login_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "'Logging out user \"%(username)s\".'", "%", "{", "'username'", ":", "request", ".", "user", ".", "username", "}", "LOG", ".", "info", "(", "ms...
Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters.
[ "Logs", "out", "the", "user", "if", "he", "is", "logged", "in", ".", "Then", "redirects", "to", "the", "log", "-", "in", "page", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L183-L206
train
openstack/horizon
openstack_auth/views.py
switch
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches an authenticated user from one project to another.""" LOG.debug('Switching to tenant %s for user "%s".', tenant_id, request.user.username) endpoint, __ = utils.fix_auth_url_version_prefix(request.user.en...
python
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches an authenticated user from one project to another.""" LOG.debug('Switching to tenant %s for user "%s".', tenant_id, request.user.username) endpoint, __ = utils.fix_auth_url_version_prefix(request.user.en...
[ "def", "switch", "(", "request", ",", "tenant_id", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "LOG", ".", "debug", "(", "'Switching to tenant %s for user \"%s\".'", ",", "tenant_id", ",", "request", ".", "user", ".", "username",...
Switches an authenticated user from one project to another.
[ "Switches", "an", "authenticated", "user", "from", "one", "project", "to", "another", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L210-L257
train
openstack/horizon
openstack_auth/views.py
switch_region
def switch_region(request, region_name, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is no...
python
def switch_region(request, region_name, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is no...
[ "def", "switch_region", "(", "request", ",", "region_name", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "if", "region_name", "in", "request", ".", "user", ".", "available_services_regions", ":", "request", ".", "session", "[", ...
Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is not switched.
[ "Switches", "the", "user", "s", "region", "for", "all", "services", "except", "Identity", "service", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L261-L280
train
openstack/horizon
openstack_auth/views.py
switch_keystone_provider
def switch_keystone_provider(request, keystone_provider=None, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherw...
python
def switch_keystone_provider(request, keystone_provider=None, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherw...
[ "def", "switch_keystone_provider", "(", "request", ",", "keystone_provider", "=", "None", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "base_token", "=", "request", ".", "session", ".", "get", "(", "'k2k_base_unscoped_token'", ",", ...
Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherwise if keystone_provider is None then we switch the user back to the Identity Provider Keystone which a non federated token auth will be ...
[ "Switches", "the", "user", "s", "keystone", "provider", "using", "K2K", "Federation" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L284-L353
train
openstack/horizon
horizon/tables/actions.py
LinkAction.get_link_url
def get_link_url(self, datum=None): """Returns the final URL based on the value of ``url``. If ``url`` is callable it will call the function. If not, it will then try to call ``reverse`` on ``url``. Failing that, it will simply return the value of ``url`` as-is. When called for...
python
def get_link_url(self, datum=None): """Returns the final URL based on the value of ``url``. If ``url`` is callable it will call the function. If not, it will then try to call ``reverse`` on ``url``. Failing that, it will simply return the value of ``url`` as-is. When called for...
[ "def", "get_link_url", "(", "self", ",", "datum", "=", "None", ")", ":", "if", "not", "self", ".", "url", ":", "raise", "NotImplementedError", "(", "'A LinkAction class must have a '", "'url attribute or define its own '", "'get_link_url method.'", ")", "if", "callabl...
Returns the final URL based on the value of ``url``. If ``url`` is callable it will call the function. If not, it will then try to call ``reverse`` on ``url``. Failing that, it will simply return the value of ``url`` as-is. When called for a row action, the current row data object will...
[ "Returns", "the", "final", "URL", "based", "on", "the", "value", "of", "url", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L388-L413
train
openstack/horizon
horizon/tables/actions.py
FilterAction.get_param_name
def get_param_name(self): """Returns the full query parameter name for this action. Defaults to ``{{ table.name }}__{{ action.name }}__{{ action.param_name }}``. """ return "__".join([self.table.name, self.name, self.param_name])
python
def get_param_name(self): """Returns the full query parameter name for this action. Defaults to ``{{ table.name }}__{{ action.name }}__{{ action.param_name }}``. """ return "__".join([self.table.name, self.name, self.param_name])
[ "def", "get_param_name", "(", "self", ")", ":", "return", "\"__\"", ".", "join", "(", "[", "self", ".", "table", ".", "name", ",", "self", ".", "name", ",", "self", ".", "param_name", "]", ")" ]
Returns the full query parameter name for this action. Defaults to ``{{ table.name }}__{{ action.name }}__{{ action.param_name }}``.
[ "Returns", "the", "full", "query", "parameter", "name", "for", "this", "action", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L492-L498
train
openstack/horizon
horizon/tables/actions.py
FilterAction.is_api_filter
def is_api_filter(self, filter_field): """Determine if agiven filter field should be used as an API filter.""" if self.filter_type == 'server': for choice in self.filter_choices: if (choice[0] == filter_field and len(choice) > 2 and choice[2]): ...
python
def is_api_filter(self, filter_field): """Determine if agiven filter field should be used as an API filter.""" if self.filter_type == 'server': for choice in self.filter_choices: if (choice[0] == filter_field and len(choice) > 2 and choice[2]): ...
[ "def", "is_api_filter", "(", "self", ",", "filter_field", ")", ":", "if", "self", ".", "filter_type", "==", "'server'", ":", "for", "choice", "in", "self", ".", "filter_choices", ":", "if", "(", "choice", "[", "0", "]", "==", "filter_field", "and", "len"...
Determine if agiven filter field should be used as an API filter.
[ "Determine", "if", "agiven", "filter", "field", "should", "be", "used", "as", "an", "API", "filter", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L534-L541
train
openstack/horizon
horizon/tables/actions.py
FilterAction.get_select_options
def get_select_options(self): """Provide the value, string, and help_text for the template to render. help_text is returned if applicable. """ if self.filter_choices: return [choice[:4] for choice in self.filter_choices # Display it If the fifth element i...
python
def get_select_options(self): """Provide the value, string, and help_text for the template to render. help_text is returned if applicable. """ if self.filter_choices: return [choice[:4] for choice in self.filter_choices # Display it If the fifth element i...
[ "def", "get_select_options", "(", "self", ")", ":", "if", "self", ".", "filter_choices", ":", "return", "[", "choice", "[", ":", "4", "]", "for", "choice", "in", "self", ".", "filter_choices", "# Display it If the fifth element is True or does not exist", "if", "l...
Provide the value, string, and help_text for the template to render. help_text is returned if applicable.
[ "Provide", "the", "value", "string", "and", "help_text", "for", "the", "template", "to", "render", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L543-L551
train
openstack/horizon
horizon/tables/actions.py
BatchAction._get_action_name
def _get_action_name(self, items=None, past=False): """Retreive action name based on the number of items and `past` flag. :param items: A list or tuple of items (or container with a __len__ method) to count the number of concerned items for which this method is call...
python
def _get_action_name(self, items=None, past=False): """Retreive action name based on the number of items and `past` flag. :param items: A list or tuple of items (or container with a __len__ method) to count the number of concerned items for which this method is call...
[ "def", "_get_action_name", "(", "self", ",", "items", "=", "None", ",", "past", "=", "False", ")", ":", "action_type", "=", "\"past\"", "if", "past", "else", "\"present\"", "if", "items", "is", "None", ":", "# Called without items parameter (by a single instance.)...
Retreive action name based on the number of items and `past` flag. :param items: A list or tuple of items (or container with a __len__ method) to count the number of concerned items for which this method is called. When this method is called for a single item (b...
[ "Retreive", "action", "name", "based", "on", "the", "number", "of", "items", "and", "past", "flag", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L697-L730
train
openstack/horizon
horizon/tables/actions.py
BatchAction.update
def update(self, request, datum): """Switches the action verbose name, if needed.""" if getattr(self, 'action_present', False): self.verbose_name = self._get_action_name() self.verbose_name_plural = self._get_action_name('plural')
python
def update(self, request, datum): """Switches the action verbose name, if needed.""" if getattr(self, 'action_present', False): self.verbose_name = self._get_action_name() self.verbose_name_plural = self._get_action_name('plural')
[ "def", "update", "(", "self", ",", "request", ",", "datum", ")", ":", "if", "getattr", "(", "self", ",", "'action_present'", ",", "False", ")", ":", "self", ".", "verbose_name", "=", "self", ".", "_get_action_name", "(", ")", "self", ".", "verbose_name_p...
Switches the action verbose name, if needed.
[ "Switches", "the", "action", "verbose", "name", "if", "needed", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L740-L744
train
openstack/horizon
horizon/tables/actions.py
BatchAction.get_default_attrs
def get_default_attrs(self): """Returns a list of the default HTML attributes for the action.""" attrs = super(BatchAction, self).get_default_attrs() attrs.update({'data-batch-action': 'true'}) return attrs
python
def get_default_attrs(self): """Returns a list of the default HTML attributes for the action.""" attrs = super(BatchAction, self).get_default_attrs() attrs.update({'data-batch-action': 'true'}) return attrs
[ "def", "get_default_attrs", "(", "self", ")", ":", "attrs", "=", "super", "(", "BatchAction", ",", "self", ")", ".", "get_default_attrs", "(", ")", "attrs", ".", "update", "(", "{", "'data-batch-action'", ":", "'true'", "}", ")", "return", "attrs" ]
Returns a list of the default HTML attributes for the action.
[ "Returns", "a", "list", "of", "the", "default", "HTML", "attributes", "for", "the", "action", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L752-L756
train
openstack/horizon
horizon/tabs/views.py
TabView.get_tabs
def get_tabs(self, request, **kwargs): """Returns the initialized tab group for this view.""" if self._tab_group is None: self._tab_group = self.tab_group_class(request, **kwargs) return self._tab_group
python
def get_tabs(self, request, **kwargs): """Returns the initialized tab group for this view.""" if self._tab_group is None: self._tab_group = self.tab_group_class(request, **kwargs) return self._tab_group
[ "def", "get_tabs", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_tab_group", "is", "None", ":", "self", ".", "_tab_group", "=", "self", ".", "tab_group_class", "(", "request", ",", "*", "*", "kwargs", ")", "retu...
Returns the initialized tab group for this view.
[ "Returns", "the", "initialized", "tab", "group", "for", "this", "view", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L40-L44
train
openstack/horizon
horizon/tabs/views.py
TabView.get_context_data
def get_context_data(self, **kwargs): """Adds the ``tab_group`` variable to the context data.""" context = super(TabView, self).get_context_data(**kwargs) try: tab_group = self.get_tabs(self.request, **kwargs) context["tab_group"] = tab_group # Make sure our d...
python
def get_context_data(self, **kwargs): """Adds the ``tab_group`` variable to the context data.""" context = super(TabView, self).get_context_data(**kwargs) try: tab_group = self.get_tabs(self.request, **kwargs) context["tab_group"] = tab_group # Make sure our d...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "TabView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "try", ":", "tab_group", "=", "self", ".", "get_tabs", "(", "...
Adds the ``tab_group`` variable to the context data.
[ "Adds", "the", "tab_group", "variable", "to", "the", "context", "data", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L46-L56
train
openstack/horizon
horizon/tabs/views.py
TabView.handle_tabbed_response
def handle_tabbed_response(self, tab_group, context): """Sends back an AJAX-appropriate response for the tab group if needed. Otherwise renders the response as normal. """ if self.request.is_ajax(): if tab_group.selected: return http.HttpResponse(tab_group.se...
python
def handle_tabbed_response(self, tab_group, context): """Sends back an AJAX-appropriate response for the tab group if needed. Otherwise renders the response as normal. """ if self.request.is_ajax(): if tab_group.selected: return http.HttpResponse(tab_group.se...
[ "def", "handle_tabbed_response", "(", "self", ",", "tab_group", ",", "context", ")", ":", "if", "self", ".", "request", ".", "is_ajax", "(", ")", ":", "if", "tab_group", ".", "selected", ":", "return", "http", ".", "HttpResponse", "(", "tab_group", ".", ...
Sends back an AJAX-appropriate response for the tab group if needed. Otherwise renders the response as normal.
[ "Sends", "back", "an", "AJAX", "-", "appropriate", "response", "for", "the", "tab", "group", "if", "needed", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L58-L68
train
openstack/horizon
horizon/tabs/views.py
TabbedTableView.load_tabs
def load_tabs(self): """Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions. """ tab_group = self.get_tabs(self.re...
python
def load_tabs(self): """Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions. """ tab_group = self.get_tabs(self.re...
[ "def", "load_tabs", "(", "self", ")", ":", "tab_group", "=", "self", ".", "get_tabs", "(", "self", ".", "request", ",", "*", "*", "self", ".", "kwargs", ")", "tabs", "=", "tab_group", ".", "get_tabs", "(", ")", "for", "tab", "in", "[", "t", "for", ...
Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions.
[ "Loads", "the", "tab", "group", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L81-L94
train
openstack/horizon
horizon/tabs/views.py
TabbedTableView.handle_table
def handle_table(self, table_dict): """Loads the table data based on a given table_dict and handles them. For the given dict containing a ``DataTable`` and a ``TableTab`` instance, it loads the table data for that tab and calls the table's :meth:`~horizon.tables.DataTable.maybe_handle` ...
python
def handle_table(self, table_dict): """Loads the table data based on a given table_dict and handles them. For the given dict containing a ``DataTable`` and a ``TableTab`` instance, it loads the table data for that tab and calls the table's :meth:`~horizon.tables.DataTable.maybe_handle` ...
[ "def", "handle_table", "(", "self", ",", "table_dict", ")", ":", "table", "=", "table_dict", "[", "'table'", "]", "tab", "=", "table_dict", "[", "'tab'", "]", "tab", ".", "load_table_data", "(", ")", "table_name", "=", "table", ".", "_meta", ".", "name",...
Loads the table data based on a given table_dict and handles them. For the given dict containing a ``DataTable`` and a ``TableTab`` instance, it loads the table data for that tab and calls the table's :meth:`~horizon.tables.DataTable.maybe_handle` method. The return value will be the re...
[ "Loads", "the", "table", "data", "based", "on", "a", "given", "table_dict", "and", "handles", "them", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L102-L117
train
openstack/horizon
openstack_dashboard/context_processors.py
openstack
def openstack(request): """Context processor necessary for OpenStack Dashboard functionality. The following variables are added to the request context: ``authorized_tenants`` A list of tenant objects which the current user has access to. ``regions`` A dictionary containing informatio...
python
def openstack(request): """Context processor necessary for OpenStack Dashboard functionality. The following variables are added to the request context: ``authorized_tenants`` A list of tenant objects which the current user has access to. ``regions`` A dictionary containing informatio...
[ "def", "openstack", "(", "request", ")", ":", "context", "=", "{", "}", "# Auth/Keystone context", "context", ".", "setdefault", "(", "'authorized_tenants'", ",", "[", "]", ")", "if", "request", ".", "user", ".", "is_authenticated", ":", "context", "[", "'au...
Context processor necessary for OpenStack Dashboard functionality. The following variables are added to the request context: ``authorized_tenants`` A list of tenant objects which the current user has access to. ``regions`` A dictionary containing information about region support, the cur...
[ "Context", "processor", "necessary", "for", "OpenStack", "Dashboard", "functionality", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/context_processors.py#L30-L110
train
openstack/horizon
openstack_auth/utils.py
is_token_valid
def is_token_valid(token, margin=None): """Timezone-aware checking of the auth token's expiration timestamp. Returns ``True`` if the token has not yet expired, otherwise ``False``. :param token: The openstack_auth.user.Token instance to check :param margin: A time margin in seconds to subtract...
python
def is_token_valid(token, margin=None): """Timezone-aware checking of the auth token's expiration timestamp. Returns ``True`` if the token has not yet expired, otherwise ``False``. :param token: The openstack_auth.user.Token instance to check :param margin: A time margin in seconds to subtract...
[ "def", "is_token_valid", "(", "token", ",", "margin", "=", "None", ")", ":", "expiration", "=", "token", ".", "expires", "# In case we get an unparseable expiration timestamp, return False", "# so you can't have a \"forever\" token just by breaking the expires param.", "if", "exp...
Timezone-aware checking of the auth token's expiration timestamp. Returns ``True`` if the token has not yet expired, otherwise ``False``. :param token: The openstack_auth.user.Token instance to check :param margin: A time margin in seconds to subtract from the real token's validity. An exam...
[ "Timezone", "-", "aware", "checking", "of", "the", "auth", "token", "s", "expiration", "timestamp", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L75-L101
train
openstack/horizon
openstack_auth/utils.py
is_safe_url
def is_safe_url(url, host=None): """Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url. """ if not url: return False netloc = urlparse.urlparse(url)[1] return not netloc or ...
python
def is_safe_url(url, host=None): """Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url. """ if not url: return False netloc = urlparse.urlparse(url)[1] return not netloc or ...
[ "def", "is_safe_url", "(", "url", ",", "host", "=", "None", ")", ":", "if", "not", "url", ":", "return", "False", "netloc", "=", "urlparse", ".", "urlparse", "(", "url", ")", "[", "1", "]", "return", "not", "netloc", "or", "netloc", "==", "host" ]
Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url.
[ "Return", "True", "if", "the", "url", "is", "a", "safe", "redirection", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L107-L116
train
openstack/horizon
openstack_auth/utils.py
build_absolute_uri
def build_absolute_uri(request, relative_url): """Ensure absolute_uri are relative to WEBROOT.""" webroot = getattr(settings, 'WEBROOT', '') if webroot.endswith("/") and relative_url.startswith("/"): webroot = webroot[:-1] return request.build_absolute_uri(webroot + relative_url)
python
def build_absolute_uri(request, relative_url): """Ensure absolute_uri are relative to WEBROOT.""" webroot = getattr(settings, 'WEBROOT', '') if webroot.endswith("/") and relative_url.startswith("/"): webroot = webroot[:-1] return request.build_absolute_uri(webroot + relative_url)
[ "def", "build_absolute_uri", "(", "request", ",", "relative_url", ")", ":", "webroot", "=", "getattr", "(", "settings", ",", "'WEBROOT'", ",", "''", ")", "if", "webroot", ".", "endswith", "(", "\"/\"", ")", "and", "relative_url", ".", "startswith", "(", "\...
Ensure absolute_uri are relative to WEBROOT.
[ "Ensure", "absolute_uri", "are", "relative", "to", "WEBROOT", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L173-L179
train
openstack/horizon
openstack_auth/utils.py
get_websso_url
def get_websso_url(request, auth_url, websso_auth): """Return the keystone endpoint for initiating WebSSO. Generate the keystone WebSSO endpoint that will redirect the user to the login page of the federated identity provider. Based on the authentication type selected by the user in the login form...
python
def get_websso_url(request, auth_url, websso_auth): """Return the keystone endpoint for initiating WebSSO. Generate the keystone WebSSO endpoint that will redirect the user to the login page of the federated identity provider. Based on the authentication type selected by the user in the login form...
[ "def", "get_websso_url", "(", "request", ",", "auth_url", ",", "websso_auth", ")", ":", "origin", "=", "build_absolute_uri", "(", "request", ",", "'/auth/websso/'", ")", "idp_mapping", "=", "getattr", "(", "settings", ",", "'WEBSSO_IDP_MAPPING'", ",", "{", "}", ...
Return the keystone endpoint for initiating WebSSO. Generate the keystone WebSSO endpoint that will redirect the user to the login page of the federated identity provider. Based on the authentication type selected by the user in the login form, it will construct the keystone WebSSO endpoint. :par...
[ "Return", "the", "keystone", "endpoint", "for", "initiating", "WebSSO", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L182-L257
train
openstack/horizon
openstack_auth/utils.py
has_in_url_path
def has_in_url_path(url, subs): """Test if any of `subs` strings is present in the `url` path.""" scheme, netloc, path, query, fragment = urlparse.urlsplit(url) return any([sub in path for sub in subs])
python
def has_in_url_path(url, subs): """Test if any of `subs` strings is present in the `url` path.""" scheme, netloc, path, query, fragment = urlparse.urlsplit(url) return any([sub in path for sub in subs])
[ "def", "has_in_url_path", "(", "url", ",", "subs", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "return", "any", "(", "[", "sub", "in", "path", "for", "sub", "in", ...
Test if any of `subs` strings is present in the `url` path.
[ "Test", "if", "any", "of", "subs", "strings", "is", "present", "in", "the", "url", "path", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L260-L263
train
openstack/horizon
openstack_auth/utils.py
url_path_replace
def url_path_replace(url, old, new, count=None): """Return a copy of url with replaced path. Return a copy of url with all occurrences of old replaced by new in the url path. If the optional argument count is given, only the first count occurrences are replaced. """ args = [] scheme, netlo...
python
def url_path_replace(url, old, new, count=None): """Return a copy of url with replaced path. Return a copy of url with all occurrences of old replaced by new in the url path. If the optional argument count is given, only the first count occurrences are replaced. """ args = [] scheme, netlo...
[ "def", "url_path_replace", "(", "url", ",", "old", ",", "new", ",", "count", "=", "None", ")", ":", "args", "=", "[", "]", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "if",...
Return a copy of url with replaced path. Return a copy of url with all occurrences of old replaced by new in the url path. If the optional argument count is given, only the first count occurrences are replaced.
[ "Return", "a", "copy", "of", "url", "with", "replaced", "path", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L266-L278
train
openstack/horizon
openstack_auth/utils.py
_augment_url_with_version
def _augment_url_with_version(auth_url): """Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) co...
python
def _augment_url_with_version(auth_url): """Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) co...
[ "def", "_augment_url_with_version", "(", "auth_url", ")", ":", "if", "has_in_url_path", "(", "auth_url", ",", "[", "\"/v2.0\"", ",", "\"/v3\"", "]", ")", ":", "return", "auth_url", "if", "get_keystone_version", "(", ")", ">=", "3", ":", "return", "url_path_app...
Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) could be there. Keystone version needs to be a...
[ "Optionally", "augment", "auth_url", "path", "with", "version", "suffix", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L287-L303
train